/******/ (() => { // webpackBootstrap
/******/ 	var __webpack_modules__ = ({

/***/ 39000:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var asn1 = exports;

asn1.bignum = __webpack_require__(89991);

asn1.define = (__webpack_require__(52747).define);
asn1.base = __webpack_require__(59313);
asn1.constants = __webpack_require__(78801);
asn1.decoders = __webpack_require__(66237);
asn1.encoders = __webpack_require__(91973);


/***/ }),

/***/ 52747:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var asn1 = __webpack_require__(39000);
var inherits = __webpack_require__(72116);

var api = exports;

api.define = function define(name, body) {
  return new Entity(name, body);
};

function Entity(name, body) {
  this.name = name;
  this.body = body;

  this.decoders = {};
  this.encoders = {};
};

Entity.prototype._createNamed = function createNamed(base) {
  var named;
  try {
    named = (__webpack_require__(51755).runInThisContext)(
      '(function ' + this.name + '(entity) {\n' +
      '  this._initNamed(entity);\n' +
      '})'
    );
  } catch (e) {
    named = function (entity) {
      this._initNamed(entity);
    };
  }
  inherits(named, base);
  named.prototype._initNamed = function initnamed(entity) {
    base.call(this, entity);
  };

  return new named(this);
};

Entity.prototype._getDecoder = function _getDecoder(enc) {
  enc = enc || 'der';
  // Lazily create decoder
  if (!this.decoders.hasOwnProperty(enc))
    this.decoders[enc] = this._createNamed(asn1.decoders[enc]);
  return this.decoders[enc];
};

Entity.prototype.decode = function decode(data, enc, options) {
  return this._getDecoder(enc).decode(data, options);
};

Entity.prototype._getEncoder = function _getEncoder(enc) {
  enc = enc || 'der';
  // Lazily create encoder
  if (!this.encoders.hasOwnProperty(enc))
    this.encoders[enc] = this._createNamed(asn1.encoders[enc]);
  return this.encoders[enc];
};

Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
  return this._getEncoder(enc).encode(data, reporter);
};


/***/ }),

/***/ 66179:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var inherits = __webpack_require__(72116);
var Reporter = (__webpack_require__(59313).Reporter);
var Buffer = (__webpack_require__(78378).Buffer);

function DecoderBuffer(base, options) {
  Reporter.call(this, options);
  if (!Buffer.isBuffer(base)) {
    this.error('Input not Buffer');
    return;
  }

  this.base = base;
  this.offset = 0;
  this.length = base.length;
}
inherits(DecoderBuffer, Reporter);
exports.t = DecoderBuffer;

DecoderBuffer.prototype.save = function save() {
  return { offset: this.offset, reporter: Reporter.prototype.save.call(this) };
};

DecoderBuffer.prototype.restore = function restore(save) {
  // Return skipped data
  var res = new DecoderBuffer(this.base);
  res.offset = save.offset;
  res.length = this.offset;

  this.offset = save.offset;
  Reporter.prototype.restore.call(this, save.reporter);

  return res;
};

DecoderBuffer.prototype.isEmpty = function isEmpty() {
  return this.offset === this.length;
};

DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) {
  if (this.offset + 1 <= this.length)
    return this.base.readUInt8(this.offset++, true);
  else
    return this.error(fail || 'DecoderBuffer overrun');
}

DecoderBuffer.prototype.skip = function skip(bytes, fail) {
  if (!(this.offset + bytes <= this.length))
    return this.error(fail || 'DecoderBuffer overrun');

  var res = new DecoderBuffer(this.base);

  // Share reporter state
  res._reporterState = this._reporterState;

  res.offset = this.offset;
  res.length = this.offset + bytes;
  this.offset += bytes;
  return res;
}

DecoderBuffer.prototype.raw = function raw(save) {
  return this.base.slice(save ? save.offset : this.offset, this.length);
}

function EncoderBuffer(value, reporter) {
  if (Array.isArray(value)) {
    this.length = 0;
    this.value = value.map(function(item) {
      if (!(item instanceof EncoderBuffer))
        item = new EncoderBuffer(item, reporter);
      this.length += item.length;
      return item;
    }, this);
  } else if (typeof value === 'number') {
    if (!(0 <= value && value <= 0xff))
      return reporter.error('non-byte EncoderBuffer value');
    this.value = value;
    this.length = 1;
  } else if (typeof value === 'string') {
    this.value = value;
    this.length = Buffer.byteLength(value);
  } else if (Buffer.isBuffer(value)) {
    this.value = value;
    this.length = value.length;
  } else {
    return reporter.error('Unsupported type: ' + typeof value);
  }
}
exports.d = EncoderBuffer;

EncoderBuffer.prototype.join = function join(out, offset) {
  if (!out)
    out = new Buffer(this.length);
  if (!offset)
    offset = 0;

  if (this.length === 0)
    return out;

  if (Array.isArray(this.value)) {
    this.value.forEach(function(item) {
      item.join(out, offset);
      offset += item.length;
    });
  } else {
    if (typeof this.value === 'number')
      out[offset] = this.value;
    else if (typeof this.value === 'string')
      out.write(this.value, offset);
    else if (Buffer.isBuffer(this.value))
      this.value.copy(out, offset);
    offset += this.length;
  }

  return out;
};


/***/ }),

/***/ 59313:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var base = exports;

base.Reporter = (__webpack_require__(62172)/* .Reporter */ .a);
base.DecoderBuffer = (__webpack_require__(66179)/* .DecoderBuffer */ .t);
base.EncoderBuffer = (__webpack_require__(66179)/* .EncoderBuffer */ .d);
base.Node = __webpack_require__(57977);


/***/ }),

/***/ 57977:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var Reporter = (__webpack_require__(59313).Reporter);
var EncoderBuffer = (__webpack_require__(59313).EncoderBuffer);
var DecoderBuffer = (__webpack_require__(59313).DecoderBuffer);
var assert = __webpack_require__(2481);

// Supported tags
var tags = [
  'seq', 'seqof', 'set', 'setof', 'objid', 'bool',
  'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc',
  'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str',
  'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr'
];

// Public methods list
var methods = [
  'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice',
  'any', 'contains'
].concat(tags);

// Overrided methods list
var overrided = [
  '_peekTag', '_decodeTag', '_use',
  '_decodeStr', '_decodeObjid', '_decodeTime',
  '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList',

  '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime',
  '_encodeNull', '_encodeInt', '_encodeBool'
];

function Node(enc, parent) {
  var state = {};
  this._baseState = state;

  state.enc = enc;

  state.parent = parent || null;
  state.children = null;

  // State
  state.tag = null;
  state.args = null;
  state.reverseArgs = null;
  state.choice = null;
  state.optional = false;
  state.any = false;
  state.obj = false;
  state.use = null;
  state.useDecoder = null;
  state.key = null;
  state['default'] = null;
  state.explicit = null;
  state.implicit = null;
  state.contains = null;

  // Should create new instance on each method
  if (!state.parent) {
    state.children = [];
    this._wrap();
  }
}
module.exports = Node;

var stateProps = [
  'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice',
  'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit',
  'implicit', 'contains'
];

Node.prototype.clone = function clone() {
  var state = this._baseState;
  var cstate = {};
  stateProps.forEach(function(prop) {
    cstate[prop] = state[prop];
  });
  var res = new this.constructor(cstate.parent);
  res._baseState = cstate;
  return res;
};

Node.prototype._wrap = function wrap() {
  var state = this._baseState;
  methods.forEach(function(method) {
    this[method] = function _wrappedMethod() {
      var clone = new this.constructor(this);
      state.children.push(clone);
      return clone[method].apply(clone, arguments);
    };
  }, this);
};

Node.prototype._init = function init(body) {
  var state = this._baseState;

  assert(state.parent === null);
  body.call(this);

  // Filter children
  state.children = state.children.filter(function(child) {
    return child._baseState.parent === this;
  }, this);
  assert.equal(state.children.length, 1, 'Root node can have only one child');
};

Node.prototype._useArgs = function useArgs(args) {
  var state = this._baseState;

  // Filter children and args
  var children = args.filter(function(arg) {
    return arg instanceof this.constructor;
  }, this);
  args = args.filter(function(arg) {
    return !(arg instanceof this.constructor);
  }, this);

  if (children.length !== 0) {
    assert(state.children === null);
    state.children = children;

    // Replace parent to maintain backward link
    children.forEach(function(child) {
      child._baseState.parent = this;
    }, this);
  }
  if (args.length !== 0) {
    assert(state.args === null);
    state.args = args;
    state.reverseArgs = args.map(function(arg) {
      if (typeof arg !== 'object' || arg.constructor !== Object)
        return arg;

      var res = {};
      Object.keys(arg).forEach(function(key) {
        if (key == (key | 0))
          key |= 0;
        var value = arg[key];
        res[value] = key;
      });
      return res;
    });
  }
};

//
// Overrided methods
//

overrided.forEach(function(method) {
  Node.prototype[method] = function _overrided() {
    var state = this._baseState;
    throw new Error(method + ' not implemented for encoding: ' + state.enc);
  };
});

//
// Public methods
//

tags.forEach(function(tag) {
  Node.prototype[tag] = function _tagMethod() {
    var state = this._baseState;
    var args = Array.prototype.slice.call(arguments);

    assert(state.tag === null);
    state.tag = tag;

    this._useArgs(args);

    return this;
  };
});

Node.prototype.use = function use(item) {
  assert(item);
  var state = this._baseState;

  assert(state.use === null);
  state.use = item;

  return this;
};

Node.prototype.optional = function optional() {
  var state = this._baseState;

  state.optional = true;

  return this;
};

Node.prototype.def = function def(val) {
  var state = this._baseState;

  assert(state['default'] === null);
  state['default'] = val;
  state.optional = true;

  return this;
};

Node.prototype.explicit = function explicit(num) {
  var state = this._baseState;

  assert(state.explicit === null && state.implicit === null);
  state.explicit = num;

  return this;
};

Node.prototype.implicit = function implicit(num) {
  var state = this._baseState;

  assert(state.explicit === null && state.implicit === null);
  state.implicit = num;

  return this;
};

Node.prototype.obj = function obj() {
  var state = this._baseState;
  var args = Array.prototype.slice.call(arguments);

  state.obj = true;

  if (args.length !== 0)
    this._useArgs(args);

  return this;
};

Node.prototype.key = function key(newKey) {
  var state = this._baseState;

  assert(state.key === null);
  state.key = newKey;

  return this;
};

Node.prototype.any = function any() {
  var state = this._baseState;

  state.any = true;

  return this;
};

Node.prototype.choice = function choice(obj) {
  var state = this._baseState;

  assert(state.choice === null);
  state.choice = obj;
  this._useArgs(Object.keys(obj).map(function(key) {
    return obj[key];
  }));

  return this;
};

Node.prototype.contains = function contains(item) {
  var state = this._baseState;

  assert(state.use === null);
  state.contains = item;

  return this;
};

//
// Decoding
//

Node.prototype._decode = function decode(input, options) {
  var state = this._baseState;

  // Decode root node
  if (state.parent === null)
    return input.wrapResult(state.children[0]._decode(input, options));

  var result = state['default'];
  var present = true;

  var prevKey = null;
  if (state.key !== null)
    prevKey = input.enterKey(state.key);

  // Check if tag is there
  if (state.optional) {
    var tag = null;
    if (state.explicit !== null)
      tag = state.explicit;
    else if (state.implicit !== null)
      tag = state.implicit;
    else if (state.tag !== null)
      tag = state.tag;

    if (tag === null && !state.any) {
      // Trial and Error
      var save = input.save();
      try {
        if (state.choice === null)
          this._decodeGeneric(state.tag, input, options);
        else
          this._decodeChoice(input, options);
        present = true;
      } catch (e) {
        present = false;
      }
      input.restore(save);
    } else {
      present = this._peekTag(input, tag, state.any);

      if (input.isError(present))
        return present;
    }
  }

  // Push object on stack
  var prevObj;
  if (state.obj && present)
    prevObj = input.enterObject();

  if (present) {
    // Unwrap explicit values
    if (state.explicit !== null) {
      var explicit = this._decodeTag(input, state.explicit);
      if (input.isError(explicit))
        return explicit;
      input = explicit;
    }

    var start = input.offset;

    // Unwrap implicit and normal values
    if (state.use === null && state.choice === null) {
      if (state.any)
        var save = input.save();
      var body = this._decodeTag(
        input,
        state.implicit !== null ? state.implicit : state.tag,
        state.any
      );
      if (input.isError(body))
        return body;

      if (state.any)
        result = input.raw(save);
      else
        input = body;
    }

    if (options && options.track && state.tag !== null)
      options.track(input.path(), start, input.length, 'tagged');

    if (options && options.track && state.tag !== null)
      options.track(input.path(), input.offset, input.length, 'content');

    // Select proper method for tag
    if (state.any)
      result = result;
    else if (state.choice === null)
      result = this._decodeGeneric(state.tag, input, options);
    else
      result = this._decodeChoice(input, options);

    if (input.isError(result))
      return result;

    // Decode children
    if (!state.any && state.choice === null && state.children !== null) {
      state.children.forEach(function decodeChildren(child) {
        // NOTE: We are ignoring errors here, to let parser continue with other
        // parts of encoded data
        child._decode(input, options);
      });
    }

    // Decode contained/encoded by schema, only in bit or octet strings
    if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) {
      var data = new DecoderBuffer(result);
      result = this._getUse(state.contains, input._reporterState.obj)
          ._decode(data, options);
    }
  }

  // Pop object
  if (state.obj && present)
    result = input.leaveObject(prevObj);

  // Set key
  if (state.key !== null && (result !== null || present === true))
    input.leaveKey(prevKey, state.key, result);
  else if (prevKey !== null)
    input.exitKey(prevKey);

  return result;
};

Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) {
  var state = this._baseState;

  if (tag === 'seq' || tag === 'set')
    return null;
  if (tag === 'seqof' || tag === 'setof')
    return this._decodeList(input, tag, state.args[0], options);
  else if (/str$/.test(tag))
    return this._decodeStr(input, tag, options);
  else if (tag === 'objid' && state.args)
    return this._decodeObjid(input, state.args[0], state.args[1], options);
  else if (tag === 'objid')
    return this._decodeObjid(input, null, null, options);
  else if (tag === 'gentime' || tag === 'utctime')
    return this._decodeTime(input, tag, options);
  else if (tag === 'null_')
    return this._decodeNull(input, options);
  else if (tag === 'bool')
    return this._decodeBool(input, options);
  else if (tag === 'objDesc')
    return this._decodeStr(input, tag, options);
  else if (tag === 'int' || tag === 'enum')
    return this._decodeInt(input, state.args && state.args[0], options);

  if (state.use !== null) {
    return this._getUse(state.use, input._reporterState.obj)
        ._decode(input, options);
  } else {
    return input.error('unknown tag: ' + tag);
  }
};

Node.prototype._getUse = function _getUse(entity, obj) {

  var state = this._baseState;
  // Create altered use decoder if implicit is set
  state.useDecoder = this._use(entity, obj);
  assert(state.useDecoder._baseState.parent === null);
  state.useDecoder = state.useDecoder._baseState.children[0];
  if (state.implicit !== state.useDecoder._baseState.implicit) {
    state.useDecoder = state.useDecoder.clone();
    state.useDecoder._baseState.implicit = state.implicit;
  }
  return state.useDecoder;
};

Node.prototype._decodeChoice = function decodeChoice(input, options) {
  var state = this._baseState;
  var result = null;
  var match = false;

  Object.keys(state.choice).some(function(key) {
    var save = input.save();
    var node = state.choice[key];
    try {
      var value = node._decode(input, options);
      if (input.isError(value))
        return false;

      result = { type: key, value: value };
      match = true;
    } catch (e) {
      input.restore(save);
      return false;
    }
    return true;
  }, this);

  if (!match)
    return input.error('Choice not matched');

  return result;
};

//
// Encoding
//

Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) {
  return new EncoderBuffer(data, this.reporter);
};

Node.prototype._encode = function encode(data, reporter, parent) {
  var state = this._baseState;
  if (state['default'] !== null && state['default'] === data)
    return;

  var result = this._encodeValue(data, reporter, parent);
  if (result === undefined)
    return;

  if (this._skipDefault(result, reporter, parent))
    return;

  return result;
};

Node.prototype._encodeValue = function encode(data, reporter, parent) {
  var state = this._baseState;

  // Decode root node
  if (state.parent === null)
    return state.children[0]._encode(data, reporter || new Reporter());

  var result = null;

  // Set reporter to share it with a child class
  this.reporter = reporter;

  // Check if data is there
  if (state.optional && data === undefined) {
    if (state['default'] !== null)
      data = state['default']
    else
      return;
  }

  // Encode children first
  var content = null;
  var primitive = false;
  if (state.any) {
    // Anything that was given is translated to buffer
    result = this._createEncoderBuffer(data);
  } else if (state.choice) {
    result = this._encodeChoice(data, reporter);
  } else if (state.contains) {
    content = this._getUse(state.contains, parent)._encode(data, reporter);
    primitive = true;
  } else if (state.children) {
    content = state.children.map(function(child) {
      if (child._baseState.tag === 'null_')
        return child._encode(null, reporter, data);

      if (child._baseState.key === null)
        return reporter.error('Child should have a key');
      var prevKey = reporter.enterKey(child._baseState.key);

      if (typeof data !== 'object')
        return reporter.error('Child expected, but input is not object');

      var res = child._encode(data[child._baseState.key], reporter, data);
      reporter.leaveKey(prevKey);

      return res;
    }, this).filter(function(child) {
      return child;
    });
    content = this._createEncoderBuffer(content);
  } else {
    if (state.tag === 'seqof' || state.tag === 'setof') {
      // TODO(indutny): this should be thrown on DSL level
      if (!(state.args && state.args.length === 1))
        return reporter.error('Too many args for : ' + state.tag);

      if (!Array.isArray(data))
        return reporter.error('seqof/setof, but data is not Array');

      var child = this.clone();
      child._baseState.implicit = null;
      content = this._createEncoderBuffer(data.map(function(item) {
        var state = this._baseState;

        return this._getUse(state.args[0], data)._encode(item, reporter);
      }, child));
    } else if (state.use !== null) {
      result = this._getUse(state.use, parent)._encode(data, reporter);
    } else {
      content = this._encodePrimitive(state.tag, data);
      primitive = true;
    }
  }

  // Encode data itself
  var result;
  if (!state.any && state.choice === null) {
    var tag = state.implicit !== null ? state.implicit : state.tag;
    var cls = state.implicit === null ? 'universal' : 'context';

    if (tag === null) {
      if (state.use === null)
        reporter.error('Tag could be omitted only for .use()');
    } else {
      if (state.use === null)
        result = this._encodeComposite(tag, primitive, cls, content);
    }
  }

  // Wrap in explicit
  if (state.explicit !== null)
    result = this._encodeComposite(state.explicit, false, 'context', result);

  return result;
};

Node.prototype._encodeChoice = function encodeChoice(data, reporter) {
  var state = this._baseState;

  var node = state.choice[data.type];
  if (!node) {
    assert(
        false,
        data.type + ' not found in ' +
            JSON.stringify(Object.keys(state.choice)));
  }
  return node._encode(data.value, reporter);
};

Node.prototype._encodePrimitive = function encodePrimitive(tag, data) {
  var state = this._baseState;

  if (/str$/.test(tag))
    return this._encodeStr(data, tag);
  else if (tag === 'objid' && state.args)
    return this._encodeObjid(data, state.reverseArgs[0], state.args[1]);
  else if (tag === 'objid')
    return this._encodeObjid(data, null, null);
  else if (tag === 'gentime' || tag === 'utctime')
    return this._encodeTime(data, tag);
  else if (tag === 'null_')
    return this._encodeNull();
  else if (tag === 'int' || tag === 'enum')
    return this._encodeInt(data, state.args && state.reverseArgs[0]);
  else if (tag === 'bool')
    return this._encodeBool(data);
  else if (tag === 'objDesc')
    return this._encodeStr(data, tag);
  else
    throw new Error('Unsupported tag: ' + tag);
};

Node.prototype._isNumstr = function isNumstr(str) {
  return /^[0-9 ]*$/.test(str);
};

Node.prototype._isPrintstr = function isPrintstr(str) {
  return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str);
};


/***/ }),

/***/ 62172:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var inherits = __webpack_require__(72116);

function Reporter(options) {
  this._reporterState = {
    obj: null,
    path: [],
    options: options || {},
    errors: []
  };
}
exports.a = Reporter;

Reporter.prototype.isError = function isError(obj) {
  return obj instanceof ReporterError;
};

Reporter.prototype.save = function save() {
  var state = this._reporterState;

  return { obj: state.obj, pathLen: state.path.length };
};

Reporter.prototype.restore = function restore(data) {
  var state = this._reporterState;

  state.obj = data.obj;
  state.path = state.path.slice(0, data.pathLen);
};

Reporter.prototype.enterKey = function enterKey(key) {
  return this._reporterState.path.push(key);
};

Reporter.prototype.exitKey = function exitKey(index) {
  var state = this._reporterState;

  state.path = state.path.slice(0, index - 1);
};

Reporter.prototype.leaveKey = function leaveKey(index, key, value) {
  var state = this._reporterState;

  this.exitKey(index);
  if (state.obj !== null)
    state.obj[key] = value;
};

Reporter.prototype.path = function path() {
  return this._reporterState.path.join('/');
};

Reporter.prototype.enterObject = function enterObject() {
  var state = this._reporterState;

  var prev = state.obj;
  state.obj = {};
  return prev;
};

Reporter.prototype.leaveObject = function leaveObject(prev) {
  var state = this._reporterState;

  var now = state.obj;
  state.obj = prev;
  return now;
};

Reporter.prototype.error = function error(msg) {
  var err;
  var state = this._reporterState;

  var inherited = msg instanceof ReporterError;
  if (inherited) {
    err = msg;
  } else {
    err = new ReporterError(state.path.map(function(elem) {
      return '[' + JSON.stringify(elem) + ']';
    }).join(''), msg.message || msg, msg.stack);
  }

  if (!state.options.partial)
    throw err;

  if (!inherited)
    state.errors.push(err);

  return err;
};

Reporter.prototype.wrapResult = function wrapResult(result) {
  var state = this._reporterState;
  if (!state.options.partial)
    return result;

  return {
    result: this.isError(result) ? null : result,
    errors: state.errors
  };
};

function ReporterError(path, msg) {
  this.path = path;
  this.rethrow(msg);
};
inherits(ReporterError, Error);

ReporterError.prototype.rethrow = function rethrow(msg) {
  this.message = msg + ' at: ' + (this.path || '(shallow)');
  if (Error.captureStackTrace)
    Error.captureStackTrace(this, ReporterError);

  if (!this.stack) {
    try {
      // IE only adds stack when thrown
      throw new Error(this.message);
    } catch (e) {
      this.stack = e.stack;
    }
  }
  return this;
};


/***/ }),

/***/ 59614:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var constants = __webpack_require__(78801);

exports.tagClass = {
  0: 'universal',
  1: 'application',
  2: 'context',
  3: 'private'
};
exports.tagClassByName = constants._reverse(exports.tagClass);

exports.tag = {
  0x00: 'end',
  0x01: 'bool',
  0x02: 'int',
  0x03: 'bitstr',
  0x04: 'octstr',
  0x05: 'null_',
  0x06: 'objid',
  0x07: 'objDesc',
  0x08: 'external',
  0x09: 'real',
  0x0a: 'enum',
  0x0b: 'embed',
  0x0c: 'utf8str',
  0x0d: 'relativeOid',
  0x10: 'seq',
  0x11: 'set',
  0x12: 'numstr',
  0x13: 'printstr',
  0x14: 't61str',
  0x15: 'videostr',
  0x16: 'ia5str',
  0x17: 'utctime',
  0x18: 'gentime',
  0x19: 'graphstr',
  0x1a: 'iso646str',
  0x1b: 'genstr',
  0x1c: 'unistr',
  0x1d: 'charstr',
  0x1e: 'bmpstr'
};
exports.tagByName = constants._reverse(exports.tag);


/***/ }),

/***/ 78801:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var constants = exports;

// Helper
constants._reverse = function reverse(map) {
  var res = {};

  Object.keys(map).forEach(function(key) {
    // Convert key to integer if it is stringified
    if ((key | 0) == key)
      key = key | 0;

    var value = map[key];
    res[value] = key;
  });

  return res;
};

constants.der = __webpack_require__(59614);


/***/ }),

/***/ 57666:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var inherits = __webpack_require__(72116);

var asn1 = __webpack_require__(39000);
var base = asn1.base;
var bignum = asn1.bignum;

// Import DER constants
var der = asn1.constants.der;

function DERDecoder(entity) {
  this.enc = 'der';
  this.name = entity.name;
  this.entity = entity;

  // Construct base tree
  this.tree = new DERNode();
  this.tree._init(entity.body);
};
module.exports = DERDecoder;

DERDecoder.prototype.decode = function decode(data, options) {
  if (!(data instanceof base.DecoderBuffer))
    data = new base.DecoderBuffer(data, options);

  return this.tree._decode(data, options);
};

// Tree methods

function DERNode(parent) {
  base.Node.call(this, 'der', parent);
}
inherits(DERNode, base.Node);

DERNode.prototype._peekTag = function peekTag(buffer, tag, any) {
  if (buffer.isEmpty())
    return false;

  var state = buffer.save();
  var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"');
  if (buffer.isError(decodedTag))
    return decodedTag;

  buffer.restore(state);

  return decodedTag.tag === tag || decodedTag.tagStr === tag ||
    (decodedTag.tagStr + 'of') === tag || any;
};

DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) {
  var decodedTag = derDecodeTag(buffer,
                                'Failed to decode tag of "' + tag + '"');
  if (buffer.isError(decodedTag))
    return decodedTag;

  var len = derDecodeLen(buffer,
                         decodedTag.primitive,
                         'Failed to get length of "' + tag + '"');

  // Failure
  if (buffer.isError(len))
    return len;

  if (!any &&
      decodedTag.tag !== tag &&
      decodedTag.tagStr !== tag &&
      decodedTag.tagStr + 'of' !== tag) {
    return buffer.error('Failed to match tag: "' + tag + '"');
  }

  if (decodedTag.primitive || len !== null)
    return buffer.skip(len, 'Failed to match body of: "' + tag + '"');

  // Indefinite length... find END tag
  var state = buffer.save();
  var res = this._skipUntilEnd(
      buffer,
      'Failed to skip indefinite length body: "' + this.tag + '"');
  if (buffer.isError(res))
    return res;

  len = buffer.offset - state.offset;
  buffer.restore(state);
  return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
};

DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) {
  while (true) {
    var tag = derDecodeTag(buffer, fail);
    if (buffer.isError(tag))
      return tag;
    var len = derDecodeLen(buffer, tag.primitive, fail);
    if (buffer.isError(len))
      return len;

    var res;
    if (tag.primitive || len !== null)
      res = buffer.skip(len)
    else
      res = this._skipUntilEnd(buffer, fail);

    // Failure
    if (buffer.isError(res))
      return res;

    if (tag.tagStr === 'end')
      break;
  }
};

DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder,
                                                    options) {
  var result = [];
  while (!buffer.isEmpty()) {
    var possibleEnd = this._peekTag(buffer, 'end');
    if (buffer.isError(possibleEnd))
      return possibleEnd;

    var res = decoder.decode(buffer, 'der', options);
    if (buffer.isError(res) && possibleEnd)
      break;
    result.push(res);
  }
  return result;
};

DERNode.prototype._decodeStr = function decodeStr(buffer, tag) {
  if (tag === 'bitstr') {
    var unused = buffer.readUInt8();
    if (buffer.isError(unused))
      return unused;
    return { unused: unused, data: buffer.raw() };
  } else if (tag === 'bmpstr') {
    var raw = buffer.raw();
    if (raw.length % 2 === 1)
      return buffer.error('Decoding of string type: bmpstr length mismatch');

    var str = '';
    for (var i = 0; i < raw.length / 2; i++) {
      str += String.fromCharCode(raw.readUInt16BE(i * 2));
    }
    return str;
  } else if (tag === 'numstr') {
    var numstr = buffer.raw().toString('ascii');
    if (!this._isNumstr(numstr)) {
      return buffer.error('Decoding of string type: ' +
                          'numstr unsupported characters');
    }
    return numstr;
  } else if (tag === 'octstr') {
    return buffer.raw();
  } else if (tag === 'objDesc') {
    return buffer.raw();
  } else if (tag === 'printstr') {
    var printstr = buffer.raw().toString('ascii');
    if (!this._isPrintstr(printstr)) {
      return buffer.error('Decoding of string type: ' +
                          'printstr unsupported characters');
    }
    return printstr;
  } else if (/str$/.test(tag)) {
    return buffer.raw().toString();
  } else {
    return buffer.error('Decoding of string type: ' + tag + ' unsupported');
  }
};

DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) {
  var result;
  var identifiers = [];
  var ident = 0;
  while (!buffer.isEmpty()) {
    var subident = buffer.readUInt8();
    ident <<= 7;
    ident |= subident & 0x7f;
    if ((subident & 0x80) === 0) {
      identifiers.push(ident);
      ident = 0;
    }
  }
  if (subident & 0x80)
    identifiers.push(ident);

  var first = (identifiers[0] / 40) | 0;
  var second = identifiers[0] % 40;

  if (relative)
    result = identifiers;
  else
    result = [first, second].concat(identifiers.slice(1));

  if (values) {
    var tmp = values[result.join(' ')];
    if (tmp === undefined)
      tmp = values[result.join('.')];
    if (tmp !== undefined)
      result = tmp;
  }

  return result;
};

DERNode.prototype._decodeTime = function decodeTime(buffer, tag) {
  var str = buffer.raw().toString();
  if (tag === 'gentime') {
    var year = str.slice(0, 4) | 0;
    var mon = str.slice(4, 6) | 0;
    var day = str.slice(6, 8) | 0;
    var hour = str.slice(8, 10) | 0;
    var min = str.slice(10, 12) | 0;
    var sec = str.slice(12, 14) | 0;
  } else if (tag === 'utctime') {
    var year = str.slice(0, 2) | 0;
    var mon = str.slice(2, 4) | 0;
    var day = str.slice(4, 6) | 0;
    var hour = str.slice(6, 8) | 0;
    var min = str.slice(8, 10) | 0;
    var sec = str.slice(10, 12) | 0;
    if (year < 70)
      year = 2000 + year;
    else
      year = 1900 + year;
  } else {
    return buffer.error('Decoding ' + tag + ' time is not supported yet');
  }

  return Date.UTC(year, mon - 1, day, hour, min, sec, 0);
};

DERNode.prototype._decodeNull = function decodeNull(buffer) {
  return null;
};

DERNode.prototype._decodeBool = function decodeBool(buffer) {
  var res = buffer.readUInt8();
  if (buffer.isError(res))
    return res;
  else
    return res !== 0;
};

DERNode.prototype._decodeInt = function decodeInt(buffer, values) {
  // Bigint, return as it is (assume big endian)
  var raw = buffer.raw();
  var res = new bignum(raw);

  if (values)
    res = values[res.toString(10)] || res;

  return res;
};

DERNode.prototype._use = function use(entity, obj) {
  if (typeof entity === 'function')
    entity = entity(obj);
  return entity._getDecoder('der').tree;
};

// Utility methods

function derDecodeTag(buf, fail) {
  var tag = buf.readUInt8(fail);
  if (buf.isError(tag))
    return tag;

  var cls = der.tagClass[tag >> 6];
  var primitive = (tag & 0x20) === 0;

  // Multi-octet tag - load
  if ((tag & 0x1f) === 0x1f) {
    var oct = tag;
    tag = 0;
    while ((oct & 0x80) === 0x80) {
      oct = buf.readUInt8(fail);
      if (buf.isError(oct))
        return oct;

      tag <<= 7;
      tag |= oct & 0x7f;
    }
  } else {
    tag &= 0x1f;
  }
  var tagStr = der.tag[tag];

  return {
    cls: cls,
    primitive: primitive,
    tag: tag,
    tagStr: tagStr
  };
}

function derDecodeLen(buf, primitive, fail) {
  var len = buf.readUInt8(fail);
  if (buf.isError(len))
    return len;

  // Indefinite form
  if (!primitive && len === 0x80)
    return null;

  // Definite form
  if ((len & 0x80) === 0) {
    // Short form
    return len;
  }

  // Long form
  var num = len & 0x7f;
  if (num > 4)
    return buf.error('length octect is too long');

  len = 0;
  for (var i = 0; i < num; i++) {
    len <<= 8;
    var j = buf.readUInt8(fail);
    if (buf.isError(j))
      return j;
    len |= j;
  }

  return len;
}


/***/ }),

/***/ 66237:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var decoders = exports;

decoders.der = __webpack_require__(57666);
decoders.pem = __webpack_require__(36687);


/***/ }),

/***/ 36687:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var inherits = __webpack_require__(72116);
var Buffer = (__webpack_require__(78378).Buffer);

var DERDecoder = __webpack_require__(57666);

function PEMDecoder(entity) {
  DERDecoder.call(this, entity);
  this.enc = 'pem';
};
inherits(PEMDecoder, DERDecoder);
module.exports = PEMDecoder;

PEMDecoder.prototype.decode = function decode(data, options) {
  var lines = data.toString().split(/[\r\n]+/g);

  var label = options.label.toUpperCase();

  var re = /^-----(BEGIN|END) ([^-]+)-----$/;
  var start = -1;
  var end = -1;
  for (var i = 0; i < lines.length; i++) {
    var match = lines[i].match(re);
    if (match === null)
      continue;

    if (match[2] !== label)
      continue;

    if (start === -1) {
      if (match[1] !== 'BEGIN')
        break;
      start = i;
    } else {
      if (match[1] !== 'END')
        break;
      end = i;
      break;
    }
  }
  if (start === -1 || end === -1)
    throw new Error('PEM section not found for: ' + label);

  var base64 = lines.slice(start + 1, end).join('');
  // Remove excessive symbols
  base64.replace(/[^a-z0-9\+\/=]+/gi, '');

  var input = new Buffer(base64, 'base64');
  return DERDecoder.prototype.decode.call(this, input, options);
};


/***/ }),

/***/ 26426:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var inherits = __webpack_require__(72116);
var Buffer = (__webpack_require__(78378).Buffer);

var asn1 = __webpack_require__(39000);
var base = asn1.base;

// Import DER constants
var der = asn1.constants.der;

function DEREncoder(entity) {
  this.enc = 'der';
  this.name = entity.name;
  this.entity = entity;

  // Construct base tree
  this.tree = new DERNode();
  this.tree._init(entity.body);
};
module.exports = DEREncoder;

DEREncoder.prototype.encode = function encode(data, reporter) {
  return this.tree._encode(data, reporter).join();
};

// Tree methods

function DERNode(parent) {
  base.Node.call(this, 'der', parent);
}
inherits(DERNode, base.Node);

DERNode.prototype._encodeComposite = function encodeComposite(tag,
                                                              primitive,
                                                              cls,
                                                              content) {
  var encodedTag = encodeTag(tag, primitive, cls, this.reporter);

  // Short form
  if (content.length < 0x80) {
    var header = new Buffer(2);
    header[0] = encodedTag;
    header[1] = content.length;
    return this._createEncoderBuffer([ header, content ]);
  }

  // Long form
  // Count octets required to store length
  var lenOctets = 1;
  for (var i = content.length; i >= 0x100; i >>= 8)
    lenOctets++;

  var header = new Buffer(1 + 1 + lenOctets);
  header[0] = encodedTag;
  header[1] = 0x80 | lenOctets;

  for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8)
    header[i] = j & 0xff;

  return this._createEncoderBuffer([ header, content ]);
};

DERNode.prototype._encodeStr = function encodeStr(str, tag) {
  if (tag === 'bitstr') {
    return this._createEncoderBuffer([ str.unused | 0, str.data ]);
  } else if (tag === 'bmpstr') {
    var buf = new Buffer(str.length * 2);
    for (var i = 0; i < str.length; i++) {
      buf.writeUInt16BE(str.charCodeAt(i), i * 2);
    }
    return this._createEncoderBuffer(buf);
  } else if (tag === 'numstr') {
    if (!this._isNumstr(str)) {
      return this.reporter.error('Encoding of string type: numstr supports ' +
                                 'only digits and space');
    }
    return this._createEncoderBuffer(str);
  } else if (tag === 'printstr') {
    if (!this._isPrintstr(str)) {
      return this.reporter.error('Encoding of string type: printstr supports ' +
                                 'only latin upper and lower case letters, ' +
                                 'digits, space, apostrophe, left and rigth ' +
                                 'parenthesis, plus sign, comma, hyphen, ' +
                                 'dot, slash, colon, equal sign, ' +
                                 'question mark');
    }
    return this._createEncoderBuffer(str);
  } else if (/str$/.test(tag)) {
    return this._createEncoderBuffer(str);
  } else if (tag === 'objDesc') {
    return this._createEncoderBuffer(str);
  } else {
    return this.reporter.error('Encoding of string type: ' + tag +
                               ' unsupported');
  }
};

DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) {
  if (typeof id === 'string') {
    if (!values)
      return this.reporter.error('string objid given, but no values map found');
    if (!values.hasOwnProperty(id))
      return this.reporter.error('objid not found in values map');
    id = values[id].split(/[\s\.]+/g);
    for (var i = 0; i < id.length; i++)
      id[i] |= 0;
  } else if (Array.isArray(id)) {
    id = id.slice();
    for (var i = 0; i < id.length; i++)
      id[i] |= 0;
  }

  if (!Array.isArray(id)) {
    return this.reporter.error('objid() should be either array or string, ' +
                               'got: ' + JSON.stringify(id));
  }

  if (!relative) {
    if (id[1] >= 40)
      return this.reporter.error('Second objid identifier OOB');
    id.splice(0, 2, id[0] * 40 + id[1]);
  }

  // Count number of octets
  var size = 0;
  for (var i = 0; i < id.length; i++) {
    var ident = id[i];
    for (size++; ident >= 0x80; ident >>= 7)
      size++;
  }

  var objid = new Buffer(size);
  var offset = objid.length - 1;
  for (var i = id.length - 1; i >= 0; i--) {
    var ident = id[i];
    objid[offset--] = ident & 0x7f;
    while ((ident >>= 7) > 0)
      objid[offset--] = 0x80 | (ident & 0x7f);
  }

  return this._createEncoderBuffer(objid);
};

function two(num) {
  if (num < 10)
    return '0' + num;
  else
    return num;
}

DERNode.prototype._encodeTime = function encodeTime(time, tag) {
  var str;
  var date = new Date(time);

  if (tag === 'gentime') {
    str = [
      two(date.getFullYear()),
      two(date.getUTCMonth() + 1),
      two(date.getUTCDate()),
      two(date.getUTCHours()),
      two(date.getUTCMinutes()),
      two(date.getUTCSeconds()),
      'Z'
    ].join('');
  } else if (tag === 'utctime') {
    str = [
      two(date.getFullYear() % 100),
      two(date.getUTCMonth() + 1),
      two(date.getUTCDate()),
      two(date.getUTCHours()),
      two(date.getUTCMinutes()),
      two(date.getUTCSeconds()),
      'Z'
    ].join('');
  } else {
    this.reporter.error('Encoding ' + tag + ' time is not supported yet');
  }

  return this._encodeStr(str, 'octstr');
};

DERNode.prototype._encodeNull = function encodeNull() {
  return this._createEncoderBuffer('');
};

DERNode.prototype._encodeInt = function encodeInt(num, values) {
  if (typeof num === 'string') {
    if (!values)
      return this.reporter.error('String int or enum given, but no values map');
    if (!values.hasOwnProperty(num)) {
      return this.reporter.error('Values map doesn\'t contain: ' +
                                 JSON.stringify(num));
    }
    num = values[num];
  }

  // Bignum, assume big endian
  if (typeof num !== 'number' && !Buffer.isBuffer(num)) {
    var numArray = num.toArray();
    if (!num.sign && numArray[0] & 0x80) {
      numArray.unshift(0);
    }
    num = new Buffer(numArray);
  }

  if (Buffer.isBuffer(num)) {
    var size = num.length;
    if (num.length === 0)
      size++;

    var out = new Buffer(size);
    num.copy(out);
    if (num.length === 0)
      out[0] = 0
    return this._createEncoderBuffer(out);
  }

  if (num < 0x80)
    return this._createEncoderBuffer(num);

  if (num < 0x100)
    return this._createEncoderBuffer([0, num]);

  var size = 1;
  for (var i = num; i >= 0x100; i >>= 8)
    size++;

  var out = new Array(size);
  for (var i = out.length - 1; i >= 0; i--) {
    out[i] = num & 0xff;
    num >>= 8;
  }
  if(out[0] & 0x80) {
    out.unshift(0);
  }

  return this._createEncoderBuffer(new Buffer(out));
};

DERNode.prototype._encodeBool = function encodeBool(value) {
  return this._createEncoderBuffer(value ? 0xff : 0);
};

DERNode.prototype._use = function use(entity, obj) {
  if (typeof entity === 'function')
    entity = entity(obj);
  return entity._getEncoder('der').tree;
};

DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) {
  var state = this._baseState;
  var i;
  if (state['default'] === null)
    return false;

  var data = dataBuffer.join();
  if (state.defaultBuffer === undefined)
    state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join();

  if (data.length !== state.defaultBuffer.length)
    return false;

  for (i=0; i < data.length; i++)
    if (data[i] !== state.defaultBuffer[i])
      return false;

  return true;
};

// Utility methods

function encodeTag(tag, primitive, cls, reporter) {
  var res;

  if (tag === 'seqof')
    tag = 'seq';
  else if (tag === 'setof')
    tag = 'set';

  if (der.tagByName.hasOwnProperty(tag))
    res = der.tagByName[tag];
  else if (typeof tag === 'number' && (tag | 0) === tag)
    res = tag;
  else
    return reporter.error('Unknown tag: ' + tag);

  if (res >= 0x1f)
    return reporter.error('Multi-octet tag encoding unsupported');

  if (!primitive)
    res |= 0x20;

  res |= (der.tagClassByName[cls || 'universal'] << 6);

  return res;
}


/***/ }),

/***/ 91973:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var encoders = exports;

encoders.der = __webpack_require__(26426);
encoders.pem = __webpack_require__(37719);


/***/ }),

/***/ 37719:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var inherits = __webpack_require__(72116);

var DEREncoder = __webpack_require__(26426);

function PEMEncoder(entity) {
  DEREncoder.call(this, entity);
  this.enc = 'pem';
};
inherits(PEMEncoder, DEREncoder);
module.exports = PEMEncoder;

PEMEncoder.prototype.encode = function encode(data, options) {
  var buf = DEREncoder.prototype.encode.call(this, data);

  var p = buf.toString('base64');
  var out = [ '-----BEGIN ' + options.label + '-----' ];
  for (var i = 0; i < p.length; i += 64)
    out.push(p.slice(i, i + 64));
  out.push('-----END ' + options.label + '-----');
  return out.join('\n');
};


/***/ }),

/***/ 67362:
/***/ ((__unused_webpack_module, exports) => {

"use strict";


exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray

var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array

var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
  lookup[i] = code[i]
  revLookup[code.charCodeAt(i)] = i
}

// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63

function getLens (b64) {
  var len = b64.length

  if (len % 4 > 0) {
    throw new Error('Invalid string. Length must be a multiple of 4')
  }

  // Trim off extra bytes after placeholder bytes are found
  // See: https://github.com/beatgammit/base64-js/issues/42
  var validLen = b64.indexOf('=')
  if (validLen === -1) validLen = len

  var placeHoldersLen = validLen === len
    ? 0
    : 4 - (validLen % 4)

  return [validLen, placeHoldersLen]
}

// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function _byteLength (b64, validLen, placeHoldersLen) {
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function toByteArray (b64) {
  var tmp
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]

  var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))

  var curByte = 0

  // if there are placeholders, only get up to the last complete 4 chars
  var len = placeHoldersLen > 0
    ? validLen - 4
    : validLen

  var i
  for (i = 0; i < len; i += 4) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 18) |
      (revLookup[b64.charCodeAt(i + 1)] << 12) |
      (revLookup[b64.charCodeAt(i + 2)] << 6) |
      revLookup[b64.charCodeAt(i + 3)]
    arr[curByte++] = (tmp >> 16) & 0xFF
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 2) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 2) |
      (revLookup[b64.charCodeAt(i + 1)] >> 4)
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 1) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 10) |
      (revLookup[b64.charCodeAt(i + 1)] << 4) |
      (revLookup[b64.charCodeAt(i + 2)] >> 2)
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  return arr
}

function tripletToBase64 (num) {
  return lookup[num >> 18 & 0x3F] +
    lookup[num >> 12 & 0x3F] +
    lookup[num >> 6 & 0x3F] +
    lookup[num & 0x3F]
}

function encodeChunk (uint8, start, end) {
  var tmp
  var output = []
  for (var i = start; i < end; i += 3) {
    tmp =
      ((uint8[i] << 16) & 0xFF0000) +
      ((uint8[i + 1] << 8) & 0xFF00) +
      (uint8[i + 2] & 0xFF)
    output.push(tripletToBase64(tmp))
  }
  return output.join('')
}

function fromByteArray (uint8) {
  var tmp
  var len = uint8.length
  var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  var parts = []
  var maxChunkLength = 16383 // must be multiple of 3

  // go through the array every three bytes, we'll deal with trailing stuff later
  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
    parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  }

  // pad the end with zeros, but make sure to not forget the extra bytes
  if (extraBytes === 1) {
    tmp = uint8[len - 1]
    parts.push(
      lookup[tmp >> 2] +
      lookup[(tmp << 4) & 0x3F] +
      '=='
    )
  } else if (extraBytes === 2) {
    tmp = (uint8[len - 2] << 8) + uint8[len - 1]
    parts.push(
      lookup[tmp >> 10] +
      lookup[(tmp >> 4) & 0x3F] +
      lookup[(tmp << 2) & 0x3F] +
      '='
    )
  }

  return parts.join('')
}


/***/ }),

/***/ 89991:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {

/* module decorator */ module = __webpack_require__.nmd(module);
(function (module, exports) {
  'use strict';

  // Utils
  function assert (val, msg) {
    if (!val) throw new Error(msg || 'Assertion failed');
  }

  // Could use `inherits` module, but don't want to move from single file
  // architecture yet.
  function inherits (ctor, superCtor) {
    ctor.super_ = superCtor;
    var TempCtor = function () {};
    TempCtor.prototype = superCtor.prototype;
    ctor.prototype = new TempCtor();
    ctor.prototype.constructor = ctor;
  }

  // BN

  function BN (number, base, endian) {
    if (BN.isBN(number)) {
      return number;
    }

    this.negative = 0;
    this.words = null;
    this.length = 0;

    // Reduction context
    this.red = null;

    if (number !== null) {
      if (base === 'le' || base === 'be') {
        endian = base;
        base = 10;
      }

      this._init(number || 0, base || 10, endian || 'be');
    }
  }
  if (typeof module === 'object') {
    module.exports = BN;
  } else {
    exports.BN = BN;
  }

  BN.BN = BN;
  BN.wordSize = 26;

  var Buffer;
  try {
    if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {
      Buffer = window.Buffer;
    } else {
      Buffer = (__webpack_require__(20399).Buffer);
    }
  } catch (e) {
  }

  BN.isBN = function isBN (num) {
    if (num instanceof BN) {
      return true;
    }

    return num !== null && typeof num === 'object' &&
      num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
  };

  BN.max = function max (left, right) {
    if (left.cmp(right) > 0) return left;
    return right;
  };

  BN.min = function min (left, right) {
    if (left.cmp(right) < 0) return left;
    return right;
  };

  BN.prototype._init = function init (number, base, endian) {
    if (typeof number === 'number') {
      return this._initNumber(number, base, endian);
    }

    if (typeof number === 'object') {
      return this._initArray(number, base, endian);
    }

    if (base === 'hex') {
      base = 16;
    }
    assert(base === (base | 0) && base >= 2 && base <= 36);

    number = number.toString().replace(/\s+/g, '');
    var start = 0;
    if (number[0] === '-') {
      start++;
      this.negative = 1;
    }

    if (start < number.length) {
      if (base === 16) {
        this._parseHex(number, start, endian);
      } else {
        this._parseBase(number, base, start);
        if (endian === 'le') {
          this._initArray(this.toArray(), base, endian);
        }
      }
    }
  };

  BN.prototype._initNumber = function _initNumber (number, base, endian) {
    if (number < 0) {
      this.negative = 1;
      number = -number;
    }
    if (number < 0x4000000) {
      this.words = [ number & 0x3ffffff ];
      this.length = 1;
    } else if (number < 0x10000000000000) {
      this.words = [
        number & 0x3ffffff,
        (number / 0x4000000) & 0x3ffffff
      ];
      this.length = 2;
    } else {
      assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
      this.words = [
        number & 0x3ffffff,
        (number / 0x4000000) & 0x3ffffff,
        1
      ];
      this.length = 3;
    }

    if (endian !== 'le') return;

    // Reverse the bytes
    this._initArray(this.toArray(), base, endian);
  };

  BN.prototype._initArray = function _initArray (number, base, endian) {
    // Perhaps a Uint8Array
    assert(typeof number.length === 'number');
    if (number.length <= 0) {
      this.words = [ 0 ];
      this.length = 1;
      return this;
    }

    this.length = Math.ceil(number.length / 3);
    this.words = new Array(this.length);
    for (var i = 0; i < this.length; i++) {
      this.words[i] = 0;
    }

    var j, w;
    var off = 0;
    if (endian === 'be') {
      for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
        w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
        this.words[j] |= (w << off) & 0x3ffffff;
        this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
        off += 24;
        if (off >= 26) {
          off -= 26;
          j++;
        }
      }
    } else if (endian === 'le') {
      for (i = 0, j = 0; i < number.length; i += 3) {
        w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
        this.words[j] |= (w << off) & 0x3ffffff;
        this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
        off += 24;
        if (off >= 26) {
          off -= 26;
          j++;
        }
      }
    }
    return this.strip();
  };

  function parseHex4Bits (string, index) {
    var c = string.charCodeAt(index);
    // 'A' - 'F'
    if (c >= 65 && c <= 70) {
      return c - 55;
    // 'a' - 'f'
    } else if (c >= 97 && c <= 102) {
      return c - 87;
    // '0' - '9'
    } else {
      return (c - 48) & 0xf;
    }
  }

  function parseHexByte (string, lowerBound, index) {
    var r = parseHex4Bits(string, index);
    if (index - 1 >= lowerBound) {
      r |= parseHex4Bits(string, index - 1) << 4;
    }
    return r;
  }

  BN.prototype._parseHex = function _parseHex (number, start, endian) {
    // Create possibly bigger array to ensure that it fits the number
    this.length = Math.ceil((number.length - start) / 6);
    this.words = new Array(this.length);
    for (var i = 0; i < this.length; i++) {
      this.words[i] = 0;
    }

    // 24-bits chunks
    var off = 0;
    var j = 0;

    var w;
    if (endian === 'be') {
      for (i = number.length - 1; i >= start; i -= 2) {
        w = parseHexByte(number, start, i) << off;
        this.words[j] |= w & 0x3ffffff;
        if (off >= 18) {
          off -= 18;
          j += 1;
          this.words[j] |= w >>> 26;
        } else {
          off += 8;
        }
      }
    } else {
      var parseLength = number.length - start;
      for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {
        w = parseHexByte(number, start, i) << off;
        this.words[j] |= w & 0x3ffffff;
        if (off >= 18) {
          off -= 18;
          j += 1;
          this.words[j] |= w >>> 26;
        } else {
          off += 8;
        }
      }
    }

    this.strip();
  };

  function parseBase (str, start, end, mul) {
    var r = 0;
    var len = Math.min(str.length, end);
    for (var i = start; i < len; i++) {
      var c = str.charCodeAt(i) - 48;

      r *= mul;

      // 'a'
      if (c >= 49) {
        r += c - 49 + 0xa;

      // 'A'
      } else if (c >= 17) {
        r += c - 17 + 0xa;

      // '0' - '9'
      } else {
        r += c;
      }
    }
    return r;
  }

  BN.prototype._parseBase = function _parseBase (number, base, start) {
    // Initialize as zero
    this.words = [ 0 ];
    this.length = 1;

    // Find length of limb in base
    for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
      limbLen++;
    }
    limbLen--;
    limbPow = (limbPow / base) | 0;

    var total = number.length - start;
    var mod = total % limbLen;
    var end = Math.min(total, total - mod) + start;

    var word = 0;
    for (var i = start; i < end; i += limbLen) {
      word = parseBase(number, i, i + limbLen, base);

      this.imuln(limbPow);
      if (this.words[0] + word < 0x4000000) {
        this.words[0] += word;
      } else {
        this._iaddn(word);
      }
    }

    if (mod !== 0) {
      var pow = 1;
      word = parseBase(number, i, number.length, base);

      for (i = 0; i < mod; i++) {
        pow *= base;
      }

      this.imuln(pow);
      if (this.words[0] + word < 0x4000000) {
        this.words[0] += word;
      } else {
        this._iaddn(word);
      }
    }

    this.strip();
  };

  BN.prototype.copy = function copy (dest) {
    dest.words = new Array(this.length);
    for (var i = 0; i < this.length; i++) {
      dest.words[i] = this.words[i];
    }
    dest.length = this.length;
    dest.negative = this.negative;
    dest.red = this.red;
  };

  BN.prototype.clone = function clone () {
    var r = new BN(null);
    this.copy(r);
    return r;
  };

  BN.prototype._expand = function _expand (size) {
    while (this.length < size) {
      this.words[this.length++] = 0;
    }
    return this;
  };

  // Remove leading `0` from `this`
  BN.prototype.strip = function strip () {
    while (this.length > 1 && this.words[this.length - 1] === 0) {
      this.length--;
    }
    return this._normSign();
  };

  BN.prototype._normSign = function _normSign () {
    // -0 = 0
    if (this.length === 1 && this.words[0] === 0) {
      this.negative = 0;
    }
    return this;
  };

  BN.prototype.inspect = function inspect () {
    return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
  };

  /*

  var zeros = [];
  var groupSizes = [];
  var groupBases = [];

  var s = '';
  var i = -1;
  while (++i < BN.wordSize) {
    zeros[i] = s;
    s += '0';
  }
  groupSizes[0] = 0;
  groupSizes[1] = 0;
  groupBases[0] = 0;
  groupBases[1] = 0;
  var base = 2 - 1;
  while (++base < 36 + 1) {
    var groupSize = 0;
    var groupBase = 1;
    while (groupBase < (1 << BN.wordSize) / base) {
      groupBase *= base;
      groupSize += 1;
    }
    groupSizes[base] = groupSize;
    groupBases[base] = groupBase;
  }

  */

  var zeros = [
    '',
    '0',
    '00',
    '000',
    '0000',
    '00000',
    '000000',
    '0000000',
    '00000000',
    '000000000',
    '0000000000',
    '00000000000',
    '000000000000',
    '0000000000000',
    '00000000000000',
    '000000000000000',
    '0000000000000000',
    '00000000000000000',
    '000000000000000000',
    '0000000000000000000',
    '00000000000000000000',
    '000000000000000000000',
    '0000000000000000000000',
    '00000000000000000000000',
    '000000000000000000000000',
    '0000000000000000000000000'
  ];

  var groupSizes = [
    0, 0,
    25, 16, 12, 11, 10, 9, 8,
    8, 7, 7, 7, 7, 6, 6,
    6, 6, 6, 6, 6, 5, 5,
    5, 5, 5, 5, 5, 5, 5,
    5, 5, 5, 5, 5, 5, 5
  ];

  var groupBases = [
    0, 0,
    33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
    43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
    16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
    6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
    24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
  ];

  BN.prototype.toString = function toString (base, padding) {
    base = base || 10;
    padding = padding | 0 || 1;

    var out;
    if (base === 16 || base === 'hex') {
      out = '';
      var off = 0;
      var carry = 0;
      for (var i = 0; i < this.length; i++) {
        var w = this.words[i];
        var word = (((w << off) | carry) & 0xffffff).toString(16);
        carry = (w >>> (24 - off)) & 0xffffff;
        off += 2;
        if (off >= 26) {
          off -= 26;
          i--;
        }
        if (carry !== 0 || i !== this.length - 1) {
          out = zeros[6 - word.length] + word + out;
        } else {
          out = word + out;
        }
      }
      if (carry !== 0) {
        out = carry.toString(16) + out;
      }
      while (out.length % padding !== 0) {
        out = '0' + out;
      }
      if (this.negative !== 0) {
        out = '-' + out;
      }
      return out;
    }

    if (base === (base | 0) && base >= 2 && base <= 36) {
      // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
      var groupSize = groupSizes[base];
      // var groupBase = Math.pow(base, groupSize);
      var groupBase = groupBases[base];
      out = '';
      var c = this.clone();
      c.negative = 0;
      while (!c.isZero()) {
        var r = c.modn(groupBase).toString(base);
        c = c.idivn(groupBase);

        if (!c.isZero()) {
          out = zeros[groupSize - r.length] + r + out;
        } else {
          out = r + out;
        }
      }
      if (this.isZero()) {
        out = '0' + out;
      }
      while (out.length % padding !== 0) {
        out = '0' + out;
      }
      if (this.negative !== 0) {
        out = '-' + out;
      }
      return out;
    }

    assert(false, 'Base should be between 2 and 36');
  };

  BN.prototype.toNumber = function toNumber () {
    var ret = this.words[0];
    if (this.length === 2) {
      ret += this.words[1] * 0x4000000;
    } else if (this.length === 3 && this.words[2] === 0x01) {
      // NOTE: at this stage it is known that the top bit is set
      ret += 0x10000000000000 + (this.words[1] * 0x4000000);
    } else if (this.length > 2) {
      assert(false, 'Number can only safely store up to 53 bits');
    }
    return (this.negative !== 0) ? -ret : ret;
  };

  BN.prototype.toJSON = function toJSON () {
    return this.toString(16);
  };

  BN.prototype.toBuffer = function toBuffer (endian, length) {
    assert(typeof Buffer !== 'undefined');
    return this.toArrayLike(Buffer, endian, length);
  };

  BN.prototype.toArray = function toArray (endian, length) {
    return this.toArrayLike(Array, endian, length);
  };

  BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
    var byteLength = this.byteLength();
    var reqLength = length || Math.max(1, byteLength);
    assert(byteLength <= reqLength, 'byte array longer than desired length');
    assert(reqLength > 0, 'Requested array length <= 0');

    this.strip();
    var littleEndian = endian === 'le';
    var res = new ArrayType(reqLength);

    var b, i;
    var q = this.clone();
    if (!littleEndian) {
      // Assume big-endian
      for (i = 0; i < reqLength - byteLength; i++) {
        res[i] = 0;
      }

      for (i = 0; !q.isZero(); i++) {
        b = q.andln(0xff);
        q.iushrn(8);

        res[reqLength - i - 1] = b;
      }
    } else {
      for (i = 0; !q.isZero(); i++) {
        b = q.andln(0xff);
        q.iushrn(8);

        res[i] = b;
      }

      for (; i < reqLength; i++) {
        res[i] = 0;
      }
    }

    return res;
  };

  if (Math.clz32) {
    BN.prototype._countBits = function _countBits (w) {
      return 32 - Math.clz32(w);
    };
  } else {
    BN.prototype._countBits = function _countBits (w) {
      var t = w;
      var r = 0;
      if (t >= 0x1000) {
        r += 13;
        t >>>= 13;
      }
      if (t >= 0x40) {
        r += 7;
        t >>>= 7;
      }
      if (t >= 0x8) {
        r += 4;
        t >>>= 4;
      }
      if (t >= 0x02) {
        r += 2;
        t >>>= 2;
      }
      return r + t;
    };
  }

  BN.prototype._zeroBits = function _zeroBits (w) {
    // Short-cut
    if (w === 0) return 26;

    var t = w;
    var r = 0;
    if ((t & 0x1fff) === 0) {
      r += 13;
      t >>>= 13;
    }
    if ((t & 0x7f) === 0) {
      r += 7;
      t >>>= 7;
    }
    if ((t & 0xf) === 0) {
      r += 4;
      t >>>= 4;
    }
    if ((t & 0x3) === 0) {
      r += 2;
      t >>>= 2;
    }
    if ((t & 0x1) === 0) {
      r++;
    }
    return r;
  };

  // Return number of used bits in a BN
  BN.prototype.bitLength = function bitLength () {
    var w = this.words[this.length - 1];
    var hi = this._countBits(w);
    return (this.length - 1) * 26 + hi;
  };

  function toBitArray (num) {
    var w = new Array(num.bitLength());

    for (var bit = 0; bit < w.length; bit++) {
      var off = (bit / 26) | 0;
      var wbit = bit % 26;

      w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
    }

    return w;
  }

  // Number of trailing zero bits
  BN.prototype.zeroBits = function zeroBits () {
    if (this.isZero()) return 0;

    var r = 0;
    for (var i = 0; i < this.length; i++) {
      var b = this._zeroBits(this.words[i]);
      r += b;
      if (b !== 26) break;
    }
    return r;
  };

  BN.prototype.byteLength = function byteLength () {
    return Math.ceil(this.bitLength() / 8);
  };

  BN.prototype.toTwos = function toTwos (width) {
    if (this.negative !== 0) {
      return this.abs().inotn(width).iaddn(1);
    }
    return this.clone();
  };

  BN.prototype.fromTwos = function fromTwos (width) {
    if (this.testn(width - 1)) {
      return this.notn(width).iaddn(1).ineg();
    }
    return this.clone();
  };

  BN.prototype.isNeg = function isNeg () {
    return this.negative !== 0;
  };

  // Return negative clone of `this`
  BN.prototype.neg = function neg () {
    return this.clone().ineg();
  };

  BN.prototype.ineg = function ineg () {
    if (!this.isZero()) {
      this.negative ^= 1;
    }

    return this;
  };

  // Or `num` with `this` in-place
  BN.prototype.iuor = function iuor (num) {
    while (this.length < num.length) {
      this.words[this.length++] = 0;
    }

    for (var i = 0; i < num.length; i++) {
      this.words[i] = this.words[i] | num.words[i];
    }

    return this.strip();
  };

  BN.prototype.ior = function ior (num) {
    assert((this.negative | num.negative) === 0);
    return this.iuor(num);
  };

  // Or `num` with `this`
  BN.prototype.or = function or (num) {
    if (this.length > num.length) return this.clone().ior(num);
    return num.clone().ior(this);
  };

  BN.prototype.uor = function uor (num) {
    if (this.length > num.length) return this.clone().iuor(num);
    return num.clone().iuor(this);
  };

  // And `num` with `this` in-place
  BN.prototype.iuand = function iuand (num) {
    // b = min-length(num, this)
    var b;
    if (this.length > num.length) {
      b = num;
    } else {
      b = this;
    }

    for (var i = 0; i < b.length; i++) {
      this.words[i] = this.words[i] & num.words[i];
    }

    this.length = b.length;

    return this.strip();
  };

  BN.prototype.iand = function iand (num) {
    assert((this.negative | num.negative) === 0);
    return this.iuand(num);
  };

  // And `num` with `this`
  BN.prototype.and = function and (num) {
    if (this.length > num.length) return this.clone().iand(num);
    return num.clone().iand(this);
  };

  BN.prototype.uand = function uand (num) {
    if (this.length > num.length) return this.clone().iuand(num);
    return num.clone().iuand(this);
  };

  // Xor `num` with `this` in-place
  BN.prototype.iuxor = function iuxor (num) {
    // a.length > b.length
    var a;
    var b;
    if (this.length > num.length) {
      a = this;
      b = num;
    } else {
      a = num;
      b = this;
    }

    for (var i = 0; i < b.length; i++) {
      this.words[i] = a.words[i] ^ b.words[i];
    }

    if (this !== a) {
      for (; i < a.length; i++) {
        this.words[i] = a.words[i];
      }
    }

    this.length = a.length;

    return this.strip();
  };

  BN.prototype.ixor = function ixor (num) {
    assert((this.negative | num.negative) === 0);
    return this.iuxor(num);
  };

  // Xor `num` with `this`
  BN.prototype.xor = function xor (num) {
    if (this.length > num.length) return this.clone().ixor(num);
    return num.clone().ixor(this);
  };

  BN.prototype.uxor = function uxor (num) {
    if (this.length > num.length) return this.clone().iuxor(num);
    return num.clone().iuxor(this);
  };

  // Not ``this`` with ``width`` bitwidth
  BN.prototype.inotn = function inotn (width) {
    assert(typeof width === 'number' && width >= 0);

    var bytesNeeded = Math.ceil(width / 26) | 0;
    var bitsLeft = width % 26;

    // Extend the buffer with leading zeroes
    this._expand(bytesNeeded);

    if (bitsLeft > 0) {
      bytesNeeded--;
    }

    // Handle complete words
    for (var i = 0; i < bytesNeeded; i++) {
      this.words[i] = ~this.words[i] & 0x3ffffff;
    }

    // Handle the residue
    if (bitsLeft > 0) {
      this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
    }

    // And remove leading zeroes
    return this.strip();
  };

  BN.prototype.notn = function notn (width) {
    return this.clone().inotn(width);
  };

  // Set `bit` of `this`
  BN.prototype.setn = function setn (bit, val) {
    assert(typeof bit === 'number' && bit >= 0);

    var off = (bit / 26) | 0;
    var wbit = bit % 26;

    this._expand(off + 1);

    if (val) {
      this.words[off] = this.words[off] | (1 << wbit);
    } else {
      this.words[off] = this.words[off] & ~(1 << wbit);
    }

    return this.strip();
  };

  // Add `num` to `this` in-place
  BN.prototype.iadd = function iadd (num) {
    var r;

    // negative + positive
    if (this.negative !== 0 && num.negative === 0) {
      this.negative = 0;
      r = this.isub(num);
      this.negative ^= 1;
      return this._normSign();

    // positive + negative
    } else if (this.negative === 0 && num.negative !== 0) {
      num.negative = 0;
      r = this.isub(num);
      num.negative = 1;
      return r._normSign();
    }

    // a.length > b.length
    var a, b;
    if (this.length > num.length) {
      a = this;
      b = num;
    } else {
      a = num;
      b = this;
    }

    var carry = 0;
    for (var i = 0; i < b.length; i++) {
      r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
      this.words[i] = r & 0x3ffffff;
      carry = r >>> 26;
    }
    for (; carry !== 0 && i < a.length; i++) {
      r = (a.words[i] | 0) + carry;
      this.words[i] = r & 0x3ffffff;
      carry = r >>> 26;
    }

    this.length = a.length;
    if (carry !== 0) {
      this.words[this.length] = carry;
      this.length++;
    // Copy the rest of the words
    } else if (a !== this) {
      for (; i < a.length; i++) {
        this.words[i] = a.words[i];
      }
    }

    return this;
  };

  // Add `num` to `this`
  BN.prototype.add = function add (num) {
    var res;
    if (num.negative !== 0 && this.negative === 0) {
      num.negative = 0;
      res = this.sub(num);
      num.negative ^= 1;
      return res;
    } else if (num.negative === 0 && this.negative !== 0) {
      this.negative = 0;
      res = num.sub(this);
      this.negative = 1;
      return res;
    }

    if (this.length > num.length) return this.clone().iadd(num);

    return num.clone().iadd(this);
  };

  // Subtract `num` from `this` in-place
  BN.prototype.isub = function isub (num) {
    // this - (-num) = this + num
    if (num.negative !== 0) {
      num.negative = 0;
      var r = this.iadd(num);
      num.negative = 1;
      return r._normSign();

    // -this - num = -(this + num)
    } else if (this.negative !== 0) {
      this.negative = 0;
      this.iadd(num);
      this.negative = 1;
      return this._normSign();
    }

    // At this point both numbers are positive
    var cmp = this.cmp(num);

    // Optimization - zeroify
    if (cmp === 0) {
      this.negative = 0;
      this.length = 1;
      this.words[0] = 0;
      return this;
    }

    // a > b
    var a, b;
    if (cmp > 0) {
      a = this;
      b = num;
    } else {
      a = num;
      b = this;
    }

    var carry = 0;
    for (var i = 0; i < b.length; i++) {
      r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
      carry = r >> 26;
      this.words[i] = r & 0x3ffffff;
    }
    for (; carry !== 0 && i < a.length; i++) {
      r = (a.words[i] | 0) + carry;
      carry = r >> 26;
      this.words[i] = r & 0x3ffffff;
    }

    // Copy rest of the words
    if (carry === 0 && i < a.length && a !== this) {
      for (; i < a.length; i++) {
        this.words[i] = a.words[i];
      }
    }

    this.length = Math.max(this.length, i);

    if (a !== this) {
      this.negative = 1;
    }

    return this.strip();
  };

  // Subtract `num` from `this`
  BN.prototype.sub = function sub (num) {
    return this.clone().isub(num);
  };

  function smallMulTo (self, num, out) {
    out.negative = num.negative ^ self.negative;
    var len = (self.length + num.length) | 0;
    out.length = len;
    len = (len - 1) | 0;

    // Peel one iteration (compiler can't do it, because of code complexity)
    var a = self.words[0] | 0;
    var b = num.words[0] | 0;
    var r = a * b;

    var lo = r & 0x3ffffff;
    var carry = (r / 0x4000000) | 0;
    out.words[0] = lo;

    for (var k = 1; k < len; k++) {
      // Sum all words with the same `i + j = k` and accumulate `ncarry`,
      // note that ncarry could be >= 0x3ffffff
      var ncarry = carry >>> 26;
      var rword = carry & 0x3ffffff;
      var maxJ = Math.min(k, num.length - 1);
      for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
        var i = (k - j) | 0;
        a = self.words[i] | 0;
        b = num.words[j] | 0;
        r = a * b + rword;
        ncarry += (r / 0x4000000) | 0;
        rword = r & 0x3ffffff;
      }
      out.words[k] = rword | 0;
      carry = ncarry | 0;
    }
    if (carry !== 0) {
      out.words[k] = carry | 0;
    } else {
      out.length--;
    }

    return out.strip();
  }

  // TODO(indutny): it may be reasonable to omit it for users who don't need
  // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
  // multiplication (like elliptic secp256k1).
  var comb10MulTo = function comb10MulTo (self, num, out) {
    var a = self.words;
    var b = num.words;
    var o = out.words;
    var c = 0;
    var lo;
    var mid;
    var hi;
    var a0 = a[0] | 0;
    var al0 = a0 & 0x1fff;
    var ah0 = a0 >>> 13;
    var a1 = a[1] | 0;
    var al1 = a1 & 0x1fff;
    var ah1 = a1 >>> 13;
    var a2 = a[2] | 0;
    var al2 = a2 & 0x1fff;
    var ah2 = a2 >>> 13;
    var a3 = a[3] | 0;
    var al3 = a3 & 0x1fff;
    var ah3 = a3 >>> 13;
    var a4 = a[4] | 0;
    var al4 = a4 & 0x1fff;
    var ah4 = a4 >>> 13;
    var a5 = a[5] | 0;
    var al5 = a5 & 0x1fff;
    var ah5 = a5 >>> 13;
    var a6 = a[6] | 0;
    var al6 = a6 & 0x1fff;
    var ah6 = a6 >>> 13;
    var a7 = a[7] | 0;
    var al7 = a7 & 0x1fff;
    var ah7 = a7 >>> 13;
    var a8 = a[8] | 0;
    var al8 = a8 & 0x1fff;
    var ah8 = a8 >>> 13;
    var a9 = a[9] | 0;
    var al9 = a9 & 0x1fff;
    var ah9 = a9 >>> 13;
    var b0 = b[0] | 0;
    var bl0 = b0 & 0x1fff;
    var bh0 = b0 >>> 13;
    var b1 = b[1] | 0;
    var bl1 = b1 & 0x1fff;
    var bh1 = b1 >>> 13;
    var b2 = b[2] | 0;
    var bl2 = b2 & 0x1fff;
    var bh2 = b2 >>> 13;
    var b3 = b[3] | 0;
    var bl3 = b3 & 0x1fff;
    var bh3 = b3 >>> 13;
    var b4 = b[4] | 0;
    var bl4 = b4 & 0x1fff;
    var bh4 = b4 >>> 13;
    var b5 = b[5] | 0;
    var bl5 = b5 & 0x1fff;
    var bh5 = b5 >>> 13;
    var b6 = b[6] | 0;
    var bl6 = b6 & 0x1fff;
    var bh6 = b6 >>> 13;
    var b7 = b[7] | 0;
    var bl7 = b7 & 0x1fff;
    var bh7 = b7 >>> 13;
    var b8 = b[8] | 0;
    var bl8 = b8 & 0x1fff;
    var bh8 = b8 >>> 13;
    var b9 = b[9] | 0;
    var bl9 = b9 & 0x1fff;
    var bh9 = b9 >>> 13;

    out.negative = self.negative ^ num.negative;
    out.length = 19;
    /* k = 0 */
    lo = Math.imul(al0, bl0);
    mid = Math.imul(al0, bh0);
    mid = (mid + Math.imul(ah0, bl0)) | 0;
    hi = Math.imul(ah0, bh0);
    var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
    w0 &= 0x3ffffff;
    /* k = 1 */
    lo = Math.imul(al1, bl0);
    mid = Math.imul(al1, bh0);
    mid = (mid + Math.imul(ah1, bl0)) | 0;
    hi = Math.imul(ah1, bh0);
    lo = (lo + Math.imul(al0, bl1)) | 0;
    mid = (mid + Math.imul(al0, bh1)) | 0;
    mid = (mid + Math.imul(ah0, bl1)) | 0;
    hi = (hi + Math.imul(ah0, bh1)) | 0;
    var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
    w1 &= 0x3ffffff;
    /* k = 2 */
    lo = Math.imul(al2, bl0);
    mid = Math.imul(al2, bh0);
    mid = (mid + Math.imul(ah2, bl0)) | 0;
    hi = Math.imul(ah2, bh0);
    lo = (lo + Math.imul(al1, bl1)) | 0;
    mid = (mid + Math.imul(al1, bh1)) | 0;
    mid = (mid + Math.imul(ah1, bl1)) | 0;
    hi = (hi + Math.imul(ah1, bh1)) | 0;
    lo = (lo + Math.imul(al0, bl2)) | 0;
    mid = (mid + Math.imul(al0, bh2)) | 0;
    mid = (mid + Math.imul(ah0, bl2)) | 0;
    hi = (hi + Math.imul(ah0, bh2)) | 0;
    var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
    w2 &= 0x3ffffff;
    /* k = 3 */
    lo = Math.imul(al3, bl0);
    mid = Math.imul(al3, bh0);
    mid = (mid + Math.imul(ah3, bl0)) | 0;
    hi = Math.imul(ah3, bh0);
    lo = (lo + Math.imul(al2, bl1)) | 0;
    mid = (mid + Math.imul(al2, bh1)) | 0;
    mid = (mid + Math.imul(ah2, bl1)) | 0;
    hi = (hi + Math.imul(ah2, bh1)) | 0;
    lo = (lo + Math.imul(al1, bl2)) | 0;
    mid = (mid + Math.imul(al1, bh2)) | 0;
    mid = (mid + Math.imul(ah1, bl2)) | 0;
    hi = (hi + Math.imul(ah1, bh2)) | 0;
    lo = (lo + Math.imul(al0, bl3)) | 0;
    mid = (mid + Math.imul(al0, bh3)) | 0;
    mid = (mid + Math.imul(ah0, bl3)) | 0;
    hi = (hi + Math.imul(ah0, bh3)) | 0;
    var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
    w3 &= 0x3ffffff;
    /* k = 4 */
    lo = Math.imul(al4, bl0);
    mid = Math.imul(al4, bh0);
    mid = (mid + Math.imul(ah4, bl0)) | 0;
    hi = Math.imul(ah4, bh0);
    lo = (lo + Math.imul(al3, bl1)) | 0;
    mid = (mid + Math.imul(al3, bh1)) | 0;
    mid = (mid + Math.imul(ah3, bl1)) | 0;
    hi = (hi + Math.imul(ah3, bh1)) | 0;
    lo = (lo + Math.imul(al2, bl2)) | 0;
    mid = (mid + Math.imul(al2, bh2)) | 0;
    mid = (mid + Math.imul(ah2, bl2)) | 0;
    hi = (hi + Math.imul(ah2, bh2)) | 0;
    lo = (lo + Math.imul(al1, bl3)) | 0;
    mid = (mid + Math.imul(al1, bh3)) | 0;
    mid = (mid + Math.imul(ah1, bl3)) | 0;
    hi = (hi + Math.imul(ah1, bh3)) | 0;
    lo = (lo + Math.imul(al0, bl4)) | 0;
    mid = (mid + Math.imul(al0, bh4)) | 0;
    mid = (mid + Math.imul(ah0, bl4)) | 0;
    hi = (hi + Math.imul(ah0, bh4)) | 0;
    var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
    w4 &= 0x3ffffff;
    /* k = 5 */
    lo = Math.imul(al5, bl0);
    mid = Math.imul(al5, bh0);
    mid = (mid + Math.imul(ah5, bl0)) | 0;
    hi = Math.imul(ah5, bh0);
    lo = (lo + Math.imul(al4, bl1)) | 0;
    mid = (mid + Math.imul(al4, bh1)) | 0;
    mid = (mid + Math.imul(ah4, bl1)) | 0;
    hi = (hi + Math.imul(ah4, bh1)) | 0;
    lo = (lo + Math.imul(al3, bl2)) | 0;
    mid = (mid + Math.imul(al3, bh2)) | 0;
    mid = (mid + Math.imul(ah3, bl2)) | 0;
    hi = (hi + Math.imul(ah3, bh2)) | 0;
    lo = (lo + Math.imul(al2, bl3)) | 0;
    mid = (mid + Math.imul(al2, bh3)) | 0;
    mid = (mid + Math.imul(ah2, bl3)) | 0;
    hi = (hi + Math.imul(ah2, bh3)) | 0;
    lo = (lo + Math.imul(al1, bl4)) | 0;
    mid = (mid + Math.imul(al1, bh4)) | 0;
    mid = (mid + Math.imul(ah1, bl4)) | 0;
    hi = (hi + Math.imul(ah1, bh4)) | 0;
    lo = (lo + Math.imul(al0, bl5)) | 0;
    mid = (mid + Math.imul(al0, bh5)) | 0;
    mid = (mid + Math.imul(ah0, bl5)) | 0;
    hi = (hi + Math.imul(ah0, bh5)) | 0;
    var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
    w5 &= 0x3ffffff;
    /* k = 6 */
    lo = Math.imul(al6, bl0);
    mid = Math.imul(al6, bh0);
    mid = (mid + Math.imul(ah6, bl0)) | 0;
    hi = Math.imul(ah6, bh0);
    lo = (lo + Math.imul(al5, bl1)) | 0;
    mid = (mid + Math.imul(al5, bh1)) | 0;
    mid = (mid + Math.imul(ah5, bl1)) | 0;
    hi = (hi + Math.imul(ah5, bh1)) | 0;
    lo = (lo + Math.imul(al4, bl2)) | 0;
    mid = (mid + Math.imul(al4, bh2)) | 0;
    mid = (mid + Math.imul(ah4, bl2)) | 0;
    hi = (hi + Math.imul(ah4, bh2)) | 0;
    lo = (lo + Math.imul(al3, bl3)) | 0;
    mid = (mid + Math.imul(al3, bh3)) | 0;
    mid = (mid + Math.imul(ah3, bl3)) | 0;
    hi = (hi + Math.imul(ah3, bh3)) | 0;
    lo = (lo + Math.imul(al2, bl4)) | 0;
    mid = (mid + Math.imul(al2, bh4)) | 0;
    mid = (mid + Math.imul(ah2, bl4)) | 0;
    hi = (hi + Math.imul(ah2, bh4)) | 0;
    lo = (lo + Math.imul(al1, bl5)) | 0;
    mid = (mid + Math.imul(al1, bh5)) | 0;
    mid = (mid + Math.imul(ah1, bl5)) | 0;
    hi = (hi + Math.imul(ah1, bh5)) | 0;
    lo = (lo + Math.imul(al0, bl6)) | 0;
    mid = (mid + Math.imul(al0, bh6)) | 0;
    mid = (mid + Math.imul(ah0, bl6)) | 0;
    hi = (hi + Math.imul(ah0, bh6)) | 0;
    var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
    w6 &= 0x3ffffff;
    /* k = 7 */
    lo = Math.imul(al7, bl0);
    mid = Math.imul(al7, bh0);
    mid = (mid + Math.imul(ah7, bl0)) | 0;
    hi = Math.imul(ah7, bh0);
    lo = (lo + Math.imul(al6, bl1)) | 0;
    mid = (mid + Math.imul(al6, bh1)) | 0;
    mid = (mid + Math.imul(ah6, bl1)) | 0;
    hi = (hi + Math.imul(ah6, bh1)) | 0;
    lo = (lo + Math.imul(al5, bl2)) | 0;
    mid = (mid + Math.imul(al5, bh2)) | 0;
    mid = (mid + Math.imul(ah5, bl2)) | 0;
    hi = (hi + Math.imul(ah5, bh2)) | 0;
    lo = (lo + Math.imul(al4, bl3)) | 0;
    mid = (mid + Math.imul(al4, bh3)) | 0;
    mid = (mid + Math.imul(ah4, bl3)) | 0;
    hi = (hi + Math.imul(ah4, bh3)) | 0;
    lo = (lo + Math.imul(al3, bl4)) | 0;
    mid = (mid + Math.imul(al3, bh4)) | 0;
    mid = (mid + Math.imul(ah3, bl4)) | 0;
    hi = (hi + Math.imul(ah3, bh4)) | 0;
    lo = (lo + Math.imul(al2, bl5)) | 0;
    mid = (mid + Math.imul(al2, bh5)) | 0;
    mid = (mid + Math.imul(ah2, bl5)) | 0;
    hi = (hi + Math.imul(ah2, bh5)) | 0;
    lo = (lo + Math.imul(al1, bl6)) | 0;
    mid = (mid + Math.imul(al1, bh6)) | 0;
    mid = (mid + Math.imul(ah1, bl6)) | 0;
    hi = (hi + Math.imul(ah1, bh6)) | 0;
    lo = (lo + Math.imul(al0, bl7)) | 0;
    mid = (mid + Math.imul(al0, bh7)) | 0;
    mid = (mid + Math.imul(ah0, bl7)) | 0;
    hi = (hi + Math.imul(ah0, bh7)) | 0;
    var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
    w7 &= 0x3ffffff;
    /* k = 8 */
    lo = Math.imul(al8, bl0);
    mid = Math.imul(al8, bh0);
    mid = (mid + Math.imul(ah8, bl0)) | 0;
    hi = Math.imul(ah8, bh0);
    lo = (lo + Math.imul(al7, bl1)) | 0;
    mid = (mid + Math.imul(al7, bh1)) | 0;
    mid = (mid + Math.imul(ah7, bl1)) | 0;
    hi = (hi + Math.imul(ah7, bh1)) | 0;
    lo = (lo + Math.imul(al6, bl2)) | 0;
    mid = (mid + Math.imul(al6, bh2)) | 0;
    mid = (mid + Math.imul(ah6, bl2)) | 0;
    hi = (hi + Math.imul(ah6, bh2)) | 0;
    lo = (lo + Math.imul(al5, bl3)) | 0;
    mid = (mid + Math.imul(al5, bh3)) | 0;
    mid = (mid + Math.imul(ah5, bl3)) | 0;
    hi = (hi + Math.imul(ah5, bh3)) | 0;
    lo = (lo + Math.imul(al4, bl4)) | 0;
    mid = (mid + Math.imul(al4, bh4)) | 0;
    mid = (mid + Math.imul(ah4, bl4)) | 0;
    hi = (hi + Math.imul(ah4, bh4)) | 0;
    lo = (lo + Math.imul(al3, bl5)) | 0;
    mid = (mid + Math.imul(al3, bh5)) | 0;
    mid = (mid + Math.imul(ah3, bl5)) | 0;
    hi = (hi + Math.imul(ah3, bh5)) | 0;
    lo = (lo + Math.imul(al2, bl6)) | 0;
    mid = (mid + Math.imul(al2, bh6)) | 0;
    mid = (mid + Math.imul(ah2, bl6)) | 0;
    hi = (hi + Math.imul(ah2, bh6)) | 0;
    lo = (lo + Math.imul(al1, bl7)) | 0;
    mid = (mid + Math.imul(al1, bh7)) | 0;
    mid = (mid + Math.imul(ah1, bl7)) | 0;
    hi = (hi + Math.imul(ah1, bh7)) | 0;
    lo = (lo + Math.imul(al0, bl8)) | 0;
    mid = (mid + Math.imul(al0, bh8)) | 0;
    mid = (mid + Math.imul(ah0, bl8)) | 0;
    hi = (hi + Math.imul(ah0, bh8)) | 0;
    var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
    w8 &= 0x3ffffff;
    /* k = 9 */
    lo = Math.imul(al9, bl0);
    mid = Math.imul(al9, bh0);
    mid = (mid + Math.imul(ah9, bl0)) | 0;
    hi = Math.imul(ah9, bh0);
    lo = (lo + Math.imul(al8, bl1)) | 0;
    mid = (mid + Math.imul(al8, bh1)) | 0;
    mid = (mid + Math.imul(ah8, bl1)) | 0;
    hi = (hi + Math.imul(ah8, bh1)) | 0;
    lo = (lo + Math.imul(al7, bl2)) | 0;
    mid = (mid + Math.imul(al7, bh2)) | 0;
    mid = (mid + Math.imul(ah7, bl2)) | 0;
    hi = (hi + Math.imul(ah7, bh2)) | 0;
    lo = (lo + Math.imul(al6, bl3)) | 0;
    mid = (mid + Math.imul(al6, bh3)) | 0;
    mid = (mid + Math.imul(ah6, bl3)) | 0;
    hi = (hi + Math.imul(ah6, bh3)) | 0;
    lo = (lo + Math.imul(al5, bl4)) | 0;
    mid = (mid + Math.imul(al5, bh4)) | 0;
    mid = (mid + Math.imul(ah5, bl4)) | 0;
    hi = (hi + Math.imul(ah5, bh4)) | 0;
    lo = (lo + Math.imul(al4, bl5)) | 0;
    mid = (mid + Math.imul(al4, bh5)) | 0;
    mid = (mid + Math.imul(ah4, bl5)) | 0;
    hi = (hi + Math.imul(ah4, bh5)) | 0;
    lo = (lo + Math.imul(al3, bl6)) | 0;
    mid = (mid + Math.imul(al3, bh6)) | 0;
    mid = (mid + Math.imul(ah3, bl6)) | 0;
    hi = (hi + Math.imul(ah3, bh6)) | 0;
    lo = (lo + Math.imul(al2, bl7)) | 0;
    mid = (mid + Math.imul(al2, bh7)) | 0;
    mid = (mid + Math.imul(ah2, bl7)) | 0;
    hi = (hi + Math.imul(ah2, bh7)) | 0;
    lo = (lo + Math.imul(al1, bl8)) | 0;
    mid = (mid + Math.imul(al1, bh8)) | 0;
    mid = (mid + Math.imul(ah1, bl8)) | 0;
    hi = (hi + Math.imul(ah1, bh8)) | 0;
    lo = (lo + Math.imul(al0, bl9)) | 0;
    mid = (mid + Math.imul(al0, bh9)) | 0;
    mid = (mid + Math.imul(ah0, bl9)) | 0;
    hi = (hi + Math.imul(ah0, bh9)) | 0;
    var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
    w9 &= 0x3ffffff;
    /* k = 10 */
    lo = Math.imul(al9, bl1);
    mid = Math.imul(al9, bh1);
    mid = (mid + Math.imul(ah9, bl1)) | 0;
    hi = Math.imul(ah9, bh1);
    lo = (lo + Math.imul(al8, bl2)) | 0;
    mid = (mid + Math.imul(al8, bh2)) | 0;
    mid = (mid + Math.imul(ah8, bl2)) | 0;
    hi = (hi + Math.imul(ah8, bh2)) | 0;
    lo = (lo + Math.imul(al7, bl3)) | 0;
    mid = (mid + Math.imul(al7, bh3)) | 0;
    mid = (mid + Math.imul(ah7, bl3)) | 0;
    hi = (hi + Math.imul(ah7, bh3)) | 0;
    lo = (lo + Math.imul(al6, bl4)) | 0;
    mid = (mid + Math.imul(al6, bh4)) | 0;
    mid = (mid + Math.imul(ah6, bl4)) | 0;
    hi = (hi + Math.imul(ah6, bh4)) | 0;
    lo = (lo + Math.imul(al5, bl5)) | 0;
    mid = (mid + Math.imul(al5, bh5)) | 0;
    mid = (mid + Math.imul(ah5, bl5)) | 0;
    hi = (hi + Math.imul(ah5, bh5)) | 0;
    lo = (lo + Math.imul(al4, bl6)) | 0;
    mid = (mid + Math.imul(al4, bh6)) | 0;
    mid = (mid + Math.imul(ah4, bl6)) | 0;
    hi = (hi + Math.imul(ah4, bh6)) | 0;
    lo = (lo + Math.imul(al3, bl7)) | 0;
    mid = (mid + Math.imul(al3, bh7)) | 0;
    mid = (mid + Math.imul(ah3, bl7)) | 0;
    hi = (hi + Math.imul(ah3, bh7)) | 0;
    lo = (lo + Math.imul(al2, bl8)) | 0;
    mid = (mid + Math.imul(al2, bh8)) | 0;
    mid = (mid + Math.imul(ah2, bl8)) | 0;
    hi = (hi + Math.imul(ah2, bh8)) | 0;
    lo = (lo + Math.imul(al1, bl9)) | 0;
    mid = (mid + Math.imul(al1, bh9)) | 0;
    mid = (mid + Math.imul(ah1, bl9)) | 0;
    hi = (hi + Math.imul(ah1, bh9)) | 0;
    var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
    w10 &= 0x3ffffff;
    /* k = 11 */
    lo = Math.imul(al9, bl2);
    mid = Math.imul(al9, bh2);
    mid = (mid + Math.imul(ah9, bl2)) | 0;
    hi = Math.imul(ah9, bh2);
    lo = (lo + Math.imul(al8, bl3)) | 0;
    mid = (mid + Math.imul(al8, bh3)) | 0;
    mid = (mid + Math.imul(ah8, bl3)) | 0;
    hi = (hi + Math.imul(ah8, bh3)) | 0;
    lo = (lo + Math.imul(al7, bl4)) | 0;
    mid = (mid + Math.imul(al7, bh4)) | 0;
    mid = (mid + Math.imul(ah7, bl4)) | 0;
    hi = (hi + Math.imul(ah7, bh4)) | 0;
    lo = (lo + Math.imul(al6, bl5)) | 0;
    mid = (mid + Math.imul(al6, bh5)) | 0;
    mid = (mid + Math.imul(ah6, bl5)) | 0;
    hi = (hi + Math.imul(ah6, bh5)) | 0;
    lo = (lo + Math.imul(al5, bl6)) | 0;
    mid = (mid + Math.imul(al5, bh6)) | 0;
    mid = (mid + Math.imul(ah5, bl6)) | 0;
    hi = (hi + Math.imul(ah5, bh6)) | 0;
    lo = (lo + Math.imul(al4, bl7)) | 0;
    mid = (mid + Math.imul(al4, bh7)) | 0;
    mid = (mid + Math.imul(ah4, bl7)) | 0;
    hi = (hi + Math.imul(ah4, bh7)) | 0;
    lo = (lo + Math.imul(al3, bl8)) | 0;
    mid = (mid + Math.imul(al3, bh8)) | 0;
    mid = (mid + Math.imul(ah3, bl8)) | 0;
    hi = (hi + Math.imul(ah3, bh8)) | 0;
    lo = (lo + Math.imul(al2, bl9)) | 0;
    mid = (mid + Math.imul(al2, bh9)) | 0;
    mid = (mid + Math.imul(ah2, bl9)) | 0;
    hi = (hi + Math.imul(ah2, bh9)) | 0;
    var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
    w11 &= 0x3ffffff;
    /* k = 12 */
    lo = Math.imul(al9, bl3);
    mid = Math.imul(al9, bh3);
    mid = (mid + Math.imul(ah9, bl3)) | 0;
    hi = Math.imul(ah9, bh3);
    lo = (lo + Math.imul(al8, bl4)) | 0;
    mid = (mid + Math.imul(al8, bh4)) | 0;
    mid = (mid + Math.imul(ah8, bl4)) | 0;
    hi = (hi + Math.imul(ah8, bh4)) | 0;
    lo = (lo + Math.imul(al7, bl5)) | 0;
    mid = (mid + Math.imul(al7, bh5)) | 0;
    mid = (mid + Math.imul(ah7, bl5)) | 0;
    hi = (hi + Math.imul(ah7, bh5)) | 0;
    lo = (lo + Math.imul(al6, bl6)) | 0;
    mid = (mid + Math.imul(al6, bh6)) | 0;
    mid = (mid + Math.imul(ah6, bl6)) | 0;
    hi = (hi + Math.imul(ah6, bh6)) | 0;
    lo = (lo + Math.imul(al5, bl7)) | 0;
    mid = (mid + Math.imul(al5, bh7)) | 0;
    mid = (mid + Math.imul(ah5, bl7)) | 0;
    hi = (hi + Math.imul(ah5, bh7)) | 0;
    lo = (lo + Math.imul(al4, bl8)) | 0;
    mid = (mid + Math.imul(al4, bh8)) | 0;
    mid = (mid + Math.imul(ah4, bl8)) | 0;
    hi = (hi + Math.imul(ah4, bh8)) | 0;
    lo = (lo + Math.imul(al3, bl9)) | 0;
    mid = (mid + Math.imul(al3, bh9)) | 0;
    mid = (mid + Math.imul(ah3, bl9)) | 0;
    hi = (hi + Math.imul(ah3, bh9)) | 0;
    var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
    w12 &= 0x3ffffff;
    /* k = 13 */
    lo = Math.imul(al9, bl4);
    mid = Math.imul(al9, bh4);
    mid = (mid + Math.imul(ah9, bl4)) | 0;
    hi = Math.imul(ah9, bh4);
    lo = (lo + Math.imul(al8, bl5)) | 0;
    mid = (mid + Math.imul(al8, bh5)) | 0;
    mid = (mid + Math.imul(ah8, bl5)) | 0;
    hi = (hi + Math.imul(ah8, bh5)) | 0;
    lo = (lo + Math.imul(al7, bl6)) | 0;
    mid = (mid + Math.imul(al7, bh6)) | 0;
    mid = (mid + Math.imul(ah7, bl6)) | 0;
    hi = (hi + Math.imul(ah7, bh6)) | 0;
    lo = (lo + Math.imul(al6, bl7)) | 0;
    mid = (mid + Math.imul(al6, bh7)) | 0;
    mid = (mid + Math.imul(ah6, bl7)) | 0;
    hi = (hi + Math.imul(ah6, bh7)) | 0;
    lo = (lo + Math.imul(al5, bl8)) | 0;
    mid = (mid + Math.imul(al5, bh8)) | 0;
    mid = (mid + Math.imul(ah5, bl8)) | 0;
    hi = (hi + Math.imul(ah5, bh8)) | 0;
    lo = (lo + Math.imul(al4, bl9)) | 0;
    mid = (mid + Math.imul(al4, bh9)) | 0;
    mid = (mid + Math.imul(ah4, bl9)) | 0;
    hi = (hi + Math.imul(ah4, bh9)) | 0;
    var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
    w13 &= 0x3ffffff;
    /* k = 14 */
    lo = Math.imul(al9, bl5);
    mid = Math.imul(al9, bh5);
    mid = (mid + Math.imul(ah9, bl5)) | 0;
    hi = Math.imul(ah9, bh5);
    lo = (lo + Math.imul(al8, bl6)) | 0;
    mid = (mid + Math.imul(al8, bh6)) | 0;
    mid = (mid + Math.imul(ah8, bl6)) | 0;
    hi = (hi + Math.imul(ah8, bh6)) | 0;
    lo = (lo + Math.imul(al7, bl7)) | 0;
    mid = (mid + Math.imul(al7, bh7)) | 0;
    mid = (mid + Math.imul(ah7, bl7)) | 0;
    hi = (hi + Math.imul(ah7, bh7)) | 0;
    lo = (lo + Math.imul(al6, bl8)) | 0;
    mid = (mid + Math.imul(al6, bh8)) | 0;
    mid = (mid + Math.imul(ah6, bl8)) | 0;
    hi = (hi + Math.imul(ah6, bh8)) | 0;
    lo = (lo + Math.imul(al5, bl9)) | 0;
    mid = (mid + Math.imul(al5, bh9)) | 0;
    mid = (mid + Math.imul(ah5, bl9)) | 0;
    hi = (hi + Math.imul(ah5, bh9)) | 0;
    var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
    w14 &= 0x3ffffff;
    /* k = 15 */
    lo = Math.imul(al9, bl6);
    mid = Math.imul(al9, bh6);
    mid = (mid + Math.imul(ah9, bl6)) | 0;
    hi = Math.imul(ah9, bh6);
    lo = (lo + Math.imul(al8, bl7)) | 0;
    mid = (mid + Math.imul(al8, bh7)) | 0;
    mid = (mid + Math.imul(ah8, bl7)) | 0;
    hi = (hi + Math.imul(ah8, bh7)) | 0;
    lo = (lo + Math.imul(al7, bl8)) | 0;
    mid = (mid + Math.imul(al7, bh8)) | 0;
    mid = (mid + Math.imul(ah7, bl8)) | 0;
    hi = (hi + Math.imul(ah7, bh8)) | 0;
    lo = (lo + Math.imul(al6, bl9)) | 0;
    mid = (mid + Math.imul(al6, bh9)) | 0;
    mid = (mid + Math.imul(ah6, bl9)) | 0;
    hi = (hi + Math.imul(ah6, bh9)) | 0;
    var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
    w15 &= 0x3ffffff;
    /* k = 16 */
    lo = Math.imul(al9, bl7);
    mid = Math.imul(al9, bh7);
    mid = (mid + Math.imul(ah9, bl7)) | 0;
    hi = Math.imul(ah9, bh7);
    lo = (lo + Math.imul(al8, bl8)) | 0;
    mid = (mid + Math.imul(al8, bh8)) | 0;
    mid = (mid + Math.imul(ah8, bl8)) | 0;
    hi = (hi + Math.imul(ah8, bh8)) | 0;
    lo = (lo + Math.imul(al7, bl9)) | 0;
    mid = (mid + Math.imul(al7, bh9)) | 0;
    mid = (mid + Math.imul(ah7, bl9)) | 0;
    hi = (hi + Math.imul(ah7, bh9)) | 0;
    var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
    w16 &= 0x3ffffff;
    /* k = 17 */
    lo = Math.imul(al9, bl8);
    mid = Math.imul(al9, bh8);
    mid = (mid + Math.imul(ah9, bl8)) | 0;
    hi = Math.imul(ah9, bh8);
    lo = (lo + Math.imul(al8, bl9)) | 0;
    mid = (mid + Math.imul(al8, bh9)) | 0;
    mid = (mid + Math.imul(ah8, bl9)) | 0;
    hi = (hi + Math.imul(ah8, bh9)) | 0;
    var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
    w17 &= 0x3ffffff;
    /* k = 18 */
    lo = Math.imul(al9, bl9);
    mid = Math.imul(al9, bh9);
    mid = (mid + Math.imul(ah9, bl9)) | 0;
    hi = Math.imul(ah9, bh9);
    var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
    w18 &= 0x3ffffff;
    o[0] = w0;
    o[1] = w1;
    o[2] = w2;
    o[3] = w3;
    o[4] = w4;
    o[5] = w5;
    o[6] = w6;
    o[7] = w7;
    o[8] = w8;
    o[9] = w9;
    o[10] = w10;
    o[11] = w11;
    o[12] = w12;
    o[13] = w13;
    o[14] = w14;
    o[15] = w15;
    o[16] = w16;
    o[17] = w17;
    o[18] = w18;
    if (c !== 0) {
      o[19] = c;
      out.length++;
    }
    return out;
  };

  // Polyfill comb
  if (!Math.imul) {
    comb10MulTo = smallMulTo;
  }

  function bigMulTo (self, num, out) {
    out.negative = num.negative ^ self.negative;
    out.length = self.length + num.length;

    var carry = 0;
    var hncarry = 0;
    for (var k = 0; k < out.length - 1; k++) {
      // Sum all words with the same `i + j = k` and accumulate `ncarry`,
      // note that ncarry could be >= 0x3ffffff
      var ncarry = hncarry;
      hncarry = 0;
      var rword = carry & 0x3ffffff;
      var maxJ = Math.min(k, num.length - 1);
      for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
        var i = k - j;
        var a = self.words[i] | 0;
        var b = num.words[j] | 0;
        var r = a * b;

        var lo = r & 0x3ffffff;
        ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
        lo = (lo + rword) | 0;
        rword = lo & 0x3ffffff;
        ncarry = (ncarry + (lo >>> 26)) | 0;

        hncarry += ncarry >>> 26;
        ncarry &= 0x3ffffff;
      }
      out.words[k] = rword;
      carry = ncarry;
      ncarry = hncarry;
    }
    if (carry !== 0) {
      out.words[k] = carry;
    } else {
      out.length--;
    }

    return out.strip();
  }

  function jumboMulTo (self, num, out) {
    var fftm = new FFTM();
    return fftm.mulp(self, num, out);
  }

  BN.prototype.mulTo = function mulTo (num, out) {
    var res;
    var len = this.length + num.length;
    if (this.length === 10 && num.length === 10) {
      res = comb10MulTo(this, num, out);
    } else if (len < 63) {
      res = smallMulTo(this, num, out);
    } else if (len < 1024) {
      res = bigMulTo(this, num, out);
    } else {
      res = jumboMulTo(this, num, out);
    }

    return res;
  };

  // Cooley-Tukey algorithm for FFT
  // slightly revisited to rely on looping instead of recursion

  function FFTM (x, y) {
    this.x = x;
    this.y = y;
  }

  FFTM.prototype.makeRBT = function makeRBT (N) {
    var t = new Array(N);
    var l = BN.prototype._countBits(N) - 1;
    for (var i = 0; i < N; i++) {
      t[i] = this.revBin(i, l, N);
    }

    return t;
  };

  // Returns binary-reversed representation of `x`
  FFTM.prototype.revBin = function revBin (x, l, N) {
    if (x === 0 || x === N - 1) return x;

    var rb = 0;
    for (var i = 0; i < l; i++) {
      rb |= (x & 1) << (l - i - 1);
      x >>= 1;
    }

    return rb;
  };

  // Performs "tweedling" phase, therefore 'emulating'
  // behaviour of the recursive algorithm
  FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
    for (var i = 0; i < N; i++) {
      rtws[i] = rws[rbt[i]];
      itws[i] = iws[rbt[i]];
    }
  };

  FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
    this.permute(rbt, rws, iws, rtws, itws, N);

    for (var s = 1; s < N; s <<= 1) {
      var l = s << 1;

      var rtwdf = Math.cos(2 * Math.PI / l);
      var itwdf = Math.sin(2 * Math.PI / l);

      for (var p = 0; p < N; p += l) {
        var rtwdf_ = rtwdf;
        var itwdf_ = itwdf;

        for (var j = 0; j < s; j++) {
          var re = rtws[p + j];
          var ie = itws[p + j];

          var ro = rtws[p + j + s];
          var io = itws[p + j + s];

          var rx = rtwdf_ * ro - itwdf_ * io;

          io = rtwdf_ * io + itwdf_ * ro;
          ro = rx;

          rtws[p + j] = re + ro;
          itws[p + j] = ie + io;

          rtws[p + j + s] = re - ro;
          itws[p + j + s] = ie - io;

          /* jshint maxdepth : false */
          if (j !== l) {
            rx = rtwdf * rtwdf_ - itwdf * itwdf_;

            itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
            rtwdf_ = rx;
          }
        }
      }
    }
  };

  FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
    var N = Math.max(m, n) | 1;
    var odd = N & 1;
    var i = 0;
    for (N = N / 2 | 0; N; N = N >>> 1) {
      i++;
    }

    return 1 << i + 1 + odd;
  };

  FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
    if (N <= 1) return;

    for (var i = 0; i < N / 2; i++) {
      var t = rws[i];

      rws[i] = rws[N - i - 1];
      rws[N - i - 1] = t;

      t = iws[i];

      iws[i] = -iws[N - i - 1];
      iws[N - i - 1] = -t;
    }
  };

  FFTM.prototype.normalize13b = function normalize13b (ws, N) {
    var carry = 0;
    for (var i = 0; i < N / 2; i++) {
      var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
        Math.round(ws[2 * i] / N) +
        carry;

      ws[i] = w & 0x3ffffff;

      if (w < 0x4000000) {
        carry = 0;
      } else {
        carry = w / 0x4000000 | 0;
      }
    }

    return ws;
  };

  FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
    var carry = 0;
    for (var i = 0; i < len; i++) {
      carry = carry + (ws[i] | 0);

      rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
      rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
    }

    // Pad with zeroes
    for (i = 2 * len; i < N; ++i) {
      rws[i] = 0;
    }

    assert(carry === 0);
    assert((carry & ~0x1fff) === 0);
  };

  FFTM.prototype.stub = function stub (N) {
    var ph = new Array(N);
    for (var i = 0; i < N; i++) {
      ph[i] = 0;
    }

    return ph;
  };

  FFTM.prototype.mulp = function mulp (x, y, out) {
    var N = 2 * this.guessLen13b(x.length, y.length);

    var rbt = this.makeRBT(N);

    var _ = this.stub(N);

    var rws = new Array(N);
    var rwst = new Array(N);
    var iwst = new Array(N);

    var nrws = new Array(N);
    var nrwst = new Array(N);
    var niwst = new Array(N);

    var rmws = out.words;
    rmws.length = N;

    this.convert13b(x.words, x.length, rws, N);
    this.convert13b(y.words, y.length, nrws, N);

    this.transform(rws, _, rwst, iwst, N, rbt);
    this.transform(nrws, _, nrwst, niwst, N, rbt);

    for (var i = 0; i < N; i++) {
      var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
      iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
      rwst[i] = rx;
    }

    this.conjugate(rwst, iwst, N);
    this.transform(rwst, iwst, rmws, _, N, rbt);
    this.conjugate(rmws, _, N);
    this.normalize13b(rmws, N);

    out.negative = x.negative ^ y.negative;
    out.length = x.length + y.length;
    return out.strip();
  };

  // Multiply `this` by `num`
  BN.prototype.mul = function mul (num) {
    var out = new BN(null);
    out.words = new Array(this.length + num.length);
    return this.mulTo(num, out);
  };

  // Multiply employing FFT
  BN.prototype.mulf = function mulf (num) {
    var out = new BN(null);
    out.words = new Array(this.length + num.length);
    return jumboMulTo(this, num, out);
  };

  // In-place Multiplication
  BN.prototype.imul = function imul (num) {
    return this.clone().mulTo(num, this);
  };

  BN.prototype.imuln = function imuln (num) {
    assert(typeof num === 'number');
    assert(num < 0x4000000);

    // Carry
    var carry = 0;
    for (var i = 0; i < this.length; i++) {
      var w = (this.words[i] | 0) * num;
      var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
      carry >>= 26;
      carry += (w / 0x4000000) | 0;
      // NOTE: lo is 27bit maximum
      carry += lo >>> 26;
      this.words[i] = lo & 0x3ffffff;
    }

    if (carry !== 0) {
      this.words[i] = carry;
      this.length++;
    }

    return this;
  };

  BN.prototype.muln = function muln (num) {
    return this.clone().imuln(num);
  };

  // `this` * `this`
  BN.prototype.sqr = function sqr () {
    return this.mul(this);
  };

  // `this` * `this` in-place
  BN.prototype.isqr = function isqr () {
    return this.imul(this.clone());
  };

  // Math.pow(`this`, `num`)
  BN.prototype.pow = function pow (num) {
    var w = toBitArray(num);
    if (w.length === 0) return new BN(1);

    // Skip leading zeroes
    var res = this;
    for (var i = 0; i < w.length; i++, res = res.sqr()) {
      if (w[i] !== 0) break;
    }

    if (++i < w.length) {
      for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
        if (w[i] === 0) continue;

        res = res.mul(q);
      }
    }

    return res;
  };

  // Shift-left in-place
  BN.prototype.iushln = function iushln (bits) {
    assert(typeof bits === 'number' && bits >= 0);
    var r = bits % 26;
    var s = (bits - r) / 26;
    var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
    var i;

    if (r !== 0) {
      var carry = 0;

      for (i = 0; i < this.length; i++) {
        var newCarry = this.words[i] & carryMask;
        var c = ((this.words[i] | 0) - newCarry) << r;
        this.words[i] = c | carry;
        carry = newCarry >>> (26 - r);
      }

      if (carry) {
        this.words[i] = carry;
        this.length++;
      }
    }

    if (s !== 0) {
      for (i = this.length - 1; i >= 0; i--) {
        this.words[i + s] = this.words[i];
      }

      for (i = 0; i < s; i++) {
        this.words[i] = 0;
      }

      this.length += s;
    }

    return this.strip();
  };

  BN.prototype.ishln = function ishln (bits) {
    // TODO(indutny): implement me
    assert(this.negative === 0);
    return this.iushln(bits);
  };

  // Shift-right in-place
  // NOTE: `hint` is a lowest bit before trailing zeroes
  // NOTE: if `extended` is present - it will be filled with destroyed bits
  BN.prototype.iushrn = function iushrn (bits, hint, extended) {
    assert(typeof bits === 'number' && bits >= 0);
    var h;
    if (hint) {
      h = (hint - (hint % 26)) / 26;
    } else {
      h = 0;
    }

    var r = bits % 26;
    var s = Math.min((bits - r) / 26, this.length);
    var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
    var maskedWords = extended;

    h -= s;
    h = Math.max(0, h);

    // Extended mode, copy masked part
    if (maskedWords) {
      for (var i = 0; i < s; i++) {
        maskedWords.words[i] = this.words[i];
      }
      maskedWords.length = s;
    }

    if (s === 0) {
      // No-op, we should not move anything at all
    } else if (this.length > s) {
      this.length -= s;
      for (i = 0; i < this.length; i++) {
        this.words[i] = this.words[i + s];
      }
    } else {
      this.words[0] = 0;
      this.length = 1;
    }

    var carry = 0;
    for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
      var word = this.words[i] | 0;
      this.words[i] = (carry << (26 - r)) | (word >>> r);
      carry = word & mask;
    }

    // Push carried bits as a mask
    if (maskedWords && carry !== 0) {
      maskedWords.words[maskedWords.length++] = carry;
    }

    if (this.length === 0) {
      this.words[0] = 0;
      this.length = 1;
    }

    return this.strip();
  };

  BN.prototype.ishrn = function ishrn (bits, hint, extended) {
    // TODO(indutny): implement me
    assert(this.negative === 0);
    return this.iushrn(bits, hint, extended);
  };

  // Shift-left
  BN.prototype.shln = function shln (bits) {
    return this.clone().ishln(bits);
  };

  BN.prototype.ushln = function ushln (bits) {
    return this.clone().iushln(bits);
  };

  // Shift-right
  BN.prototype.shrn = function shrn (bits) {
    return this.clone().ishrn(bits);
  };

  BN.prototype.ushrn = function ushrn (bits) {
    return this.clone().iushrn(bits);
  };

  // Test if n bit is set
  BN.prototype.testn = function testn (bit) {
    assert(typeof bit === 'number' && bit >= 0);
    var r = bit % 26;
    var s = (bit - r) / 26;
    var q = 1 << r;

    // Fast case: bit is much higher than all existing words
    if (this.length <= s) return false;

    // Check bit and return
    var w = this.words[s];

    return !!(w & q);
  };

  // Return only lowers bits of number (in-place)
  BN.prototype.imaskn = function imaskn (bits) {
    assert(typeof bits === 'number' && bits >= 0);
    var r = bits % 26;
    var s = (bits - r) / 26;

    assert(this.negative === 0, 'imaskn works only with positive numbers');

    if (this.length <= s) {
      return this;
    }

    if (r !== 0) {
      s++;
    }
    this.length = Math.min(s, this.length);

    if (r !== 0) {
      var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
      this.words[this.length - 1] &= mask;
    }

    return this.strip();
  };

  // Return only lowers bits of number
  BN.prototype.maskn = function maskn (bits) {
    return this.clone().imaskn(bits);
  };

  // Add plain number `num` to `this`
  BN.prototype.iaddn = function iaddn (num) {
    assert(typeof num === 'number');
    assert(num < 0x4000000);
    if (num < 0) return this.isubn(-num);

    // Possible sign change
    if (this.negative !== 0) {
      if (this.length === 1 && (this.words[0] | 0) < num) {
        this.words[0] = num - (this.words[0] | 0);
        this.negative = 0;
        return this;
      }

      this.negative = 0;
      this.isubn(num);
      this.negative = 1;
      return this;
    }

    // Add without checks
    return this._iaddn(num);
  };

  BN.prototype._iaddn = function _iaddn (num) {
    this.words[0] += num;

    // Carry
    for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
      this.words[i] -= 0x4000000;
      if (i === this.length - 1) {
        this.words[i + 1] = 1;
      } else {
        this.words[i + 1]++;
      }
    }
    this.length = Math.max(this.length, i + 1);

    return this;
  };

  // Subtract plain number `num` from `this`
  BN.prototype.isubn = function isubn (num) {
    assert(typeof num === 'number');
    assert(num < 0x4000000);
    if (num < 0) return this.iaddn(-num);

    if (this.negative !== 0) {
      this.negative = 0;
      this.iaddn(num);
      this.negative = 1;
      return this;
    }

    this.words[0] -= num;

    if (this.length === 1 && this.words[0] < 0) {
      this.words[0] = -this.words[0];
      this.negative = 1;
    } else {
      // Carry
      for (var i = 0; i < this.length && this.words[i] < 0; i++) {
        this.words[i] += 0x4000000;
        this.words[i + 1] -= 1;
      }
    }

    return this.strip();
  };

  BN.prototype.addn = function addn (num) {
    return this.clone().iaddn(num);
  };

  BN.prototype.subn = function subn (num) {
    return this.clone().isubn(num);
  };

  BN.prototype.iabs = function iabs () {
    this.negative = 0;

    return this;
  };

  BN.prototype.abs = function abs () {
    return this.clone().iabs();
  };

  BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
    var len = num.length + shift;
    var i;

    this._expand(len);

    var w;
    var carry = 0;
    for (i = 0; i < num.length; i++) {
      w = (this.words[i + shift] | 0) + carry;
      var right = (num.words[i] | 0) * mul;
      w -= right & 0x3ffffff;
      carry = (w >> 26) - ((right / 0x4000000) | 0);
      this.words[i + shift] = w & 0x3ffffff;
    }
    for (; i < this.length - shift; i++) {
      w = (this.words[i + shift] | 0) + carry;
      carry = w >> 26;
      this.words[i + shift] = w & 0x3ffffff;
    }

    if (carry === 0) return this.strip();

    // Subtraction overflow
    assert(carry === -1);
    carry = 0;
    for (i = 0; i < this.length; i++) {
      w = -(this.words[i] | 0) + carry;
      carry = w >> 26;
      this.words[i] = w & 0x3ffffff;
    }
    this.negative = 1;

    return this.strip();
  };

  BN.prototype._wordDiv = function _wordDiv (num, mode) {
    var shift = this.length - num.length;

    var a = this.clone();
    var b = num;

    // Normalize
    var bhi = b.words[b.length - 1] | 0;
    var bhiBits = this._countBits(bhi);
    shift = 26 - bhiBits;
    if (shift !== 0) {
      b = b.ushln(shift);
      a.iushln(shift);
      bhi = b.words[b.length - 1] | 0;
    }

    // Initialize quotient
    var m = a.length - b.length;
    var q;

    if (mode !== 'mod') {
      q = new BN(null);
      q.length = m + 1;
      q.words = new Array(q.length);
      for (var i = 0; i < q.length; i++) {
        q.words[i] = 0;
      }
    }

    var diff = a.clone()._ishlnsubmul(b, 1, m);
    if (diff.negative === 0) {
      a = diff;
      if (q) {
        q.words[m] = 1;
      }
    }

    for (var j = m - 1; j >= 0; j--) {
      var qj = (a.words[b.length + j] | 0) * 0x4000000 +
        (a.words[b.length + j - 1] | 0);

      // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
      // (0x7ffffff)
      qj = Math.min((qj / bhi) | 0, 0x3ffffff);

      a._ishlnsubmul(b, qj, j);
      while (a.negative !== 0) {
        qj--;
        a.negative = 0;
        a._ishlnsubmul(b, 1, j);
        if (!a.isZero()) {
          a.negative ^= 1;
        }
      }
      if (q) {
        q.words[j] = qj;
      }
    }
    if (q) {
      q.strip();
    }
    a.strip();

    // Denormalize
    if (mode !== 'div' && shift !== 0) {
      a.iushrn(shift);
    }

    return {
      div: q || null,
      mod: a
    };
  };

  // NOTE: 1) `mode` can be set to `mod` to request mod only,
  //       to `div` to request div only, or be absent to
  //       request both div & mod
  //       2) `positive` is true if unsigned mod is requested
  BN.prototype.divmod = function divmod (num, mode, positive) {
    assert(!num.isZero());

    if (this.isZero()) {
      return {
        div: new BN(0),
        mod: new BN(0)
      };
    }

    var div, mod, res;
    if (this.negative !== 0 && num.negative === 0) {
      res = this.neg().divmod(num, mode);

      if (mode !== 'mod') {
        div = res.div.neg();
      }

      if (mode !== 'div') {
        mod = res.mod.neg();
        if (positive && mod.negative !== 0) {
          mod.iadd(num);
        }
      }

      return {
        div: div,
        mod: mod
      };
    }

    if (this.negative === 0 && num.negative !== 0) {
      res = this.divmod(num.neg(), mode);

      if (mode !== 'mod') {
        div = res.div.neg();
      }

      return {
        div: div,
        mod: res.mod
      };
    }

    if ((this.negative & num.negative) !== 0) {
      res = this.neg().divmod(num.neg(), mode);

      if (mode !== 'div') {
        mod = res.mod.neg();
        if (positive && mod.negative !== 0) {
          mod.isub(num);
        }
      }

      return {
        div: res.div,
        mod: mod
      };
    }

    // Both numbers are positive at this point

    // Strip both numbers to approximate shift value
    if (num.length > this.length || this.cmp(num) < 0) {
      return {
        div: new BN(0),
        mod: this
      };
    }

    // Very short reduction
    if (num.length === 1) {
      if (mode === 'div') {
        return {
          div: this.divn(num.words[0]),
          mod: null
        };
      }

      if (mode === 'mod') {
        return {
          div: null,
          mod: new BN(this.modn(num.words[0]))
        };
      }

      return {
        div: this.divn(num.words[0]),
        mod: new BN(this.modn(num.words[0]))
      };
    }

    return this._wordDiv(num, mode);
  };

  // Find `this` / `num`
  BN.prototype.div = function div (num) {
    return this.divmod(num, 'div', false).div;
  };

  // Find `this` % `num`
  BN.prototype.mod = function mod (num) {
    return this.divmod(num, 'mod', false).mod;
  };

  BN.prototype.umod = function umod (num) {
    return this.divmod(num, 'mod', true).mod;
  };

  // Find Round(`this` / `num`)
  BN.prototype.divRound = function divRound (num) {
    var dm = this.divmod(num);

    // Fast case - exact division
    if (dm.mod.isZero()) return dm.div;

    var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;

    var half = num.ushrn(1);
    var r2 = num.andln(1);
    var cmp = mod.cmp(half);

    // Round down
    if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;

    // Round up
    return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
  };

  BN.prototype.modn = function modn (num) {
    assert(num <= 0x3ffffff);
    var p = (1 << 26) % num;

    var acc = 0;
    for (var i = this.length - 1; i >= 0; i--) {
      acc = (p * acc + (this.words[i] | 0)) % num;
    }

    return acc;
  };

  // In-place division by number
  BN.prototype.idivn = function idivn (num) {
    assert(num <= 0x3ffffff);

    var carry = 0;
    for (var i = this.length - 1; i >= 0; i--) {
      var w = (this.words[i] | 0) + carry * 0x4000000;
      this.words[i] = (w / num) | 0;
      carry = w % num;
    }

    return this.strip();
  };

  BN.prototype.divn = function divn (num) {
    return this.clone().idivn(num);
  };

  BN.prototype.egcd = function egcd (p) {
    assert(p.negative === 0);
    assert(!p.isZero());

    var x = this;
    var y = p.clone();

    if (x.negative !== 0) {
      x = x.umod(p);
    } else {
      x = x.clone();
    }

    // A * x + B * y = x
    var A = new BN(1);
    var B = new BN(0);

    // C * x + D * y = y
    var C = new BN(0);
    var D = new BN(1);

    var g = 0;

    while (x.isEven() && y.isEven()) {
      x.iushrn(1);
      y.iushrn(1);
      ++g;
    }

    var yp = y.clone();
    var xp = x.clone();

    while (!x.isZero()) {
      for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
      if (i > 0) {
        x.iushrn(i);
        while (i-- > 0) {
          if (A.isOdd() || B.isOdd()) {
            A.iadd(yp);
            B.isub(xp);
          }

          A.iushrn(1);
          B.iushrn(1);
        }
      }

      for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
      if (j > 0) {
        y.iushrn(j);
        while (j-- > 0) {
          if (C.isOdd() || D.isOdd()) {
            C.iadd(yp);
            D.isub(xp);
          }

          C.iushrn(1);
          D.iushrn(1);
        }
      }

      if (x.cmp(y) >= 0) {
        x.isub(y);
        A.isub(C);
        B.isub(D);
      } else {
        y.isub(x);
        C.isub(A);
        D.isub(B);
      }
    }

    return {
      a: C,
      b: D,
      gcd: y.iushln(g)
    };
  };

  // This is reduced incarnation of the binary EEA
  // above, designated to invert members of the
  // _prime_ fields F(p) at a maximal speed
  BN.prototype._invmp = function _invmp (p) {
    assert(p.negative === 0);
    assert(!p.isZero());

    var a = this;
    var b = p.clone();

    if (a.negative !== 0) {
      a = a.umod(p);
    } else {
      a = a.clone();
    }

    var x1 = new BN(1);
    var x2 = new BN(0);

    var delta = b.clone();

    while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
      for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
      if (i > 0) {
        a.iushrn(i);
        while (i-- > 0) {
          if (x1.isOdd()) {
            x1.iadd(delta);
          }

          x1.iushrn(1);
        }
      }

      for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
      if (j > 0) {
        b.iushrn(j);
        while (j-- > 0) {
          if (x2.isOdd()) {
            x2.iadd(delta);
          }

          x2.iushrn(1);
        }
      }

      if (a.cmp(b) >= 0) {
        a.isub(b);
        x1.isub(x2);
      } else {
        b.isub(a);
        x2.isub(x1);
      }
    }

    var res;
    if (a.cmpn(1) === 0) {
      res = x1;
    } else {
      res = x2;
    }

    if (res.cmpn(0) < 0) {
      res.iadd(p);
    }

    return res;
  };

  BN.prototype.gcd = function gcd (num) {
    if (this.isZero()) return num.abs();
    if (num.isZero()) return this.abs();

    var a = this.clone();
    var b = num.clone();
    a.negative = 0;
    b.negative = 0;

    // Remove common factor of two
    for (var shift = 0; a.isEven() && b.isEven(); shift++) {
      a.iushrn(1);
      b.iushrn(1);
    }

    do {
      while (a.isEven()) {
        a.iushrn(1);
      }
      while (b.isEven()) {
        b.iushrn(1);
      }

      var r = a.cmp(b);
      if (r < 0) {
        // Swap `a` and `b` to make `a` always bigger than `b`
        var t = a;
        a = b;
        b = t;
      } else if (r === 0 || b.cmpn(1) === 0) {
        break;
      }

      a.isub(b);
    } while (true);

    return b.iushln(shift);
  };

  // Invert number in the field F(num)
  BN.prototype.invm = function invm (num) {
    return this.egcd(num).a.umod(num);
  };

  BN.prototype.isEven = function isEven () {
    return (this.words[0] & 1) === 0;
  };

  BN.prototype.isOdd = function isOdd () {
    return (this.words[0] & 1) === 1;
  };

  // And first word and num
  BN.prototype.andln = function andln (num) {
    return this.words[0] & num;
  };

  // Increment at the bit position in-line
  BN.prototype.bincn = function bincn (bit) {
    assert(typeof bit === 'number');
    var r = bit % 26;
    var s = (bit - r) / 26;
    var q = 1 << r;

    // Fast case: bit is much higher than all existing words
    if (this.length <= s) {
      this._expand(s + 1);
      this.words[s] |= q;
      return this;
    }

    // Add bit and propagate, if needed
    var carry = q;
    for (var i = s; carry !== 0 && i < this.length; i++) {
      var w = this.words[i] | 0;
      w += carry;
      carry = w >>> 26;
      w &= 0x3ffffff;
      this.words[i] = w;
    }
    if (carry !== 0) {
      this.words[i] = carry;
      this.length++;
    }
    return this;
  };

  BN.prototype.isZero = function isZero () {
    return this.length === 1 && this.words[0] === 0;
  };

  BN.prototype.cmpn = function cmpn (num) {
    var negative = num < 0;

    if (this.negative !== 0 && !negative) return -1;
    if (this.negative === 0 && negative) return 1;

    this.strip();

    var res;
    if (this.length > 1) {
      res = 1;
    } else {
      if (negative) {
        num = -num;
      }

      assert(num <= 0x3ffffff, 'Number is too big');

      var w = this.words[0] | 0;
      res = w === num ? 0 : w < num ? -1 : 1;
    }
    if (this.negative !== 0) return -res | 0;
    return res;
  };

  // Compare two numbers and return:
  // 1 - if `this` > `num`
  // 0 - if `this` == `num`
  // -1 - if `this` < `num`
  BN.prototype.cmp = function cmp (num) {
    if (this.negative !== 0 && num.negative === 0) return -1;
    if (this.negative === 0 && num.negative !== 0) return 1;

    var res = this.ucmp(num);
    if (this.negative !== 0) return -res | 0;
    return res;
  };

  // Unsigned comparison
  BN.prototype.ucmp = function ucmp (num) {
    // At this point both numbers have the same sign
    if (this.length > num.length) return 1;
    if (this.length < num.length) return -1;

    var res = 0;
    for (var i = this.length - 1; i >= 0; i--) {
      var a = this.words[i] | 0;
      var b = num.words[i] | 0;

      if (a === b) continue;
      if (a < b) {
        res = -1;
      } else if (a > b) {
        res = 1;
      }
      break;
    }
    return res;
  };

  BN.prototype.gtn = function gtn (num) {
    return this.cmpn(num) === 1;
  };

  BN.prototype.gt = function gt (num) {
    return this.cmp(num) === 1;
  };

  BN.prototype.gten = function gten (num) {
    return this.cmpn(num) >= 0;
  };

  BN.prototype.gte = function gte (num) {
    return this.cmp(num) >= 0;
  };

  BN.prototype.ltn = function ltn (num) {
    return this.cmpn(num) === -1;
  };

  BN.prototype.lt = function lt (num) {
    return this.cmp(num) === -1;
  };

  BN.prototype.lten = function lten (num) {
    return this.cmpn(num) <= 0;
  };

  BN.prototype.lte = function lte (num) {
    return this.cmp(num) <= 0;
  };

  BN.prototype.eqn = function eqn (num) {
    return this.cmpn(num) === 0;
  };

  BN.prototype.eq = function eq (num) {
    return this.cmp(num) === 0;
  };

  //
  // A reduce context, could be using montgomery or something better, depending
  // on the `m` itself.
  //
  BN.red = function red (num) {
    return new Red(num);
  };

  BN.prototype.toRed = function toRed (ctx) {
    assert(!this.red, 'Already a number in reduction context');
    assert(this.negative === 0, 'red works only with positives');
    return ctx.convertTo(this)._forceRed(ctx);
  };

  BN.prototype.fromRed = function fromRed () {
    assert(this.red, 'fromRed works only with numbers in reduction context');
    return this.red.convertFrom(this);
  };

  BN.prototype._forceRed = function _forceRed (ctx) {
    this.red = ctx;
    return this;
  };

  BN.prototype.forceRed = function forceRed (ctx) {
    assert(!this.red, 'Already a number in reduction context');
    return this._forceRed(ctx);
  };

  BN.prototype.redAdd = function redAdd (num) {
    assert(this.red, 'redAdd works only with red numbers');
    return this.red.add(this, num);
  };

  BN.prototype.redIAdd = function redIAdd (num) {
    assert(this.red, 'redIAdd works only with red numbers');
    return this.red.iadd(this, num);
  };

  BN.prototype.redSub = function redSub (num) {
    assert(this.red, 'redSub works only with red numbers');
    return this.red.sub(this, num);
  };

  BN.prototype.redISub = function redISub (num) {
    assert(this.red, 'redISub works only with red numbers');
    return this.red.isub(this, num);
  };

  BN.prototype.redShl = function redShl (num) {
    assert(this.red, 'redShl works only with red numbers');
    return this.red.shl(this, num);
  };

  BN.prototype.redMul = function redMul (num) {
    assert(this.red, 'redMul works only with red numbers');
    this.red._verify2(this, num);
    return this.red.mul(this, num);
  };

  BN.prototype.redIMul = function redIMul (num) {
    assert(this.red, 'redMul works only with red numbers');
    this.red._verify2(this, num);
    return this.red.imul(this, num);
  };

  BN.prototype.redSqr = function redSqr () {
    assert(this.red, 'redSqr works only with red numbers');
    this.red._verify1(this);
    return this.red.sqr(this);
  };

  BN.prototype.redISqr = function redISqr () {
    assert(this.red, 'redISqr works only with red numbers');
    this.red._verify1(this);
    return this.red.isqr(this);
  };

  // Square root over p
  BN.prototype.redSqrt = function redSqrt () {
    assert(this.red, 'redSqrt works only with red numbers');
    this.red._verify1(this);
    return this.red.sqrt(this);
  };

  BN.prototype.redInvm = function redInvm () {
    assert(this.red, 'redInvm works only with red numbers');
    this.red._verify1(this);
    return this.red.invm(this);
  };

  // Return negative clone of `this` % `red modulo`
  BN.prototype.redNeg = function redNeg () {
    assert(this.red, 'redNeg works only with red numbers');
    this.red._verify1(this);
    return this.red.neg(this);
  };

  BN.prototype.redPow = function redPow (num) {
    assert(this.red && !num.red, 'redPow(normalNum)');
    this.red._verify1(this);
    return this.red.pow(this, num);
  };

  // Prime numbers with efficient reduction
  var primes = {
    k256: null,
    p224: null,
    p192: null,
    p25519: null
  };

  // Pseudo-Mersenne prime
  function MPrime (name, p) {
    // P = 2 ^ N - K
    this.name = name;
    this.p = new BN(p, 16);
    this.n = this.p.bitLength();
    this.k = new BN(1).iushln(this.n).isub(this.p);

    this.tmp = this._tmp();
  }

  MPrime.prototype._tmp = function _tmp () {
    var tmp = new BN(null);
    tmp.words = new Array(Math.ceil(this.n / 13));
    return tmp;
  };

  MPrime.prototype.ireduce = function ireduce (num) {
    // Assumes that `num` is less than `P^2`
    // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
    var r = num;
    var rlen;

    do {
      this.split(r, this.tmp);
      r = this.imulK(r);
      r = r.iadd(this.tmp);
      rlen = r.bitLength();
    } while (rlen > this.n);

    var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
    if (cmp === 0) {
      r.words[0] = 0;
      r.length = 1;
    } else if (cmp > 0) {
      r.isub(this.p);
    } else {
      if (r.strip !== undefined) {
        // r is BN v4 instance
        r.strip();
      } else {
        // r is BN v5 instance
        r._strip();
      }
    }

    return r;
  };

  MPrime.prototype.split = function split (input, out) {
    input.iushrn(this.n, 0, out);
  };

  MPrime.prototype.imulK = function imulK (num) {
    return num.imul(this.k);
  };

  function K256 () {
    MPrime.call(
      this,
      'k256',
      'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
  }
  inherits(K256, MPrime);

  K256.prototype.split = function split (input, output) {
    // 256 = 9 * 26 + 22
    var mask = 0x3fffff;

    var outLen = Math.min(input.length, 9);
    for (var i = 0; i < outLen; i++) {
      output.words[i] = input.words[i];
    }
    output.length = outLen;

    if (input.length <= 9) {
      input.words[0] = 0;
      input.length = 1;
      return;
    }

    // Shift by 9 limbs
    var prev = input.words[9];
    output.words[output.length++] = prev & mask;

    for (i = 10; i < input.length; i++) {
      var next = input.words[i] | 0;
      input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
      prev = next;
    }
    prev >>>= 22;
    input.words[i - 10] = prev;
    if (prev === 0 && input.length > 10) {
      input.length -= 10;
    } else {
      input.length -= 9;
    }
  };

  K256.prototype.imulK = function imulK (num) {
    // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
    num.words[num.length] = 0;
    num.words[num.length + 1] = 0;
    num.length += 2;

    // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
    var lo = 0;
    for (var i = 0; i < num.length; i++) {
      var w = num.words[i] | 0;
      lo += w * 0x3d1;
      num.words[i] = lo & 0x3ffffff;
      lo = w * 0x40 + ((lo / 0x4000000) | 0);
    }

    // Fast length reduction
    if (num.words[num.length - 1] === 0) {
      num.length--;
      if (num.words[num.length - 1] === 0) {
        num.length--;
      }
    }
    return num;
  };

  function P224 () {
    MPrime.call(
      this,
      'p224',
      'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
  }
  inherits(P224, MPrime);

  function P192 () {
    MPrime.call(
      this,
      'p192',
      'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
  }
  inherits(P192, MPrime);

  function P25519 () {
    // 2 ^ 255 - 19
    MPrime.call(
      this,
      '25519',
      '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
  }
  inherits(P25519, MPrime);

  P25519.prototype.imulK = function imulK (num) {
    // K = 0x13
    var carry = 0;
    for (var i = 0; i < num.length; i++) {
      var hi = (num.words[i] | 0) * 0x13 + carry;
      var lo = hi & 0x3ffffff;
      hi >>>= 26;

      num.words[i] = lo;
      carry = hi;
    }
    if (carry !== 0) {
      num.words[num.length++] = carry;
    }
    return num;
  };

  // Exported mostly for testing purposes, use plain name instead
  BN._prime = function prime (name) {
    // Cached version of prime
    if (primes[name]) return primes[name];

    var prime;
    if (name === 'k256') {
      prime = new K256();
    } else if (name === 'p224') {
      prime = new P224();
    } else if (name === 'p192') {
      prime = new P192();
    } else if (name === 'p25519') {
      prime = new P25519();
    } else {
      throw new Error('Unknown prime ' + name);
    }
    primes[name] = prime;

    return prime;
  };

  //
  // Base reduction engine
  //
  function Red (m) {
    if (typeof m === 'string') {
      var prime = BN._prime(m);
      this.m = prime.p;
      this.prime = prime;
    } else {
      assert(m.gtn(1), 'modulus must be greater than 1');
      this.m = m;
      this.prime = null;
    }
  }

  Red.prototype._verify1 = function _verify1 (a) {
    assert(a.negative === 0, 'red works only with positives');
    assert(a.red, 'red works only with red numbers');
  };

  Red.prototype._verify2 = function _verify2 (a, b) {
    assert((a.negative | b.negative) === 0, 'red works only with positives');
    assert(a.red && a.red === b.red,
      'red works only with red numbers');
  };

  Red.prototype.imod = function imod (a) {
    if (this.prime) return this.prime.ireduce(a)._forceRed(this);
    return a.umod(this.m)._forceRed(this);
  };

  Red.prototype.neg = function neg (a) {
    if (a.isZero()) {
      return a.clone();
    }

    return this.m.sub(a)._forceRed(this);
  };

  Red.prototype.add = function add (a, b) {
    this._verify2(a, b);

    var res = a.add(b);
    if (res.cmp(this.m) >= 0) {
      res.isub(this.m);
    }
    return res._forceRed(this);
  };

  Red.prototype.iadd = function iadd (a, b) {
    this._verify2(a, b);

    var res = a.iadd(b);
    if (res.cmp(this.m) >= 0) {
      res.isub(this.m);
    }
    return res;
  };

  Red.prototype.sub = function sub (a, b) {
    this._verify2(a, b);

    var res = a.sub(b);
    if (res.cmpn(0) < 0) {
      res.iadd(this.m);
    }
    return res._forceRed(this);
  };

  Red.prototype.isub = function isub (a, b) {
    this._verify2(a, b);

    var res = a.isub(b);
    if (res.cmpn(0) < 0) {
      res.iadd(this.m);
    }
    return res;
  };

  Red.prototype.shl = function shl (a, num) {
    this._verify1(a);
    return this.imod(a.ushln(num));
  };

  Red.prototype.imul = function imul (a, b) {
    this._verify2(a, b);
    return this.imod(a.imul(b));
  };

  Red.prototype.mul = function mul (a, b) {
    this._verify2(a, b);
    return this.imod(a.mul(b));
  };

  Red.prototype.isqr = function isqr (a) {
    return this.imul(a, a.clone());
  };

  Red.prototype.sqr = function sqr (a) {
    return this.mul(a, a);
  };

  Red.prototype.sqrt = function sqrt (a) {
    if (a.isZero()) return a.clone();

    var mod3 = this.m.andln(3);
    assert(mod3 % 2 === 1);

    // Fast case
    if (mod3 === 3) {
      var pow = this.m.add(new BN(1)).iushrn(2);
      return this.pow(a, pow);
    }

    // Tonelli-Shanks algorithm (Totally unoptimized and slow)
    //
    // Find Q and S, that Q * 2 ^ S = (P - 1)
    var q = this.m.subn(1);
    var s = 0;
    while (!q.isZero() && q.andln(1) === 0) {
      s++;
      q.iushrn(1);
    }
    assert(!q.isZero());

    var one = new BN(1).toRed(this);
    var nOne = one.redNeg();

    // Find quadratic non-residue
    // NOTE: Max is such because of generalized Riemann hypothesis.
    var lpow = this.m.subn(1).iushrn(1);
    var z = this.m.bitLength();
    z = new BN(2 * z * z).toRed(this);

    while (this.pow(z, lpow).cmp(nOne) !== 0) {
      z.redIAdd(nOne);
    }

    var c = this.pow(z, q);
    var r = this.pow(a, q.addn(1).iushrn(1));
    var t = this.pow(a, q);
    var m = s;
    while (t.cmp(one) !== 0) {
      var tmp = t;
      for (var i = 0; tmp.cmp(one) !== 0; i++) {
        tmp = tmp.redSqr();
      }
      assert(i < m);
      var b = this.pow(c, new BN(1).iushln(m - i - 1));

      r = r.redMul(b);
      c = b.redSqr();
      t = t.redMul(c);
      m = i;
    }

    return r;
  };

  Red.prototype.invm = function invm (a) {
    var inv = a._invmp(this.m);
    if (inv.negative !== 0) {
      inv.negative = 0;
      return this.imod(inv).redNeg();
    } else {
      return this.imod(inv);
    }
  };

  Red.prototype.pow = function pow (a, num) {
    if (num.isZero()) return new BN(1).toRed(this);
    if (num.cmpn(1) === 0) return a.clone();

    var windowSize = 4;
    var wnd = new Array(1 << windowSize);
    wnd[0] = new BN(1).toRed(this);
    wnd[1] = a;
    for (var i = 2; i < wnd.length; i++) {
      wnd[i] = this.mul(wnd[i - 1], a);
    }

    var res = wnd[0];
    var current = 0;
    var currentLen = 0;
    var start = num.bitLength() % 26;
    if (start === 0) {
      start = 26;
    }

    for (i = num.length - 1; i >= 0; i--) {
      var word = num.words[i];
      for (var j = start - 1; j >= 0; j--) {
        var bit = (word >> j) & 1;
        if (res !== wnd[0]) {
          res = this.sqr(res);
        }

        if (bit === 0 && current === 0) {
          currentLen = 0;
          continue;
        }

        current <<= 1;
        current |= bit;
        currentLen++;
        if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;

        res = this.mul(res, wnd[current]);
        currentLen = 0;
        current = 0;
      }
      start = 26;
    }

    return res;
  };

  Red.prototype.convertTo = function convertTo (num) {
    var r = num.umod(this.m);

    return r === num ? r.clone() : r;
  };

  Red.prototype.convertFrom = function convertFrom (num) {
    var res = num.clone();
    res.red = null;
    return res;
  };

  //
  // Montgomery method engine
  //

  BN.mont = function mont (num) {
    return new Mont(num);
  };

  function Mont (m) {
    Red.call(this, m);

    this.shift = this.m.bitLength();
    if (this.shift % 26 !== 0) {
      this.shift += 26 - (this.shift % 26);
    }

    this.r = new BN(1).iushln(this.shift);
    this.r2 = this.imod(this.r.sqr());
    this.rinv = this.r._invmp(this.m);

    this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
    this.minv = this.minv.umod(this.r);
    this.minv = this.r.sub(this.minv);
  }
  inherits(Mont, Red);

  Mont.prototype.convertTo = function convertTo (num) {
    return this.imod(num.ushln(this.shift));
  };

  Mont.prototype.convertFrom = function convertFrom (num) {
    var r = this.imod(num.mul(this.rinv));
    r.red = null;
    return r;
  };

  Mont.prototype.imul = function imul (a, b) {
    if (a.isZero() || b.isZero()) {
      a.words[0] = 0;
      a.length = 1;
      return a;
    }

    var t = a.imul(b);
    var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
    var u = t.isub(c).iushrn(this.shift);
    var res = u;

    if (u.cmp(this.m) >= 0) {
      res = u.isub(this.m);
    } else if (u.cmpn(0) < 0) {
      res = u.iadd(this.m);
    }

    return res._forceRed(this);
  };

  Mont.prototype.mul = function mul (a, b) {
    if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);

    var t = a.mul(b);
    var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
    var u = t.isub(c).iushrn(this.shift);
    var res = u;
    if (u.cmp(this.m) >= 0) {
      res = u.isub(this.m);
    } else if (u.cmpn(0) < 0) {
      res = u.iadd(this.m);
    }

    return res._forceRed(this);
  };

  Mont.prototype.invm = function invm (a) {
    // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
    var res = this.imod(a._invmp(this.m).mul(this.r2));
    return res._forceRed(this);
  };
})( false || module, this);


/***/ }),

/***/ 12293:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {

/* module decorator */ module = __webpack_require__.nmd(module);
(function (module, exports) {
  'use strict';

  // Utils
  function assert (val, msg) {
    if (!val) throw new Error(msg || 'Assertion failed');
  }

  // Could use `inherits` module, but don't want to move from single file
  // architecture yet.
  function inherits (ctor, superCtor) {
    ctor.super_ = superCtor;
    var TempCtor = function () {};
    TempCtor.prototype = superCtor.prototype;
    ctor.prototype = new TempCtor();
    ctor.prototype.constructor = ctor;
  }

  // BN

  function BN (number, base, endian) {
    if (BN.isBN(number)) {
      return number;
    }

    this.negative = 0;
    this.words = null;
    this.length = 0;

    // Reduction context
    this.red = null;

    if (number !== null) {
      if (base === 'le' || base === 'be') {
        endian = base;
        base = 10;
      }

      this._init(number || 0, base || 10, endian || 'be');
    }
  }
  if (typeof module === 'object') {
    module.exports = BN;
  } else {
    exports.BN = BN;
  }

  BN.BN = BN;
  BN.wordSize = 26;

  var Buffer;
  try {
    if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {
      Buffer = window.Buffer;
    } else {
      Buffer = (__webpack_require__(34149).Buffer);
    }
  } catch (e) {
  }

  BN.isBN = function isBN (num) {
    if (num instanceof BN) {
      return true;
    }

    return num !== null && typeof num === 'object' &&
      num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
  };

  BN.max = function max (left, right) {
    if (left.cmp(right) > 0) return left;
    return right;
  };

  BN.min = function min (left, right) {
    if (left.cmp(right) < 0) return left;
    return right;
  };

  BN.prototype._init = function init (number, base, endian) {
    if (typeof number === 'number') {
      return this._initNumber(number, base, endian);
    }

    if (typeof number === 'object') {
      return this._initArray(number, base, endian);
    }

    if (base === 'hex') {
      base = 16;
    }
    assert(base === (base | 0) && base >= 2 && base <= 36);

    number = number.toString().replace(/\s+/g, '');
    var start = 0;
    if (number[0] === '-') {
      start++;
      this.negative = 1;
    }

    if (start < number.length) {
      if (base === 16) {
        this._parseHex(number, start, endian);
      } else {
        this._parseBase(number, base, start);
        if (endian === 'le') {
          this._initArray(this.toArray(), base, endian);
        }
      }
    }
  };

  BN.prototype._initNumber = function _initNumber (number, base, endian) {
    if (number < 0) {
      this.negative = 1;
      number = -number;
    }
    if (number < 0x4000000) {
      this.words = [number & 0x3ffffff];
      this.length = 1;
    } else if (number < 0x10000000000000) {
      this.words = [
        number & 0x3ffffff,
        (number / 0x4000000) & 0x3ffffff
      ];
      this.length = 2;
    } else {
      assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
      this.words = [
        number & 0x3ffffff,
        (number / 0x4000000) & 0x3ffffff,
        1
      ];
      this.length = 3;
    }

    if (endian !== 'le') return;

    // Reverse the bytes
    this._initArray(this.toArray(), base, endian);
  };

  BN.prototype._initArray = function _initArray (number, base, endian) {
    // Perhaps a Uint8Array
    assert(typeof number.length === 'number');
    if (number.length <= 0) {
      this.words = [0];
      this.length = 1;
      return this;
    }

    this.length = Math.ceil(number.length / 3);
    this.words = new Array(this.length);
    for (var i = 0; i < this.length; i++) {
      this.words[i] = 0;
    }

    var j, w;
    var off = 0;
    if (endian === 'be') {
      for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
        w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
        this.words[j] |= (w << off) & 0x3ffffff;
        this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
        off += 24;
        if (off >= 26) {
          off -= 26;
          j++;
        }
      }
    } else if (endian === 'le') {
      for (i = 0, j = 0; i < number.length; i += 3) {
        w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
        this.words[j] |= (w << off) & 0x3ffffff;
        this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
        off += 24;
        if (off >= 26) {
          off -= 26;
          j++;
        }
      }
    }
    return this._strip();
  };

  function parseHex4Bits (string, index) {
    var c = string.charCodeAt(index);
    // '0' - '9'
    if (c >= 48 && c <= 57) {
      return c - 48;
    // 'A' - 'F'
    } else if (c >= 65 && c <= 70) {
      return c - 55;
    // 'a' - 'f'
    } else if (c >= 97 && c <= 102) {
      return c - 87;
    } else {
      assert(false, 'Invalid character in ' + string);
    }
  }

  function parseHexByte (string, lowerBound, index) {
    var r = parseHex4Bits(string, index);
    if (index - 1 >= lowerBound) {
      r |= parseHex4Bits(string, index - 1) << 4;
    }
    return r;
  }

  BN.prototype._parseHex = function _parseHex (number, start, endian) {
    // Create possibly bigger array to ensure that it fits the number
    this.length = Math.ceil((number.length - start) / 6);
    this.words = new Array(this.length);
    for (var i = 0; i < this.length; i++) {
      this.words[i] = 0;
    }

    // 24-bits chunks
    var off = 0;
    var j = 0;

    var w;
    if (endian === 'be') {
      for (i = number.length - 1; i >= start; i -= 2) {
        w = parseHexByte(number, start, i) << off;
        this.words[j] |= w & 0x3ffffff;
        if (off >= 18) {
          off -= 18;
          j += 1;
          this.words[j] |= w >>> 26;
        } else {
          off += 8;
        }
      }
    } else {
      var parseLength = number.length - start;
      for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {
        w = parseHexByte(number, start, i) << off;
        this.words[j] |= w & 0x3ffffff;
        if (off >= 18) {
          off -= 18;
          j += 1;
          this.words[j] |= w >>> 26;
        } else {
          off += 8;
        }
      }
    }

    this._strip();
  };

  function parseBase (str, start, end, mul) {
    var r = 0;
    var b = 0;
    var len = Math.min(str.length, end);
    for (var i = start; i < len; i++) {
      var c = str.charCodeAt(i) - 48;

      r *= mul;

      // 'a'
      if (c >= 49) {
        b = c - 49 + 0xa;

      // 'A'
      } else if (c >= 17) {
        b = c - 17 + 0xa;

      // '0' - '9'
      } else {
        b = c;
      }
      assert(c >= 0 && b < mul, 'Invalid character');
      r += b;
    }
    return r;
  }

  BN.prototype._parseBase = function _parseBase (number, base, start) {
    // Initialize as zero
    this.words = [0];
    this.length = 1;

    // Find length of limb in base
    for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
      limbLen++;
    }
    limbLen--;
    limbPow = (limbPow / base) | 0;

    var total = number.length - start;
    var mod = total % limbLen;
    var end = Math.min(total, total - mod) + start;

    var word = 0;
    for (var i = start; i < end; i += limbLen) {
      word = parseBase(number, i, i + limbLen, base);

      this.imuln(limbPow);
      if (this.words[0] + word < 0x4000000) {
        this.words[0] += word;
      } else {
        this._iaddn(word);
      }
    }

    if (mod !== 0) {
      var pow = 1;
      word = parseBase(number, i, number.length, base);

      for (i = 0; i < mod; i++) {
        pow *= base;
      }

      this.imuln(pow);
      if (this.words[0] + word < 0x4000000) {
        this.words[0] += word;
      } else {
        this._iaddn(word);
      }
    }

    this._strip();
  };

  BN.prototype.copy = function copy (dest) {
    dest.words = new Array(this.length);
    for (var i = 0; i < this.length; i++) {
      dest.words[i] = this.words[i];
    }
    dest.length = this.length;
    dest.negative = this.negative;
    dest.red = this.red;
  };

  function move (dest, src) {
    dest.words = src.words;
    dest.length = src.length;
    dest.negative = src.negative;
    dest.red = src.red;
  }

  BN.prototype._move = function _move (dest) {
    move(dest, this);
  };

  BN.prototype.clone = function clone () {
    var r = new BN(null);
    this.copy(r);
    return r;
  };

  BN.prototype._expand = function _expand (size) {
    while (this.length < size) {
      this.words[this.length++] = 0;
    }
    return this;
  };

  // Remove leading `0` from `this`
  BN.prototype._strip = function strip () {
    while (this.length > 1 && this.words[this.length - 1] === 0) {
      this.length--;
    }
    return this._normSign();
  };

  BN.prototype._normSign = function _normSign () {
    // -0 = 0
    if (this.length === 1 && this.words[0] === 0) {
      this.negative = 0;
    }
    return this;
  };

  // Check Symbol.for because not everywhere where Symbol defined
  // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility
  if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') {
    try {
      BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect;
    } catch (e) {
      BN.prototype.inspect = inspect;
    }
  } else {
    BN.prototype.inspect = inspect;
  }

  function inspect () {
    return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
  }

  /*

  var zeros = [];
  var groupSizes = [];
  var groupBases = [];

  var s = '';
  var i = -1;
  while (++i < BN.wordSize) {
    zeros[i] = s;
    s += '0';
  }
  groupSizes[0] = 0;
  groupSizes[1] = 0;
  groupBases[0] = 0;
  groupBases[1] = 0;
  var base = 2 - 1;
  while (++base < 36 + 1) {
    var groupSize = 0;
    var groupBase = 1;
    while (groupBase < (1 << BN.wordSize) / base) {
      groupBase *= base;
      groupSize += 1;
    }
    groupSizes[base] = groupSize;
    groupBases[base] = groupBase;
  }

  */

  var zeros = [
    '',
    '0',
    '00',
    '000',
    '0000',
    '00000',
    '000000',
    '0000000',
    '00000000',
    '000000000',
    '0000000000',
    '00000000000',
    '000000000000',
    '0000000000000',
    '00000000000000',
    '000000000000000',
    '0000000000000000',
    '00000000000000000',
    '000000000000000000',
    '0000000000000000000',
    '00000000000000000000',
    '000000000000000000000',
    '0000000000000000000000',
    '00000000000000000000000',
    '000000000000000000000000',
    '0000000000000000000000000'
  ];

  var groupSizes = [
    0, 0,
    25, 16, 12, 11, 10, 9, 8,
    8, 7, 7, 7, 7, 6, 6,
    6, 6, 6, 6, 6, 5, 5,
    5, 5, 5, 5, 5, 5, 5,
    5, 5, 5, 5, 5, 5, 5
  ];

  var groupBases = [
    0, 0,
    33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
    43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
    16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
    6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
    24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
  ];

  BN.prototype.toString = function toString (base, padding) {
    base = base || 10;
    padding = padding | 0 || 1;

    var out;
    if (base === 16 || base === 'hex') {
      out = '';
      var off = 0;
      var carry = 0;
      for (var i = 0; i < this.length; i++) {
        var w = this.words[i];
        var word = (((w << off) | carry) & 0xffffff).toString(16);
        carry = (w >>> (24 - off)) & 0xffffff;
        off += 2;
        if (off >= 26) {
          off -= 26;
          i--;
        }
        if (carry !== 0 || i !== this.length - 1) {
          out = zeros[6 - word.length] + word + out;
        } else {
          out = word + out;
        }
      }
      if (carry !== 0) {
        out = carry.toString(16) + out;
      }
      while (out.length % padding !== 0) {
        out = '0' + out;
      }
      if (this.negative !== 0) {
        out = '-' + out;
      }
      return out;
    }

    if (base === (base | 0) && base >= 2 && base <= 36) {
      // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
      var groupSize = groupSizes[base];
      // var groupBase = Math.pow(base, groupSize);
      var groupBase = groupBases[base];
      out = '';
      var c = this.clone();
      c.negative = 0;
      while (!c.isZero()) {
        var r = c.modrn(groupBase).toString(base);
        c = c.idivn(groupBase);

        if (!c.isZero()) {
          out = zeros[groupSize - r.length] + r + out;
        } else {
          out = r + out;
        }
      }
      if (this.isZero()) {
        out = '0' + out;
      }
      while (out.length % padding !== 0) {
        out = '0' + out;
      }
      if (this.negative !== 0) {
        out = '-' + out;
      }
      return out;
    }

    assert(false, 'Base should be between 2 and 36');
  };

  BN.prototype.toNumber = function toNumber () {
    var ret = this.words[0];
    if (this.length === 2) {
      ret += this.words[1] * 0x4000000;
    } else if (this.length === 3 && this.words[2] === 0x01) {
      // NOTE: at this stage it is known that the top bit is set
      ret += 0x10000000000000 + (this.words[1] * 0x4000000);
    } else if (this.length > 2) {
      assert(false, 'Number can only safely store up to 53 bits');
    }
    return (this.negative !== 0) ? -ret : ret;
  };

  BN.prototype.toJSON = function toJSON () {
    return this.toString(16, 2);
  };

  if (Buffer) {
    BN.prototype.toBuffer = function toBuffer (endian, length) {
      return this.toArrayLike(Buffer, endian, length);
    };
  }

  BN.prototype.toArray = function toArray (endian, length) {
    return this.toArrayLike(Array, endian, length);
  };

  var allocate = function allocate (ArrayType, size) {
    if (ArrayType.allocUnsafe) {
      return ArrayType.allocUnsafe(size);
    }
    return new ArrayType(size);
  };

  BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
    this._strip();

    var byteLength = this.byteLength();
    var reqLength = length || Math.max(1, byteLength);
    assert(byteLength <= reqLength, 'byte array longer than desired length');
    assert(reqLength > 0, 'Requested array length <= 0');

    var res = allocate(ArrayType, reqLength);
    var postfix = endian === 'le' ? 'LE' : 'BE';
    this['_toArrayLike' + postfix](res, byteLength);
    return res;
  };

  BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) {
    var position = 0;
    var carry = 0;

    for (var i = 0, shift = 0; i < this.length; i++) {
      var word = (this.words[i] << shift) | carry;

      res[position++] = word & 0xff;
      if (position < res.length) {
        res[position++] = (word >> 8) & 0xff;
      }
      if (position < res.length) {
        res[position++] = (word >> 16) & 0xff;
      }

      if (shift === 6) {
        if (position < res.length) {
          res[position++] = (word >> 24) & 0xff;
        }
        carry = 0;
        shift = 0;
      } else {
        carry = word >>> 24;
        shift += 2;
      }
    }

    if (position < res.length) {
      res[position++] = carry;

      while (position < res.length) {
        res[position++] = 0;
      }
    }
  };

  BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) {
    var position = res.length - 1;
    var carry = 0;

    for (var i = 0, shift = 0; i < this.length; i++) {
      var word = (this.words[i] << shift) | carry;

      res[position--] = word & 0xff;
      if (position >= 0) {
        res[position--] = (word >> 8) & 0xff;
      }
      if (position >= 0) {
        res[position--] = (word >> 16) & 0xff;
      }

      if (shift === 6) {
        if (position >= 0) {
          res[position--] = (word >> 24) & 0xff;
        }
        carry = 0;
        shift = 0;
      } else {
        carry = word >>> 24;
        shift += 2;
      }
    }

    if (position >= 0) {
      res[position--] = carry;

      while (position >= 0) {
        res[position--] = 0;
      }
    }
  };

  if (Math.clz32) {
    BN.prototype._countBits = function _countBits (w) {
      return 32 - Math.clz32(w);
    };
  } else {
    BN.prototype._countBits = function _countBits (w) {
      var t = w;
      var r = 0;
      if (t >= 0x1000) {
        r += 13;
        t >>>= 13;
      }
      if (t >= 0x40) {
        r += 7;
        t >>>= 7;
      }
      if (t >= 0x8) {
        r += 4;
        t >>>= 4;
      }
      if (t >= 0x02) {
        r += 2;
        t >>>= 2;
      }
      return r + t;
    };
  }

  BN.prototype._zeroBits = function _zeroBits (w) {
    // Short-cut
    if (w === 0) return 26;

    var t = w;
    var r = 0;
    if ((t & 0x1fff) === 0) {
      r += 13;
      t >>>= 13;
    }
    if ((t & 0x7f) === 0) {
      r += 7;
      t >>>= 7;
    }
    if ((t & 0xf) === 0) {
      r += 4;
      t >>>= 4;
    }
    if ((t & 0x3) === 0) {
      r += 2;
      t >>>= 2;
    }
    if ((t & 0x1) === 0) {
      r++;
    }
    return r;
  };

  // Return number of used bits in a BN
  BN.prototype.bitLength = function bitLength () {
    var w = this.words[this.length - 1];
    var hi = this._countBits(w);
    return (this.length - 1) * 26 + hi;
  };

  function toBitArray (num) {
    var w = new Array(num.bitLength());

    for (var bit = 0; bit < w.length; bit++) {
      var off = (bit / 26) | 0;
      var wbit = bit % 26;

      w[bit] = (num.words[off] >>> wbit) & 0x01;
    }

    return w;
  }

  // Number of trailing zero bits
  BN.prototype.zeroBits = function zeroBits () {
    if (this.isZero()) return 0;

    var r = 0;
    for (var i = 0; i < this.length; i++) {
      var b = this._zeroBits(this.words[i]);
      r += b;
      if (b !== 26) break;
    }
    return r;
  };

  BN.prototype.byteLength = function byteLength () {
    return Math.ceil(this.bitLength() / 8);
  };

  BN.prototype.toTwos = function toTwos (width) {
    if (this.negative !== 0) {
      return this.abs().inotn(width).iaddn(1);
    }
    return this.clone();
  };

  BN.prototype.fromTwos = function fromTwos (width) {
    if (this.testn(width - 1)) {
      return this.notn(width).iaddn(1).ineg();
    }
    return this.clone();
  };

  BN.prototype.isNeg = function isNeg () {
    return this.negative !== 0;
  };

  // Return negative clone of `this`
  BN.prototype.neg = function neg () {
    return this.clone().ineg();
  };

  BN.prototype.ineg = function ineg () {
    if (!this.isZero()) {
      this.negative ^= 1;
    }

    return this;
  };

  // Or `num` with `this` in-place
  BN.prototype.iuor = function iuor (num) {
    while (this.length < num.length) {
      this.words[this.length++] = 0;
    }

    for (var i = 0; i < num.length; i++) {
      this.words[i] = this.words[i] | num.words[i];
    }

    return this._strip();
  };

  BN.prototype.ior = function ior (num) {
    assert((this.negative | num.negative) === 0);
    return this.iuor(num);
  };

  // Or `num` with `this`
  BN.prototype.or = function or (num) {
    if (this.length > num.length) return this.clone().ior(num);
    return num.clone().ior(this);
  };

  BN.prototype.uor = function uor (num) {
    if (this.length > num.length) return this.clone().iuor(num);
    return num.clone().iuor(this);
  };

  // And `num` with `this` in-place
  BN.prototype.iuand = function iuand (num) {
    // b = min-length(num, this)
    var b;
    if (this.length > num.length) {
      b = num;
    } else {
      b = this;
    }

    for (var i = 0; i < b.length; i++) {
      this.words[i] = this.words[i] & num.words[i];
    }

    this.length = b.length;

    return this._strip();
  };

  BN.prototype.iand = function iand (num) {
    assert((this.negative | num.negative) === 0);
    return this.iuand(num);
  };

  // And `num` with `this`
  BN.prototype.and = function and (num) {
    if (this.length > num.length) return this.clone().iand(num);
    return num.clone().iand(this);
  };

  BN.prototype.uand = function uand (num) {
    if (this.length > num.length) return this.clone().iuand(num);
    return num.clone().iuand(this);
  };

  // Xor `num` with `this` in-place
  BN.prototype.iuxor = function iuxor (num) {
    // a.length > b.length
    var a;
    var b;
    if (this.length > num.length) {
      a = this;
      b = num;
    } else {
      a = num;
      b = this;
    }

    for (var i = 0; i < b.length; i++) {
      this.words[i] = a.words[i] ^ b.words[i];
    }

    if (this !== a) {
      for (; i < a.length; i++) {
        this.words[i] = a.words[i];
      }
    }

    this.length = a.length;

    return this._strip();
  };

  BN.prototype.ixor = function ixor (num) {
    assert((this.negative | num.negative) === 0);
    return this.iuxor(num);
  };

  // Xor `num` with `this`
  BN.prototype.xor = function xor (num) {
    if (this.length > num.length) return this.clone().ixor(num);
    return num.clone().ixor(this);
  };

  BN.prototype.uxor = function uxor (num) {
    if (this.length > num.length) return this.clone().iuxor(num);
    return num.clone().iuxor(this);
  };

  // Not ``this`` with ``width`` bitwidth
  BN.prototype.inotn = function inotn (width) {
    assert(typeof width === 'number' && width >= 0);

    var bytesNeeded = Math.ceil(width / 26) | 0;
    var bitsLeft = width % 26;

    // Extend the buffer with leading zeroes
    this._expand(bytesNeeded);

    if (bitsLeft > 0) {
      bytesNeeded--;
    }

    // Handle complete words
    for (var i = 0; i < bytesNeeded; i++) {
      this.words[i] = ~this.words[i] & 0x3ffffff;
    }

    // Handle the residue
    if (bitsLeft > 0) {
      this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
    }

    // And remove leading zeroes
    return this._strip();
  };

  BN.prototype.notn = function notn (width) {
    return this.clone().inotn(width);
  };

  // Set `bit` of `this`
  BN.prototype.setn = function setn (bit, val) {
    assert(typeof bit === 'number' && bit >= 0);

    var off = (bit / 26) | 0;
    var wbit = bit % 26;

    this._expand(off + 1);

    if (val) {
      this.words[off] = this.words[off] | (1 << wbit);
    } else {
      this.words[off] = this.words[off] & ~(1 << wbit);
    }

    return this._strip();
  };

  // Add `num` to `this` in-place
  BN.prototype.iadd = function iadd (num) {
    var r;

    // negative + positive
    if (this.negative !== 0 && num.negative === 0) {
      this.negative = 0;
      r = this.isub(num);
      this.negative ^= 1;
      return this._normSign();

    // positive + negative
    } else if (this.negative === 0 && num.negative !== 0) {
      num.negative = 0;
      r = this.isub(num);
      num.negative = 1;
      return r._normSign();
    }

    // a.length > b.length
    var a, b;
    if (this.length > num.length) {
      a = this;
      b = num;
    } else {
      a = num;
      b = this;
    }

    var carry = 0;
    for (var i = 0; i < b.length; i++) {
      r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
      this.words[i] = r & 0x3ffffff;
      carry = r >>> 26;
    }
    for (; carry !== 0 && i < a.length; i++) {
      r = (a.words[i] | 0) + carry;
      this.words[i] = r & 0x3ffffff;
      carry = r >>> 26;
    }

    this.length = a.length;
    if (carry !== 0) {
      this.words[this.length] = carry;
      this.length++;
    // Copy the rest of the words
    } else if (a !== this) {
      for (; i < a.length; i++) {
        this.words[i] = a.words[i];
      }
    }

    return this;
  };

  // Add `num` to `this`
  BN.prototype.add = function add (num) {
    var res;
    if (num.negative !== 0 && this.negative === 0) {
      num.negative = 0;
      res = this.sub(num);
      num.negative ^= 1;
      return res;
    } else if (num.negative === 0 && this.negative !== 0) {
      this.negative = 0;
      res = num.sub(this);
      this.negative = 1;
      return res;
    }

    if (this.length > num.length) return this.clone().iadd(num);

    return num.clone().iadd(this);
  };

  // Subtract `num` from `this` in-place
  BN.prototype.isub = function isub (num) {
    // this - (-num) = this + num
    if (num.negative !== 0) {
      num.negative = 0;
      var r = this.iadd(num);
      num.negative = 1;
      return r._normSign();

    // -this - num = -(this + num)
    } else if (this.negative !== 0) {
      this.negative = 0;
      this.iadd(num);
      this.negative = 1;
      return this._normSign();
    }

    // At this point both numbers are positive
    var cmp = this.cmp(num);

    // Optimization - zeroify
    if (cmp === 0) {
      this.negative = 0;
      this.length = 1;
      this.words[0] = 0;
      return this;
    }

    // a > b
    var a, b;
    if (cmp > 0) {
      a = this;
      b = num;
    } else {
      a = num;
      b = this;
    }

    var carry = 0;
    for (var i = 0; i < b.length; i++) {
      r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
      carry = r >> 26;
      this.words[i] = r & 0x3ffffff;
    }
    for (; carry !== 0 && i < a.length; i++) {
      r = (a.words[i] | 0) + carry;
      carry = r >> 26;
      this.words[i] = r & 0x3ffffff;
    }

    // Copy rest of the words
    if (carry === 0 && i < a.length && a !== this) {
      for (; i < a.length; i++) {
        this.words[i] = a.words[i];
      }
    }

    this.length = Math.max(this.length, i);

    if (a !== this) {
      this.negative = 1;
    }

    return this._strip();
  };

  // Subtract `num` from `this`
  BN.prototype.sub = function sub (num) {
    return this.clone().isub(num);
  };

  function smallMulTo (self, num, out) {
    out.negative = num.negative ^ self.negative;
    var len = (self.length + num.length) | 0;
    out.length = len;
    len = (len - 1) | 0;

    // Peel one iteration (compiler can't do it, because of code complexity)
    var a = self.words[0] | 0;
    var b = num.words[0] | 0;
    var r = a * b;

    var lo = r & 0x3ffffff;
    var carry = (r / 0x4000000) | 0;
    out.words[0] = lo;

    for (var k = 1; k < len; k++) {
      // Sum all words with the same `i + j = k` and accumulate `ncarry`,
      // note that ncarry could be >= 0x3ffffff
      var ncarry = carry >>> 26;
      var rword = carry & 0x3ffffff;
      var maxJ = Math.min(k, num.length - 1);
      for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
        var i = (k - j) | 0;
        a = self.words[i] | 0;
        b = num.words[j] | 0;
        r = a * b + rword;
        ncarry += (r / 0x4000000) | 0;
        rword = r & 0x3ffffff;
      }
      out.words[k] = rword | 0;
      carry = ncarry | 0;
    }
    if (carry !== 0) {
      out.words[k] = carry | 0;
    } else {
      out.length--;
    }

    return out._strip();
  }

  // TODO(indutny): it may be reasonable to omit it for users who don't need
  // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
  // multiplication (like elliptic secp256k1).
  var comb10MulTo = function comb10MulTo (self, num, out) {
    var a = self.words;
    var b = num.words;
    var o = out.words;
    var c = 0;
    var lo;
    var mid;
    var hi;
    var a0 = a[0] | 0;
    var al0 = a0 & 0x1fff;
    var ah0 = a0 >>> 13;
    var a1 = a[1] | 0;
    var al1 = a1 & 0x1fff;
    var ah1 = a1 >>> 13;
    var a2 = a[2] | 0;
    var al2 = a2 & 0x1fff;
    var ah2 = a2 >>> 13;
    var a3 = a[3] | 0;
    var al3 = a3 & 0x1fff;
    var ah3 = a3 >>> 13;
    var a4 = a[4] | 0;
    var al4 = a4 & 0x1fff;
    var ah4 = a4 >>> 13;
    var a5 = a[5] | 0;
    var al5 = a5 & 0x1fff;
    var ah5 = a5 >>> 13;
    var a6 = a[6] | 0;
    var al6 = a6 & 0x1fff;
    var ah6 = a6 >>> 13;
    var a7 = a[7] | 0;
    var al7 = a7 & 0x1fff;
    var ah7 = a7 >>> 13;
    var a8 = a[8] | 0;
    var al8 = a8 & 0x1fff;
    var ah8 = a8 >>> 13;
    var a9 = a[9] | 0;
    var al9 = a9 & 0x1fff;
    var ah9 = a9 >>> 13;
    var b0 = b[0] | 0;
    var bl0 = b0 & 0x1fff;
    var bh0 = b0 >>> 13;
    var b1 = b[1] | 0;
    var bl1 = b1 & 0x1fff;
    var bh1 = b1 >>> 13;
    var b2 = b[2] | 0;
    var bl2 = b2 & 0x1fff;
    var bh2 = b2 >>> 13;
    var b3 = b[3] | 0;
    var bl3 = b3 & 0x1fff;
    var bh3 = b3 >>> 13;
    var b4 = b[4] | 0;
    var bl4 = b4 & 0x1fff;
    var bh4 = b4 >>> 13;
    var b5 = b[5] | 0;
    var bl5 = b5 & 0x1fff;
    var bh5 = b5 >>> 13;
    var b6 = b[6] | 0;
    var bl6 = b6 & 0x1fff;
    var bh6 = b6 >>> 13;
    var b7 = b[7] | 0;
    var bl7 = b7 & 0x1fff;
    var bh7 = b7 >>> 13;
    var b8 = b[8] | 0;
    var bl8 = b8 & 0x1fff;
    var bh8 = b8 >>> 13;
    var b9 = b[9] | 0;
    var bl9 = b9 & 0x1fff;
    var bh9 = b9 >>> 13;

    out.negative = self.negative ^ num.negative;
    out.length = 19;
    /* k = 0 */
    lo = Math.imul(al0, bl0);
    mid = Math.imul(al0, bh0);
    mid = (mid + Math.imul(ah0, bl0)) | 0;
    hi = Math.imul(ah0, bh0);
    var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
    w0 &= 0x3ffffff;
    /* k = 1 */
    lo = Math.imul(al1, bl0);
    mid = Math.imul(al1, bh0);
    mid = (mid + Math.imul(ah1, bl0)) | 0;
    hi = Math.imul(ah1, bh0);
    lo = (lo + Math.imul(al0, bl1)) | 0;
    mid = (mid + Math.imul(al0, bh1)) | 0;
    mid = (mid + Math.imul(ah0, bl1)) | 0;
    hi = (hi + Math.imul(ah0, bh1)) | 0;
    var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
    w1 &= 0x3ffffff;
    /* k = 2 */
    lo = Math.imul(al2, bl0);
    mid = Math.imul(al2, bh0);
    mid = (mid + Math.imul(ah2, bl0)) | 0;
    hi = Math.imul(ah2, bh0);
    lo = (lo + Math.imul(al1, bl1)) | 0;
    mid = (mid + Math.imul(al1, bh1)) | 0;
    mid = (mid + Math.imul(ah1, bl1)) | 0;
    hi = (hi + Math.imul(ah1, bh1)) | 0;
    lo = (lo + Math.imul(al0, bl2)) | 0;
    mid = (mid + Math.imul(al0, bh2)) | 0;
    mid = (mid + Math.imul(ah0, bl2)) | 0;
    hi = (hi + Math.imul(ah0, bh2)) | 0;
    var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
    w2 &= 0x3ffffff;
    /* k = 3 */
    lo = Math.imul(al3, bl0);
    mid = Math.imul(al3, bh0);
    mid = (mid + Math.imul(ah3, bl0)) | 0;
    hi = Math.imul(ah3, bh0);
    lo = (lo + Math.imul(al2, bl1)) | 0;
    mid = (mid + Math.imul(al2, bh1)) | 0;
    mid = (mid + Math.imul(ah2, bl1)) | 0;
    hi = (hi + Math.imul(ah2, bh1)) | 0;
    lo = (lo + Math.imul(al1, bl2)) | 0;
    mid = (mid + Math.imul(al1, bh2)) | 0;
    mid = (mid + Math.imul(ah1, bl2)) | 0;
    hi = (hi + Math.imul(ah1, bh2)) | 0;
    lo = (lo + Math.imul(al0, bl3)) | 0;
    mid = (mid + Math.imul(al0, bh3)) | 0;
    mid = (mid + Math.imul(ah0, bl3)) | 0;
    hi = (hi + Math.imul(ah0, bh3)) | 0;
    var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
    w3 &= 0x3ffffff;
    /* k = 4 */
    lo = Math.imul(al4, bl0);
    mid = Math.imul(al4, bh0);
    mid = (mid + Math.imul(ah4, bl0)) | 0;
    hi = Math.imul(ah4, bh0);
    lo = (lo + Math.imul(al3, bl1)) | 0;
    mid = (mid + Math.imul(al3, bh1)) | 0;
    mid = (mid + Math.imul(ah3, bl1)) | 0;
    hi = (hi + Math.imul(ah3, bh1)) | 0;
    lo = (lo + Math.imul(al2, bl2)) | 0;
    mid = (mid + Math.imul(al2, bh2)) | 0;
    mid = (mid + Math.imul(ah2, bl2)) | 0;
    hi = (hi + Math.imul(ah2, bh2)) | 0;
    lo = (lo + Math.imul(al1, bl3)) | 0;
    mid = (mid + Math.imul(al1, bh3)) | 0;
    mid = (mid + Math.imul(ah1, bl3)) | 0;
    hi = (hi + Math.imul(ah1, bh3)) | 0;
    lo = (lo + Math.imul(al0, bl4)) | 0;
    mid = (mid + Math.imul(al0, bh4)) | 0;
    mid = (mid + Math.imul(ah0, bl4)) | 0;
    hi = (hi + Math.imul(ah0, bh4)) | 0;
    var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
    w4 &= 0x3ffffff;
    /* k = 5 */
    lo = Math.imul(al5, bl0);
    mid = Math.imul(al5, bh0);
    mid = (mid + Math.imul(ah5, bl0)) | 0;
    hi = Math.imul(ah5, bh0);
    lo = (lo + Math.imul(al4, bl1)) | 0;
    mid = (mid + Math.imul(al4, bh1)) | 0;
    mid = (mid + Math.imul(ah4, bl1)) | 0;
    hi = (hi + Math.imul(ah4, bh1)) | 0;
    lo = (lo + Math.imul(al3, bl2)) | 0;
    mid = (mid + Math.imul(al3, bh2)) | 0;
    mid = (mid + Math.imul(ah3, bl2)) | 0;
    hi = (hi + Math.imul(ah3, bh2)) | 0;
    lo = (lo + Math.imul(al2, bl3)) | 0;
    mid = (mid + Math.imul(al2, bh3)) | 0;
    mid = (mid + Math.imul(ah2, bl3)) | 0;
    hi = (hi + Math.imul(ah2, bh3)) | 0;
    lo = (lo + Math.imul(al1, bl4)) | 0;
    mid = (mid + Math.imul(al1, bh4)) | 0;
    mid = (mid + Math.imul(ah1, bl4)) | 0;
    hi = (hi + Math.imul(ah1, bh4)) | 0;
    lo = (lo + Math.imul(al0, bl5)) | 0;
    mid = (mid + Math.imul(al0, bh5)) | 0;
    mid = (mid + Math.imul(ah0, bl5)) | 0;
    hi = (hi + Math.imul(ah0, bh5)) | 0;
    var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
    w5 &= 0x3ffffff;
    /* k = 6 */
    lo = Math.imul(al6, bl0);
    mid = Math.imul(al6, bh0);
    mid = (mid + Math.imul(ah6, bl0)) | 0;
    hi = Math.imul(ah6, bh0);
    lo = (lo + Math.imul(al5, bl1)) | 0;
    mid = (mid + Math.imul(al5, bh1)) | 0;
    mid = (mid + Math.imul(ah5, bl1)) | 0;
    hi = (hi + Math.imul(ah5, bh1)) | 0;
    lo = (lo + Math.imul(al4, bl2)) | 0;
    mid = (mid + Math.imul(al4, bh2)) | 0;
    mid = (mid + Math.imul(ah4, bl2)) | 0;
    hi = (hi + Math.imul(ah4, bh2)) | 0;
    lo = (lo + Math.imul(al3, bl3)) | 0;
    mid = (mid + Math.imul(al3, bh3)) | 0;
    mid = (mid + Math.imul(ah3, bl3)) | 0;
    hi = (hi + Math.imul(ah3, bh3)) | 0;
    lo = (lo + Math.imul(al2, bl4)) | 0;
    mid = (mid + Math.imul(al2, bh4)) | 0;
    mid = (mid + Math.imul(ah2, bl4)) | 0;
    hi = (hi + Math.imul(ah2, bh4)) | 0;
    lo = (lo + Math.imul(al1, bl5)) | 0;
    mid = (mid + Math.imul(al1, bh5)) | 0;
    mid = (mid + Math.imul(ah1, bl5)) | 0;
    hi = (hi + Math.imul(ah1, bh5)) | 0;
    lo = (lo + Math.imul(al0, bl6)) | 0;
    mid = (mid + Math.imul(al0, bh6)) | 0;
    mid = (mid + Math.imul(ah0, bl6)) | 0;
    hi = (hi + Math.imul(ah0, bh6)) | 0;
    var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
    w6 &= 0x3ffffff;
    /* k = 7 */
    lo = Math.imul(al7, bl0);
    mid = Math.imul(al7, bh0);
    mid = (mid + Math.imul(ah7, bl0)) | 0;
    hi = Math.imul(ah7, bh0);
    lo = (lo + Math.imul(al6, bl1)) | 0;
    mid = (mid + Math.imul(al6, bh1)) | 0;
    mid = (mid + Math.imul(ah6, bl1)) | 0;
    hi = (hi + Math.imul(ah6, bh1)) | 0;
    lo = (lo + Math.imul(al5, bl2)) | 0;
    mid = (mid + Math.imul(al5, bh2)) | 0;
    mid = (mid + Math.imul(ah5, bl2)) | 0;
    hi = (hi + Math.imul(ah5, bh2)) | 0;
    lo = (lo + Math.imul(al4, bl3)) | 0;
    mid = (mid + Math.imul(al4, bh3)) | 0;
    mid = (mid + Math.imul(ah4, bl3)) | 0;
    hi = (hi + Math.imul(ah4, bh3)) | 0;
    lo = (lo + Math.imul(al3, bl4)) | 0;
    mid = (mid + Math.imul(al3, bh4)) | 0;
    mid = (mid + Math.imul(ah3, bl4)) | 0;
    hi = (hi + Math.imul(ah3, bh4)) | 0;
    lo = (lo + Math.imul(al2, bl5)) | 0;
    mid = (mid + Math.imul(al2, bh5)) | 0;
    mid = (mid + Math.imul(ah2, bl5)) | 0;
    hi = (hi + Math.imul(ah2, bh5)) | 0;
    lo = (lo + Math.imul(al1, bl6)) | 0;
    mid = (mid + Math.imul(al1, bh6)) | 0;
    mid = (mid + Math.imul(ah1, bl6)) | 0;
    hi = (hi + Math.imul(ah1, bh6)) | 0;
    lo = (lo + Math.imul(al0, bl7)) | 0;
    mid = (mid + Math.imul(al0, bh7)) | 0;
    mid = (mid + Math.imul(ah0, bl7)) | 0;
    hi = (hi + Math.imul(ah0, bh7)) | 0;
    var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
    w7 &= 0x3ffffff;
    /* k = 8 */
    lo = Math.imul(al8, bl0);
    mid = Math.imul(al8, bh0);
    mid = (mid + Math.imul(ah8, bl0)) | 0;
    hi = Math.imul(ah8, bh0);
    lo = (lo + Math.imul(al7, bl1)) | 0;
    mid = (mid + Math.imul(al7, bh1)) | 0;
    mid = (mid + Math.imul(ah7, bl1)) | 0;
    hi = (hi + Math.imul(ah7, bh1)) | 0;
    lo = (lo + Math.imul(al6, bl2)) | 0;
    mid = (mid + Math.imul(al6, bh2)) | 0;
    mid = (mid + Math.imul(ah6, bl2)) | 0;
    hi = (hi + Math.imul(ah6, bh2)) | 0;
    lo = (lo + Math.imul(al5, bl3)) | 0;
    mid = (mid + Math.imul(al5, bh3)) | 0;
    mid = (mid + Math.imul(ah5, bl3)) | 0;
    hi = (hi + Math.imul(ah5, bh3)) | 0;
    lo = (lo + Math.imul(al4, bl4)) | 0;
    mid = (mid + Math.imul(al4, bh4)) | 0;
    mid = (mid + Math.imul(ah4, bl4)) | 0;
    hi = (hi + Math.imul(ah4, bh4)) | 0;
    lo = (lo + Math.imul(al3, bl5)) | 0;
    mid = (mid + Math.imul(al3, bh5)) | 0;
    mid = (mid + Math.imul(ah3, bl5)) | 0;
    hi = (hi + Math.imul(ah3, bh5)) | 0;
    lo = (lo + Math.imul(al2, bl6)) | 0;
    mid = (mid + Math.imul(al2, bh6)) | 0;
    mid = (mid + Math.imul(ah2, bl6)) | 0;
    hi = (hi + Math.imul(ah2, bh6)) | 0;
    lo = (lo + Math.imul(al1, bl7)) | 0;
    mid = (mid + Math.imul(al1, bh7)) | 0;
    mid = (mid + Math.imul(ah1, bl7)) | 0;
    hi = (hi + Math.imul(ah1, bh7)) | 0;
    lo = (lo + Math.imul(al0, bl8)) | 0;
    mid = (mid + Math.imul(al0, bh8)) | 0;
    mid = (mid + Math.imul(ah0, bl8)) | 0;
    hi = (hi + Math.imul(ah0, bh8)) | 0;
    var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
    w8 &= 0x3ffffff;
    /* k = 9 */
    lo = Math.imul(al9, bl0);
    mid = Math.imul(al9, bh0);
    mid = (mid + Math.imul(ah9, bl0)) | 0;
    hi = Math.imul(ah9, bh0);
    lo = (lo + Math.imul(al8, bl1)) | 0;
    mid = (mid + Math.imul(al8, bh1)) | 0;
    mid = (mid + Math.imul(ah8, bl1)) | 0;
    hi = (hi + Math.imul(ah8, bh1)) | 0;
    lo = (lo + Math.imul(al7, bl2)) | 0;
    mid = (mid + Math.imul(al7, bh2)) | 0;
    mid = (mid + Math.imul(ah7, bl2)) | 0;
    hi = (hi + Math.imul(ah7, bh2)) | 0;
    lo = (lo + Math.imul(al6, bl3)) | 0;
    mid = (mid + Math.imul(al6, bh3)) | 0;
    mid = (mid + Math.imul(ah6, bl3)) | 0;
    hi = (hi + Math.imul(ah6, bh3)) | 0;
    lo = (lo + Math.imul(al5, bl4)) | 0;
    mid = (mid + Math.imul(al5, bh4)) | 0;
    mid = (mid + Math.imul(ah5, bl4)) | 0;
    hi = (hi + Math.imul(ah5, bh4)) | 0;
    lo = (lo + Math.imul(al4, bl5)) | 0;
    mid = (mid + Math.imul(al4, bh5)) | 0;
    mid = (mid + Math.imul(ah4, bl5)) | 0;
    hi = (hi + Math.imul(ah4, bh5)) | 0;
    lo = (lo + Math.imul(al3, bl6)) | 0;
    mid = (mid + Math.imul(al3, bh6)) | 0;
    mid = (mid + Math.imul(ah3, bl6)) | 0;
    hi = (hi + Math.imul(ah3, bh6)) | 0;
    lo = (lo + Math.imul(al2, bl7)) | 0;
    mid = (mid + Math.imul(al2, bh7)) | 0;
    mid = (mid + Math.imul(ah2, bl7)) | 0;
    hi = (hi + Math.imul(ah2, bh7)) | 0;
    lo = (lo + Math.imul(al1, bl8)) | 0;
    mid = (mid + Math.imul(al1, bh8)) | 0;
    mid = (mid + Math.imul(ah1, bl8)) | 0;
    hi = (hi + Math.imul(ah1, bh8)) | 0;
    lo = (lo + Math.imul(al0, bl9)) | 0;
    mid = (mid + Math.imul(al0, bh9)) | 0;
    mid = (mid + Math.imul(ah0, bl9)) | 0;
    hi = (hi + Math.imul(ah0, bh9)) | 0;
    var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
    w9 &= 0x3ffffff;
    /* k = 10 */
    lo = Math.imul(al9, bl1);
    mid = Math.imul(al9, bh1);
    mid = (mid + Math.imul(ah9, bl1)) | 0;
    hi = Math.imul(ah9, bh1);
    lo = (lo + Math.imul(al8, bl2)) | 0;
    mid = (mid + Math.imul(al8, bh2)) | 0;
    mid = (mid + Math.imul(ah8, bl2)) | 0;
    hi = (hi + Math.imul(ah8, bh2)) | 0;
    lo = (lo + Math.imul(al7, bl3)) | 0;
    mid = (mid + Math.imul(al7, bh3)) | 0;
    mid = (mid + Math.imul(ah7, bl3)) | 0;
    hi = (hi + Math.imul(ah7, bh3)) | 0;
    lo = (lo + Math.imul(al6, bl4)) | 0;
    mid = (mid + Math.imul(al6, bh4)) | 0;
    mid = (mid + Math.imul(ah6, bl4)) | 0;
    hi = (hi + Math.imul(ah6, bh4)) | 0;
    lo = (lo + Math.imul(al5, bl5)) | 0;
    mid = (mid + Math.imul(al5, bh5)) | 0;
    mid = (mid + Math.imul(ah5, bl5)) | 0;
    hi = (hi + Math.imul(ah5, bh5)) | 0;
    lo = (lo + Math.imul(al4, bl6)) | 0;
    mid = (mid + Math.imul(al4, bh6)) | 0;
    mid = (mid + Math.imul(ah4, bl6)) | 0;
    hi = (hi + Math.imul(ah4, bh6)) | 0;
    lo = (lo + Math.imul(al3, bl7)) | 0;
    mid = (mid + Math.imul(al3, bh7)) | 0;
    mid = (mid + Math.imul(ah3, bl7)) | 0;
    hi = (hi + Math.imul(ah3, bh7)) | 0;
    lo = (lo + Math.imul(al2, bl8)) | 0;
    mid = (mid + Math.imul(al2, bh8)) | 0;
    mid = (mid + Math.imul(ah2, bl8)) | 0;
    hi = (hi + Math.imul(ah2, bh8)) | 0;
    lo = (lo + Math.imul(al1, bl9)) | 0;
    mid = (mid + Math.imul(al1, bh9)) | 0;
    mid = (mid + Math.imul(ah1, bl9)) | 0;
    hi = (hi + Math.imul(ah1, bh9)) | 0;
    var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
    w10 &= 0x3ffffff;
    /* k = 11 */
    lo = Math.imul(al9, bl2);
    mid = Math.imul(al9, bh2);
    mid = (mid + Math.imul(ah9, bl2)) | 0;
    hi = Math.imul(ah9, bh2);
    lo = (lo + Math.imul(al8, bl3)) | 0;
    mid = (mid + Math.imul(al8, bh3)) | 0;
    mid = (mid + Math.imul(ah8, bl3)) | 0;
    hi = (hi + Math.imul(ah8, bh3)) | 0;
    lo = (lo + Math.imul(al7, bl4)) | 0;
    mid = (mid + Math.imul(al7, bh4)) | 0;
    mid = (mid + Math.imul(ah7, bl4)) | 0;
    hi = (hi + Math.imul(ah7, bh4)) | 0;
    lo = (lo + Math.imul(al6, bl5)) | 0;
    mid = (mid + Math.imul(al6, bh5)) | 0;
    mid = (mid + Math.imul(ah6, bl5)) | 0;
    hi = (hi + Math.imul(ah6, bh5)) | 0;
    lo = (lo + Math.imul(al5, bl6)) | 0;
    mid = (mid + Math.imul(al5, bh6)) | 0;
    mid = (mid + Math.imul(ah5, bl6)) | 0;
    hi = (hi + Math.imul(ah5, bh6)) | 0;
    lo = (lo + Math.imul(al4, bl7)) | 0;
    mid = (mid + Math.imul(al4, bh7)) | 0;
    mid = (mid + Math.imul(ah4, bl7)) | 0;
    hi = (hi + Math.imul(ah4, bh7)) | 0;
    lo = (lo + Math.imul(al3, bl8)) | 0;
    mid = (mid + Math.imul(al3, bh8)) | 0;
    mid = (mid + Math.imul(ah3, bl8)) | 0;
    hi = (hi + Math.imul(ah3, bh8)) | 0;
    lo = (lo + Math.imul(al2, bl9)) | 0;
    mid = (mid + Math.imul(al2, bh9)) | 0;
    mid = (mid + Math.imul(ah2, bl9)) | 0;
    hi = (hi + Math.imul(ah2, bh9)) | 0;
    var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
    w11 &= 0x3ffffff;
    /* k = 12 */
    lo = Math.imul(al9, bl3);
    mid = Math.imul(al9, bh3);
    mid = (mid + Math.imul(ah9, bl3)) | 0;
    hi = Math.imul(ah9, bh3);
    lo = (lo + Math.imul(al8, bl4)) | 0;
    mid = (mid + Math.imul(al8, bh4)) | 0;
    mid = (mid + Math.imul(ah8, bl4)) | 0;
    hi = (hi + Math.imul(ah8, bh4)) | 0;
    lo = (lo + Math.imul(al7, bl5)) | 0;
    mid = (mid + Math.imul(al7, bh5)) | 0;
    mid = (mid + Math.imul(ah7, bl5)) | 0;
    hi = (hi + Math.imul(ah7, bh5)) | 0;
    lo = (lo + Math.imul(al6, bl6)) | 0;
    mid = (mid + Math.imul(al6, bh6)) | 0;
    mid = (mid + Math.imul(ah6, bl6)) | 0;
    hi = (hi + Math.imul(ah6, bh6)) | 0;
    lo = (lo + Math.imul(al5, bl7)) | 0;
    mid = (mid + Math.imul(al5, bh7)) | 0;
    mid = (mid + Math.imul(ah5, bl7)) | 0;
    hi = (hi + Math.imul(ah5, bh7)) | 0;
    lo = (lo + Math.imul(al4, bl8)) | 0;
    mid = (mid + Math.imul(al4, bh8)) | 0;
    mid = (mid + Math.imul(ah4, bl8)) | 0;
    hi = (hi + Math.imul(ah4, bh8)) | 0;
    lo = (lo + Math.imul(al3, bl9)) | 0;
    mid = (mid + Math.imul(al3, bh9)) | 0;
    mid = (mid + Math.imul(ah3, bl9)) | 0;
    hi = (hi + Math.imul(ah3, bh9)) | 0;
    var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
    w12 &= 0x3ffffff;
    /* k = 13 */
    lo = Math.imul(al9, bl4);
    mid = Math.imul(al9, bh4);
    mid = (mid + Math.imul(ah9, bl4)) | 0;
    hi = Math.imul(ah9, bh4);
    lo = (lo + Math.imul(al8, bl5)) | 0;
    mid = (mid + Math.imul(al8, bh5)) | 0;
    mid = (mid + Math.imul(ah8, bl5)) | 0;
    hi = (hi + Math.imul(ah8, bh5)) | 0;
    lo = (lo + Math.imul(al7, bl6)) | 0;
    mid = (mid + Math.imul(al7, bh6)) | 0;
    mid = (mid + Math.imul(ah7, bl6)) | 0;
    hi = (hi + Math.imul(ah7, bh6)) | 0;
    lo = (lo + Math.imul(al6, bl7)) | 0;
    mid = (mid + Math.imul(al6, bh7)) | 0;
    mid = (mid + Math.imul(ah6, bl7)) | 0;
    hi = (hi + Math.imul(ah6, bh7)) | 0;
    lo = (lo + Math.imul(al5, bl8)) | 0;
    mid = (mid + Math.imul(al5, bh8)) | 0;
    mid = (mid + Math.imul(ah5, bl8)) | 0;
    hi = (hi + Math.imul(ah5, bh8)) | 0;
    lo = (lo + Math.imul(al4, bl9)) | 0;
    mid = (mid + Math.imul(al4, bh9)) | 0;
    mid = (mid + Math.imul(ah4, bl9)) | 0;
    hi = (hi + Math.imul(ah4, bh9)) | 0;
    var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
    w13 &= 0x3ffffff;
    /* k = 14 */
    lo = Math.imul(al9, bl5);
    mid = Math.imul(al9, bh5);
    mid = (mid + Math.imul(ah9, bl5)) | 0;
    hi = Math.imul(ah9, bh5);
    lo = (lo + Math.imul(al8, bl6)) | 0;
    mid = (mid + Math.imul(al8, bh6)) | 0;
    mid = (mid + Math.imul(ah8, bl6)) | 0;
    hi = (hi + Math.imul(ah8, bh6)) | 0;
    lo = (lo + Math.imul(al7, bl7)) | 0;
    mid = (mid + Math.imul(al7, bh7)) | 0;
    mid = (mid + Math.imul(ah7, bl7)) | 0;
    hi = (hi + Math.imul(ah7, bh7)) | 0;
    lo = (lo + Math.imul(al6, bl8)) | 0;
    mid = (mid + Math.imul(al6, bh8)) | 0;
    mid = (mid + Math.imul(ah6, bl8)) | 0;
    hi = (hi + Math.imul(ah6, bh8)) | 0;
    lo = (lo + Math.imul(al5, bl9)) | 0;
    mid = (mid + Math.imul(al5, bh9)) | 0;
    mid = (mid + Math.imul(ah5, bl9)) | 0;
    hi = (hi + Math.imul(ah5, bh9)) | 0;
    var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
    w14 &= 0x3ffffff;
    /* k = 15 */
    lo = Math.imul(al9, bl6);
    mid = Math.imul(al9, bh6);
    mid = (mid + Math.imul(ah9, bl6)) | 0;
    hi = Math.imul(ah9, bh6);
    lo = (lo + Math.imul(al8, bl7)) | 0;
    mid = (mid + Math.imul(al8, bh7)) | 0;
    mid = (mid + Math.imul(ah8, bl7)) | 0;
    hi = (hi + Math.imul(ah8, bh7)) | 0;
    lo = (lo + Math.imul(al7, bl8)) | 0;
    mid = (mid + Math.imul(al7, bh8)) | 0;
    mid = (mid + Math.imul(ah7, bl8)) | 0;
    hi = (hi + Math.imul(ah7, bh8)) | 0;
    lo = (lo + Math.imul(al6, bl9)) | 0;
    mid = (mid + Math.imul(al6, bh9)) | 0;
    mid = (mid + Math.imul(ah6, bl9)) | 0;
    hi = (hi + Math.imul(ah6, bh9)) | 0;
    var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
    w15 &= 0x3ffffff;
    /* k = 16 */
    lo = Math.imul(al9, bl7);
    mid = Math.imul(al9, bh7);
    mid = (mid + Math.imul(ah9, bl7)) | 0;
    hi = Math.imul(ah9, bh7);
    lo = (lo + Math.imul(al8, bl8)) | 0;
    mid = (mid + Math.imul(al8, bh8)) | 0;
    mid = (mid + Math.imul(ah8, bl8)) | 0;
    hi = (hi + Math.imul(ah8, bh8)) | 0;
    lo = (lo + Math.imul(al7, bl9)) | 0;
    mid = (mid + Math.imul(al7, bh9)) | 0;
    mid = (mid + Math.imul(ah7, bl9)) | 0;
    hi = (hi + Math.imul(ah7, bh9)) | 0;
    var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
    w16 &= 0x3ffffff;
    /* k = 17 */
    lo = Math.imul(al9, bl8);
    mid = Math.imul(al9, bh8);
    mid = (mid + Math.imul(ah9, bl8)) | 0;
    hi = Math.imul(ah9, bh8);
    lo = (lo + Math.imul(al8, bl9)) | 0;
    mid = (mid + Math.imul(al8, bh9)) | 0;
    mid = (mid + Math.imul(ah8, bl9)) | 0;
    hi = (hi + Math.imul(ah8, bh9)) | 0;
    var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
    w17 &= 0x3ffffff;
    /* k = 18 */
    lo = Math.imul(al9, bl9);
    mid = Math.imul(al9, bh9);
    mid = (mid + Math.imul(ah9, bl9)) | 0;
    hi = Math.imul(ah9, bh9);
    var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
    w18 &= 0x3ffffff;
    o[0] = w0;
    o[1] = w1;
    o[2] = w2;
    o[3] = w3;
    o[4] = w4;
    o[5] = w5;
    o[6] = w6;
    o[7] = w7;
    o[8] = w8;
    o[9] = w9;
    o[10] = w10;
    o[11] = w11;
    o[12] = w12;
    o[13] = w13;
    o[14] = w14;
    o[15] = w15;
    o[16] = w16;
    o[17] = w17;
    o[18] = w18;
    if (c !== 0) {
      o[19] = c;
      out.length++;
    }
    return out;
  };

  // Polyfill comb
  if (!Math.imul) {
    comb10MulTo = smallMulTo;
  }

  function bigMulTo (self, num, out) {
    out.negative = num.negative ^ self.negative;
    out.length = self.length + num.length;

    var carry = 0;
    var hncarry = 0;
    for (var k = 0; k < out.length - 1; k++) {
      // Sum all words with the same `i + j = k` and accumulate `ncarry`,
      // note that ncarry could be >= 0x3ffffff
      var ncarry = hncarry;
      hncarry = 0;
      var rword = carry & 0x3ffffff;
      var maxJ = Math.min(k, num.length - 1);
      for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
        var i = k - j;
        var a = self.words[i] | 0;
        var b = num.words[j] | 0;
        var r = a * b;

        var lo = r & 0x3ffffff;
        ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
        lo = (lo + rword) | 0;
        rword = lo & 0x3ffffff;
        ncarry = (ncarry + (lo >>> 26)) | 0;

        hncarry += ncarry >>> 26;
        ncarry &= 0x3ffffff;
      }
      out.words[k] = rword;
      carry = ncarry;
      ncarry = hncarry;
    }
    if (carry !== 0) {
      out.words[k] = carry;
    } else {
      out.length--;
    }

    return out._strip();
  }

  function jumboMulTo (self, num, out) {
    // Temporary disable, see https://github.com/indutny/bn.js/issues/211
    // var fftm = new FFTM();
    // return fftm.mulp(self, num, out);
    return bigMulTo(self, num, out);
  }

  BN.prototype.mulTo = function mulTo (num, out) {
    var res;
    var len = this.length + num.length;
    if (this.length === 10 && num.length === 10) {
      res = comb10MulTo(this, num, out);
    } else if (len < 63) {
      res = smallMulTo(this, num, out);
    } else if (len < 1024) {
      res = bigMulTo(this, num, out);
    } else {
      res = jumboMulTo(this, num, out);
    }

    return res;
  };

  // Cooley-Tukey algorithm for FFT
  // slightly revisited to rely on looping instead of recursion

  function FFTM (x, y) {
    this.x = x;
    this.y = y;
  }

  FFTM.prototype.makeRBT = function makeRBT (N) {
    var t = new Array(N);
    var l = BN.prototype._countBits(N) - 1;
    for (var i = 0; i < N; i++) {
      t[i] = this.revBin(i, l, N);
    }

    return t;
  };

  // Returns binary-reversed representation of `x`
  FFTM.prototype.revBin = function revBin (x, l, N) {
    if (x === 0 || x === N - 1) return x;

    var rb = 0;
    for (var i = 0; i < l; i++) {
      rb |= (x & 1) << (l - i - 1);
      x >>= 1;
    }

    return rb;
  };

  // Performs "tweedling" phase, therefore 'emulating'
  // behaviour of the recursive algorithm
  FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
    for (var i = 0; i < N; i++) {
      rtws[i] = rws[rbt[i]];
      itws[i] = iws[rbt[i]];
    }
  };

  FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
    this.permute(rbt, rws, iws, rtws, itws, N);

    for (var s = 1; s < N; s <<= 1) {
      var l = s << 1;

      var rtwdf = Math.cos(2 * Math.PI / l);
      var itwdf = Math.sin(2 * Math.PI / l);

      for (var p = 0; p < N; p += l) {
        var rtwdf_ = rtwdf;
        var itwdf_ = itwdf;

        for (var j = 0; j < s; j++) {
          var re = rtws[p + j];
          var ie = itws[p + j];

          var ro = rtws[p + j + s];
          var io = itws[p + j + s];

          var rx = rtwdf_ * ro - itwdf_ * io;

          io = rtwdf_ * io + itwdf_ * ro;
          ro = rx;

          rtws[p + j] = re + ro;
          itws[p + j] = ie + io;

          rtws[p + j + s] = re - ro;
          itws[p + j + s] = ie - io;

          /* jshint maxdepth : false */
          if (j !== l) {
            rx = rtwdf * rtwdf_ - itwdf * itwdf_;

            itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
            rtwdf_ = rx;
          }
        }
      }
    }
  };

  FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
    var N = Math.max(m, n) | 1;
    var odd = N & 1;
    var i = 0;
    for (N = N / 2 | 0; N; N = N >>> 1) {
      i++;
    }

    return 1 << i + 1 + odd;
  };

  FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
    if (N <= 1) return;

    for (var i = 0; i < N / 2; i++) {
      var t = rws[i];

      rws[i] = rws[N - i - 1];
      rws[N - i - 1] = t;

      t = iws[i];

      iws[i] = -iws[N - i - 1];
      iws[N - i - 1] = -t;
    }
  };

  FFTM.prototype.normalize13b = function normalize13b (ws, N) {
    var carry = 0;
    for (var i = 0; i < N / 2; i++) {
      var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
        Math.round(ws[2 * i] / N) +
        carry;

      ws[i] = w & 0x3ffffff;

      if (w < 0x4000000) {
        carry = 0;
      } else {
        carry = w / 0x4000000 | 0;
      }
    }

    return ws;
  };

  FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
    var carry = 0;
    for (var i = 0; i < len; i++) {
      carry = carry + (ws[i] | 0);

      rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
      rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
    }

    // Pad with zeroes
    for (i = 2 * len; i < N; ++i) {
      rws[i] = 0;
    }

    assert(carry === 0);
    assert((carry & ~0x1fff) === 0);
  };

  FFTM.prototype.stub = function stub (N) {
    var ph = new Array(N);
    for (var i = 0; i < N; i++) {
      ph[i] = 0;
    }

    return ph;
  };

  FFTM.prototype.mulp = function mulp (x, y, out) {
    var N = 2 * this.guessLen13b(x.length, y.length);

    var rbt = this.makeRBT(N);

    var _ = this.stub(N);

    var rws = new Array(N);
    var rwst = new Array(N);
    var iwst = new Array(N);

    var nrws = new Array(N);
    var nrwst = new Array(N);
    var niwst = new Array(N);

    var rmws = out.words;
    rmws.length = N;

    this.convert13b(x.words, x.length, rws, N);
    this.convert13b(y.words, y.length, nrws, N);

    this.transform(rws, _, rwst, iwst, N, rbt);
    this.transform(nrws, _, nrwst, niwst, N, rbt);

    for (var i = 0; i < N; i++) {
      var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
      iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
      rwst[i] = rx;
    }

    this.conjugate(rwst, iwst, N);
    this.transform(rwst, iwst, rmws, _, N, rbt);
    this.conjugate(rmws, _, N);
    this.normalize13b(rmws, N);

    out.negative = x.negative ^ y.negative;
    out.length = x.length + y.length;
    return out._strip();
  };

  // Multiply `this` by `num`
  BN.prototype.mul = function mul (num) {
    var out = new BN(null);
    out.words = new Array(this.length + num.length);
    return this.mulTo(num, out);
  };

  // Multiply employing FFT
  BN.prototype.mulf = function mulf (num) {
    var out = new BN(null);
    out.words = new Array(this.length + num.length);
    return jumboMulTo(this, num, out);
  };

  // In-place Multiplication
  BN.prototype.imul = function imul (num) {
    return this.clone().mulTo(num, this);
  };

  BN.prototype.imuln = function imuln (num) {
    var isNegNum = num < 0;
    if (isNegNum) num = -num;

    assert(typeof num === 'number');
    assert(num < 0x4000000);

    // Carry
    var carry = 0;
    for (var i = 0; i < this.length; i++) {
      var w = (this.words[i] | 0) * num;
      var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
      carry >>= 26;
      carry += (w / 0x4000000) | 0;
      // NOTE: lo is 27bit maximum
      carry += lo >>> 26;
      this.words[i] = lo & 0x3ffffff;
    }

    if (carry !== 0) {
      this.words[i] = carry;
      this.length++;
    }

    return isNegNum ? this.ineg() : this;
  };

  BN.prototype.muln = function muln (num) {
    return this.clone().imuln(num);
  };

  // `this` * `this`
  BN.prototype.sqr = function sqr () {
    return this.mul(this);
  };

  // `this` * `this` in-place
  BN.prototype.isqr = function isqr () {
    return this.imul(this.clone());
  };

  // Math.pow(`this`, `num`)
  BN.prototype.pow = function pow (num) {
    var w = toBitArray(num);
    if (w.length === 0) return new BN(1);

    // Skip leading zeroes
    var res = this;
    for (var i = 0; i < w.length; i++, res = res.sqr()) {
      if (w[i] !== 0) break;
    }

    if (++i < w.length) {
      for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
        if (w[i] === 0) continue;

        res = res.mul(q);
      }
    }

    return res;
  };

  // Shift-left in-place
  BN.prototype.iushln = function iushln (bits) {
    assert(typeof bits === 'number' && bits >= 0);
    var r = bits % 26;
    var s = (bits - r) / 26;
    var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
    var i;

    if (r !== 0) {
      var carry = 0;

      for (i = 0; i < this.length; i++) {
        var newCarry = this.words[i] & carryMask;
        var c = ((this.words[i] | 0) - newCarry) << r;
        this.words[i] = c | carry;
        carry = newCarry >>> (26 - r);
      }

      if (carry) {
        this.words[i] = carry;
        this.length++;
      }
    }

    if (s !== 0) {
      for (i = this.length - 1; i >= 0; i--) {
        this.words[i + s] = this.words[i];
      }

      for (i = 0; i < s; i++) {
        this.words[i] = 0;
      }

      this.length += s;
    }

    return this._strip();
  };

  BN.prototype.ishln = function ishln (bits) {
    // TODO(indutny): implement me
    assert(this.negative === 0);
    return this.iushln(bits);
  };

  // Shift-right in-place
  // NOTE: `hint` is a lowest bit before trailing zeroes
  // NOTE: if `extended` is present - it will be filled with destroyed bits
  BN.prototype.iushrn = function iushrn (bits, hint, extended) {
    assert(typeof bits === 'number' && bits >= 0);
    var h;
    if (hint) {
      h = (hint - (hint % 26)) / 26;
    } else {
      h = 0;
    }

    var r = bits % 26;
    var s = Math.min((bits - r) / 26, this.length);
    var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
    var maskedWords = extended;

    h -= s;
    h = Math.max(0, h);

    // Extended mode, copy masked part
    if (maskedWords) {
      for (var i = 0; i < s; i++) {
        maskedWords.words[i] = this.words[i];
      }
      maskedWords.length = s;
    }

    if (s === 0) {
      // No-op, we should not move anything at all
    } else if (this.length > s) {
      this.length -= s;
      for (i = 0; i < this.length; i++) {
        this.words[i] = this.words[i + s];
      }
    } else {
      this.words[0] = 0;
      this.length = 1;
    }

    var carry = 0;
    for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
      var word = this.words[i] | 0;
      this.words[i] = (carry << (26 - r)) | (word >>> r);
      carry = word & mask;
    }

    // Push carried bits as a mask
    if (maskedWords && carry !== 0) {
      maskedWords.words[maskedWords.length++] = carry;
    }

    if (this.length === 0) {
      this.words[0] = 0;
      this.length = 1;
    }

    return this._strip();
  };

  BN.prototype.ishrn = function ishrn (bits, hint, extended) {
    // TODO(indutny): implement me
    assert(this.negative === 0);
    return this.iushrn(bits, hint, extended);
  };

  // Shift-left
  BN.prototype.shln = function shln (bits) {
    return this.clone().ishln(bits);
  };

  BN.prototype.ushln = function ushln (bits) {
    return this.clone().iushln(bits);
  };

  // Shift-right
  BN.prototype.shrn = function shrn (bits) {
    return this.clone().ishrn(bits);
  };

  BN.prototype.ushrn = function ushrn (bits) {
    return this.clone().iushrn(bits);
  };

  // Test if n bit is set
  BN.prototype.testn = function testn (bit) {
    assert(typeof bit === 'number' && bit >= 0);
    var r = bit % 26;
    var s = (bit - r) / 26;
    var q = 1 << r;

    // Fast case: bit is much higher than all existing words
    if (this.length <= s) return false;

    // Check bit and return
    var w = this.words[s];

    return !!(w & q);
  };

  // Return only lowers bits of number (in-place)
  BN.prototype.imaskn = function imaskn (bits) {
    assert(typeof bits === 'number' && bits >= 0);
    var r = bits % 26;
    var s = (bits - r) / 26;

    assert(this.negative === 0, 'imaskn works only with positive numbers');

    if (this.length <= s) {
      return this;
    }

    if (r !== 0) {
      s++;
    }
    this.length = Math.min(s, this.length);

    if (r !== 0) {
      var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
      this.words[this.length - 1] &= mask;
    }

    return this._strip();
  };

  // Return only lowers bits of number
  BN.prototype.maskn = function maskn (bits) {
    return this.clone().imaskn(bits);
  };

  // Add plain number `num` to `this`
  BN.prototype.iaddn = function iaddn (num) {
    assert(typeof num === 'number');
    assert(num < 0x4000000);
    if (num < 0) return this.isubn(-num);

    // Possible sign change
    if (this.negative !== 0) {
      if (this.length === 1 && (this.words[0] | 0) <= num) {
        this.words[0] = num - (this.words[0] | 0);
        this.negative = 0;
        return this;
      }

      this.negative = 0;
      this.isubn(num);
      this.negative = 1;
      return this;
    }

    // Add without checks
    return this._iaddn(num);
  };

  BN.prototype._iaddn = function _iaddn (num) {
    this.words[0] += num;

    // Carry
    for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
      this.words[i] -= 0x4000000;
      if (i === this.length - 1) {
        this.words[i + 1] = 1;
      } else {
        this.words[i + 1]++;
      }
    }
    this.length = Math.max(this.length, i + 1);

    return this;
  };

  // Subtract plain number `num` from `this`
  BN.prototype.isubn = function isubn (num) {
    assert(typeof num === 'number');
    assert(num < 0x4000000);
    if (num < 0) return this.iaddn(-num);

    if (this.negative !== 0) {
      this.negative = 0;
      this.iaddn(num);
      this.negative = 1;
      return this;
    }

    this.words[0] -= num;

    if (this.length === 1 && this.words[0] < 0) {
      this.words[0] = -this.words[0];
      this.negative = 1;
    } else {
      // Carry
      for (var i = 0; i < this.length && this.words[i] < 0; i++) {
        this.words[i] += 0x4000000;
        this.words[i + 1] -= 1;
      }
    }

    return this._strip();
  };

  BN.prototype.addn = function addn (num) {
    return this.clone().iaddn(num);
  };

  BN.prototype.subn = function subn (num) {
    return this.clone().isubn(num);
  };

  BN.prototype.iabs = function iabs () {
    this.negative = 0;

    return this;
  };

  BN.prototype.abs = function abs () {
    return this.clone().iabs();
  };

  BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
    var len = num.length + shift;
    var i;

    this._expand(len);

    var w;
    var carry = 0;
    for (i = 0; i < num.length; i++) {
      w = (this.words[i + shift] | 0) + carry;
      var right = (num.words[i] | 0) * mul;
      w -= right & 0x3ffffff;
      carry = (w >> 26) - ((right / 0x4000000) | 0);
      this.words[i + shift] = w & 0x3ffffff;
    }
    for (; i < this.length - shift; i++) {
      w = (this.words[i + shift] | 0) + carry;
      carry = w >> 26;
      this.words[i + shift] = w & 0x3ffffff;
    }

    if (carry === 0) return this._strip();

    // Subtraction overflow
    assert(carry === -1);
    carry = 0;
    for (i = 0; i < this.length; i++) {
      w = -(this.words[i] | 0) + carry;
      carry = w >> 26;
      this.words[i] = w & 0x3ffffff;
    }
    this.negative = 1;

    return this._strip();
  };

  BN.prototype._wordDiv = function _wordDiv (num, mode) {
    var shift = this.length - num.length;

    var a = this.clone();
    var b = num;

    // Normalize
    var bhi = b.words[b.length - 1] | 0;
    var bhiBits = this._countBits(bhi);
    shift = 26 - bhiBits;
    if (shift !== 0) {
      b = b.ushln(shift);
      a.iushln(shift);
      bhi = b.words[b.length - 1] | 0;
    }

    // Initialize quotient
    var m = a.length - b.length;
    var q;

    if (mode !== 'mod') {
      q = new BN(null);
      q.length = m + 1;
      q.words = new Array(q.length);
      for (var i = 0; i < q.length; i++) {
        q.words[i] = 0;
      }
    }

    var diff = a.clone()._ishlnsubmul(b, 1, m);
    if (diff.negative === 0) {
      a = diff;
      if (q) {
        q.words[m] = 1;
      }
    }

    for (var j = m - 1; j >= 0; j--) {
      var qj = (a.words[b.length + j] | 0) * 0x4000000 +
        (a.words[b.length + j - 1] | 0);

      // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
      // (0x7ffffff)
      qj = Math.min((qj / bhi) | 0, 0x3ffffff);

      a._ishlnsubmul(b, qj, j);
      while (a.negative !== 0) {
        qj--;
        a.negative = 0;
        a._ishlnsubmul(b, 1, j);
        if (!a.isZero()) {
          a.negative ^= 1;
        }
      }
      if (q) {
        q.words[j] = qj;
      }
    }
    if (q) {
      q._strip();
    }
    a._strip();

    // Denormalize
    if (mode !== 'div' && shift !== 0) {
      a.iushrn(shift);
    }

    return {
      div: q || null,
      mod: a
    };
  };

  // NOTE: 1) `mode` can be set to `mod` to request mod only,
  //       to `div` to request div only, or be absent to
  //       request both div & mod
  //       2) `positive` is true if unsigned mod is requested
  BN.prototype.divmod = function divmod (num, mode, positive) {
    assert(!num.isZero());

    if (this.isZero()) {
      return {
        div: new BN(0),
        mod: new BN(0)
      };
    }

    var div, mod, res;
    if (this.negative !== 0 && num.negative === 0) {
      res = this.neg().divmod(num, mode);

      if (mode !== 'mod') {
        div = res.div.neg();
      }

      if (mode !== 'div') {
        mod = res.mod.neg();
        if (positive && mod.negative !== 0) {
          mod.iadd(num);
        }
      }

      return {
        div: div,
        mod: mod
      };
    }

    if (this.negative === 0 && num.negative !== 0) {
      res = this.divmod(num.neg(), mode);

      if (mode !== 'mod') {
        div = res.div.neg();
      }

      return {
        div: div,
        mod: res.mod
      };
    }

    if ((this.negative & num.negative) !== 0) {
      res = this.neg().divmod(num.neg(), mode);

      if (mode !== 'div') {
        mod = res.mod.neg();
        if (positive && mod.negative !== 0) {
          mod.isub(num);
        }
      }

      return {
        div: res.div,
        mod: mod
      };
    }

    // Both numbers are positive at this point

    // Strip both numbers to approximate shift value
    if (num.length > this.length || this.cmp(num) < 0) {
      return {
        div: new BN(0),
        mod: this
      };
    }

    // Very short reduction
    if (num.length === 1) {
      if (mode === 'div') {
        return {
          div: this.divn(num.words[0]),
          mod: null
        };
      }

      if (mode === 'mod') {
        return {
          div: null,
          mod: new BN(this.modrn(num.words[0]))
        };
      }

      return {
        div: this.divn(num.words[0]),
        mod: new BN(this.modrn(num.words[0]))
      };
    }

    return this._wordDiv(num, mode);
  };

  // Find `this` / `num`
  BN.prototype.div = function div (num) {
    return this.divmod(num, 'div', false).div;
  };

  // Find `this` % `num`
  BN.prototype.mod = function mod (num) {
    return this.divmod(num, 'mod', false).mod;
  };

  BN.prototype.umod = function umod (num) {
    return this.divmod(num, 'mod', true).mod;
  };

  // Find Round(`this` / `num`)
  BN.prototype.divRound = function divRound (num) {
    var dm = this.divmod(num);

    // Fast case - exact division
    if (dm.mod.isZero()) return dm.div;

    var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;

    var half = num.ushrn(1);
    var r2 = num.andln(1);
    var cmp = mod.cmp(half);

    // Round down
    if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div;

    // Round up
    return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
  };

  BN.prototype.modrn = function modrn (num) {
    var isNegNum = num < 0;
    if (isNegNum) num = -num;

    assert(num <= 0x3ffffff);
    var p = (1 << 26) % num;

    var acc = 0;
    for (var i = this.length - 1; i >= 0; i--) {
      acc = (p * acc + (this.words[i] | 0)) % num;
    }

    return isNegNum ? -acc : acc;
  };

  // WARNING: DEPRECATED
  BN.prototype.modn = function modn (num) {
    return this.modrn(num);
  };

  // In-place division by number
  BN.prototype.idivn = function idivn (num) {
    var isNegNum = num < 0;
    if (isNegNum) num = -num;

    assert(num <= 0x3ffffff);

    var carry = 0;
    for (var i = this.length - 1; i >= 0; i--) {
      var w = (this.words[i] | 0) + carry * 0x4000000;
      this.words[i] = (w / num) | 0;
      carry = w % num;
    }

    this._strip();
    return isNegNum ? this.ineg() : this;
  };

  BN.prototype.divn = function divn (num) {
    return this.clone().idivn(num);
  };

  BN.prototype.egcd = function egcd (p) {
    assert(p.negative === 0);
    assert(!p.isZero());

    var x = this;
    var y = p.clone();

    if (x.negative !== 0) {
      x = x.umod(p);
    } else {
      x = x.clone();
    }

    // A * x + B * y = x
    var A = new BN(1);
    var B = new BN(0);

    // C * x + D * y = y
    var C = new BN(0);
    var D = new BN(1);

    var g = 0;

    while (x.isEven() && y.isEven()) {
      x.iushrn(1);
      y.iushrn(1);
      ++g;
    }

    var yp = y.clone();
    var xp = x.clone();

    while (!x.isZero()) {
      for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
      if (i > 0) {
        x.iushrn(i);
        while (i-- > 0) {
          if (A.isOdd() || B.isOdd()) {
            A.iadd(yp);
            B.isub(xp);
          }

          A.iushrn(1);
          B.iushrn(1);
        }
      }

      for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
      if (j > 0) {
        y.iushrn(j);
        while (j-- > 0) {
          if (C.isOdd() || D.isOdd()) {
            C.iadd(yp);
            D.isub(xp);
          }

          C.iushrn(1);
          D.iushrn(1);
        }
      }

      if (x.cmp(y) >= 0) {
        x.isub(y);
        A.isub(C);
        B.isub(D);
      } else {
        y.isub(x);
        C.isub(A);
        D.isub(B);
      }
    }

    return {
      a: C,
      b: D,
      gcd: y.iushln(g)
    };
  };

  // This is reduced incarnation of the binary EEA
  // above, designated to invert members of the
  // _prime_ fields F(p) at a maximal speed
  BN.prototype._invmp = function _invmp (p) {
    assert(p.negative === 0);
    assert(!p.isZero());

    var a = this;
    var b = p.clone();

    if (a.negative !== 0) {
      a = a.umod(p);
    } else {
      a = a.clone();
    }

    var x1 = new BN(1);
    var x2 = new BN(0);

    var delta = b.clone();

    while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
      for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
      if (i > 0) {
        a.iushrn(i);
        while (i-- > 0) {
          if (x1.isOdd()) {
            x1.iadd(delta);
          }

          x1.iushrn(1);
        }
      }

      for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
      if (j > 0) {
        b.iushrn(j);
        while (j-- > 0) {
          if (x2.isOdd()) {
            x2.iadd(delta);
          }

          x2.iushrn(1);
        }
      }

      if (a.cmp(b) >= 0) {
        a.isub(b);
        x1.isub(x2);
      } else {
        b.isub(a);
        x2.isub(x1);
      }
    }

    var res;
    if (a.cmpn(1) === 0) {
      res = x1;
    } else {
      res = x2;
    }

    if (res.cmpn(0) < 0) {
      res.iadd(p);
    }

    return res;
  };

  BN.prototype.gcd = function gcd (num) {
    if (this.isZero()) return num.abs();
    if (num.isZero()) return this.abs();

    var a = this.clone();
    var b = num.clone();
    a.negative = 0;
    b.negative = 0;

    // Remove common factor of two
    for (var shift = 0; a.isEven() && b.isEven(); shift++) {
      a.iushrn(1);
      b.iushrn(1);
    }

    do {
      while (a.isEven()) {
        a.iushrn(1);
      }
      while (b.isEven()) {
        b.iushrn(1);
      }

      var r = a.cmp(b);
      if (r < 0) {
        // Swap `a` and `b` to make `a` always bigger than `b`
        var t = a;
        a = b;
        b = t;
      } else if (r === 0 || b.cmpn(1) === 0) {
        break;
      }

      a.isub(b);
    } while (true);

    return b.iushln(shift);
  };

  // Invert number in the field F(num)
  BN.prototype.invm = function invm (num) {
    return this.egcd(num).a.umod(num);
  };

  BN.prototype.isEven = function isEven () {
    return (this.words[0] & 1) === 0;
  };

  BN.prototype.isOdd = function isOdd () {
    return (this.words[0] & 1) === 1;
  };

  // And first word and num
  BN.prototype.andln = function andln (num) {
    return this.words[0] & num;
  };

  // Increment at the bit position in-line
  BN.prototype.bincn = function bincn (bit) {
    assert(typeof bit === 'number');
    var r = bit % 26;
    var s = (bit - r) / 26;
    var q = 1 << r;

    // Fast case: bit is much higher than all existing words
    if (this.length <= s) {
      this._expand(s + 1);
      this.words[s] |= q;
      return this;
    }

    // Add bit and propagate, if needed
    var carry = q;
    for (var i = s; carry !== 0 && i < this.length; i++) {
      var w = this.words[i] | 0;
      w += carry;
      carry = w >>> 26;
      w &= 0x3ffffff;
      this.words[i] = w;
    }
    if (carry !== 0) {
      this.words[i] = carry;
      this.length++;
    }
    return this;
  };

  BN.prototype.isZero = function isZero () {
    return this.length === 1 && this.words[0] === 0;
  };

  BN.prototype.cmpn = function cmpn (num) {
    var negative = num < 0;

    if (this.negative !== 0 && !negative) return -1;
    if (this.negative === 0 && negative) return 1;

    this._strip();

    var res;
    if (this.length > 1) {
      res = 1;
    } else {
      if (negative) {
        num = -num;
      }

      assert(num <= 0x3ffffff, 'Number is too big');

      var w = this.words[0] | 0;
      res = w === num ? 0 : w < num ? -1 : 1;
    }
    if (this.negative !== 0) return -res | 0;
    return res;
  };

  // Compare two numbers and return:
  // 1 - if `this` > `num`
  // 0 - if `this` == `num`
  // -1 - if `this` < `num`
  BN.prototype.cmp = function cmp (num) {
    if (this.negative !== 0 && num.negative === 0) return -1;
    if (this.negative === 0 && num.negative !== 0) return 1;

    var res = this.ucmp(num);
    if (this.negative !== 0) return -res | 0;
    return res;
  };

  // Unsigned comparison
  BN.prototype.ucmp = function ucmp (num) {
    // At this point both numbers have the same sign
    if (this.length > num.length) return 1;
    if (this.length < num.length) return -1;

    var res = 0;
    for (var i = this.length - 1; i >= 0; i--) {
      var a = this.words[i] | 0;
      var b = num.words[i] | 0;

      if (a === b) continue;
      if (a < b) {
        res = -1;
      } else if (a > b) {
        res = 1;
      }
      break;
    }
    return res;
  };

  BN.prototype.gtn = function gtn (num) {
    return this.cmpn(num) === 1;
  };

  BN.prototype.gt = function gt (num) {
    return this.cmp(num) === 1;
  };

  BN.prototype.gten = function gten (num) {
    return this.cmpn(num) >= 0;
  };

  BN.prototype.gte = function gte (num) {
    return this.cmp(num) >= 0;
  };

  BN.prototype.ltn = function ltn (num) {
    return this.cmpn(num) === -1;
  };

  BN.prototype.lt = function lt (num) {
    return this.cmp(num) === -1;
  };

  BN.prototype.lten = function lten (num) {
    return this.cmpn(num) <= 0;
  };

  BN.prototype.lte = function lte (num) {
    return this.cmp(num) <= 0;
  };

  BN.prototype.eqn = function eqn (num) {
    return this.cmpn(num) === 0;
  };

  BN.prototype.eq = function eq (num) {
    return this.cmp(num) === 0;
  };

  //
  // A reduce context, could be using montgomery or something better, depending
  // on the `m` itself.
  //
  BN.red = function red (num) {
    return new Red(num);
  };

  BN.prototype.toRed = function toRed (ctx) {
    assert(!this.red, 'Already a number in reduction context');
    assert(this.negative === 0, 'red works only with positives');
    return ctx.convertTo(this)._forceRed(ctx);
  };

  BN.prototype.fromRed = function fromRed () {
    assert(this.red, 'fromRed works only with numbers in reduction context');
    return this.red.convertFrom(this);
  };

  BN.prototype._forceRed = function _forceRed (ctx) {
    this.red = ctx;
    return this;
  };

  BN.prototype.forceRed = function forceRed (ctx) {
    assert(!this.red, 'Already a number in reduction context');
    return this._forceRed(ctx);
  };

  BN.prototype.redAdd = function redAdd (num) {
    assert(this.red, 'redAdd works only with red numbers');
    return this.red.add(this, num);
  };

  BN.prototype.redIAdd = function redIAdd (num) {
    assert(this.red, 'redIAdd works only with red numbers');
    return this.red.iadd(this, num);
  };

  BN.prototype.redSub = function redSub (num) {
    assert(this.red, 'redSub works only with red numbers');
    return this.red.sub(this, num);
  };

  BN.prototype.redISub = function redISub (num) {
    assert(this.red, 'redISub works only with red numbers');
    return this.red.isub(this, num);
  };

  BN.prototype.redShl = function redShl (num) {
    assert(this.red, 'redShl works only with red numbers');
    return this.red.shl(this, num);
  };

  BN.prototype.redMul = function redMul (num) {
    assert(this.red, 'redMul works only with red numbers');
    this.red._verify2(this, num);
    return this.red.mul(this, num);
  };

  BN.prototype.redIMul = function redIMul (num) {
    assert(this.red, 'redMul works only with red numbers');
    this.red._verify2(this, num);
    return this.red.imul(this, num);
  };

  BN.prototype.redSqr = function redSqr () {
    assert(this.red, 'redSqr works only with red numbers');
    this.red._verify1(this);
    return this.red.sqr(this);
  };

  BN.prototype.redISqr = function redISqr () {
    assert(this.red, 'redISqr works only with red numbers');
    this.red._verify1(this);
    return this.red.isqr(this);
  };

  // Square root over p
  BN.prototype.redSqrt = function redSqrt () {
    assert(this.red, 'redSqrt works only with red numbers');
    this.red._verify1(this);
    return this.red.sqrt(this);
  };

  BN.prototype.redInvm = function redInvm () {
    assert(this.red, 'redInvm works only with red numbers');
    this.red._verify1(this);
    return this.red.invm(this);
  };

  // Return negative clone of `this` % `red modulo`
  BN.prototype.redNeg = function redNeg () {
    assert(this.red, 'redNeg works only with red numbers');
    this.red._verify1(this);
    return this.red.neg(this);
  };

  BN.prototype.redPow = function redPow (num) {
    assert(this.red && !num.red, 'redPow(normalNum)');
    this.red._verify1(this);
    return this.red.pow(this, num);
  };

  // Prime numbers with efficient reduction
  var primes = {
    k256: null,
    p224: null,
    p192: null,
    p25519: null
  };

  // Pseudo-Mersenne prime
  function MPrime (name, p) {
    // P = 2 ^ N - K
    this.name = name;
    this.p = new BN(p, 16);
    this.n = this.p.bitLength();
    this.k = new BN(1).iushln(this.n).isub(this.p);

    this.tmp = this._tmp();
  }

  MPrime.prototype._tmp = function _tmp () {
    var tmp = new BN(null);
    tmp.words = new Array(Math.ceil(this.n / 13));
    return tmp;
  };

  MPrime.prototype.ireduce = function ireduce (num) {
    // Assumes that `num` is less than `P^2`
    // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
    var r = num;
    var rlen;

    do {
      this.split(r, this.tmp);
      r = this.imulK(r);
      r = r.iadd(this.tmp);
      rlen = r.bitLength();
    } while (rlen > this.n);

    var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
    if (cmp === 0) {
      r.words[0] = 0;
      r.length = 1;
    } else if (cmp > 0) {
      r.isub(this.p);
    } else {
      if (r.strip !== undefined) {
        // r is a BN v4 instance
        r.strip();
      } else {
        // r is a BN v5 instance
        r._strip();
      }
    }

    return r;
  };

  MPrime.prototype.split = function split (input, out) {
    input.iushrn(this.n, 0, out);
  };

  MPrime.prototype.imulK = function imulK (num) {
    return num.imul(this.k);
  };

  function K256 () {
    MPrime.call(
      this,
      'k256',
      'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
  }
  inherits(K256, MPrime);

  K256.prototype.split = function split (input, output) {
    // 256 = 9 * 26 + 22
    var mask = 0x3fffff;

    var outLen = Math.min(input.length, 9);
    for (var i = 0; i < outLen; i++) {
      output.words[i] = input.words[i];
    }
    output.length = outLen;

    if (input.length <= 9) {
      input.words[0] = 0;
      input.length = 1;
      return;
    }

    // Shift by 9 limbs
    var prev = input.words[9];
    output.words[output.length++] = prev & mask;

    for (i = 10; i < input.length; i++) {
      var next = input.words[i] | 0;
      input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
      prev = next;
    }
    prev >>>= 22;
    input.words[i - 10] = prev;
    if (prev === 0 && input.length > 10) {
      input.length -= 10;
    } else {
      input.length -= 9;
    }
  };

  K256.prototype.imulK = function imulK (num) {
    // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
    num.words[num.length] = 0;
    num.words[num.length + 1] = 0;
    num.length += 2;

    // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
    var lo = 0;
    for (var i = 0; i < num.length; i++) {
      var w = num.words[i] | 0;
      lo += w * 0x3d1;
      num.words[i] = lo & 0x3ffffff;
      lo = w * 0x40 + ((lo / 0x4000000) | 0);
    }

    // Fast length reduction
    if (num.words[num.length - 1] === 0) {
      num.length--;
      if (num.words[num.length - 1] === 0) {
        num.length--;
      }
    }
    return num;
  };

  function P224 () {
    MPrime.call(
      this,
      'p224',
      'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
  }
  inherits(P224, MPrime);

  function P192 () {
    MPrime.call(
      this,
      'p192',
      'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
  }
  inherits(P192, MPrime);

  function P25519 () {
    // 2 ^ 255 - 19
    MPrime.call(
      this,
      '25519',
      '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
  }
  inherits(P25519, MPrime);

  P25519.prototype.imulK = function imulK (num) {
    // K = 0x13
    var carry = 0;
    for (var i = 0; i < num.length; i++) {
      var hi = (num.words[i] | 0) * 0x13 + carry;
      var lo = hi & 0x3ffffff;
      hi >>>= 26;

      num.words[i] = lo;
      carry = hi;
    }
    if (carry !== 0) {
      num.words[num.length++] = carry;
    }
    return num;
  };

  // Exported mostly for testing purposes, use plain name instead
  BN._prime = function prime (name) {
    // Cached version of prime
    if (primes[name]) return primes[name];

    var prime;
    if (name === 'k256') {
      prime = new K256();
    } else if (name === 'p224') {
      prime = new P224();
    } else if (name === 'p192') {
      prime = new P192();
    } else if (name === 'p25519') {
      prime = new P25519();
    } else {
      throw new Error('Unknown prime ' + name);
    }
    primes[name] = prime;

    return prime;
  };

  //
  // Base reduction engine
  //
  function Red (m) {
    if (typeof m === 'string') {
      var prime = BN._prime(m);
      this.m = prime.p;
      this.prime = prime;
    } else {
      assert(m.gtn(1), 'modulus must be greater than 1');
      this.m = m;
      this.prime = null;
    }
  }

  Red.prototype._verify1 = function _verify1 (a) {
    assert(a.negative === 0, 'red works only with positives');
    assert(a.red, 'red works only with red numbers');
  };

  Red.prototype._verify2 = function _verify2 (a, b) {
    assert((a.negative | b.negative) === 0, 'red works only with positives');
    assert(a.red && a.red === b.red,
      'red works only with red numbers');
  };

  Red.prototype.imod = function imod (a) {
    if (this.prime) return this.prime.ireduce(a)._forceRed(this);

    move(a, a.umod(this.m)._forceRed(this));
    return a;
  };

  Red.prototype.neg = function neg (a) {
    if (a.isZero()) {
      return a.clone();
    }

    return this.m.sub(a)._forceRed(this);
  };

  Red.prototype.add = function add (a, b) {
    this._verify2(a, b);

    var res = a.add(b);
    if (res.cmp(this.m) >= 0) {
      res.isub(this.m);
    }
    return res._forceRed(this);
  };

  Red.prototype.iadd = function iadd (a, b) {
    this._verify2(a, b);

    var res = a.iadd(b);
    if (res.cmp(this.m) >= 0) {
      res.isub(this.m);
    }
    return res;
  };

  Red.prototype.sub = function sub (a, b) {
    this._verify2(a, b);

    var res = a.sub(b);
    if (res.cmpn(0) < 0) {
      res.iadd(this.m);
    }
    return res._forceRed(this);
  };

  Red.prototype.isub = function isub (a, b) {
    this._verify2(a, b);

    var res = a.isub(b);
    if (res.cmpn(0) < 0) {
      res.iadd(this.m);
    }
    return res;
  };

  Red.prototype.shl = function shl (a, num) {
    this._verify1(a);
    return this.imod(a.ushln(num));
  };

  Red.prototype.imul = function imul (a, b) {
    this._verify2(a, b);
    return this.imod(a.imul(b));
  };

  Red.prototype.mul = function mul (a, b) {
    this._verify2(a, b);
    return this.imod(a.mul(b));
  };

  Red.prototype.isqr = function isqr (a) {
    return this.imul(a, a.clone());
  };

  Red.prototype.sqr = function sqr (a) {
    return this.mul(a, a);
  };

  Red.prototype.sqrt = function sqrt (a) {
    if (a.isZero()) return a.clone();

    var mod3 = this.m.andln(3);
    assert(mod3 % 2 === 1);

    // Fast case
    if (mod3 === 3) {
      var pow = this.m.add(new BN(1)).iushrn(2);
      return this.pow(a, pow);
    }

    // Tonelli-Shanks algorithm (Totally unoptimized and slow)
    //
    // Find Q and S, that Q * 2 ^ S = (P - 1)
    var q = this.m.subn(1);
    var s = 0;
    while (!q.isZero() && q.andln(1) === 0) {
      s++;
      q.iushrn(1);
    }
    assert(!q.isZero());

    var one = new BN(1).toRed(this);
    var nOne = one.redNeg();

    // Find quadratic non-residue
    // NOTE: Max is such because of generalized Riemann hypothesis.
    var lpow = this.m.subn(1).iushrn(1);
    var z = this.m.bitLength();
    z = new BN(2 * z * z).toRed(this);

    while (this.pow(z, lpow).cmp(nOne) !== 0) {
      z.redIAdd(nOne);
    }

    var c = this.pow(z, q);
    var r = this.pow(a, q.addn(1).iushrn(1));
    var t = this.pow(a, q);
    var m = s;
    while (t.cmp(one) !== 0) {
      var tmp = t;
      for (var i = 0; tmp.cmp(one) !== 0; i++) {
        tmp = tmp.redSqr();
      }
      assert(i < m);
      var b = this.pow(c, new BN(1).iushln(m - i - 1));

      r = r.redMul(b);
      c = b.redSqr();
      t = t.redMul(c);
      m = i;
    }

    return r;
  };

  Red.prototype.invm = function invm (a) {
    var inv = a._invmp(this.m);
    if (inv.negative !== 0) {
      inv.negative = 0;
      return this.imod(inv).redNeg();
    } else {
      return this.imod(inv);
    }
  };

  Red.prototype.pow = function pow (a, num) {
    if (num.isZero()) return new BN(1).toRed(this);
    if (num.cmpn(1) === 0) return a.clone();

    var windowSize = 4;
    var wnd = new Array(1 << windowSize);
    wnd[0] = new BN(1).toRed(this);
    wnd[1] = a;
    for (var i = 2; i < wnd.length; i++) {
      wnd[i] = this.mul(wnd[i - 1], a);
    }

    var res = wnd[0];
    var current = 0;
    var currentLen = 0;
    var start = num.bitLength() % 26;
    if (start === 0) {
      start = 26;
    }

    for (i = num.length - 1; i >= 0; i--) {
      var word = num.words[i];
      for (var j = start - 1; j >= 0; j--) {
        var bit = (word >> j) & 1;
        if (res !== wnd[0]) {
          res = this.sqr(res);
        }

        if (bit === 0 && current === 0) {
          currentLen = 0;
          continue;
        }

        current <<= 1;
        current |= bit;
        currentLen++;
        if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;

        res = this.mul(res, wnd[current]);
        currentLen = 0;
        current = 0;
      }
      start = 26;
    }

    return res;
  };

  Red.prototype.convertTo = function convertTo (num) {
    var r = num.umod(this.m);

    return r === num ? r.clone() : r;
  };

  Red.prototype.convertFrom = function convertFrom (num) {
    var res = num.clone();
    res.red = null;
    return res;
  };

  //
  // Montgomery method engine
  //

  BN.mont = function mont (num) {
    return new Mont(num);
  };

  function Mont (m) {
    Red.call(this, m);

    this.shift = this.m.bitLength();
    if (this.shift % 26 !== 0) {
      this.shift += 26 - (this.shift % 26);
    }

    this.r = new BN(1).iushln(this.shift);
    this.r2 = this.imod(this.r.sqr());
    this.rinv = this.r._invmp(this.m);

    this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
    this.minv = this.minv.umod(this.r);
    this.minv = this.r.sub(this.minv);
  }
  inherits(Mont, Red);

  Mont.prototype.convertTo = function convertTo (num) {
    return this.imod(num.ushln(this.shift));
  };

  Mont.prototype.convertFrom = function convertFrom (num) {
    var r = this.imod(num.mul(this.rinv));
    r.red = null;
    return r;
  };

  Mont.prototype.imul = function imul (a, b) {
    if (a.isZero() || b.isZero()) {
      a.words[0] = 0;
      a.length = 1;
      return a;
    }

    var t = a.imul(b);
    var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
    var u = t.isub(c).iushrn(this.shift);
    var res = u;

    if (u.cmp(this.m) >= 0) {
      res = u.isub(this.m);
    } else if (u.cmpn(0) < 0) {
      res = u.iadd(this.m);
    }

    return res._forceRed(this);
  };

  Mont.prototype.mul = function mul (a, b) {
    if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);

    var t = a.mul(b);
    var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
    var u = t.isub(c).iushrn(this.shift);
    var res = u;
    if (u.cmp(this.m) >= 0) {
      res = u.isub(this.m);
    } else if (u.cmpn(0) < 0) {
      res = u.iadd(this.m);
    }

    return res._forceRed(this);
  };

  Mont.prototype.invm = function invm (a) {
    // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
    var res = this.imod(a._invmp(this.m).mul(this.r2));
    return res._forceRed(this);
  };
})( false || module, this);


/***/ }),

/***/ 35973:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var r;

module.exports = function rand(len) {
  if (!r)
    r = new Rand(null);

  return r.generate(len);
};

function Rand(rand) {
  this.rand = rand;
}
module.exports.Rand = Rand;

Rand.prototype.generate = function generate(len) {
  return this._rand(len);
};

// Emulate crypto API using randy
Rand.prototype._rand = function _rand(n) {
  if (this.rand.getBytes)
    return this.rand.getBytes(n);

  var res = new Uint8Array(n);
  for (var i = 0; i < res.length; i++)
    res[i] = this.rand.getByte();
  return res;
};

if (typeof self === 'object') {
  if (self.crypto && self.crypto.getRandomValues) {
    // Modern browsers
    Rand.prototype._rand = function _rand(n) {
      var arr = new Uint8Array(n);
      self.crypto.getRandomValues(arr);
      return arr;
    };
  } else if (self.msCrypto && self.msCrypto.getRandomValues) {
    // IE
    Rand.prototype._rand = function _rand(n) {
      var arr = new Uint8Array(n);
      self.msCrypto.getRandomValues(arr);
      return arr;
    };

  // Safari's WebWorkers do not have `crypto`
  } else if (typeof window === 'object') {
    // Old junk
    Rand.prototype._rand = function() {
      throw new Error('Not implemented yet');
    };
  }
} else {
  // Node.js or Web worker with no crypto support
  try {
    var crypto = __webpack_require__(89780);
    if (typeof crypto.randomBytes !== 'function')
      throw new Error('Not supported');

    Rand.prototype._rand = function _rand(n) {
      return crypto.randomBytes(n);
    };
  } catch (e) {
  }
}


/***/ }),

/***/ 95807:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

// based on the aes implimentation in triple sec
// https://github.com/keybase/triplesec
// which is in turn based on the one from crypto-js
// https://code.google.com/p/crypto-js/

var Buffer = (__webpack_require__(60571).Buffer)

function asUInt32Array (buf) {
  if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)

  var len = (buf.length / 4) | 0
  var out = new Array(len)

  for (var i = 0; i < len; i++) {
    out[i] = buf.readUInt32BE(i * 4)
  }

  return out
}

function scrubVec (v) {
  for (var i = 0; i < v.length; v++) {
    v[i] = 0
  }
}

function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) {
  var SUB_MIX0 = SUB_MIX[0]
  var SUB_MIX1 = SUB_MIX[1]
  var SUB_MIX2 = SUB_MIX[2]
  var SUB_MIX3 = SUB_MIX[3]

  var s0 = M[0] ^ keySchedule[0]
  var s1 = M[1] ^ keySchedule[1]
  var s2 = M[2] ^ keySchedule[2]
  var s3 = M[3] ^ keySchedule[3]
  var t0, t1, t2, t3
  var ksRow = 4

  for (var round = 1; round < nRounds; round++) {
    t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++]
    t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++]
    t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++]
    t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++]
    s0 = t0
    s1 = t1
    s2 = t2
    s3 = t3
  }

  t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]
  t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]
  t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]
  t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]
  t0 = t0 >>> 0
  t1 = t1 >>> 0
  t2 = t2 >>> 0
  t3 = t3 >>> 0

  return [t0, t1, t2, t3]
}

// AES constants
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
var G = (function () {
  // Compute double table
  var d = new Array(256)
  for (var j = 0; j < 256; j++) {
    if (j < 128) {
      d[j] = j << 1
    } else {
      d[j] = (j << 1) ^ 0x11b
    }
  }

  var SBOX = []
  var INV_SBOX = []
  var SUB_MIX = [[], [], [], []]
  var INV_SUB_MIX = [[], [], [], []]

  // Walk GF(2^8)
  var x = 0
  var xi = 0
  for (var i = 0; i < 256; ++i) {
    // Compute sbox
    var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
    sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
    SBOX[x] = sx
    INV_SBOX[sx] = x

    // Compute multiplication
    var x2 = d[x]
    var x4 = d[x2]
    var x8 = d[x4]

    // Compute sub bytes, mix columns tables
    var t = (d[sx] * 0x101) ^ (sx * 0x1010100)
    SUB_MIX[0][x] = (t << 24) | (t >>> 8)
    SUB_MIX[1][x] = (t << 16) | (t >>> 16)
    SUB_MIX[2][x] = (t << 8) | (t >>> 24)
    SUB_MIX[3][x] = t

    // Compute inv sub bytes, inv mix columns tables
    t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
    INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
    INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
    INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
    INV_SUB_MIX[3][sx] = t

    if (x === 0) {
      x = xi = 1
    } else {
      x = x2 ^ d[d[d[x8 ^ x2]]]
      xi ^= d[d[xi]]
    }
  }

  return {
    SBOX: SBOX,
    INV_SBOX: INV_SBOX,
    SUB_MIX: SUB_MIX,
    INV_SUB_MIX: INV_SUB_MIX
  }
})()

function AES (key) {
  this._key = asUInt32Array(key)
  this._reset()
}

AES.blockSize = 4 * 4
AES.keySize = 256 / 8
AES.prototype.blockSize = AES.blockSize
AES.prototype.keySize = AES.keySize
AES.prototype._reset = function () {
  var keyWords = this._key
  var keySize = keyWords.length
  var nRounds = keySize + 6
  var ksRows = (nRounds + 1) * 4

  var keySchedule = []
  for (var k = 0; k < keySize; k++) {
    keySchedule[k] = keyWords[k]
  }

  for (k = keySize; k < ksRows; k++) {
    var t = keySchedule[k - 1]

    if (k % keySize === 0) {
      t = (t << 8) | (t >>> 24)
      t =
        (G.SBOX[t >>> 24] << 24) |
        (G.SBOX[(t >>> 16) & 0xff] << 16) |
        (G.SBOX[(t >>> 8) & 0xff] << 8) |
        (G.SBOX[t & 0xff])

      t ^= RCON[(k / keySize) | 0] << 24
    } else if (keySize > 6 && k % keySize === 4) {
      t =
        (G.SBOX[t >>> 24] << 24) |
        (G.SBOX[(t >>> 16) & 0xff] << 16) |
        (G.SBOX[(t >>> 8) & 0xff] << 8) |
        (G.SBOX[t & 0xff])
    }

    keySchedule[k] = keySchedule[k - keySize] ^ t
  }

  var invKeySchedule = []
  for (var ik = 0; ik < ksRows; ik++) {
    var ksR = ksRows - ik
    var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)]

    if (ik < 4 || ksR <= 4) {
      invKeySchedule[ik] = tt
    } else {
      invKeySchedule[ik] =
        G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^
        G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^
        G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^
        G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]]
    }
  }

  this._nRounds = nRounds
  this._keySchedule = keySchedule
  this._invKeySchedule = invKeySchedule
}

AES.prototype.encryptBlockRaw = function (M) {
  M = asUInt32Array(M)
  return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds)
}

AES.prototype.encryptBlock = function (M) {
  var out = this.encryptBlockRaw(M)
  var buf = Buffer.allocUnsafe(16)
  buf.writeUInt32BE(out[0], 0)
  buf.writeUInt32BE(out[1], 4)
  buf.writeUInt32BE(out[2], 8)
  buf.writeUInt32BE(out[3], 12)
  return buf
}

AES.prototype.decryptBlock = function (M) {
  M = asUInt32Array(M)

  // swap
  var m1 = M[1]
  M[1] = M[3]
  M[3] = m1

  var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds)
  var buf = Buffer.allocUnsafe(16)
  buf.writeUInt32BE(out[0], 0)
  buf.writeUInt32BE(out[3], 4)
  buf.writeUInt32BE(out[2], 8)
  buf.writeUInt32BE(out[1], 12)
  return buf
}

AES.prototype.scrub = function () {
  scrubVec(this._keySchedule)
  scrubVec(this._invKeySchedule)
  scrubVec(this._key)
}

module.exports.AES = AES


/***/ }),

/***/ 9331:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var aes = __webpack_require__(95807)
var Buffer = (__webpack_require__(60571).Buffer)
var Transform = __webpack_require__(94156)
var inherits = __webpack_require__(72116)
var GHASH = __webpack_require__(76869)
var xor = __webpack_require__(4287)
var incr32 = __webpack_require__(31173)

function xorTest (a, b) {
  var out = 0
  if (a.length !== b.length) out++

  var len = Math.min(a.length, b.length)
  for (var i = 0; i < len; ++i) {
    out += (a[i] ^ b[i])
  }

  return out
}

function calcIv (self, iv, ck) {
  if (iv.length === 12) {
    self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])])
    return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])])
  }
  var ghash = new GHASH(ck)
  var len = iv.length
  var toPad = len % 16
  ghash.update(iv)
  if (toPad) {
    toPad = 16 - toPad
    ghash.update(Buffer.alloc(toPad, 0))
  }
  ghash.update(Buffer.alloc(8, 0))
  var ivBits = len * 8
  var tail = Buffer.alloc(8)
  tail.writeUIntBE(ivBits, 0, 8)
  ghash.update(tail)
  self._finID = ghash.state
  var out = Buffer.from(self._finID)
  incr32(out)
  return out
}
function StreamCipher (mode, key, iv, decrypt) {
  Transform.call(this)

  var h = Buffer.alloc(4, 0)

  this._cipher = new aes.AES(key)
  var ck = this._cipher.encryptBlock(h)
  this._ghash = new GHASH(ck)
  iv = calcIv(this, iv, ck)

  this._prev = Buffer.from(iv)
  this._cache = Buffer.allocUnsafe(0)
  this._secCache = Buffer.allocUnsafe(0)
  this._decrypt = decrypt
  this._alen = 0
  this._len = 0
  this._mode = mode

  this._authTag = null
  this._called = false
}

inherits(StreamCipher, Transform)

StreamCipher.prototype._update = function (chunk) {
  if (!this._called && this._alen) {
    var rump = 16 - (this._alen % 16)
    if (rump < 16) {
      rump = Buffer.alloc(rump, 0)
      this._ghash.update(rump)
    }
  }

  this._called = true
  var out = this._mode.encrypt(this, chunk)
  if (this._decrypt) {
    this._ghash.update(chunk)
  } else {
    this._ghash.update(out)
  }
  this._len += chunk.length
  return out
}

StreamCipher.prototype._final = function () {
  if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data')

  var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID))
  if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data')

  this._authTag = tag
  this._cipher.scrub()
}

StreamCipher.prototype.getAuthTag = function getAuthTag () {
  if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state')

  return this._authTag
}

StreamCipher.prototype.setAuthTag = function setAuthTag (tag) {
  if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state')

  this._authTag = tag
}

StreamCipher.prototype.setAAD = function setAAD (buf) {
  if (this._called) throw new Error('Attempting to set AAD in unsupported state')

  this._ghash.update(buf)
  this._alen += buf.length
}

module.exports = StreamCipher


/***/ }),

/***/ 17044:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var ciphers = __webpack_require__(85094)
var deciphers = __webpack_require__(83870)
var modes = __webpack_require__(39072)

function getCiphers () {
  return Object.keys(modes)
}

exports.createCipher = exports.Cipher = ciphers.createCipher
exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv
exports.createDecipher = exports.Decipher = deciphers.createDecipher
exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv
exports.listCiphers = exports.getCiphers = getCiphers


/***/ }),

/***/ 83870:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var AuthCipher = __webpack_require__(9331)
var Buffer = (__webpack_require__(60571).Buffer)
var MODES = __webpack_require__(24959)
var StreamCipher = __webpack_require__(40597)
var Transform = __webpack_require__(94156)
var aes = __webpack_require__(95807)
var ebtk = __webpack_require__(32615)
var inherits = __webpack_require__(72116)

function Decipher (mode, key, iv) {
  Transform.call(this)

  this._cache = new Splitter()
  this._last = void 0
  this._cipher = new aes.AES(key)
  this._prev = Buffer.from(iv)
  this._mode = mode
  this._autopadding = true
}

inherits(Decipher, Transform)

Decipher.prototype._update = function (data) {
  this._cache.add(data)
  var chunk
  var thing
  var out = []
  while ((chunk = this._cache.get(this._autopadding))) {
    thing = this._mode.decrypt(this, chunk)
    out.push(thing)
  }
  return Buffer.concat(out)
}

Decipher.prototype._final = function () {
  var chunk = this._cache.flush()
  if (this._autopadding) {
    return unpad(this._mode.decrypt(this, chunk))
  } else if (chunk) {
    throw new Error('data not multiple of block length')
  }
}

Decipher.prototype.setAutoPadding = function (setTo) {
  this._autopadding = !!setTo
  return this
}

function Splitter () {
  this.cache = Buffer.allocUnsafe(0)
}

Splitter.prototype.add = function (data) {
  this.cache = Buffer.concat([this.cache, data])
}

Splitter.prototype.get = function (autoPadding) {
  var out
  if (autoPadding) {
    if (this.cache.length > 16) {
      out = this.cache.slice(0, 16)
      this.cache = this.cache.slice(16)
      return out
    }
  } else {
    if (this.cache.length >= 16) {
      out = this.cache.slice(0, 16)
      this.cache = this.cache.slice(16)
      return out
    }
  }

  return null
}

Splitter.prototype.flush = function () {
  if (this.cache.length) return this.cache
}

function unpad (last) {
  var padded = last[15]
  if (padded < 1 || padded > 16) {
    throw new Error('unable to decrypt data')
  }
  var i = -1
  while (++i < padded) {
    if (last[(i + (16 - padded))] !== padded) {
      throw new Error('unable to decrypt data')
    }
  }
  if (padded === 16) return

  return last.slice(0, 16 - padded)
}

function createDecipheriv (suite, password, iv) {
  var config = MODES[suite.toLowerCase()]
  if (!config) throw new TypeError('invalid suite type')

  if (typeof iv === 'string') iv = Buffer.from(iv)
  if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)

  if (typeof password === 'string') password = Buffer.from(password)
  if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)

  if (config.type === 'stream') {
    return new StreamCipher(config.module, password, iv, true)
  } else if (config.type === 'auth') {
    return new AuthCipher(config.module, password, iv, true)
  }

  return new Decipher(config.module, password, iv)
}

function createDecipher (suite, password) {
  var config = MODES[suite.toLowerCase()]
  if (!config) throw new TypeError('invalid suite type')

  var keys = ebtk(password, false, config.key, config.iv)
  return createDecipheriv(suite, keys.key, keys.iv)
}

exports.createDecipher = createDecipher
exports.createDecipheriv = createDecipheriv


/***/ }),

/***/ 85094:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var MODES = __webpack_require__(24959)
var AuthCipher = __webpack_require__(9331)
var Buffer = (__webpack_require__(60571).Buffer)
var StreamCipher = __webpack_require__(40597)
var Transform = __webpack_require__(94156)
var aes = __webpack_require__(95807)
var ebtk = __webpack_require__(32615)
var inherits = __webpack_require__(72116)

function Cipher (mode, key, iv) {
  Transform.call(this)

  this._cache = new Splitter()
  this._cipher = new aes.AES(key)
  this._prev = Buffer.from(iv)
  this._mode = mode
  this._autopadding = true
}

inherits(Cipher, Transform)

Cipher.prototype._update = function (data) {
  this._cache.add(data)
  var chunk
  var thing
  var out = []

  while ((chunk = this._cache.get())) {
    thing = this._mode.encrypt(this, chunk)
    out.push(thing)
  }

  return Buffer.concat(out)
}

var PADDING = Buffer.alloc(16, 0x10)

Cipher.prototype._final = function () {
  var chunk = this._cache.flush()
  if (this._autopadding) {
    chunk = this._mode.encrypt(this, chunk)
    this._cipher.scrub()
    return chunk
  }

  if (!chunk.equals(PADDING)) {
    this._cipher.scrub()
    throw new Error('data not multiple of block length')
  }
}

Cipher.prototype.setAutoPadding = function (setTo) {
  this._autopadding = !!setTo
  return this
}

function Splitter () {
  this.cache = Buffer.allocUnsafe(0)
}

Splitter.prototype.add = function (data) {
  this.cache = Buffer.concat([this.cache, data])
}

Splitter.prototype.get = function () {
  if (this.cache.length > 15) {
    var out = this.cache.slice(0, 16)
    this.cache = this.cache.slice(16)
    return out
  }
  return null
}

Splitter.prototype.flush = function () {
  var len = 16 - this.cache.length
  var padBuff = Buffer.allocUnsafe(len)

  var i = -1
  while (++i < len) {
    padBuff.writeUInt8(len, i)
  }

  return Buffer.concat([this.cache, padBuff])
}

function createCipheriv (suite, password, iv) {
  var config = MODES[suite.toLowerCase()]
  if (!config) throw new TypeError('invalid suite type')

  if (typeof password === 'string') password = Buffer.from(password)
  if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)

  if (typeof iv === 'string') iv = Buffer.from(iv)
  if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)

  if (config.type === 'stream') {
    return new StreamCipher(config.module, password, iv)
  } else if (config.type === 'auth') {
    return new AuthCipher(config.module, password, iv)
  }

  return new Cipher(config.module, password, iv)
}

function createCipher (suite, password) {
  var config = MODES[suite.toLowerCase()]
  if (!config) throw new TypeError('invalid suite type')

  var keys = ebtk(password, false, config.key, config.iv)
  return createCipheriv(suite, keys.key, keys.iv)
}

exports.createCipheriv = createCipheriv
exports.createCipher = createCipher


/***/ }),

/***/ 76869:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var Buffer = (__webpack_require__(60571).Buffer)
var ZEROES = Buffer.alloc(16, 0)

function toArray (buf) {
  return [
    buf.readUInt32BE(0),
    buf.readUInt32BE(4),
    buf.readUInt32BE(8),
    buf.readUInt32BE(12)
  ]
}

function fromArray (out) {
  var buf = Buffer.allocUnsafe(16)
  buf.writeUInt32BE(out[0] >>> 0, 0)
  buf.writeUInt32BE(out[1] >>> 0, 4)
  buf.writeUInt32BE(out[2] >>> 0, 8)
  buf.writeUInt32BE(out[3] >>> 0, 12)
  return buf
}

function GHASH (key) {
  this.h = key
  this.state = Buffer.alloc(16, 0)
  this.cache = Buffer.allocUnsafe(0)
}

// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
// by Juho Vähä-Herttua
GHASH.prototype.ghash = function (block) {
  var i = -1
  while (++i < block.length) {
    this.state[i] ^= block[i]
  }
  this._multiply()
}

GHASH.prototype._multiply = function () {
  var Vi = toArray(this.h)
  var Zi = [0, 0, 0, 0]
  var j, xi, lsbVi
  var i = -1
  while (++i < 128) {
    xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0
    if (xi) {
      // Z_i+1 = Z_i ^ V_i
      Zi[0] ^= Vi[0]
      Zi[1] ^= Vi[1]
      Zi[2] ^= Vi[2]
      Zi[3] ^= Vi[3]
    }

    // Store the value of LSB(V_i)
    lsbVi = (Vi[3] & 1) !== 0

    // V_i+1 = V_i >> 1
    for (j = 3; j > 0; j--) {
      Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)
    }
    Vi[0] = Vi[0] >>> 1

    // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
    if (lsbVi) {
      Vi[0] = Vi[0] ^ (0xe1 << 24)
    }
  }
  this.state = fromArray(Zi)
}

GHASH.prototype.update = function (buf) {
  this.cache = Buffer.concat([this.cache, buf])
  var chunk
  while (this.cache.length >= 16) {
    chunk = this.cache.slice(0, 16)
    this.cache = this.cache.slice(16)
    this.ghash(chunk)
  }
}

GHASH.prototype.final = function (abl, bl) {
  if (this.cache.length) {
    this.ghash(Buffer.concat([this.cache, ZEROES], 16))
  }

  this.ghash(fromArray([0, abl, 0, bl]))
  return this.state
}

module.exports = GHASH


/***/ }),

/***/ 31173:
/***/ ((module) => {

function incr32 (iv) {
  var len = iv.length
  var item
  while (len--) {
    item = iv.readUInt8(len)
    if (item === 255) {
      iv.writeUInt8(0, len)
    } else {
      item++
      iv.writeUInt8(item, len)
      break
    }
  }
}
module.exports = incr32


/***/ }),

/***/ 35213:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var xor = __webpack_require__(4287)

exports.encrypt = function (self, block) {
  var data = xor(block, self._prev)

  self._prev = self._cipher.encryptBlock(data)
  return self._prev
}

exports.decrypt = function (self, block) {
  var pad = self._prev

  self._prev = block
  var out = self._cipher.decryptBlock(block)

  return xor(out, pad)
}


/***/ }),

/***/ 13978:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var Buffer = (__webpack_require__(60571).Buffer)
var xor = __webpack_require__(4287)

function encryptStart (self, data, decrypt) {
  var len = data.length
  var out = xor(data, self._cache)
  self._cache = self._cache.slice(len)
  self._prev = Buffer.concat([self._prev, decrypt ? data : out])
  return out
}

exports.encrypt = function (self, data, decrypt) {
  var out = Buffer.allocUnsafe(0)
  var len

  while (data.length) {
    if (self._cache.length === 0) {
      self._cache = self._cipher.encryptBlock(self._prev)
      self._prev = Buffer.allocUnsafe(0)
    }

    if (self._cache.length <= data.length) {
      len = self._cache.length
      out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)])
      data = data.slice(len)
    } else {
      out = Buffer.concat([out, encryptStart(self, data, decrypt)])
      break
    }
  }

  return out
}


/***/ }),

/***/ 50407:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var Buffer = (__webpack_require__(60571).Buffer)

function encryptByte (self, byteParam, decrypt) {
  var pad
  var i = -1
  var len = 8
  var out = 0
  var bit, value
  while (++i < len) {
    pad = self._cipher.encryptBlock(self._prev)
    bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0
    value = pad[0] ^ bit
    out += ((value & 0x80) >> (i % 8))
    self._prev = shiftIn(self._prev, decrypt ? bit : value)
  }
  return out
}

function shiftIn (buffer, value) {
  var len = buffer.length
  var i = -1
  var out = Buffer.allocUnsafe(buffer.length)
  buffer = Buffer.concat([buffer, Buffer.from([value])])

  while (++i < len) {
    out[i] = buffer[i] << 1 | buffer[i + 1] >> (7)
  }

  return out
}

exports.encrypt = function (self, chunk, decrypt) {
  var len = chunk.length
  var out = Buffer.allocUnsafe(len)
  var i = -1

  while (++i < len) {
    out[i] = encryptByte(self, chunk[i], decrypt)
  }

  return out
}


/***/ }),

/***/ 28152:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var Buffer = (__webpack_require__(60571).Buffer)

function encryptByte (self, byteParam, decrypt) {
  var pad = self._cipher.encryptBlock(self._prev)
  var out = pad[0] ^ byteParam

  self._prev = Buffer.concat([
    self._prev.slice(1),
    Buffer.from([decrypt ? byteParam : out])
  ])

  return out
}

exports.encrypt = function (self, chunk, decrypt) {
  var len = chunk.length
  var out = Buffer.allocUnsafe(len)
  var i = -1

  while (++i < len) {
    out[i] = encryptByte(self, chunk[i], decrypt)
  }

  return out
}


/***/ }),

/***/ 70520:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var xor = __webpack_require__(4287)
var Buffer = (__webpack_require__(60571).Buffer)
var incr32 = __webpack_require__(31173)

function getBlock (self) {
  var out = self._cipher.encryptBlockRaw(self._prev)
  incr32(self._prev)
  return out
}

var blockSize = 16
exports.encrypt = function (self, chunk) {
  var chunkNum = Math.ceil(chunk.length / blockSize)
  var start = self._cache.length
  self._cache = Buffer.concat([
    self._cache,
    Buffer.allocUnsafe(chunkNum * blockSize)
  ])
  for (var i = 0; i < chunkNum; i++) {
    var out = getBlock(self)
    var offset = start + i * blockSize
    self._cache.writeUInt32BE(out[0], offset + 0)
    self._cache.writeUInt32BE(out[1], offset + 4)
    self._cache.writeUInt32BE(out[2], offset + 8)
    self._cache.writeUInt32BE(out[3], offset + 12)
  }
  var pad = self._cache.slice(0, chunk.length)
  self._cache = self._cache.slice(chunk.length)
  return xor(chunk, pad)
}


/***/ }),

/***/ 70017:
/***/ ((__unused_webpack_module, exports) => {

exports.encrypt = function (self, block) {
  return self._cipher.encryptBlock(block)
}

exports.decrypt = function (self, block) {
  return self._cipher.decryptBlock(block)
}


/***/ }),

/***/ 24959:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var modeModules = {
  ECB: __webpack_require__(70017),
  CBC: __webpack_require__(35213),
  CFB: __webpack_require__(13978),
  CFB8: __webpack_require__(28152),
  CFB1: __webpack_require__(50407),
  OFB: __webpack_require__(13134),
  CTR: __webpack_require__(70520),
  GCM: __webpack_require__(70520)
}

var modes = __webpack_require__(39072)

for (var key in modes) {
  modes[key].module = modeModules[modes[key].mode]
}

module.exports = modes


/***/ }),

/***/ 13134:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var xor = __webpack_require__(4287)

function getBlock (self) {
  self._prev = self._cipher.encryptBlock(self._prev)
  return self._prev
}

exports.encrypt = function (self, chunk) {
  while (self._cache.length < chunk.length) {
    self._cache = Buffer.concat([self._cache, getBlock(self)])
  }

  var pad = self._cache.slice(0, chunk.length)
  self._cache = self._cache.slice(chunk.length)
  return xor(chunk, pad)
}


/***/ }),

/***/ 40597:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var aes = __webpack_require__(95807)
var Buffer = (__webpack_require__(60571).Buffer)
var Transform = __webpack_require__(94156)
var inherits = __webpack_require__(72116)

function StreamCipher (mode, key, iv, decrypt) {
  Transform.call(this)

  this._cipher = new aes.AES(key)
  this._prev = Buffer.from(iv)
  this._cache = Buffer.allocUnsafe(0)
  this._secCache = Buffer.allocUnsafe(0)
  this._decrypt = decrypt
  this._mode = mode
}

inherits(StreamCipher, Transform)

StreamCipher.prototype._update = function (chunk) {
  return this._mode.encrypt(this, chunk, this._decrypt)
}

StreamCipher.prototype._final = function () {
  this._cipher.scrub()
}

module.exports = StreamCipher


/***/ }),

/***/ 12209:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var DES = __webpack_require__(63076)
var aes = __webpack_require__(17044)
var aesModes = __webpack_require__(24959)
var desModes = __webpack_require__(23708)
var ebtk = __webpack_require__(32615)

function createCipher (suite, password) {
  suite = suite.toLowerCase()

  var keyLen, ivLen
  if (aesModes[suite]) {
    keyLen = aesModes[suite].key
    ivLen = aesModes[suite].iv
  } else if (desModes[suite]) {
    keyLen = desModes[suite].key * 8
    ivLen = desModes[suite].iv
  } else {
    throw new TypeError('invalid suite type')
  }

  var keys = ebtk(password, false, keyLen, ivLen)
  return createCipheriv(suite, keys.key, keys.iv)
}

function createDecipher (suite, password) {
  suite = suite.toLowerCase()

  var keyLen, ivLen
  if (aesModes[suite]) {
    keyLen = aesModes[suite].key
    ivLen = aesModes[suite].iv
  } else if (desModes[suite]) {
    keyLen = desModes[suite].key * 8
    ivLen = desModes[suite].iv
  } else {
    throw new TypeError('invalid suite type')
  }

  var keys = ebtk(password, false, keyLen, ivLen)
  return createDecipheriv(suite, keys.key, keys.iv)
}

function createCipheriv (suite, key, iv) {
  suite = suite.toLowerCase()
  if (aesModes[suite]) return aes.createCipheriv(suite, key, iv)
  if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite })

  throw new TypeError('invalid suite type')
}

function createDecipheriv (suite, key, iv) {
  suite = suite.toLowerCase()
  if (aesModes[suite]) return aes.createDecipheriv(suite, key, iv)
  if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite, decrypt: true })

  throw new TypeError('invalid suite type')
}

function getCiphers () {
  return Object.keys(desModes).concat(aes.getCiphers())
}

exports.createCipher = exports.Cipher = createCipher
exports.createCipheriv = exports.Cipheriv = createCipheriv
exports.createDecipher = exports.Decipher = createDecipher
exports.createDecipheriv = exports.Decipheriv = createDecipheriv
exports.listCiphers = exports.getCiphers = getCiphers


/***/ }),

/***/ 63076:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var CipherBase = __webpack_require__(94156)
var des = __webpack_require__(17893)
var inherits = __webpack_require__(72116)
var Buffer = (__webpack_require__(60571).Buffer)

var modes = {
  'des-ede3-cbc': des.CBC.instantiate(des.EDE),
  'des-ede3': des.EDE,
  'des-ede-cbc': des.CBC.instantiate(des.EDE),
  'des-ede': des.EDE,
  'des-cbc': des.CBC.instantiate(des.DES),
  'des-ecb': des.DES
}
modes.des = modes['des-cbc']
modes.des3 = modes['des-ede3-cbc']
module.exports = DES
inherits(DES, CipherBase)
function DES (opts) {
  CipherBase.call(this)
  var modeName = opts.mode.toLowerCase()
  var mode = modes[modeName]
  var type
  if (opts.decrypt) {
    type = 'decrypt'
  } else {
    type = 'encrypt'
  }
  var key = opts.key
  if (!Buffer.isBuffer(key)) {
    key = Buffer.from(key)
  }
  if (modeName === 'des-ede' || modeName === 'des-ede-cbc') {
    key = Buffer.concat([key, key.slice(0, 8)])
  }
  var iv = opts.iv
  if (!Buffer.isBuffer(iv)) {
    iv = Buffer.from(iv)
  }
  this._des = mode.create({
    key: key,
    iv: iv,
    type: type
  })
}
DES.prototype._update = function (data) {
  return Buffer.from(this._des.update(data))
}
DES.prototype._final = function () {
  return Buffer.from(this._des.final())
}


/***/ }),

/***/ 23708:
/***/ ((__unused_webpack_module, exports) => {

exports["des-ecb"] = {
  key: 8,
  iv: 0
}
exports["des-cbc"] = exports.des = {
  key: 8,
  iv: 8
}
exports["des-ede3-cbc"] = exports.des3 = {
  key: 24,
  iv: 8
}
exports["des-ede3"] = {
  key: 24,
  iv: 0
}
exports["des-ede-cbc"] = {
  key: 16,
  iv: 8
}
exports["des-ede"] = {
  key: 16,
  iv: 0
}


/***/ }),

/***/ 19501:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var BN = __webpack_require__(12293);
var randomBytes = __webpack_require__(66290);
var Buffer = (__webpack_require__(60571).Buffer);

function getr(priv) {
	var len = priv.modulus.byteLength();
	var r;
	do {
		r = new BN(randomBytes(len));
	} while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2));
	return r;
}

function blind(priv) {
	var r = getr(priv);
	var blinder = r.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed();
	return { blinder: blinder, unblinder: r.invm(priv.modulus) };
}

function crt(msg, priv) {
	var blinds = blind(priv);
	var len = priv.modulus.byteLength();
	var blinded = new BN(msg).mul(blinds.blinder).umod(priv.modulus);
	var c1 = blinded.toRed(BN.mont(priv.prime1));
	var c2 = blinded.toRed(BN.mont(priv.prime2));
	var qinv = priv.coefficient;
	var p = priv.prime1;
	var q = priv.prime2;
	var m1 = c1.redPow(priv.exponent1).fromRed();
	var m2 = c2.redPow(priv.exponent2).fromRed();
	var h = m1.isub(m2).imul(qinv).umod(p).imul(q);
	return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer, 'be', len);
}
crt.getr = getr;

module.exports = crt;


/***/ }),

/***/ 44076:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


module.exports = __webpack_require__(76178);


/***/ }),

/***/ 29483:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var Buffer = (__webpack_require__(60571).Buffer);
var createHash = __webpack_require__(63044);
var stream = __webpack_require__(4073);
var inherits = __webpack_require__(72116);
var sign = __webpack_require__(22690);
var verify = __webpack_require__(21422);

var algorithms = __webpack_require__(76178);
Object.keys(algorithms).forEach(function (key) {
  algorithms[key].id = Buffer.from(algorithms[key].id, 'hex');
  algorithms[key.toLowerCase()] = algorithms[key];
});

function Sign(algorithm) {
  stream.Writable.call(this);

  var data = algorithms[algorithm];
  if (!data) { throw new Error('Unknown message digest'); }

  this._hashType = data.hash;
  this._hash = createHash(data.hash);
  this._tag = data.id;
  this._signType = data.sign;
}
inherits(Sign, stream.Writable);

Sign.prototype._write = function _write(data, _, done) {
  this._hash.update(data);
  done();
};

Sign.prototype.update = function update(data, enc) {
  this._hash.update(typeof data === 'string' ? Buffer.from(data, enc) : data);

  return this;
};

Sign.prototype.sign = function signMethod(key, enc) {
  this.end();
  var hash = this._hash.digest();
  var sig = sign(hash, key, this._hashType, this._signType, this._tag);

  return enc ? sig.toString(enc) : sig;
};

function Verify(algorithm) {
  stream.Writable.call(this);

  var data = algorithms[algorithm];
  if (!data) { throw new Error('Unknown message digest'); }

  this._hash = createHash(data.hash);
  this._tag = data.id;
  this._signType = data.sign;
}
inherits(Verify, stream.Writable);

Verify.prototype._write = function _write(data, _, done) {
  this._hash.update(data);
  done();
};

Verify.prototype.update = function update(data, enc) {
  this._hash.update(typeof data === 'string' ? Buffer.from(data, enc) : data);

  return this;
};

Verify.prototype.verify = function verifyMethod(key, sig, enc) {
  var sigBuffer = typeof sig === 'string' ? Buffer.from(sig, enc) : sig;

  this.end();
  var hash = this._hash.digest();
  return verify(sigBuffer, hash, key, this._signType, this._tag);
};

function createSign(algorithm) {
  return new Sign(algorithm);
}

function createVerify(algorithm) {
  return new Verify(algorithm);
}

module.exports = {
  Sign: createSign,
  Verify: createVerify,
  createSign: createSign,
  createVerify: createVerify
};


/***/ }),

/***/ 22690:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
var Buffer = (__webpack_require__(60571).Buffer);
var createHmac = __webpack_require__(65842);
var crt = __webpack_require__(19501);
var EC = (__webpack_require__(74198).ec);
var BN = __webpack_require__(12293);
var parseKeys = __webpack_require__(20672);
var curves = __webpack_require__(69644);

var RSA_PKCS1_PADDING = 1;

function sign(hash, key, hashType, signType, tag) {
  var priv = parseKeys(key);
  if (priv.curve) {
    // rsa keys can be interpreted as ecdsa ones in openssl
    if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') { throw new Error('wrong private key type'); }
    return ecSign(hash, priv);
  } else if (priv.type === 'dsa') {
    if (signType !== 'dsa') { throw new Error('wrong private key type'); }
    return dsaSign(hash, priv, hashType);
  }
  if (signType !== 'rsa' && signType !== 'ecdsa/rsa') { throw new Error('wrong private key type'); }
  if (key.padding !== undefined && key.padding !== RSA_PKCS1_PADDING) { throw new Error('illegal or unsupported padding mode'); }

  hash = Buffer.concat([tag, hash]);
  var len = priv.modulus.byteLength();
  var pad = [0, 1];
  while (hash.length + pad.length + 1 < len) { pad.push(0xff); }
  pad.push(0x00);
  var i = -1;
  while (++i < hash.length) { pad.push(hash[i]); }

  var out = crt(pad, priv);
  return out;
}

function ecSign(hash, priv) {
  var curveId = curves[priv.curve.join('.')];
  if (!curveId) { throw new Error('unknown curve ' + priv.curve.join('.')); }

  var curve = new EC(curveId);
  var key = curve.keyFromPrivate(priv.privateKey);
  var out = key.sign(hash);

  return Buffer.from(out.toDER());
}

function dsaSign(hash, priv, algo) {
  var x = priv.params.priv_key;
  var p = priv.params.p;
  var q = priv.params.q;
  var g = priv.params.g;
  var r = new BN(0);
  var k;
  var H = bits2int(hash, q).mod(q);
  var s = false;
  var kv = getKey(x, q, hash, algo);
  while (s === false) {
    k = makeKey(q, kv, algo);
    r = makeR(g, k, p, q);
    s = k.invm(q).imul(H.add(x.mul(r))).mod(q);
    if (s.cmpn(0) === 0) {
      s = false;
      r = new BN(0);
    }
  }
  return toDER(r, s);
}

function toDER(r, s) {
  r = r.toArray();
  s = s.toArray();

  // Pad values
  if (r[0] & 0x80) { r = [0].concat(r); }
  if (s[0] & 0x80) { s = [0].concat(s); }

  var total = r.length + s.length + 4;
  var res = [
    0x30, total, 0x02, r.length
  ];
  res = res.concat(r, [0x02, s.length], s);
  return Buffer.from(res);
}

function getKey(x, q, hash, algo) {
  x = Buffer.from(x.toArray());
  if (x.length < q.byteLength()) {
    var zeros = Buffer.alloc(q.byteLength() - x.length);
    x = Buffer.concat([zeros, x]);
  }
  var hlen = hash.length;
  var hbits = bits2octets(hash, q);
  var v = Buffer.alloc(hlen);
  v.fill(1);
  var k = Buffer.alloc(hlen);
  k = createHmac(algo, k).update(v).update(Buffer.from([0])).update(x).update(hbits).digest();
  v = createHmac(algo, k).update(v).digest();
  k = createHmac(algo, k).update(v).update(Buffer.from([1])).update(x).update(hbits).digest();
  v = createHmac(algo, k).update(v).digest();
  return { k: k, v: v };
}

function bits2int(obits, q) {
  var bits = new BN(obits);
  var shift = (obits.length << 3) - q.bitLength();
  if (shift > 0) { bits.ishrn(shift); }
  return bits;
}

function bits2octets(bits, q) {
  bits = bits2int(bits, q);
  bits = bits.mod(q);
  var out = Buffer.from(bits.toArray());
  if (out.length < q.byteLength()) {
    var zeros = Buffer.alloc(q.byteLength() - out.length);
    out = Buffer.concat([zeros, out]);
  }
  return out;
}

function makeKey(q, kv, algo) {
  var t;
  var k;

  do {
    t = Buffer.alloc(0);

    while (t.length * 8 < q.bitLength()) {
      kv.v = createHmac(algo, kv.k).update(kv.v).digest();
      t = Buffer.concat([t, kv.v]);
    }

    k = bits2int(t, q);
    kv.k = createHmac(algo, kv.k).update(kv.v).update(Buffer.from([0])).digest();
    kv.v = createHmac(algo, kv.k).update(kv.v).digest();
  } while (k.cmp(q) !== -1);

  return k;
}

function makeR(g, k, p, q) {
  return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q);
}

module.exports = sign;
module.exports.getKey = getKey;
module.exports.makeKey = makeKey;


/***/ }),

/***/ 21422:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
var Buffer = (__webpack_require__(60571).Buffer);
var BN = __webpack_require__(12293);
var EC = (__webpack_require__(74198).ec);
var parseKeys = __webpack_require__(20672);
var curves = __webpack_require__(69644);

function verify(sig, hash, key, signType, tag) {
  var pub = parseKeys(key);
  if (pub.type === 'ec') {
    // rsa keys can be interpreted as ecdsa ones in openssl
    if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') { throw new Error('wrong public key type'); }
    return ecVerify(sig, hash, pub);
  } else if (pub.type === 'dsa') {
    if (signType !== 'dsa') { throw new Error('wrong public key type'); }
    return dsaVerify(sig, hash, pub);
  }
  if (signType !== 'rsa' && signType !== 'ecdsa/rsa') { throw new Error('wrong public key type'); }

  hash = Buffer.concat([tag, hash]);
  var len = pub.modulus.byteLength();
  var pad = [1];
  var padNum = 0;
  while (hash.length + pad.length + 2 < len) {
    pad.push(0xff);
    padNum += 1;
  }
  pad.push(0x00);
  var i = -1;
  while (++i < hash.length) {
    pad.push(hash[i]);
  }
  pad = Buffer.from(pad);
  var red = BN.mont(pub.modulus);
  sig = new BN(sig).toRed(red);

  sig = sig.redPow(new BN(pub.publicExponent));
  sig = Buffer.from(sig.fromRed().toArray());
  var out = padNum < 8 ? 1 : 0;
  len = Math.min(sig.length, pad.length);
  if (sig.length !== pad.length) { out = 1; }

  i = -1;
  while (++i < len) { out |= sig[i] ^ pad[i]; }
  return out === 0;
}

function ecVerify(sig, hash, pub) {
  var curveId = curves[pub.data.algorithm.curve.join('.')];
  if (!curveId) { throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.')); }

  var curve = new EC(curveId);
  var pubkey = pub.data.subjectPrivateKey.data;

  return curve.verify(hash, sig, pubkey);
}

function dsaVerify(sig, hash, pub) {
  var p = pub.data.p;
  var q = pub.data.q;
  var g = pub.data.g;
  var y = pub.data.pub_key;
  var unpacked = parseKeys.signature.decode(sig, 'der');
  var s = unpacked.s;
  var r = unpacked.r;
  checkValue(s, q);
  checkValue(r, q);
  var montp = BN.mont(p);
  var w = s.invm(q);
  var v = g.toRed(montp)
    .redPow(new BN(hash).mul(w).mod(q))
    .fromRed()
    .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed())
    .mod(p)
    .mod(q);
  return v.cmp(r) === 0;
}

function checkValue(b, q) {
  if (b.cmpn(0) <= 0) { throw new Error('invalid sig'); }
  if (b.cmp(q) >= 0) { throw new Error('invalid sig'); }
}

module.exports = verify;


/***/ }),

/***/ 4287:
/***/ ((module) => {

module.exports = function xor (a, b) {
  var length = Math.min(a.length, b.length)
  var buffer = new Buffer(length)

  for (var i = 0; i < length; ++i) {
    buffer[i] = a[i] ^ b[i]
  }

  return buffer
}


/***/ }),

/***/ 78378:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";
/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */
/* eslint-disable no-proto */



const base64 = __webpack_require__(67362)
const ieee754 = __webpack_require__(98319)
const customInspectSymbol =
  (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation
    ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
    : null

exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50

const K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH

/**
 * If `Buffer.TYPED_ARRAY_SUPPORT`:
 *   === true    Use Uint8Array implementation (fastest)
 *   === false   Print warning and recommend using `buffer` v4.x which has an Object
 *               implementation (most compatible, even IE6)
 *
 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
 * Opera 11.6+, iOS 4.2+.
 *
 * We report that the browser does not support typed arrays if the are not subclassable
 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
 * for __proto__ and has a buggy typed array implementation.
 */
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()

if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
    typeof console.error === 'function') {
  console.error(
    'This browser lacks typed array (Uint8Array) support which is required by ' +
    '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  )
}

function typedArraySupport () {
  // Can typed array instances can be augmented?
  try {
    const arr = new Uint8Array(1)
    const proto = { foo: function () { return 42 } }
    Object.setPrototypeOf(proto, Uint8Array.prototype)
    Object.setPrototypeOf(arr, proto)
    return arr.foo() === 42
  } catch (e) {
    return false
  }
}

Object.defineProperty(Buffer.prototype, 'parent', {
  enumerable: true,
  get: function () {
    if (!Buffer.isBuffer(this)) return undefined
    return this.buffer
  }
})

Object.defineProperty(Buffer.prototype, 'offset', {
  enumerable: true,
  get: function () {
    if (!Buffer.isBuffer(this)) return undefined
    return this.byteOffset
  }
})

function createBuffer (length) {
  if (length > K_MAX_LENGTH) {
    throw new RangeError('The value "' + length + '" is invalid for option "size"')
  }
  // Return an augmented `Uint8Array` instance
  const buf = new Uint8Array(length)
  Object.setPrototypeOf(buf, Buffer.prototype)
  return buf
}

/**
 * The Buffer constructor returns instances of `Uint8Array` that have their
 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
 * returns a single octet.
 *
 * The `Uint8Array` prototype remains unmodified.
 */

function Buffer (arg, encodingOrOffset, length) {
  // Common case.
  if (typeof arg === 'number') {
    if (typeof encodingOrOffset === 'string') {
      throw new TypeError(
        'The "string" argument must be of type string. Received type number'
      )
    }
    return allocUnsafe(arg)
  }
  return from(arg, encodingOrOffset, length)
}

Buffer.poolSize = 8192 // not used by this implementation

function from (value, encodingOrOffset, length) {
  if (typeof value === 'string') {
    return fromString(value, encodingOrOffset)
  }

  if (ArrayBuffer.isView(value)) {
    return fromArrayView(value)
  }

  if (value == null) {
    throw new TypeError(
      'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
      'or Array-like Object. Received type ' + (typeof value)
    )
  }

  if (isInstance(value, ArrayBuffer) ||
      (value && isInstance(value.buffer, ArrayBuffer))) {
    return fromArrayBuffer(value, encodingOrOffset, length)
  }

  if (typeof SharedArrayBuffer !== 'undefined' &&
      (isInstance(value, SharedArrayBuffer) ||
      (value && isInstance(value.buffer, SharedArrayBuffer)))) {
    return fromArrayBuffer(value, encodingOrOffset, length)
  }

  if (typeof value === 'number') {
    throw new TypeError(
      'The "value" argument must not be of type number. Received type number'
    )
  }

  const valueOf = value.valueOf && value.valueOf()
  if (valueOf != null && valueOf !== value) {
    return Buffer.from(valueOf, encodingOrOffset, length)
  }

  const b = fromObject(value)
  if (b) return b

  if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
      typeof value[Symbol.toPrimitive] === 'function') {
    return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length)
  }

  throw new TypeError(
    'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
    'or Array-like Object. Received type ' + (typeof value)
  )
}

/**
 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
 * if value is a number.
 * Buffer.from(str[, encoding])
 * Buffer.from(array)
 * Buffer.from(buffer)
 * Buffer.from(arrayBuffer[, byteOffset[, length]])
 **/
Buffer.from = function (value, encodingOrOffset, length) {
  return from(value, encodingOrOffset, length)
}

// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)
Object.setPrototypeOf(Buffer, Uint8Array)

function assertSize (size) {
  if (typeof size !== 'number') {
    throw new TypeError('"size" argument must be of type number')
  } else if (size < 0) {
    throw new RangeError('The value "' + size + '" is invalid for option "size"')
  }
}

function alloc (size, fill, encoding) {
  assertSize(size)
  if (size <= 0) {
    return createBuffer(size)
  }
  if (fill !== undefined) {
    // Only pay attention to encoding if it's a string. This
    // prevents accidentally sending in a number that would
    // be interpreted as a start offset.
    return typeof encoding === 'string'
      ? createBuffer(size).fill(fill, encoding)
      : createBuffer(size).fill(fill)
  }
  return createBuffer(size)
}

/**
 * Creates a new filled Buffer instance.
 * alloc(size[, fill[, encoding]])
 **/
Buffer.alloc = function (size, fill, encoding) {
  return alloc(size, fill, encoding)
}

function allocUnsafe (size) {
  assertSize(size)
  return createBuffer(size < 0 ? 0 : checked(size) | 0)
}

/**
 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
 * */
Buffer.allocUnsafe = function (size) {
  return allocUnsafe(size)
}
/**
 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
 */
Buffer.allocUnsafeSlow = function (size) {
  return allocUnsafe(size)
}

function fromString (string, encoding) {
  if (typeof encoding !== 'string' || encoding === '') {
    encoding = 'utf8'
  }

  if (!Buffer.isEncoding(encoding)) {
    throw new TypeError('Unknown encoding: ' + encoding)
  }

  const length = byteLength(string, encoding) | 0
  let buf = createBuffer(length)

  const actual = buf.write(string, encoding)

  if (actual !== length) {
    // Writing a hex string, for example, that contains invalid characters will
    // cause everything after the first invalid character to be ignored. (e.g.
    // 'abxxcd' will be treated as 'ab')
    buf = buf.slice(0, actual)
  }

  return buf
}

function fromArrayLike (array) {
  const length = array.length < 0 ? 0 : checked(array.length) | 0
  const buf = createBuffer(length)
  for (let i = 0; i < length; i += 1) {
    buf[i] = array[i] & 255
  }
  return buf
}

function fromArrayView (arrayView) {
  if (isInstance(arrayView, Uint8Array)) {
    const copy = new Uint8Array(arrayView)
    return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)
  }
  return fromArrayLike(arrayView)
}

function fromArrayBuffer (array, byteOffset, length) {
  if (byteOffset < 0 || array.byteLength < byteOffset) {
    throw new RangeError('"offset" is outside of buffer bounds')
  }

  if (array.byteLength < byteOffset + (length || 0)) {
    throw new RangeError('"length" is outside of buffer bounds')
  }

  let buf
  if (byteOffset === undefined && length === undefined) {
    buf = new Uint8Array(array)
  } else if (length === undefined) {
    buf = new Uint8Array(array, byteOffset)
  } else {
    buf = new Uint8Array(array, byteOffset, length)
  }

  // Return an augmented `Uint8Array` instance
  Object.setPrototypeOf(buf, Buffer.prototype)

  return buf
}

function fromObject (obj) {
  if (Buffer.isBuffer(obj)) {
    const len = checked(obj.length) | 0
    const buf = createBuffer(len)

    if (buf.length === 0) {
      return buf
    }

    obj.copy(buf, 0, 0, len)
    return buf
  }

  if (obj.length !== undefined) {
    if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
      return createBuffer(0)
    }
    return fromArrayLike(obj)
  }

  if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
    return fromArrayLike(obj.data)
  }
}

function checked (length) {
  // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  // length is NaN (which is otherwise coerced to zero.)
  if (length >= K_MAX_LENGTH) {
    throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
                         'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  }
  return length | 0
}

function SlowBuffer (length) {
  if (+length != length) { // eslint-disable-line eqeqeq
    length = 0
  }
  return Buffer.alloc(+length)
}

Buffer.isBuffer = function isBuffer (b) {
  return b != null && b._isBuffer === true &&
    b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
}

Buffer.compare = function compare (a, b) {
  if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
    throw new TypeError(
      'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
    )
  }

  if (a === b) return 0

  let x = a.length
  let y = b.length

  for (let i = 0, len = Math.min(x, y); i < len; ++i) {
    if (a[i] !== b[i]) {
      x = a[i]
      y = b[i]
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
}

Buffer.isEncoding = function isEncoding (encoding) {
  switch (String(encoding).toLowerCase()) {
    case 'hex':
    case 'utf8':
    case 'utf-8':
    case 'ascii':
    case 'latin1':
    case 'binary':
    case 'base64':
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return true
    default:
      return false
  }
}

Buffer.concat = function concat (list, length) {
  if (!Array.isArray(list)) {
    throw new TypeError('"list" argument must be an Array of Buffers')
  }

  if (list.length === 0) {
    return Buffer.alloc(0)
  }

  let i
  if (length === undefined) {
    length = 0
    for (i = 0; i < list.length; ++i) {
      length += list[i].length
    }
  }

  const buffer = Buffer.allocUnsafe(length)
  let pos = 0
  for (i = 0; i < list.length; ++i) {
    let buf = list[i]
    if (isInstance(buf, Uint8Array)) {
      if (pos + buf.length > buffer.length) {
        if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
        buf.copy(buffer, pos)
      } else {
        Uint8Array.prototype.set.call(
          buffer,
          buf,
          pos
        )
      }
    } else if (!Buffer.isBuffer(buf)) {
      throw new TypeError('"list" argument must be an Array of Buffers')
    } else {
      buf.copy(buffer, pos)
    }
    pos += buf.length
  }
  return buffer
}

function byteLength (string, encoding) {
  if (Buffer.isBuffer(string)) {
    return string.length
  }
  if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
    return string.byteLength
  }
  if (typeof string !== 'string') {
    throw new TypeError(
      'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
      'Received type ' + typeof string
    )
  }

  const len = string.length
  const mustMatch = (arguments.length > 2 && arguments[2] === true)
  if (!mustMatch && len === 0) return 0

  // Use a for loop to avoid recursion
  let loweredCase = false
  for (;;) {
    switch (encoding) {
      case 'ascii':
      case 'latin1':
      case 'binary':
        return len
      case 'utf8':
      case 'utf-8':
        return utf8ToBytes(string).length
      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return len * 2
      case 'hex':
        return len >>> 1
      case 'base64':
        return base64ToBytes(string).length
      default:
        if (loweredCase) {
          return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
        }
        encoding = ('' + encoding).toLowerCase()
        loweredCase = true
    }
  }
}
Buffer.byteLength = byteLength

function slowToString (encoding, start, end) {
  let loweredCase = false

  // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  // property of a typed array.

  // This behaves neither like String nor Uint8Array in that we set start/end
  // to their upper/lower bounds if the value passed is out of range.
  // undefined is handled specially as per ECMA-262 6th Edition,
  // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  if (start === undefined || start < 0) {
    start = 0
  }
  // Return early if start > this.length. Done here to prevent potential uint32
  // coercion fail below.
  if (start > this.length) {
    return ''
  }

  if (end === undefined || end > this.length) {
    end = this.length
  }

  if (end <= 0) {
    return ''
  }

  // Force coercion to uint32. This will also coerce falsey/NaN values to 0.
  end >>>= 0
  start >>>= 0

  if (end <= start) {
    return ''
  }

  if (!encoding) encoding = 'utf8'

  while (true) {
    switch (encoding) {
      case 'hex':
        return hexSlice(this, start, end)

      case 'utf8':
      case 'utf-8':
        return utf8Slice(this, start, end)

      case 'ascii':
        return asciiSlice(this, start, end)

      case 'latin1':
      case 'binary':
        return latin1Slice(this, start, end)

      case 'base64':
        return base64Slice(this, start, end)

      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return utf16leSlice(this, start, end)

      default:
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
        encoding = (encoding + '').toLowerCase()
        loweredCase = true
    }
  }
}

// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true

function swap (b, n, m) {
  const i = b[n]
  b[n] = b[m]
  b[m] = i
}

Buffer.prototype.swap16 = function swap16 () {
  const len = this.length
  if (len % 2 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 16-bits')
  }
  for (let i = 0; i < len; i += 2) {
    swap(this, i, i + 1)
  }
  return this
}

Buffer.prototype.swap32 = function swap32 () {
  const len = this.length
  if (len % 4 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 32-bits')
  }
  for (let i = 0; i < len; i += 4) {
    swap(this, i, i + 3)
    swap(this, i + 1, i + 2)
  }
  return this
}

Buffer.prototype.swap64 = function swap64 () {
  const len = this.length
  if (len % 8 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 64-bits')
  }
  for (let i = 0; i < len; i += 8) {
    swap(this, i, i + 7)
    swap(this, i + 1, i + 6)
    swap(this, i + 2, i + 5)
    swap(this, i + 3, i + 4)
  }
  return this
}

Buffer.prototype.toString = function toString () {
  const length = this.length
  if (length === 0) return ''
  if (arguments.length === 0) return utf8Slice(this, 0, length)
  return slowToString.apply(this, arguments)
}

Buffer.prototype.toLocaleString = Buffer.prototype.toString

Buffer.prototype.equals = function equals (b) {
  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  if (this === b) return true
  return Buffer.compare(this, b) === 0
}

Buffer.prototype.inspect = function inspect () {
  let str = ''
  const max = exports.INSPECT_MAX_BYTES
  str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  if (this.length > max) str += ' ... '
  return '<Buffer ' + str + '>'
}
if (customInspectSymbol) {
  Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect
}

Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  if (isInstance(target, Uint8Array)) {
    target = Buffer.from(target, target.offset, target.byteLength)
  }
  if (!Buffer.isBuffer(target)) {
    throw new TypeError(
      'The "target" argument must be one of type Buffer or Uint8Array. ' +
      'Received type ' + (typeof target)
    )
  }

  if (start === undefined) {
    start = 0
  }
  if (end === undefined) {
    end = target ? target.length : 0
  }
  if (thisStart === undefined) {
    thisStart = 0
  }
  if (thisEnd === undefined) {
    thisEnd = this.length
  }

  if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
    throw new RangeError('out of range index')
  }

  if (thisStart >= thisEnd && start >= end) {
    return 0
  }
  if (thisStart >= thisEnd) {
    return -1
  }
  if (start >= end) {
    return 1
  }

  start >>>= 0
  end >>>= 0
  thisStart >>>= 0
  thisEnd >>>= 0

  if (this === target) return 0

  let x = thisEnd - thisStart
  let y = end - start
  const len = Math.min(x, y)

  const thisCopy = this.slice(thisStart, thisEnd)
  const targetCopy = target.slice(start, end)

  for (let i = 0; i < len; ++i) {
    if (thisCopy[i] !== targetCopy[i]) {
      x = thisCopy[i]
      y = targetCopy[i]
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
}

// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  // Empty buffer means no match
  if (buffer.length === 0) return -1

  // Normalize byteOffset
  if (typeof byteOffset === 'string') {
    encoding = byteOffset
    byteOffset = 0
  } else if (byteOffset > 0x7fffffff) {
    byteOffset = 0x7fffffff
  } else if (byteOffset < -0x80000000) {
    byteOffset = -0x80000000
  }
  byteOffset = +byteOffset // Coerce to Number.
  if (numberIsNaN(byteOffset)) {
    // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
    byteOffset = dir ? 0 : (buffer.length - 1)
  }

  // Normalize byteOffset: negative offsets start from the end of the buffer
  if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  if (byteOffset >= buffer.length) {
    if (dir) return -1
    else byteOffset = buffer.length - 1
  } else if (byteOffset < 0) {
    if (dir) byteOffset = 0
    else return -1
  }

  // Normalize val
  if (typeof val === 'string') {
    val = Buffer.from(val, encoding)
  }

  // Finally, search either indexOf (if dir is true) or lastIndexOf
  if (Buffer.isBuffer(val)) {
    // Special case: looking for empty string/buffer always fails
    if (val.length === 0) {
      return -1
    }
    return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  } else if (typeof val === 'number') {
    val = val & 0xFF // Search for a byte value [0-255]
    if (typeof Uint8Array.prototype.indexOf === 'function') {
      if (dir) {
        return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
      } else {
        return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
      }
    }
    return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
  }

  throw new TypeError('val must be string, number or Buffer')
}

function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  let indexSize = 1
  let arrLength = arr.length
  let valLength = val.length

  if (encoding !== undefined) {
    encoding = String(encoding).toLowerCase()
    if (encoding === 'ucs2' || encoding === 'ucs-2' ||
        encoding === 'utf16le' || encoding === 'utf-16le') {
      if (arr.length < 2 || val.length < 2) {
        return -1
      }
      indexSize = 2
      arrLength /= 2
      valLength /= 2
      byteOffset /= 2
    }
  }

  function read (buf, i) {
    if (indexSize === 1) {
      return buf[i]
    } else {
      return buf.readUInt16BE(i * indexSize)
    }
  }

  let i
  if (dir) {
    let foundIndex = -1
    for (i = byteOffset; i < arrLength; i++) {
      if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
        if (foundIndex === -1) foundIndex = i
        if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
      } else {
        if (foundIndex !== -1) i -= i - foundIndex
        foundIndex = -1
      }
    }
  } else {
    if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
    for (i = byteOffset; i >= 0; i--) {
      let found = true
      for (let j = 0; j < valLength; j++) {
        if (read(arr, i + j) !== read(val, j)) {
          found = false
          break
        }
      }
      if (found) return i
    }
  }

  return -1
}

Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  return this.indexOf(val, byteOffset, encoding) !== -1
}

Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}

Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}

function hexWrite (buf, string, offset, length) {
  offset = Number(offset) || 0
  const remaining = buf.length - offset
  if (!length) {
    length = remaining
  } else {
    length = Number(length)
    if (length > remaining) {
      length = remaining
    }
  }

  const strLen = string.length

  if (length > strLen / 2) {
    length = strLen / 2
  }
  let i
  for (i = 0; i < length; ++i) {
    const parsed = parseInt(string.substr(i * 2, 2), 16)
    if (numberIsNaN(parsed)) return i
    buf[offset + i] = parsed
  }
  return i
}

function utf8Write (buf, string, offset, length) {
  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}

function asciiWrite (buf, string, offset, length) {
  return blitBuffer(asciiToBytes(string), buf, offset, length)
}

function base64Write (buf, string, offset, length) {
  return blitBuffer(base64ToBytes(string), buf, offset, length)
}

function ucs2Write (buf, string, offset, length) {
  return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}

Buffer.prototype.write = function write (string, offset, length, encoding) {
  // Buffer#write(string)
  if (offset === undefined) {
    encoding = 'utf8'
    length = this.length
    offset = 0
  // Buffer#write(string, encoding)
  } else if (length === undefined && typeof offset === 'string') {
    encoding = offset
    length = this.length
    offset = 0
  // Buffer#write(string, offset[, length][, encoding])
  } else if (isFinite(offset)) {
    offset = offset >>> 0
    if (isFinite(length)) {
      length = length >>> 0
      if (encoding === undefined) encoding = 'utf8'
    } else {
      encoding = length
      length = undefined
    }
  } else {
    throw new Error(
      'Buffer.write(string, encoding, offset[, length]) is no longer supported'
    )
  }

  const remaining = this.length - offset
  if (length === undefined || length > remaining) length = remaining

  if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
    throw new RangeError('Attempt to write outside buffer bounds')
  }

  if (!encoding) encoding = 'utf8'

  let loweredCase = false
  for (;;) {
    switch (encoding) {
      case 'hex':
        return hexWrite(this, string, offset, length)

      case 'utf8':
      case 'utf-8':
        return utf8Write(this, string, offset, length)

      case 'ascii':
      case 'latin1':
      case 'binary':
        return asciiWrite(this, string, offset, length)

      case 'base64':
        // Warning: maxLength not taken into account in base64Write
        return base64Write(this, string, offset, length)

      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return ucs2Write(this, string, offset, length)

      default:
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
        encoding = ('' + encoding).toLowerCase()
        loweredCase = true
    }
  }
}

Buffer.prototype.toJSON = function toJSON () {
  return {
    type: 'Buffer',
    data: Array.prototype.slice.call(this._arr || this, 0)
  }
}

function base64Slice (buf, start, end) {
  if (start === 0 && end === buf.length) {
    return base64.fromByteArray(buf)
  } else {
    return base64.fromByteArray(buf.slice(start, end))
  }
}

function utf8Slice (buf, start, end) {
  end = Math.min(buf.length, end)
  const res = []

  let i = start
  while (i < end) {
    const firstByte = buf[i]
    let codePoint = null
    let bytesPerSequence = (firstByte > 0xEF)
      ? 4
      : (firstByte > 0xDF)
          ? 3
          : (firstByte > 0xBF)
              ? 2
              : 1

    if (i + bytesPerSequence <= end) {
      let secondByte, thirdByte, fourthByte, tempCodePoint

      switch (bytesPerSequence) {
        case 1:
          if (firstByte < 0x80) {
            codePoint = firstByte
          }
          break
        case 2:
          secondByte = buf[i + 1]
          if ((secondByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
            if (tempCodePoint > 0x7F) {
              codePoint = tempCodePoint
            }
          }
          break
        case 3:
          secondByte = buf[i + 1]
          thirdByte = buf[i + 2]
          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
            if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
              codePoint = tempCodePoint
            }
          }
          break
        case 4:
          secondByte = buf[i + 1]
          thirdByte = buf[i + 2]
          fourthByte = buf[i + 3]
          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
            if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
              codePoint = tempCodePoint
            }
          }
      }
    }

    if (codePoint === null) {
      // we did not generate a valid codePoint so insert a
      // replacement char (U+FFFD) and advance only 1 byte
      codePoint = 0xFFFD
      bytesPerSequence = 1
    } else if (codePoint > 0xFFFF) {
      // encode to utf16 (surrogate pair dance)
      codePoint -= 0x10000
      res.push(codePoint >>> 10 & 0x3FF | 0xD800)
      codePoint = 0xDC00 | codePoint & 0x3FF
    }

    res.push(codePoint)
    i += bytesPerSequence
  }

  return decodeCodePointsArray(res)
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000

function decodeCodePointsArray (codePoints) {
  const len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }

  // Decode in chunks to avoid "call stack size exceeded".
  let res = ''
  let i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}

function asciiSlice (buf, start, end) {
  let ret = ''
  end = Math.min(buf.length, end)

  for (let i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i] & 0x7F)
  }
  return ret
}

function latin1Slice (buf, start, end) {
  let ret = ''
  end = Math.min(buf.length, end)

  for (let i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i])
  }
  return ret
}

function hexSlice (buf, start, end) {
  const len = buf.length

  if (!start || start < 0) start = 0
  if (!end || end < 0 || end > len) end = len

  let out = ''
  for (let i = start; i < end; ++i) {
    out += hexSliceLookupTable[buf[i]]
  }
  return out
}

function utf16leSlice (buf, start, end) {
  const bytes = buf.slice(start, end)
  let res = ''
  // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
  for (let i = 0; i < bytes.length - 1; i += 2) {
    res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  }
  return res
}

Buffer.prototype.slice = function slice (start, end) {
  const len = this.length
  start = ~~start
  end = end === undefined ? len : ~~end

  if (start < 0) {
    start += len
    if (start < 0) start = 0
  } else if (start > len) {
    start = len
  }

  if (end < 0) {
    end += len
    if (end < 0) end = 0
  } else if (end > len) {
    end = len
  }

  if (end < start) end = start

  const newBuf = this.subarray(start, end)
  // Return an augmented `Uint8Array` instance
  Object.setPrototypeOf(newBuf, Buffer.prototype)

  return newBuf
}

/*
 * Need to make sure that buffer isn't trying to write out of bounds.
 */
function checkOffset (offset, ext, length) {
  if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}

Buffer.prototype.readUintLE =
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  let val = this[offset]
  let mul = 1
  let i = 0
  while (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul
  }

  return val
}

Buffer.prototype.readUintBE =
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) {
    checkOffset(offset, byteLength, this.length)
  }

  let val = this[offset + --byteLength]
  let mul = 1
  while (byteLength > 0 && (mul *= 0x100)) {
    val += this[offset + --byteLength] * mul
  }

  return val
}

Buffer.prototype.readUint8 =
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 1, this.length)
  return this[offset]
}

Buffer.prototype.readUint16LE =
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  return this[offset] | (this[offset + 1] << 8)
}

Buffer.prototype.readUint16BE =
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  return (this[offset] << 8) | this[offset + 1]
}

Buffer.prototype.readUint32LE =
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return ((this[offset]) |
      (this[offset + 1] << 8) |
      (this[offset + 2] << 16)) +
      (this[offset + 3] * 0x1000000)
}

Buffer.prototype.readUint32BE =
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset] * 0x1000000) +
    ((this[offset + 1] << 16) |
    (this[offset + 2] << 8) |
    this[offset + 3])
}

Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) {
  offset = offset >>> 0
  validateNumber(offset, 'offset')
  const first = this[offset]
  const last = this[offset + 7]
  if (first === undefined || last === undefined) {
    boundsError(offset, this.length - 8)
  }

  const lo = first +
    this[++offset] * 2 ** 8 +
    this[++offset] * 2 ** 16 +
    this[++offset] * 2 ** 24

  const hi = this[++offset] +
    this[++offset] * 2 ** 8 +
    this[++offset] * 2 ** 16 +
    last * 2 ** 24

  return BigInt(lo) + (BigInt(hi) << BigInt(32))
})

Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) {
  offset = offset >>> 0
  validateNumber(offset, 'offset')
  const first = this[offset]
  const last = this[offset + 7]
  if (first === undefined || last === undefined) {
    boundsError(offset, this.length - 8)
  }

  const hi = first * 2 ** 24 +
    this[++offset] * 2 ** 16 +
    this[++offset] * 2 ** 8 +
    this[++offset]

  const lo = this[++offset] * 2 ** 24 +
    this[++offset] * 2 ** 16 +
    this[++offset] * 2 ** 8 +
    last

  return (BigInt(hi) << BigInt(32)) + BigInt(lo)
})

Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  let val = this[offset]
  let mul = 1
  let i = 0
  while (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul
  }
  mul *= 0x80

  if (val >= mul) val -= Math.pow(2, 8 * byteLength)

  return val
}

Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  let i = byteLength
  let mul = 1
  let val = this[offset + --i]
  while (i > 0 && (mul *= 0x100)) {
    val += this[offset + --i] * mul
  }
  mul *= 0x80

  if (val >= mul) val -= Math.pow(2, 8 * byteLength)

  return val
}

Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 1, this.length)
  if (!(this[offset] & 0x80)) return (this[offset])
  return ((0xff - this[offset] + 1) * -1)
}

Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  const val = this[offset] | (this[offset + 1] << 8)
  return (val & 0x8000) ? val | 0xFFFF0000 : val
}

Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  const val = this[offset + 1] | (this[offset] << 8)
  return (val & 0x8000) ? val | 0xFFFF0000 : val
}

Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset]) |
    (this[offset + 1] << 8) |
    (this[offset + 2] << 16) |
    (this[offset + 3] << 24)
}

Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset] << 24) |
    (this[offset + 1] << 16) |
    (this[offset + 2] << 8) |
    (this[offset + 3])
}

Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) {
  offset = offset >>> 0
  validateNumber(offset, 'offset')
  const first = this[offset]
  const last = this[offset + 7]
  if (first === undefined || last === undefined) {
    boundsError(offset, this.length - 8)
  }

  const val = this[offset + 4] +
    this[offset + 5] * 2 ** 8 +
    this[offset + 6] * 2 ** 16 +
    (last << 24) // Overflow

  return (BigInt(val) << BigInt(32)) +
    BigInt(first +
    this[++offset] * 2 ** 8 +
    this[++offset] * 2 ** 16 +
    this[++offset] * 2 ** 24)
})

Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) {
  offset = offset >>> 0
  validateNumber(offset, 'offset')
  const first = this[offset]
  const last = this[offset + 7]
  if (first === undefined || last === undefined) {
    boundsError(offset, this.length - 8)
  }

  const val = (first << 24) + // Overflow
    this[++offset] * 2 ** 16 +
    this[++offset] * 2 ** 8 +
    this[++offset]

  return (BigInt(val) << BigInt(32)) +
    BigInt(this[++offset] * 2 ** 24 +
    this[++offset] * 2 ** 16 +
    this[++offset] * 2 ** 8 +
    last)
})

Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)
  return ieee754.read(this, offset, true, 23, 4)
}

Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)
  return ieee754.read(this, offset, false, 23, 4)
}

Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 8, this.length)
  return ieee754.read(this, offset, true, 52, 8)
}

Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 8, this.length)
  return ieee754.read(this, offset, false, 52, 8)
}

function checkInt (buf, value, offset, ext, max, min) {
  if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
}

Buffer.prototype.writeUintLE =
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) {
    const maxBytes = Math.pow(2, 8 * byteLength) - 1
    checkInt(this, value, offset, byteLength, maxBytes, 0)
  }

  let mul = 1
  let i = 0
  this[offset] = value & 0xFF
  while (++i < byteLength && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeUintBE =
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) {
    const maxBytes = Math.pow(2, 8 * byteLength) - 1
    checkInt(this, value, offset, byteLength, maxBytes, 0)
  }

  let i = byteLength - 1
  let mul = 1
  this[offset + i] = value & 0xFF
  while (--i >= 0 && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeUint8 =
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  this[offset] = (value & 0xff)
  return offset + 1
}

Buffer.prototype.writeUint16LE =
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  this[offset] = (value & 0xff)
  this[offset + 1] = (value >>> 8)
  return offset + 2
}

Buffer.prototype.writeUint16BE =
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  this[offset] = (value >>> 8)
  this[offset + 1] = (value & 0xff)
  return offset + 2
}

Buffer.prototype.writeUint32LE =
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  this[offset + 3] = (value >>> 24)
  this[offset + 2] = (value >>> 16)
  this[offset + 1] = (value >>> 8)
  this[offset] = (value & 0xff)
  return offset + 4
}

Buffer.prototype.writeUint32BE =
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  this[offset] = (value >>> 24)
  this[offset + 1] = (value >>> 16)
  this[offset + 2] = (value >>> 8)
  this[offset + 3] = (value & 0xff)
  return offset + 4
}

function wrtBigUInt64LE (buf, value, offset, min, max) {
  checkIntBI(value, min, max, buf, offset, 7)

  let lo = Number(value & BigInt(0xffffffff))
  buf[offset++] = lo
  lo = lo >> 8
  buf[offset++] = lo
  lo = lo >> 8
  buf[offset++] = lo
  lo = lo >> 8
  buf[offset++] = lo
  let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))
  buf[offset++] = hi
  hi = hi >> 8
  buf[offset++] = hi
  hi = hi >> 8
  buf[offset++] = hi
  hi = hi >> 8
  buf[offset++] = hi
  return offset
}

function wrtBigUInt64BE (buf, value, offset, min, max) {
  checkIntBI(value, min, max, buf, offset, 7)

  let lo = Number(value & BigInt(0xffffffff))
  buf[offset + 7] = lo
  lo = lo >> 8
  buf[offset + 6] = lo
  lo = lo >> 8
  buf[offset + 5] = lo
  lo = lo >> 8
  buf[offset + 4] = lo
  let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))
  buf[offset + 3] = hi
  hi = hi >> 8
  buf[offset + 2] = hi
  hi = hi >> 8
  buf[offset + 1] = hi
  hi = hi >> 8
  buf[offset] = hi
  return offset + 8
}

Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) {
  return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))
})

Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) {
  return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))
})

Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    const limit = Math.pow(2, (8 * byteLength) - 1)

    checkInt(this, value, offset, byteLength, limit - 1, -limit)
  }

  let i = 0
  let mul = 1
  let sub = 0
  this[offset] = value & 0xFF
  while (++i < byteLength && (mul *= 0x100)) {
    if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
      sub = 1
    }
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    const limit = Math.pow(2, (8 * byteLength) - 1)

    checkInt(this, value, offset, byteLength, limit - 1, -limit)
  }

  let i = byteLength - 1
  let mul = 1
  let sub = 0
  this[offset + i] = value & 0xFF
  while (--i >= 0 && (mul *= 0x100)) {
    if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
      sub = 1
    }
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  if (value < 0) value = 0xff + value + 1
  this[offset] = (value & 0xff)
  return offset + 1
}

Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  this[offset] = (value & 0xff)
  this[offset + 1] = (value >>> 8)
  return offset + 2
}

Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  this[offset] = (value >>> 8)
  this[offset + 1] = (value & 0xff)
  return offset + 2
}

Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  this[offset] = (value & 0xff)
  this[offset + 1] = (value >>> 8)
  this[offset + 2] = (value >>> 16)
  this[offset + 3] = (value >>> 24)
  return offset + 4
}

Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  if (value < 0) value = 0xffffffff + value + 1
  this[offset] = (value >>> 24)
  this[offset + 1] = (value >>> 16)
  this[offset + 2] = (value >>> 8)
  this[offset + 3] = (value & 0xff)
  return offset + 4
}

Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) {
  return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))
})

Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {
  return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))
})

function checkIEEE754 (buf, value, offset, ext, max, min) {
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
  if (offset < 0) throw new RangeError('Index out of range')
}

function writeFloat (buf, value, offset, littleEndian, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  }
  ieee754.write(buf, value, offset, littleEndian, 23, 4)
  return offset + 4
}

Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  return writeFloat(this, value, offset, true, noAssert)
}

Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  return writeFloat(this, value, offset, false, noAssert)
}

function writeDouble (buf, value, offset, littleEndian, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  }
  ieee754.write(buf, value, offset, littleEndian, 52, 8)
  return offset + 8
}

Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  return writeDouble(this, value, offset, true, noAssert)
}

Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  return writeDouble(this, value, offset, false, noAssert)
}

// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  if (!start) start = 0
  if (!end && end !== 0) end = this.length
  if (targetStart >= target.length) targetStart = target.length
  if (!targetStart) targetStart = 0
  if (end > 0 && end < start) end = start

  // Copy 0 bytes; we're done
  if (end === start) return 0
  if (target.length === 0 || this.length === 0) return 0

  // Fatal error conditions
  if (targetStart < 0) {
    throw new RangeError('targetStart out of bounds')
  }
  if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  if (end < 0) throw new RangeError('sourceEnd out of bounds')

  // Are we oob?
  if (end > this.length) end = this.length
  if (target.length - targetStart < end - start) {
    end = target.length - targetStart + start
  }

  const len = end - start

  if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
    // Use built-in when available, missing from IE11
    this.copyWithin(targetStart, start, end)
  } else {
    Uint8Array.prototype.set.call(
      target,
      this.subarray(start, end),
      targetStart
    )
  }

  return len
}

// Usage:
//    buffer.fill(number[, offset[, end]])
//    buffer.fill(buffer[, offset[, end]])
//    buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
  // Handle string cases:
  if (typeof val === 'string') {
    if (typeof start === 'string') {
      encoding = start
      start = 0
      end = this.length
    } else if (typeof end === 'string') {
      encoding = end
      end = this.length
    }
    if (encoding !== undefined && typeof encoding !== 'string') {
      throw new TypeError('encoding must be a string')
    }
    if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
      throw new TypeError('Unknown encoding: ' + encoding)
    }
    if (val.length === 1) {
      const code = val.charCodeAt(0)
      if ((encoding === 'utf8' && code < 128) ||
          encoding === 'latin1') {
        // Fast path: If `val` fits into a single byte, use that numeric value.
        val = code
      }
    }
  } else if (typeof val === 'number') {
    val = val & 255
  } else if (typeof val === 'boolean') {
    val = Number(val)
  }

  // Invalid ranges are not set to a default, so can range check early.
  if (start < 0 || this.length < start || this.length < end) {
    throw new RangeError('Out of range index')
  }

  if (end <= start) {
    return this
  }

  start = start >>> 0
  end = end === undefined ? this.length : end >>> 0

  if (!val) val = 0

  let i
  if (typeof val === 'number') {
    for (i = start; i < end; ++i) {
      this[i] = val
    }
  } else {
    const bytes = Buffer.isBuffer(val)
      ? val
      : Buffer.from(val, encoding)
    const len = bytes.length
    if (len === 0) {
      throw new TypeError('The value "' + val +
        '" is invalid for argument "value"')
    }
    for (i = 0; i < end - start; ++i) {
      this[i + start] = bytes[i % len]
    }
  }

  return this
}

// CUSTOM ERRORS
// =============

// Simplified versions from Node, changed for Buffer-only usage
const errors = {}
function E (sym, getMessage, Base) {
  errors[sym] = class NodeError extends Base {
    constructor () {
      super()

      Object.defineProperty(this, 'message', {
        value: getMessage.apply(this, arguments),
        writable: true,
        configurable: true
      })

      // Add the error code to the name to include it in the stack trace.
      this.name = `${this.name} [${sym}]`
      // Access the stack to generate the error message including the error code
      // from the name.
      this.stack // eslint-disable-line no-unused-expressions
      // Reset the name to the actual name.
      delete this.name
    }

    get code () {
      return sym
    }

    set code (value) {
      Object.defineProperty(this, 'code', {
        configurable: true,
        enumerable: true,
        value,
        writable: true
      })
    }

    toString () {
      return `${this.name} [${sym}]: ${this.message}`
    }
  }
}

E('ERR_BUFFER_OUT_OF_BOUNDS',
  function (name) {
    if (name) {
      return `${name} is outside of buffer bounds`
    }

    return 'Attempt to access memory outside buffer bounds'
  }, RangeError)
E('ERR_INVALID_ARG_TYPE',
  function (name, actual) {
    return `The "${name}" argument must be of type number. Received type ${typeof actual}`
  }, TypeError)
E('ERR_OUT_OF_RANGE',
  function (str, range, input) {
    let msg = `The value of "${str}" is out of range.`
    let received = input
    if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
      received = addNumericalSeparator(String(input))
    } else if (typeof input === 'bigint') {
      received = String(input)
      if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
        received = addNumericalSeparator(received)
      }
      received += 'n'
    }
    msg += ` It must be ${range}. Received ${received}`
    return msg
  }, RangeError)

function addNumericalSeparator (val) {
  let res = ''
  let i = val.length
  const start = val[0] === '-' ? 1 : 0
  for (; i >= start + 4; i -= 3) {
    res = `_${val.slice(i - 3, i)}${res}`
  }
  return `${val.slice(0, i)}${res}`
}

// CHECK FUNCTIONS
// ===============

function checkBounds (buf, offset, byteLength) {
  validateNumber(offset, 'offset')
  if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {
    boundsError(offset, buf.length - (byteLength + 1))
  }
}

function checkIntBI (value, min, max, buf, offset, byteLength) {
  if (value > max || value < min) {
    const n = typeof min === 'bigint' ? 'n' : ''
    let range
    if (byteLength > 3) {
      if (min === 0 || min === BigInt(0)) {
        range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`
      } else {
        range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +
                `${(byteLength + 1) * 8 - 1}${n}`
      }
    } else {
      range = `>= ${min}${n} and <= ${max}${n}`
    }
    throw new errors.ERR_OUT_OF_RANGE('value', range, value)
  }
  checkBounds(buf, offset, byteLength)
}

function validateNumber (value, name) {
  if (typeof value !== 'number') {
    throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)
  }
}

function boundsError (value, length, type) {
  if (Math.floor(value) !== value) {
    validateNumber(value, type)
    throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value)
  }

  if (length < 0) {
    throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()
  }

  throw new errors.ERR_OUT_OF_RANGE(type || 'offset',
                                    `>= ${type ? 1 : 0} and <= ${length}`,
                                    value)
}

// HELPER FUNCTIONS
// ================

const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g

function base64clean (str) {
  // Node takes equal signs as end of the Base64 encoding
  str = str.split('=')[0]
  // Node strips out invalid characters like \n and \t from the string, base64-js does not
  str = str.trim().replace(INVALID_BASE64_RE, '')
  // Node converts strings with length < 2 to ''
  if (str.length < 2) return ''
  // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  while (str.length % 4 !== 0) {
    str = str + '='
  }
  return str
}

function utf8ToBytes (string, units) {
  units = units || Infinity
  let codePoint
  const length = string.length
  let leadSurrogate = null
  const bytes = []

  for (let i = 0; i < length; ++i) {
    codePoint = string.charCodeAt(i)

    // is surrogate component
    if (codePoint > 0xD7FF && codePoint < 0xE000) {
      // last char was a lead
      if (!leadSurrogate) {
        // no lead yet
        if (codePoint > 0xDBFF) {
          // unexpected trail
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
          continue
        } else if (i + 1 === length) {
          // unpaired lead
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
          continue
        }

        // valid lead
        leadSurrogate = codePoint

        continue
      }

      // 2 leads in a row
      if (codePoint < 0xDC00) {
        if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
        leadSurrogate = codePoint
        continue
      }

      // valid surrogate pair
      codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
    } else if (leadSurrogate) {
      // valid bmp char, but last char was a lead
      if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
    }

    leadSurrogate = null

    // encode utf8
    if (codePoint < 0x80) {
      if ((units -= 1) < 0) break
      bytes.push(codePoint)
    } else if (codePoint < 0x800) {
      if ((units -= 2) < 0) break
      bytes.push(
        codePoint >> 0x6 | 0xC0,
        codePoint & 0x3F | 0x80
      )
    } else if (codePoint < 0x10000) {
      if ((units -= 3) < 0) break
      bytes.push(
        codePoint >> 0xC | 0xE0,
        codePoint >> 0x6 & 0x3F | 0x80,
        codePoint & 0x3F | 0x80
      )
    } else if (codePoint < 0x110000) {
      if ((units -= 4) < 0) break
      bytes.push(
        codePoint >> 0x12 | 0xF0,
        codePoint >> 0xC & 0x3F | 0x80,
        codePoint >> 0x6 & 0x3F | 0x80,
        codePoint & 0x3F | 0x80
      )
    } else {
      throw new Error('Invalid code point')
    }
  }

  return bytes
}

function asciiToBytes (str) {
  const byteArray = []
  for (let i = 0; i < str.length; ++i) {
    // Node's code seems to be doing this and not & 0x7F..
    byteArray.push(str.charCodeAt(i) & 0xFF)
  }
  return byteArray
}

function utf16leToBytes (str, units) {
  let c, hi, lo
  const byteArray = []
  for (let i = 0; i < str.length; ++i) {
    if ((units -= 2) < 0) break

    c = str.charCodeAt(i)
    hi = c >> 8
    lo = c % 256
    byteArray.push(lo)
    byteArray.push(hi)
  }

  return byteArray
}

function base64ToBytes (str) {
  return base64.toByteArray(base64clean(str))
}

function blitBuffer (src, dst, offset, length) {
  let i
  for (i = 0; i < length; ++i) {
    if ((i + offset >= dst.length) || (i >= src.length)) break
    dst[i + offset] = src[i]
  }
  return i
}

// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
// the `instanceof` check but they should be treated as of that type.
// See: https://github.com/feross/buffer/issues/166
function isInstance (obj, type) {
  return obj instanceof type ||
    (obj != null && obj.constructor != null && obj.constructor.name != null &&
      obj.constructor.name === type.name)
}
function numberIsNaN (obj) {
  // For IE11 support
  return obj !== obj // eslint-disable-line no-self-compare
}

// Create lookup table for `toString('hex')`
// See: https://github.com/feross/buffer/issues/219
const hexSliceLookupTable = (function () {
  const alphabet = '0123456789abcdef'
  const table = new Array(256)
  for (let i = 0; i < 16; ++i) {
    const i16 = i * 16
    for (let j = 0; j < 16; ++j) {
      table[i16 + j] = alphabet[i] + alphabet[j]
    }
  }
  return table
})()

// Return not function with Error if BigInt not supported
function defineBigIntMethod (fn) {
  return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn
}

function BufferBigIntNotDefined () {
  throw new Error('BigInt not supported')
}


/***/ }),

/***/ 85220:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


const ipRegex = __webpack_require__(35140);

const defaultOpts = {exact: false};

const v4str = `${ipRegex.v4().source}\\/(3[0-2]|[12]?[0-9])`;
const v6str = `${ipRegex.v6().source}\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])`;

// can not precompile the non-exact regexes because global flag makes the regex object stateful
// which would require the user to reset .lastIndex on subsequent calls
const v4exact = new RegExp(`^${v4str}$`);
const v6exact = new RegExp(`^${v6str}$`);
const v46exact = new RegExp(`(?:^${v4str}$)|(?:^${v6str}$)`);

module.exports = ({exact} = defaultOpts) => exact ? v46exact : new RegExp(`(?:${v4str})|(?:${v6str})`, "g");
module.exports.v4 = ({exact} = defaultOpts) => exact ? v4exact : new RegExp(v4str, "g");
module.exports.v6 = ({exact} = defaultOpts) => exact ? v6exact : new RegExp(v6str, "g");


/***/ }),

/***/ 94156:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var Buffer = (__webpack_require__(60571).Buffer);
var Transform = (__webpack_require__(51940).Transform);
var StringDecoder = (__webpack_require__(63205)/* .StringDecoder */ .I);
var inherits = __webpack_require__(72116);

function CipherBase(hashMode) {
	Transform.call(this);
	this.hashMode = typeof hashMode === 'string';
	if (this.hashMode) {
		this[hashMode] = this._finalOrDigest;
	} else {
		this['final'] = this._finalOrDigest;
	}
	if (this._final) {
		this.__final = this._final;
		this._final = null;
	}
	this._decoder = null;
	this._encoding = null;
}
inherits(CipherBase, Transform);

var useUint8Array = typeof Uint8Array !== 'undefined';
var useArrayBuffer = typeof ArrayBuffer !== 'undefined'
	&& typeof Uint8Array !== 'undefined'
	&& ArrayBuffer.isView
	&& (Buffer.prototype instanceof Uint8Array || Buffer.TYPED_ARRAY_SUPPORT);

function toBuffer(data, encoding) {
	/*
	 * No need to do anything for exact instance
	 * This is only valid when safe-buffer.Buffer === buffer.Buffer, i.e. when Buffer.from/Buffer.alloc existed
	 */
	if (data instanceof Buffer) {
		return data;
	}

	// Convert strings to Buffer
	if (typeof data === 'string') {
		return Buffer.from(data, encoding);
	}

	/*
	 * Wrap any TypedArray instances and DataViews
	 * Makes sense only on engines with full TypedArray support -- let Buffer detect that
	 */
	if (useArrayBuffer && ArrayBuffer.isView(data)) {
		// Bug in Node.js <6.3.1, which treats this as out-of-bounds
		if (data.byteLength === 0) {
			return Buffer.alloc(0);
		}

		var res = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
		/*
		 * Recheck result size, as offset/length doesn't work on Node.js <5.10
		 * We just go to Uint8Array case if this fails
		 */
		if (res.byteLength === data.byteLength) {
			return res;
		}
	}

	/*
	 * Uint8Array in engines where Buffer.from might not work with ArrayBuffer, just copy over
	 * Doesn't make sense with other TypedArray instances
	 */
	if (useUint8Array && data instanceof Uint8Array) {
		return Buffer.from(data);
	}

	/*
	 * Old Buffer polyfill on an engine that doesn't have TypedArray support
	 * Also, this is from a different Buffer polyfill implementation then we have, as instanceof check failed
	 * Convert to our current Buffer implementation
	 */
	if (
		Buffer.isBuffer(data)
			&& data.constructor
			&& typeof data.constructor.isBuffer === 'function'
			&& data.constructor.isBuffer(data)
	) {
		return Buffer.from(data);
	}

	throw new TypeError('The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView.');
}

CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
	var bufferData = toBuffer(data, inputEnc); // asserts correct input type
	var outData = this._update(bufferData);
	if (this.hashMode) {
		return this;
	}

	if (outputEnc) {
		outData = this._toString(outData, outputEnc);
	}

	return outData;
};

CipherBase.prototype.setAutoPadding = function () {};
CipherBase.prototype.getAuthTag = function () {
	throw new Error('trying to get auth tag in unsupported state');
};

CipherBase.prototype.setAuthTag = function () {
	throw new Error('trying to set auth tag in unsupported state');
};

CipherBase.prototype.setAAD = function () {
	throw new Error('trying to set aad in unsupported state');
};

CipherBase.prototype._transform = function (data, _, next) {
	var err;
	try {
		if (this.hashMode) {
			this._update(data);
		} else {
			this.push(this._update(data));
		}
	} catch (e) {
		err = e;
	} finally {
		next(err);
	}
};
CipherBase.prototype._flush = function (done) {
	var err;
	try {
		this.push(this.__final());
	} catch (e) {
		err = e;
	}

	done(err);
};
CipherBase.prototype._finalOrDigest = function (outputEnc) {
	var outData = this.__final() || Buffer.alloc(0);
	if (outputEnc) {
		outData = this._toString(outData, outputEnc, true);
	}
	return outData;
};

CipherBase.prototype._toString = function (value, enc, fin) {
	if (!this._decoder) {
		this._decoder = new StringDecoder(enc);
		this._encoding = enc;
	}

	if (this._encoding !== enc) {
		throw new Error('can’t switch encodings');
	}

	var out = this._decoder.write(value);
	if (fin) {
		out += this._decoder.end();
	}

	return out;
};

module.exports = CipherBase;


/***/ }),

/***/ 51258:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


/**
 * Module dependenices
 */

const clone = __webpack_require__(4031);
const typeOf = __webpack_require__(17884);
const isPlainObject = __webpack_require__(18093);

function cloneDeep(val, instanceClone) {
  switch (typeOf(val)) {
    case 'object':
      return cloneObjectDeep(val, instanceClone);
    case 'array':
      return cloneArrayDeep(val, instanceClone);
    default: {
      return clone(val);
    }
  }
}

function cloneObjectDeep(val, instanceClone) {
  if (typeof instanceClone === 'function') {
    return instanceClone(val);
  }
  if (instanceClone || isPlainObject(val)) {
    const res = new val.constructor();
    for (let key in val) {
      res[key] = cloneDeep(val[key], instanceClone);
    }
    return res;
  }
  return val;
}

function cloneArrayDeep(val, instanceClone) {
  const res = new val.constructor(val.length);
  for (let i = 0; i < val.length; i++) {
    res[i] = cloneDeep(val[i], instanceClone);
  }
  return res;
}

/**
 * Expose `cloneDeep`
 */

module.exports = cloneDeep;


/***/ }),

/***/ 86731:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.

function isArray(arg) {
  if (Array.isArray) {
    return Array.isArray(arg);
  }
  return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;

function isBoolean(arg) {
  return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;

function isNull(arg) {
  return arg === null;
}
exports.isNull = isNull;

function isNullOrUndefined(arg) {
  return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;

function isNumber(arg) {
  return typeof arg === 'number';
}
exports.isNumber = isNumber;

function isString(arg) {
  return typeof arg === 'string';
}
exports.isString = isString;

function isSymbol(arg) {
  return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;

function isUndefined(arg) {
  return arg === void 0;
}
exports.isUndefined = isUndefined;

function isRegExp(re) {
  return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;

function isObject(arg) {
  return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;

function isDate(d) {
  return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;

function isError(e) {
  return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;

function isFunction(arg) {
  return typeof arg === 'function';
}
exports.isFunction = isFunction;

function isPrimitive(arg) {
  return arg === null ||
         typeof arg === 'boolean' ||
         typeof arg === 'number' ||
         typeof arg === 'string' ||
         typeof arg === 'symbol' ||  // ES6 symbol
         typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;

exports.isBuffer = __webpack_require__(78378).Buffer.isBuffer;

function objectToString(o) {
  return Object.prototype.toString.call(o);
}


/***/ }),

/***/ 67999:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var elliptic = __webpack_require__(74198)
var BN = __webpack_require__(89991)

module.exports = function createECDH (curve) {
  return new ECDH(curve)
}

var aliases = {
  secp256k1: {
    name: 'secp256k1',
    byteLength: 32
  },
  secp224r1: {
    name: 'p224',
    byteLength: 28
  },
  prime256v1: {
    name: 'p256',
    byteLength: 32
  },
  prime192v1: {
    name: 'p192',
    byteLength: 24
  },
  ed25519: {
    name: 'ed25519',
    byteLength: 32
  },
  secp384r1: {
    name: 'p384',
    byteLength: 48
  },
  secp521r1: {
    name: 'p521',
    byteLength: 66
  }
}

aliases.p224 = aliases.secp224r1
aliases.p256 = aliases.secp256r1 = aliases.prime256v1
aliases.p192 = aliases.secp192r1 = aliases.prime192v1
aliases.p384 = aliases.secp384r1
aliases.p521 = aliases.secp521r1

function ECDH (curve) {
  this.curveType = aliases[curve]
  if (!this.curveType) {
    this.curveType = {
      name: curve
    }
  }
  this.curve = new elliptic.ec(this.curveType.name) // eslint-disable-line new-cap
  this.keys = void 0
}

ECDH.prototype.generateKeys = function (enc, format) {
  this.keys = this.curve.genKeyPair()
  return this.getPublicKey(enc, format)
}

ECDH.prototype.computeSecret = function (other, inenc, enc) {
  inenc = inenc || 'utf8'
  if (!Buffer.isBuffer(other)) {
    other = new Buffer(other, inenc)
  }
  var otherPub = this.curve.keyFromPublic(other).getPublic()
  var out = otherPub.mul(this.keys.getPrivate()).getX()
  return formatReturnValue(out, enc, this.curveType.byteLength)
}

ECDH.prototype.getPublicKey = function (enc, format) {
  var key = this.keys.getPublic(format === 'compressed', true)
  if (format === 'hybrid') {
    if (key[key.length - 1] % 2) {
      key[0] = 7
    } else {
      key[0] = 6
    }
  }
  return formatReturnValue(key, enc)
}

ECDH.prototype.getPrivateKey = function (enc) {
  return formatReturnValue(this.keys.getPrivate(), enc)
}

ECDH.prototype.setPublicKey = function (pub, enc) {
  enc = enc || 'utf8'
  if (!Buffer.isBuffer(pub)) {
    pub = new Buffer(pub, enc)
  }
  this.keys._importPublic(pub)
  return this
}

ECDH.prototype.setPrivateKey = function (priv, enc) {
  enc = enc || 'utf8'
  if (!Buffer.isBuffer(priv)) {
    priv = new Buffer(priv, enc)
  }

  var _priv = new BN(priv)
  _priv = _priv.toString(16)
  this.keys = this.curve.genKeyPair()
  this.keys._importPrivate(_priv)
  return this
}

function formatReturnValue (bn, enc, len) {
  if (!Array.isArray(bn)) {
    bn = bn.toArray()
  }
  var buf = new Buffer(bn)
  if (len && buf.length < len) {
    var zeros = new Buffer(len - buf.length)
    zeros.fill(0)
    buf = Buffer.concat([zeros, buf])
  }
  if (!enc) {
    return buf
  } else {
    return buf.toString(enc)
  }
}


/***/ }),

/***/ 63044:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var inherits = __webpack_require__(72116)
var MD5 = __webpack_require__(29160)
var RIPEMD160 = __webpack_require__(84861)
var sha = __webpack_require__(79997)
var Base = __webpack_require__(94156)

function Hash (hash) {
  Base.call(this, 'digest')

  this._hash = hash
}

inherits(Hash, Base)

Hash.prototype._update = function (data) {
  this._hash.update(data)
}

Hash.prototype._final = function () {
  return this._hash.digest()
}

module.exports = function createHash (alg) {
  alg = alg.toLowerCase()
  if (alg === 'md5') return new MD5()
  if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160()

  return new Hash(sha(alg))
}


/***/ }),

/***/ 51168:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var MD5 = __webpack_require__(29160)

module.exports = function (buffer) {
  return new MD5().update(buffer).digest()
}


/***/ }),

/***/ 65842:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var inherits = __webpack_require__(72116)
var Legacy = __webpack_require__(16531)
var Base = __webpack_require__(94156)
var Buffer = (__webpack_require__(60571).Buffer)
var md5 = __webpack_require__(51168)
var RIPEMD160 = __webpack_require__(84861)

var sha = __webpack_require__(79997)

var ZEROS = Buffer.alloc(128)

function Hmac (alg, key) {
  Base.call(this, 'digest')
  if (typeof key === 'string') {
    key = Buffer.from(key)
  }

  var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64

  this._alg = alg
  this._key = key
  if (key.length > blocksize) {
    var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
    key = hash.update(key).digest()
  } else if (key.length < blocksize) {
    key = Buffer.concat([key, ZEROS], blocksize)
  }

  var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
  var opad = this._opad = Buffer.allocUnsafe(blocksize)

  for (var i = 0; i < blocksize; i++) {
    ipad[i] = key[i] ^ 0x36
    opad[i] = key[i] ^ 0x5C
  }
  this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
  this._hash.update(ipad)
}

inherits(Hmac, Base)

Hmac.prototype._update = function (data) {
  this._hash.update(data)
}

Hmac.prototype._final = function () {
  var h = this._hash.digest()
  var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)
  return hash.update(this._opad).update(h).digest()
}

module.exports = function createHmac (alg, key) {
  alg = alg.toLowerCase()
  if (alg === 'rmd160' || alg === 'ripemd160') {
    return new Hmac('rmd160', key)
  }
  if (alg === 'md5') {
    return new Legacy(md5, key)
  }
  return new Hmac(alg, key)
}


/***/ }),

/***/ 16531:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var inherits = __webpack_require__(72116)
var Buffer = (__webpack_require__(60571).Buffer)

var Base = __webpack_require__(94156)

var ZEROS = Buffer.alloc(128)
var blocksize = 64

function Hmac (alg, key) {
  Base.call(this, 'digest')
  if (typeof key === 'string') {
    key = Buffer.from(key)
  }

  this._alg = alg
  this._key = key

  if (key.length > blocksize) {
    key = alg(key)
  } else if (key.length < blocksize) {
    key = Buffer.concat([key, ZEROS], blocksize)
  }

  var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
  var opad = this._opad = Buffer.allocUnsafe(blocksize)

  for (var i = 0; i < blocksize; i++) {
    ipad[i] = key[i] ^ 0x36
    opad[i] = key[i] ^ 0x5C
  }

  this._hash = [ipad]
}

inherits(Hmac, Base)

Hmac.prototype._update = function (data) {
  this._hash.push(data)
}

Hmac.prototype._final = function () {
  var h = this._alg(Buffer.concat(this._hash))
  return this._alg(Buffer.concat([this._opad, h]))
}
module.exports = Hmac


/***/ }),

/***/ 23923:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";


exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = __webpack_require__(66290)
exports.createHash = exports.Hash = __webpack_require__(63044)
exports.createHmac = exports.Hmac = __webpack_require__(65842)

var algos = __webpack_require__(44076)
var algoKeys = Object.keys(algos)
var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys)
exports.getHashes = function () {
  return hashes
}

var p = __webpack_require__(8033)
exports.pbkdf2 = p.pbkdf2
exports.pbkdf2Sync = p.pbkdf2Sync

var aes = __webpack_require__(12209)

exports.Cipher = aes.Cipher
exports.createCipher = aes.createCipher
exports.Cipheriv = aes.Cipheriv
exports.createCipheriv = aes.createCipheriv
exports.Decipher = aes.Decipher
exports.createDecipher = aes.createDecipher
exports.Decipheriv = aes.Decipheriv
exports.createDecipheriv = aes.createDecipheriv
exports.getCiphers = aes.getCiphers
exports.listCiphers = aes.listCiphers

var dh = __webpack_require__(13195)

exports.DiffieHellmanGroup = dh.DiffieHellmanGroup
exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup
exports.getDiffieHellman = dh.getDiffieHellman
exports.createDiffieHellman = dh.createDiffieHellman
exports.DiffieHellman = dh.DiffieHellman

var sign = __webpack_require__(29483)

exports.createSign = sign.createSign
exports.Sign = sign.Sign
exports.createVerify = sign.createVerify
exports.Verify = sign.Verify

exports.createECDH = __webpack_require__(67999)

var publicEncrypt = __webpack_require__(74352)

exports.publicEncrypt = publicEncrypt.publicEncrypt
exports.privateEncrypt = publicEncrypt.privateEncrypt
exports.publicDecrypt = publicEncrypt.publicDecrypt
exports.privateDecrypt = publicEncrypt.privateDecrypt

// the least I can do is make error messages for the rest of the node.js/crypto api.
// ;[
//   'createCredentials'
// ].forEach(function (name) {
//   exports[name] = function () {
//     throw new Error([
//       'sorry, ' + name + ' is not implemented yet',
//       'we accept pull requests',
//       'https://github.com/crypto-browserify/crypto-browserify'
//     ].join('\n'))
//   }
// })

var rf = __webpack_require__(66026)

exports.randomFill = rf.randomFill
exports.randomFillSync = rf.randomFillSync

exports.createCredentials = function () {
  throw new Error([
    'sorry, createCredentials is not implemented yet',
    'we accept pull requests',
    'https://github.com/crypto-browserify/crypto-browserify'
  ].join('\n'))
}

exports.constants = {
  'DH_CHECK_P_NOT_SAFE_PRIME': 2,
  'DH_CHECK_P_NOT_PRIME': 1,
  'DH_UNABLE_TO_CHECK_GENERATOR': 4,
  'DH_NOT_SUITABLE_GENERATOR': 8,
  'NPN_ENABLED': 1,
  'ALPN_ENABLED': 1,
  'RSA_PKCS1_PADDING': 1,
  'RSA_SSLV23_PADDING': 2,
  'RSA_NO_PADDING': 3,
  'RSA_PKCS1_OAEP_PADDING': 4,
  'RSA_X931_PADDING': 5,
  'RSA_PKCS1_PSS_PADDING': 6,
  'POINT_CONVERSION_COMPRESSED': 2,
  'POINT_CONVERSION_UNCOMPRESSED': 4,
  'POINT_CONVERSION_HYBRID': 6
}


/***/ }),

/***/ 50322:
/***/ (function(module, exports, __webpack_require__) {

;(function (root, factory) {
	if (true) {
		// CommonJS
		module.exports = exports = factory();
	}
	else {}
}(this, function () {

	/*globals window, global, require*/

	/**
	 * CryptoJS core components.
	 */
	var CryptoJS = CryptoJS || (function (Math, undefined) {

	    var crypto;

	    // Native crypto from window (Browser)
	    if (typeof window !== 'undefined' && window.crypto) {
	        crypto = window.crypto;
	    }

	    // Native crypto in web worker (Browser)
	    if (typeof self !== 'undefined' && self.crypto) {
	        crypto = self.crypto;
	    }

	    // Native crypto from worker
	    if (typeof globalThis !== 'undefined' && globalThis.crypto) {
	        crypto = globalThis.crypto;
	    }

	    // Native (experimental IE 11) crypto from window (Browser)
	    if (!crypto && typeof window !== 'undefined' && window.msCrypto) {
	        crypto = window.msCrypto;
	    }

	    // Native crypto from global (NodeJS)
	    if (!crypto && typeof __webpack_require__.g !== 'undefined' && __webpack_require__.g.crypto) {
	        crypto = __webpack_require__.g.crypto;
	    }

	    // Native crypto import via require (NodeJS)
	    if (!crypto && "function" === 'function') {
	        try {
	            crypto = __webpack_require__(73936);
	        } catch (err) {}
	    }

	    /*
	     * Cryptographically secure pseudorandom number generator
	     *
	     * As Math.random() is cryptographically not safe to use
	     */
	    var cryptoSecureRandomInt = function () {
	        if (crypto) {
	            // Use getRandomValues method (Browser)
	            if (typeof crypto.getRandomValues === 'function') {
	                try {
	                    return crypto.getRandomValues(new Uint32Array(1))[0];
	                } catch (err) {}
	            }

	            // Use randomBytes method (NodeJS)
	            if (typeof crypto.randomBytes === 'function') {
	                try {
	                    return crypto.randomBytes(4).readInt32LE();
	                } catch (err) {}
	            }
	        }

	        throw new Error('Native crypto module could not be used to get secure random number.');
	    };

	    /*
	     * Local polyfill of Object.create

	     */
	    var create = Object.create || (function () {
	        function F() {}

	        return function (obj) {
	            var subtype;

	            F.prototype = obj;

	            subtype = new F();

	            F.prototype = null;

	            return subtype;
	        };
	    }());

	    /**
	     * CryptoJS namespace.
	     */
	    var C = {};

	    /**
	     * Library namespace.
	     */
	    var C_lib = C.lib = {};

	    /**
	     * Base object for prototypal inheritance.
	     */
	    var Base = C_lib.Base = (function () {


	        return {
	            /**
	             * Creates a new object that inherits from this object.
	             *
	             * @param {Object} overrides Properties to copy into the new object.
	             *
	             * @return {Object} The new object.
	             *
	             * @static
	             *
	             * @example
	             *
	             *     var MyType = CryptoJS.lib.Base.extend({
	             *         field: 'value',
	             *
	             *         method: function () {
	             *         }
	             *     });
	             */
	            extend: function (overrides) {
	                // Spawn
	                var subtype = create(this);

	                // Augment
	                if (overrides) {
	                    subtype.mixIn(overrides);
	                }

	                // Create default initializer
	                if (!subtype.hasOwnProperty('init') || this.init === subtype.init) {
	                    subtype.init = function () {
	                        subtype.$super.init.apply(this, arguments);
	                    };
	                }

	                // Initializer's prototype is the subtype object
	                subtype.init.prototype = subtype;

	                // Reference supertype
	                subtype.$super = this;

	                return subtype;
	            },

	            /**
	             * Extends this object and runs the init method.
	             * Arguments to create() will be passed to init().
	             *
	             * @return {Object} The new object.
	             *
	             * @static
	             *
	             * @example
	             *
	             *     var instance = MyType.create();
	             */
	            create: function () {
	                var instance = this.extend();
	                instance.init.apply(instance, arguments);

	                return instance;
	            },

	            /**
	             * Initializes a newly created object.
	             * Override this method to add some logic when your objects are created.
	             *
	             * @example
	             *
	             *     var MyType = CryptoJS.lib.Base.extend({
	             *         init: function () {
	             *             // ...
	             *         }
	             *     });
	             */
	            init: function () {
	            },

	            /**
	             * Copies properties into this object.
	             *
	             * @param {Object} properties The properties to mix in.
	             *
	             * @example
	             *
	             *     MyType.mixIn({
	             *         field: 'value'
	             *     });
	             */
	            mixIn: function (properties) {
	                for (var propertyName in properties) {
	                    if (properties.hasOwnProperty(propertyName)) {
	                        this[propertyName] = properties[propertyName];
	                    }
	                }

	                // IE won't copy toString using the loop above
	                if (properties.hasOwnProperty('toString')) {
	                    this.toString = properties.toString;
	                }
	            },

	            /**
	             * Creates a copy of this object.
	             *
	             * @return {Object} The clone.
	             *
	             * @example
	             *
	             *     var clone = instance.clone();
	             */
	            clone: function () {
	                return this.init.prototype.extend(this);
	            }
	        };
	    }());

	    /**
	     * An array of 32-bit words.
	     *
	     * @property {Array} words The array of 32-bit words.
	     * @property {number} sigBytes The number of significant bytes in this word array.
	     */
	    var WordArray = C_lib.WordArray = Base.extend({
	        /**
	         * Initializes a newly created word array.
	         *
	         * @param {Array} words (Optional) An array of 32-bit words.
	         * @param {number} sigBytes (Optional) The number of significant bytes in the words.
	         *
	         * @example
	         *
	         *     var wordArray = CryptoJS.lib.WordArray.create();
	         *     var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
	         *     var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
	         */
	        init: function (words, sigBytes) {
	            words = this.words = words || [];

	            if (sigBytes != undefined) {
	                this.sigBytes = sigBytes;
	            } else {
	                this.sigBytes = words.length * 4;
	            }
	        },

	        /**
	         * Converts this word array to a string.
	         *
	         * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
	         *
	         * @return {string} The stringified word array.
	         *
	         * @example
	         *
	         *     var string = wordArray + '';
	         *     var string = wordArray.toString();
	         *     var string = wordArray.toString(CryptoJS.enc.Utf8);
	         */
	        toString: function (encoder) {
	            return (encoder || Hex).stringify(this);
	        },

	        /**
	         * Concatenates a word array to this word array.
	         *
	         * @param {WordArray} wordArray The word array to append.
	         *
	         * @return {WordArray} This word array.
	         *
	         * @example
	         *
	         *     wordArray1.concat(wordArray2);
	         */
	        concat: function (wordArray) {
	            // Shortcuts
	            var thisWords = this.words;
	            var thatWords = wordArray.words;
	            var thisSigBytes = this.sigBytes;
	            var thatSigBytes = wordArray.sigBytes;

	            // Clamp excess bits
	            this.clamp();

	            // Concat
	            if (thisSigBytes % 4) {
	                // Copy one byte at a time
	                for (var i = 0; i < thatSigBytes; i++) {
	                    var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
	                    thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
	                }
	            } else {
	                // Copy one word at a time
	                for (var j = 0; j < thatSigBytes; j += 4) {
	                    thisWords[(thisSigBytes + j) >>> 2] = thatWords[j >>> 2];
	                }
	            }
	            this.sigBytes += thatSigBytes;

	            // Chainable
	            return this;
	        },

	        /**
	         * Removes insignificant bits.
	         *
	         * @example
	         *
	         *     wordArray.clamp();
	         */
	        clamp: function () {
	            // Shortcuts
	            var words = this.words;
	            var sigBytes = this.sigBytes;

	            // Clamp
	            words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
	            words.length = Math.ceil(sigBytes / 4);
	        },

	        /**
	         * Creates a copy of this word array.
	         *
	         * @return {WordArray} The clone.
	         *
	         * @example
	         *
	         *     var clone = wordArray.clone();
	         */
	        clone: function () {
	            var clone = Base.clone.call(this);
	            clone.words = this.words.slice(0);

	            return clone;
	        },

	        /**
	         * Creates a word array filled with random bytes.
	         *
	         * @param {number} nBytes The number of random bytes to generate.
	         *
	         * @return {WordArray} The random word array.
	         *
	         * @static
	         *
	         * @example
	         *
	         *     var wordArray = CryptoJS.lib.WordArray.random(16);
	         */
	        random: function (nBytes) {
	            var words = [];

	            for (var i = 0; i < nBytes; i += 4) {
	                words.push(cryptoSecureRandomInt());
	            }

	            return new WordArray.init(words, nBytes);
	        }
	    });

	    /**
	     * Encoder namespace.
	     */
	    var C_enc = C.enc = {};

	    /**
	     * Hex encoding strategy.
	     */
	    var Hex = C_enc.Hex = {
	        /**
	         * Converts a word array to a hex string.
	         *
	         * @param {WordArray} wordArray The word array.
	         *
	         * @return {string} The hex string.
	         *
	         * @static
	         *
	         * @example
	         *
	         *     var hexString = CryptoJS.enc.Hex.stringify(wordArray);
	         */
	        stringify: function (wordArray) {
	            // Shortcuts
	            var words = wordArray.words;
	            var sigBytes = wordArray.sigBytes;

	            // Convert
	            var hexChars = [];
	            for (var i = 0; i < sigBytes; i++) {
	                var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
	                hexChars.push((bite >>> 4).toString(16));
	                hexChars.push((bite & 0x0f).toString(16));
	            }

	            return hexChars.join('');
	        },

	        /**
	         * Converts a hex string to a word array.
	         *
	         * @param {string} hexStr The hex string.
	         *
	         * @return {WordArray} The word array.
	         *
	         * @static
	         *
	         * @example
	         *
	         *     var wordArray = CryptoJS.enc.Hex.parse(hexString);
	         */
	        parse: function (hexStr) {
	            // Shortcut
	            var hexStrLength = hexStr.length;

	            // Convert
	            var words = [];
	            for (var i = 0; i < hexStrLength; i += 2) {
	                words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
	            }

	            return new WordArray.init(words, hexStrLength / 2);
	        }
	    };

	    /**
	     * Latin1 encoding strategy.
	     */
	    var Latin1 = C_enc.Latin1 = {
	        /**
	         * Converts a word array to a Latin1 string.
	         *
	         * @param {WordArray} wordArray The word array.
	         *
	         * @return {string} The Latin1 string.
	         *
	         * @static
	         *
	         * @example
	         *
	         *     var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
	         */
	        stringify: function (wordArray) {
	            // Shortcuts
	            var words = wordArray.words;
	            var sigBytes = wordArray.sigBytes;

	            // Convert
	            var latin1Chars = [];
	            for (var i = 0; i < sigBytes; i++) {
	                var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
	                latin1Chars.push(String.fromCharCode(bite));
	            }

	            return latin1Chars.join('');
	        },

	        /**
	         * Converts a Latin1 string to a word array.
	         *
	         * @param {string} latin1Str The Latin1 string.
	         *
	         * @return {WordArray} The word array.
	         *
	         * @static
	         *
	         * @example
	         *
	         *     var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
	         */
	        parse: function (latin1Str) {
	            // Shortcut
	            var latin1StrLength = latin1Str.length;

	            // Convert
	            var words = [];
	            for (var i = 0; i < latin1StrLength; i++) {
	                words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
	            }

	            return new WordArray.init(words, latin1StrLength);
	        }
	    };

	    /**
	     * UTF-8 encoding strategy.
	     */
	    var Utf8 = C_enc.Utf8 = {
	        /**
	         * Converts a word array to a UTF-8 string.
	         *
	         * @param {WordArray} wordArray The word array.
	         *
	         * @return {string} The UTF-8 string.
	         *
	         * @static
	         *
	         * @example
	         *
	         *     var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
	         */
	        stringify: function (wordArray) {
	            try {
	                return decodeURIComponent(escape(Latin1.stringify(wordArray)));
	            } catch (e) {
	                throw new Error('Malformed UTF-8 data');
	            }
	        },

	        /**
	         * Converts a UTF-8 string to a word array.
	         *
	         * @param {string} utf8Str The UTF-8 string.
	         *
	         * @return {WordArray} The word array.
	         *
	         * @static
	         *
	         * @example
	         *
	         *     var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
	         */
	        parse: function (utf8Str) {
	            return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
	        }
	    };

	    /**
	     * Abstract buffered block algorithm template.
	     *
	     * The property blockSize must be implemented in a concrete subtype.
	     *
	     * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
	     */
	    var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
	        /**
	         * Resets this block algorithm's data buffer to its initial state.
	         *
	         * @example
	         *
	         *     bufferedBlockAlgorithm.reset();
	         */
	        reset: function () {
	            // Initial values
	            this._data = new WordArray.init();
	            this._nDataBytes = 0;
	        },

	        /**
	         * Adds new data to this block algorithm's buffer.
	         *
	         * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
	         *
	         * @example
	         *
	         *     bufferedBlockAlgorithm._append('data');
	         *     bufferedBlockAlgorithm._append(wordArray);
	         */
	        _append: function (data) {
	            // Convert string to WordArray, else assume WordArray already
	            if (typeof data == 'string') {
	                data = Utf8.parse(data);
	            }

	            // Append
	            this._data.concat(data);
	            this._nDataBytes += data.sigBytes;
	        },

	        /**
	         * Processes available data blocks.
	         *
	         * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
	         *
	         * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
	         *
	         * @return {WordArray} The processed data.
	         *
	         * @example
	         *
	         *     var processedData = bufferedBlockAlgorithm._process();
	         *     var processedData = bufferedBlockAlgorithm._process(!!'flush');
	         */
	        _process: function (doFlush) {
	            var processedWords;

	            // Shortcuts
	            var data = this._data;
	            var dataWords = data.words;
	            var dataSigBytes = data.sigBytes;
	            var blockSize = this.blockSize;
	            var blockSizeBytes = blockSize * 4;

	            // Count blocks ready
	            var nBlocksReady = dataSigBytes / blockSizeBytes;
	            if (doFlush) {
	                // Round up to include partial blocks
	                nBlocksReady = Math.ceil(nBlocksReady);
	            } else {
	                // Round down to include only full blocks,
	                // less the number of blocks that must remain in the buffer
	                nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
	            }

	            // Count words ready
	            var nWordsReady = nBlocksReady * blockSize;

	            // Count bytes ready
	            var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);

	            // Process blocks
	            if (nWordsReady) {
	                for (var offset = 0; offset < nWordsReady; offset += blockSize) {
	                    // Perform concrete-algorithm logic
	                    this._doProcessBlock(dataWords, offset);
	                }

	                // Remove processed words
	                processedWords = dataWords.splice(0, nWordsReady);
	                data.sigBytes -= nBytesReady;
	            }

	            // Return processed words
	            return new WordArray.init(processedWords, nBytesReady);
	        },

	        /**
	         * Creates a copy of this object.
	         *
	         * @return {Object} The clone.
	         *
	         * @example
	         *
	         *     var clone = bufferedBlockAlgorithm.clone();
	         */
	        clone: function () {
	            var clone = Base.clone.call(this);
	            clone._data = this._data.clone();

	            return clone;
	        },

	        _minBufferSize: 0
	    });

	    /**
	     * Abstract hasher template.
	     *
	     * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
	     */
	    var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
	        /**
	         * Configuration options.
	         */
	        cfg: Base.extend(),

	        /**
	         * Initializes a newly created hasher.
	         *
	         * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
	         *
	         * @example
	         *
	         *     var hasher = CryptoJS.algo.SHA256.create();
	         */
	        init: function (cfg) {
	            // Apply config defaults
	            this.cfg = this.cfg.extend(cfg);

	            // Set initial values
	            this.reset();
	        },

	        /**
	         * Resets this hasher to its initial state.
	         *
	         * @example
	         *
	         *     hasher.reset();
	         */
	        reset: function () {
	            // Reset data buffer
	            BufferedBlockAlgorithm.reset.call(this);

	            // Perform concrete-hasher logic
	            this._doReset();
	        },

	        /**
	         * Updates this hasher with a message.
	         *
	         * @param {WordArray|string} messageUpdate The message to append.
	         *
	         * @return {Hasher} This hasher.
	         *
	         * @example
	         *
	         *     hasher.update('message');
	         *     hasher.update(wordArray);
	         */
	        update: function (messageUpdate) {
	            // Append
	            this._append(messageUpdate);

	            // Update the hash
	            this._process();

	            // Chainable
	            return this;
	        },

	        /**
	         * Finalizes the hash computation.
	         * Note that the finalize operation is effectively a destructive, read-once operation.
	         *
	         * @param {WordArray|string} messageUpdate (Optional) A final message update.
	         *
	         * @return {WordArray} The hash.
	         *
	         * @example
	         *
	         *     var hash = hasher.finalize();
	         *     var hash = hasher.finalize('message');
	         *     var hash = hasher.finalize(wordArray);
	         */
	        finalize: function (messageUpdate) {
	            // Final message update
	            if (messageUpdate) {
	                this._append(messageUpdate);
	            }

	            // Perform concrete-hasher logic
	            var hash = this._doFinalize();

	            return hash;
	        },

	        blockSize: 512/32,

	        /**
	         * Creates a shortcut function to a hasher's object interface.
	         *
	         * @param {Hasher} hasher The hasher to create a helper for.
	         *
	         * @return {Function} The shortcut function.
	         *
	         * @static
	         *
	         * @example
	         *
	         *     var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
	         */
	        _createHelper: function (hasher) {
	            return function (message, cfg) {
	                return new hasher.init(cfg).finalize(message);
	            };
	        },

	        /**
	         * Creates a shortcut function to the HMAC's object interface.
	         *
	         * @param {Hasher} hasher The hasher to use in this HMAC helper.
	         *
	         * @return {Function} The shortcut function.
	         *
	         * @static
	         *
	         * @example
	         *
	         *     var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
	         */
	        _createHmacHelper: function (hasher) {
	            return function (message, key) {
	                return new C_algo.HMAC.init(hasher, key).finalize(message);
	            };
	        }
	    });

	    /**
	     * Algorithm namespace.
	     */
	    var C_algo = C.algo = {};

	    return C;
	}(Math));


	return CryptoJS;

}));

/***/ }),

/***/ 55625:
/***/ (function(module, exports, __webpack_require__) {

;(function (root, factory) {
	if (true) {
		// CommonJS
		module.exports = exports = factory(__webpack_require__(50322));
	}
	else {}
}(this, function (CryptoJS) {

	(function (Math) {
	    // Shortcuts
	    var C = CryptoJS;
	    var C_lib = C.lib;
	    var WordArray = C_lib.WordArray;
	    var Hasher = C_lib.Hasher;
	    var C_algo = C.algo;

	    // Constants table
	    var T = [];

	    // Compute constants
	    (function () {
	        for (var i = 0; i < 64; i++) {
	            T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
	        }
	    }());

	    /**
	     * MD5 hash algorithm.
	     */
	    var MD5 = C_algo.MD5 = Hasher.extend({
	        _doReset: function () {
	            this._hash = new WordArray.init([
	                0x67452301, 0xefcdab89,
	                0x98badcfe, 0x10325476
	            ]);
	        },

	        _doProcessBlock: function (M, offset) {
	            // Swap endian
	            for (var i = 0; i < 16; i++) {
	                // Shortcuts
	                var offset_i = offset + i;
	                var M_offset_i = M[offset_i];

	                M[offset_i] = (
	                    (((M_offset_i << 8)  | (M_offset_i >>> 24)) & 0x00ff00ff) |
	                    (((M_offset_i << 24) | (M_offset_i >>> 8))  & 0xff00ff00)
	                );
	            }

	            // Shortcuts
	            var H = this._hash.words;

	            var M_offset_0  = M[offset + 0];
	            var M_offset_1  = M[offset + 1];
	            var M_offset_2  = M[offset + 2];
	            var M_offset_3  = M[offset + 3];
	            var M_offset_4  = M[offset + 4];
	            var M_offset_5  = M[offset + 5];
	            var M_offset_6  = M[offset + 6];
	            var M_offset_7  = M[offset + 7];
	            var M_offset_8  = M[offset + 8];
	            var M_offset_9  = M[offset + 9];
	            var M_offset_10 = M[offset + 10];
	            var M_offset_11 = M[offset + 11];
	            var M_offset_12 = M[offset + 12];
	            var M_offset_13 = M[offset + 13];
	            var M_offset_14 = M[offset + 14];
	            var M_offset_15 = M[offset + 15];

	            // Working variables
	            var a = H[0];
	            var b = H[1];
	            var c = H[2];
	            var d = H[3];

	            // Computation
	            a = FF(a, b, c, d, M_offset_0,  7,  T[0]);
	            d = FF(d, a, b, c, M_offset_1,  12, T[1]);
	            c = FF(c, d, a, b, M_offset_2,  17, T[2]);
	            b = FF(b, c, d, a, M_offset_3,  22, T[3]);
	            a = FF(a, b, c, d, M_offset_4,  7,  T[4]);
	            d = FF(d, a, b, c, M_offset_5,  12, T[5]);
	            c = FF(c, d, a, b, M_offset_6,  17, T[6]);
	            b = FF(b, c, d, a, M_offset_7,  22, T[7]);
	            a = FF(a, b, c, d, M_offset_8,  7,  T[8]);
	            d = FF(d, a, b, c, M_offset_9,  12, T[9]);
	            c = FF(c, d, a, b, M_offset_10, 17, T[10]);
	            b = FF(b, c, d, a, M_offset_11, 22, T[11]);
	            a = FF(a, b, c, d, M_offset_12, 7,  T[12]);
	            d = FF(d, a, b, c, M_offset_13, 12, T[13]);
	            c = FF(c, d, a, b, M_offset_14, 17, T[14]);
	            b = FF(b, c, d, a, M_offset_15, 22, T[15]);

	            a = GG(a, b, c, d, M_offset_1,  5,  T[16]);
	            d = GG(d, a, b, c, M_offset_6,  9,  T[17]);
	            c = GG(c, d, a, b, M_offset_11, 14, T[18]);
	            b = GG(b, c, d, a, M_offset_0,  20, T[19]);
	            a = GG(a, b, c, d, M_offset_5,  5,  T[20]);
	            d = GG(d, a, b, c, M_offset_10, 9,  T[21]);
	            c = GG(c, d, a, b, M_offset_15, 14, T[22]);
	            b = GG(b, c, d, a, M_offset_4,  20, T[23]);
	            a = GG(a, b, c, d, M_offset_9,  5,  T[24]);
	            d = GG(d, a, b, c, M_offset_14, 9,  T[25]);
	            c = GG(c, d, a, b, M_offset_3,  14, T[26]);
	            b = GG(b, c, d, a, M_offset_8,  20, T[27]);
	            a = GG(a, b, c, d, M_offset_13, 5,  T[28]);
	            d = GG(d, a, b, c, M_offset_2,  9,  T[29]);
	            c = GG(c, d, a, b, M_offset_7,  14, T[30]);
	            b = GG(b, c, d, a, M_offset_12, 20, T[31]);

	            a = HH(a, b, c, d, M_offset_5,  4,  T[32]);
	            d = HH(d, a, b, c, M_offset_8,  11, T[33]);
	            c = HH(c, d, a, b, M_offset_11, 16, T[34]);
	            b = HH(b, c, d, a, M_offset_14, 23, T[35]);
	            a = HH(a, b, c, d, M_offset_1,  4,  T[36]);
	            d = HH(d, a, b, c, M_offset_4,  11, T[37]);
	            c = HH(c, d, a, b, M_offset_7,  16, T[38]);
	            b = HH(b, c, d, a, M_offset_10, 23, T[39]);
	            a = HH(a, b, c, d, M_offset_13, 4,  T[40]);
	            d = HH(d, a, b, c, M_offset_0,  11, T[41]);
	            c = HH(c, d, a, b, M_offset_3,  16, T[42]);
	            b = HH(b, c, d, a, M_offset_6,  23, T[43]);
	            a = HH(a, b, c, d, M_offset_9,  4,  T[44]);
	            d = HH(d, a, b, c, M_offset_12, 11, T[45]);
	            c = HH(c, d, a, b, M_offset_15, 16, T[46]);
	            b = HH(b, c, d, a, M_offset_2,  23, T[47]);

	            a = II(a, b, c, d, M_offset_0,  6,  T[48]);
	            d = II(d, a, b, c, M_offset_7,  10, T[49]);
	            c = II(c, d, a, b, M_offset_14, 15, T[50]);
	            b = II(b, c, d, a, M_offset_5,  21, T[51]);
	            a = II(a, b, c, d, M_offset_12, 6,  T[52]);
	            d = II(d, a, b, c, M_offset_3,  10, T[53]);
	            c = II(c, d, a, b, M_offset_10, 15, T[54]);
	            b = II(b, c, d, a, M_offset_1,  21, T[55]);
	            a = II(a, b, c, d, M_offset_8,  6,  T[56]);
	            d = II(d, a, b, c, M_offset_15, 10, T[57]);
	            c = II(c, d, a, b, M_offset_6,  15, T[58]);
	            b = II(b, c, d, a, M_offset_13, 21, T[59]);
	            a = II(a, b, c, d, M_offset_4,  6,  T[60]);
	            d = II(d, a, b, c, M_offset_11, 10, T[61]);
	            c = II(c, d, a, b, M_offset_2,  15, T[62]);
	            b = II(b, c, d, a, M_offset_9,  21, T[63]);

	            // Intermediate hash value
	            H[0] = (H[0] + a) | 0;
	            H[1] = (H[1] + b) | 0;
	            H[2] = (H[2] + c) | 0;
	            H[3] = (H[3] + d) | 0;
	        },

	        _doFinalize: function () {
	            // Shortcuts
	            var data = this._data;
	            var dataWords = data.words;

	            var nBitsTotal = this._nDataBytes * 8;
	            var nBitsLeft = data.sigBytes * 8;

	            // Add padding
	            dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);

	            var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
	            var nBitsTotalL = nBitsTotal;
	            dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (
	                (((nBitsTotalH << 8)  | (nBitsTotalH >>> 24)) & 0x00ff00ff) |
	                (((nBitsTotalH << 24) | (nBitsTotalH >>> 8))  & 0xff00ff00)
	            );
	            dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
	                (((nBitsTotalL << 8)  | (nBitsTotalL >>> 24)) & 0x00ff00ff) |
	                (((nBitsTotalL << 24) | (nBitsTotalL >>> 8))  & 0xff00ff00)
	            );

	            data.sigBytes = (dataWords.length + 1) * 4;

	            // Hash final blocks
	            this._process();

	            // Shortcuts
	            var hash = this._hash;
	            var H = hash.words;

	            // Swap endian
	            for (var i = 0; i < 4; i++) {
	                // Shortcut
	                var H_i = H[i];

	                H[i] = (((H_i << 8)  | (H_i >>> 24)) & 0x00ff00ff) |
	                       (((H_i << 24) | (H_i >>> 8))  & 0xff00ff00);
	            }

	            // Return final computed hash
	            return hash;
	        },

	        clone: function () {
	            var clone = Hasher.clone.call(this);
	            clone._hash = this._hash.clone();

	            return clone;
	        }
	    });

	    function FF(a, b, c, d, x, s, t) {
	        var n = a + ((b & c) | (~b & d)) + x + t;
	        return ((n << s) | (n >>> (32 - s))) + b;
	    }

	    function GG(a, b, c, d, x, s, t) {
	        var n = a + ((b & d) | (c & ~d)) + x + t;
	        return ((n << s) | (n >>> (32 - s))) + b;
	    }

	    function HH(a, b, c, d, x, s, t) {
	        var n = a + (b ^ c ^ d) + x + t;
	        return ((n << s) | (n >>> (32 - s))) + b;
	    }

	    function II(a, b, c, d, x, s, t) {
	        var n = a + (c ^ (b | ~d)) + x + t;
	        return ((n << s) | (n >>> (32 - s))) + b;
	    }

	    /**
	     * Shortcut function to the hasher's object interface.
	     *
	     * @param {WordArray|string} message The message to hash.
	     *
	     * @return {WordArray} The hash.
	     *
	     * @static
	     *
	     * @example
	     *
	     *     var hash = CryptoJS.MD5('message');
	     *     var hash = CryptoJS.MD5(wordArray);
	     */
	    C.MD5 = Hasher._createHelper(MD5);

	    /**
	     * Shortcut function to the HMAC's object interface.
	     *
	     * @param {WordArray|string} message The message to hash.
	     * @param {WordArray|string} key The secret key.
	     *
	     * @return {WordArray} The HMAC.
	     *
	     * @static
	     *
	     * @example
	     *
	     *     var hmac = CryptoJS.HmacMD5(message, key);
	     */
	    C.HmacMD5 = Hasher._createHmacHelper(MD5);
	}(Math));


	return CryptoJS.MD5;

}));

/***/ }),

/***/ 67050:
/***/ (function(module, exports, __webpack_require__) {

;(function (root, factory) {
	if (true) {
		// CommonJS
		module.exports = exports = factory(__webpack_require__(50322));
	}
	else {}
}(this, function (CryptoJS) {

	(function (Math) {
	    // Shortcuts
	    var C = CryptoJS;
	    var C_lib = C.lib;
	    var WordArray = C_lib.WordArray;
	    var Hasher = C_lib.Hasher;
	    var C_algo = C.algo;

	    // Initialization and round constants tables
	    var H = [];
	    var K = [];

	    // Compute constants
	    (function () {
	        function isPrime(n) {
	            var sqrtN = Math.sqrt(n);
	            for (var factor = 2; factor <= sqrtN; factor++) {
	                if (!(n % factor)) {
	                    return false;
	                }
	            }

	            return true;
	        }

	        function getFractionalBits(n) {
	            return ((n - (n | 0)) * 0x100000000) | 0;
	        }

	        var n = 2;
	        var nPrime = 0;
	        while (nPrime < 64) {
	            if (isPrime(n)) {
	                if (nPrime < 8) {
	                    H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
	                }
	                K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));

	                nPrime++;
	            }

	            n++;
	        }
	    }());

	    // Reusable object
	    var W = [];

	    /**
	     * SHA-256 hash algorithm.
	     */
	    var SHA256 = C_algo.SHA256 = Hasher.extend({
	        _doReset: function () {
	            this._hash = new WordArray.init(H.slice(0));
	        },

	        _doProcessBlock: function (M, offset) {
	            // Shortcut
	            var H = this._hash.words;

	            // Working variables
	            var a = H[0];
	            var b = H[1];
	            var c = H[2];
	            var d = H[3];
	            var e = H[4];
	            var f = H[5];
	            var g = H[6];
	            var h = H[7];

	            // Computation
	            for (var i = 0; i < 64; i++) {
	                if (i < 16) {
	                    W[i] = M[offset + i] | 0;
	                } else {
	                    var gamma0x = W[i - 15];
	                    var gamma0  = ((gamma0x << 25) | (gamma0x >>> 7))  ^
	                                  ((gamma0x << 14) | (gamma0x >>> 18)) ^
	                                   (gamma0x >>> 3);

	                    var gamma1x = W[i - 2];
	                    var gamma1  = ((gamma1x << 15) | (gamma1x >>> 17)) ^
	                                  ((gamma1x << 13) | (gamma1x >>> 19)) ^
	                                   (gamma1x >>> 10);

	                    W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
	                }

	                var ch  = (e & f) ^ (~e & g);
	                var maj = (a & b) ^ (a & c) ^ (b & c);

	                var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
	                var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7)  | (e >>> 25));

	                var t1 = h + sigma1 + ch + K[i] + W[i];
	                var t2 = sigma0 + maj;

	                h = g;
	                g = f;
	                f = e;
	                e = (d + t1) | 0;
	                d = c;
	                c = b;
	                b = a;
	                a = (t1 + t2) | 0;
	            }

	            // Intermediate hash value
	            H[0] = (H[0] + a) | 0;
	            H[1] = (H[1] + b) | 0;
	            H[2] = (H[2] + c) | 0;
	            H[3] = (H[3] + d) | 0;
	            H[4] = (H[4] + e) | 0;
	            H[5] = (H[5] + f) | 0;
	            H[6] = (H[6] + g) | 0;
	            H[7] = (H[7] + h) | 0;
	        },

	        _doFinalize: function () {
	            // Shortcuts
	            var data = this._data;
	            var dataWords = data.words;

	            var nBitsTotal = this._nDataBytes * 8;
	            var nBitsLeft = data.sigBytes * 8;

	            // Add padding
	            dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
	            dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
	            dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
	            data.sigBytes = dataWords.length * 4;

	            // Hash final blocks
	            this._process();

	            // Return final computed hash
	            return this._hash;
	        },

	        clone: function () {
	            var clone = Hasher.clone.call(this);
	            clone._hash = this._hash.clone();

	            return clone;
	        }
	    });

	    /**
	     * Shortcut function to the hasher's object interface.
	     *
	     * @param {WordArray|string} message The message to hash.
	     *
	     * @return {WordArray} The hash.
	     *
	     * @static
	     *
	     * @example
	     *
	     *     var hash = CryptoJS.SHA256('message');
	     *     var hash = CryptoJS.SHA256(wordArray);
	     */
	    C.SHA256 = Hasher._createHelper(SHA256);

	    /**
	     * Shortcut function to the HMAC's object interface.
	     *
	     * @param {WordArray|string} message The message to hash.
	     * @param {WordArray|string} key The secret key.
	     *
	     * @return {WordArray} The HMAC.
	     *
	     * @static
	     *
	     * @example
	     *
	     *     var hmac = CryptoJS.HmacSHA256(message, key);
	     */
	    C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
	}(Math));


	return CryptoJS.SHA256;

}));

/***/ }),

/***/ 17893:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";


exports.utils = __webpack_require__(47615);
exports.Cipher = __webpack_require__(5235);
exports.DES = __webpack_require__(92734);
exports.CBC = __webpack_require__(8376);
exports.EDE = __webpack_require__(95234);


/***/ }),

/***/ 8376:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";


var assert = __webpack_require__(2481);
var inherits = __webpack_require__(72116);

var proto = {};

function CBCState(iv) {
  assert.equal(iv.length, 8, 'Invalid IV length');

  this.iv = new Array(8);
  for (var i = 0; i < this.iv.length; i++)
    this.iv[i] = iv[i];
}

function instantiate(Base) {
  function CBC(options) {
    Base.call(this, options);
    this._cbcInit();
  }
  inherits(CBC, Base);

  var keys = Object.keys(proto);
  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    CBC.prototype[key] = proto[key];
  }

  CBC.create = function create(options) {
    return new CBC(options);
  };

  return CBC;
}

exports.instantiate = instantiate;

proto._cbcInit = function _cbcInit() {
  var state = new CBCState(this.options.iv);
  this._cbcState = state;
};

proto._update = function _update(inp, inOff, out, outOff) {
  var state = this._cbcState;
  var superProto = this.constructor.super_.prototype;

  var iv = state.iv;
  if (this.type === 'encrypt') {
    for (var i = 0; i < this.blockSize; i++)
      iv[i] ^= inp[inOff + i];

    superProto._update.call(this, iv, 0, out, outOff);

    for (var i = 0; i < this.blockSize; i++)
      iv[i] = out[outOff + i];
  } else {
    superProto._update.call(this, inp, inOff, out, outOff);

    for (var i = 0; i < this.blockSize; i++)
      out[outOff + i] ^= iv[i];

    for (var i = 0; i < this.blockSize; i++)
      iv[i] = inp[inOff + i];
  }
};


/***/ }),

/***/ 5235:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var assert = __webpack_require__(2481);

function Cipher(options) {
  this.options = options;

  this.type = this.options.type;
  this.blockSize = 8;
  this._init();

  this.buffer = new Array(this.blockSize);
  this.bufferOff = 0;
  this.padding = options.padding !== false
}
module.exports = Cipher;

Cipher.prototype._init = function _init() {
  // Might be overrided
};

Cipher.prototype.update = function update(data) {
  if (data.length === 0)
    return [];

  if (this.type === 'decrypt')
    return this._updateDecrypt(data);
  else
    return this._updateEncrypt(data);
};

Cipher.prototype._buffer = function _buffer(data, off) {
  // Append data to buffer
  var min = Math.min(this.buffer.length - this.bufferOff, data.length - off);
  for (var i = 0; i < min; i++)
    this.buffer[this.bufferOff + i] = data[off + i];
  this.bufferOff += min;

  // Shift next
  return min;
};

Cipher.prototype._flushBuffer = function _flushBuffer(out, off) {
  this._update(this.buffer, 0, out, off);
  this.bufferOff = 0;
  return this.blockSize;
};

Cipher.prototype._updateEncrypt = function _updateEncrypt(data) {
  var inputOff = 0;
  var outputOff = 0;

  var count = ((this.bufferOff + data.length) / this.blockSize) | 0;
  var out = new Array(count * this.blockSize);

  if (this.bufferOff !== 0) {
    inputOff += this._buffer(data, inputOff);

    if (this.bufferOff === this.buffer.length)
      outputOff += this._flushBuffer(out, outputOff);
  }

  // Write blocks
  var max = data.length - ((data.length - inputOff) % this.blockSize);
  for (; inputOff < max; inputOff += this.blockSize) {
    this._update(data, inputOff, out, outputOff);
    outputOff += this.blockSize;
  }

  // Queue rest
  for (; inputOff < data.length; inputOff++, this.bufferOff++)
    this.buffer[this.bufferOff] = data[inputOff];

  return out;
};

Cipher.prototype._updateDecrypt = function _updateDecrypt(data) {
  var inputOff = 0;
  var outputOff = 0;

  var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1;
  var out = new Array(count * this.blockSize);

  // TODO(indutny): optimize it, this is far from optimal
  for (; count > 0; count--) {
    inputOff += this._buffer(data, inputOff);
    outputOff += this._flushBuffer(out, outputOff);
  }

  // Buffer rest of the input
  inputOff += this._buffer(data, inputOff);

  return out;
};

Cipher.prototype.final = function final(buffer) {
  var first;
  if (buffer)
    first = this.update(buffer);

  var last;
  if (this.type === 'encrypt')
    last = this._finalEncrypt();
  else
    last = this._finalDecrypt();

  if (first)
    return first.concat(last);
  else
    return last;
};

Cipher.prototype._pad = function _pad(buffer, off) {
  if (off === 0)
    return false;

  while (off < buffer.length)
    buffer[off++] = 0;

  return true;
};

Cipher.prototype._finalEncrypt = function _finalEncrypt() {
  if (!this._pad(this.buffer, this.bufferOff))
    return [];

  var out = new Array(this.blockSize);
  this._update(this.buffer, 0, out, 0);
  return out;
};

Cipher.prototype._unpad = function _unpad(buffer) {
  return buffer;
};

Cipher.prototype._finalDecrypt = function _finalDecrypt() {
  assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt');
  var out = new Array(this.blockSize);
  this._flushBuffer(out, 0);

  return this._unpad(out);
};


/***/ }),

/***/ 92734:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var assert = __webpack_require__(2481);
var inherits = __webpack_require__(72116);

var utils = __webpack_require__(47615);
var Cipher = __webpack_require__(5235);

function DESState() {
  this.tmp = new Array(2);
  this.keys = null;
}

function DES(options) {
  Cipher.call(this, options);

  var state = new DESState();
  this._desState = state;

  this.deriveKeys(state, options.key);
}
inherits(DES, Cipher);
module.exports = DES;

DES.create = function create(options) {
  return new DES(options);
};

var shiftTable = [
  1, 1, 2, 2, 2, 2, 2, 2,
  1, 2, 2, 2, 2, 2, 2, 1
];

DES.prototype.deriveKeys = function deriveKeys(state, key) {
  state.keys = new Array(16 * 2);

  assert.equal(key.length, this.blockSize, 'Invalid key length');

  var kL = utils.readUInt32BE(key, 0);
  var kR = utils.readUInt32BE(key, 4);

  utils.pc1(kL, kR, state.tmp, 0);
  kL = state.tmp[0];
  kR = state.tmp[1];
  for (var i = 0; i < state.keys.length; i += 2) {
    var shift = shiftTable[i >>> 1];
    kL = utils.r28shl(kL, shift);
    kR = utils.r28shl(kR, shift);
    utils.pc2(kL, kR, state.keys, i);
  }
};

DES.prototype._update = function _update(inp, inOff, out, outOff) {
  var state = this._desState;

  var l = utils.readUInt32BE(inp, inOff);
  var r = utils.readUInt32BE(inp, inOff + 4);

  // Initial Permutation
  utils.ip(l, r, state.tmp, 0);
  l = state.tmp[0];
  r = state.tmp[1];

  if (this.type === 'encrypt')
    this._encrypt(state, l, r, state.tmp, 0);
  else
    this._decrypt(state, l, r, state.tmp, 0);

  l = state.tmp[0];
  r = state.tmp[1];

  utils.writeUInt32BE(out, l, outOff);
  utils.writeUInt32BE(out, r, outOff + 4);
};

DES.prototype._pad = function _pad(buffer, off) {
  if (this.padding === false) {
    return false;
  }

  var value = buffer.length - off;
  for (var i = off; i < buffer.length; i++)
    buffer[i] = value;

  return true;
};

DES.prototype._unpad = function _unpad(buffer) {
  if (this.padding === false) {
    return buffer;
  }

  var pad = buffer[buffer.length - 1];
  for (var i = buffer.length - pad; i < buffer.length; i++)
    assert.equal(buffer[i], pad);

  return buffer.slice(0, buffer.length - pad);
};

DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) {
  var l = lStart;
  var r = rStart;

  // Apply f() x16 times
  for (var i = 0; i < state.keys.length; i += 2) {
    var keyL = state.keys[i];
    var keyR = state.keys[i + 1];

    // f(r, k)
    utils.expand(r, state.tmp, 0);

    keyL ^= state.tmp[0];
    keyR ^= state.tmp[1];
    var s = utils.substitute(keyL, keyR);
    var f = utils.permute(s);

    var t = r;
    r = (l ^ f) >>> 0;
    l = t;
  }

  // Reverse Initial Permutation
  utils.rip(r, l, out, off);
};

DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) {
  var l = rStart;
  var r = lStart;

  // Apply f() x16 times
  for (var i = state.keys.length - 2; i >= 0; i -= 2) {
    var keyL = state.keys[i];
    var keyR = state.keys[i + 1];

    // f(r, k)
    utils.expand(l, state.tmp, 0);

    keyL ^= state.tmp[0];
    keyR ^= state.tmp[1];
    var s = utils.substitute(keyL, keyR);
    var f = utils.permute(s);

    var t = l;
    l = (r ^ f) >>> 0;
    r = t;
  }

  // Reverse Initial Permutation
  utils.rip(l, r, out, off);
};


/***/ }),

/***/ 95234:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var assert = __webpack_require__(2481);
var inherits = __webpack_require__(72116);

var Cipher = __webpack_require__(5235);
var DES = __webpack_require__(92734);

function EDEState(type, key) {
  assert.equal(key.length, 24, 'Invalid key length');

  var k1 = key.slice(0, 8);
  var k2 = key.slice(8, 16);
  var k3 = key.slice(16, 24);

  if (type === 'encrypt') {
    this.ciphers = [
      DES.create({ type: 'encrypt', key: k1 }),
      DES.create({ type: 'decrypt', key: k2 }),
      DES.create({ type: 'encrypt', key: k3 })
    ];
  } else {
    this.ciphers = [
      DES.create({ type: 'decrypt', key: k3 }),
      DES.create({ type: 'encrypt', key: k2 }),
      DES.create({ type: 'decrypt', key: k1 })
    ];
  }
}

function EDE(options) {
  Cipher.call(this, options);

  var state = new EDEState(this.type, this.options.key);
  this._edeState = state;
}
inherits(EDE, Cipher);

module.exports = EDE;

EDE.create = function create(options) {
  return new EDE(options);
};

EDE.prototype._update = function _update(inp, inOff, out, outOff) {
  var state = this._edeState;

  state.ciphers[0]._update(inp, inOff, out, outOff);
  state.ciphers[1]._update(out, outOff, out, outOff);
  state.ciphers[2]._update(out, outOff, out, outOff);
};

EDE.prototype._pad = DES.prototype._pad;
EDE.prototype._unpad = DES.prototype._unpad;


/***/ }),

/***/ 47615:
/***/ ((__unused_webpack_module, exports) => {

"use strict";


exports.readUInt32BE = function readUInt32BE(bytes, off) {
  var res =  (bytes[0 + off] << 24) |
             (bytes[1 + off] << 16) |
             (bytes[2 + off] << 8) |
             bytes[3 + off];
  return res >>> 0;
};

exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) {
  bytes[0 + off] = value >>> 24;
  bytes[1 + off] = (value >>> 16) & 0xff;
  bytes[2 + off] = (value >>> 8) & 0xff;
  bytes[3 + off] = value & 0xff;
};

exports.ip = function ip(inL, inR, out, off) {
  var outL = 0;
  var outR = 0;

  for (var i = 6; i >= 0; i -= 2) {
    for (var j = 0; j <= 24; j += 8) {
      outL <<= 1;
      outL |= (inR >>> (j + i)) & 1;
    }
    for (var j = 0; j <= 24; j += 8) {
      outL <<= 1;
      outL |= (inL >>> (j + i)) & 1;
    }
  }

  for (var i = 6; i >= 0; i -= 2) {
    for (var j = 1; j <= 25; j += 8) {
      outR <<= 1;
      outR |= (inR >>> (j + i)) & 1;
    }
    for (var j = 1; j <= 25; j += 8) {
      outR <<= 1;
      outR |= (inL >>> (j + i)) & 1;
    }
  }

  out[off + 0] = outL >>> 0;
  out[off + 1] = outR >>> 0;
};

exports.rip = function rip(inL, inR, out, off) {
  var outL = 0;
  var outR = 0;

  for (var i = 0; i < 4; i++) {
    for (var j = 24; j >= 0; j -= 8) {
      outL <<= 1;
      outL |= (inR >>> (j + i)) & 1;
      outL <<= 1;
      outL |= (inL >>> (j + i)) & 1;
    }
  }
  for (var i = 4; i < 8; i++) {
    for (var j = 24; j >= 0; j -= 8) {
      outR <<= 1;
      outR |= (inR >>> (j + i)) & 1;
      outR <<= 1;
      outR |= (inL >>> (j + i)) & 1;
    }
  }

  out[off + 0] = outL >>> 0;
  out[off + 1] = outR >>> 0;
};

exports.pc1 = function pc1(inL, inR, out, off) {
  var outL = 0;
  var outR = 0;

  // 7, 15, 23, 31, 39, 47, 55, 63
  // 6, 14, 22, 30, 39, 47, 55, 63
  // 5, 13, 21, 29, 39, 47, 55, 63
  // 4, 12, 20, 28
  for (var i = 7; i >= 5; i--) {
    for (var j = 0; j <= 24; j += 8) {
      outL <<= 1;
      outL |= (inR >> (j + i)) & 1;
    }
    for (var j = 0; j <= 24; j += 8) {
      outL <<= 1;
      outL |= (inL >> (j + i)) & 1;
    }
  }
  for (var j = 0; j <= 24; j += 8) {
    outL <<= 1;
    outL |= (inR >> (j + i)) & 1;
  }

  // 1, 9, 17, 25, 33, 41, 49, 57
  // 2, 10, 18, 26, 34, 42, 50, 58
  // 3, 11, 19, 27, 35, 43, 51, 59
  // 36, 44, 52, 60
  for (var i = 1; i <= 3; i++) {
    for (var j = 0; j <= 24; j += 8) {
      outR <<= 1;
      outR |= (inR >> (j + i)) & 1;
    }
    for (var j = 0; j <= 24; j += 8) {
      outR <<= 1;
      outR |= (inL >> (j + i)) & 1;
    }
  }
  for (var j = 0; j <= 24; j += 8) {
    outR <<= 1;
    outR |= (inL >> (j + i)) & 1;
  }

  out[off + 0] = outL >>> 0;
  out[off + 1] = outR >>> 0;
};

exports.r28shl = function r28shl(num, shift) {
  return ((num << shift) & 0xfffffff) | (num >>> (28 - shift));
};

var pc2table = [
  // inL => outL
  14, 11, 17, 4, 27, 23, 25, 0,
  13, 22, 7, 18, 5, 9, 16, 24,
  2, 20, 12, 21, 1, 8, 15, 26,

  // inR => outR
  15, 4, 25, 19, 9, 1, 26, 16,
  5, 11, 23, 8, 12, 7, 17, 0,
  22, 3, 10, 14, 6, 20, 27, 24
];

exports.pc2 = function pc2(inL, inR, out, off) {
  var outL = 0;
  var outR = 0;

  var len = pc2table.length >>> 1;
  for (var i = 0; i < len; i++) {
    outL <<= 1;
    outL |= (inL >>> pc2table[i]) & 0x1;
  }
  for (var i = len; i < pc2table.length; i++) {
    outR <<= 1;
    outR |= (inR >>> pc2table[i]) & 0x1;
  }

  out[off + 0] = outL >>> 0;
  out[off + 1] = outR >>> 0;
};

exports.expand = function expand(r, out, off) {
  var outL = 0;
  var outR = 0;

  outL = ((r & 1) << 5) | (r >>> 27);
  for (var i = 23; i >= 15; i -= 4) {
    outL <<= 6;
    outL |= (r >>> i) & 0x3f;
  }
  for (var i = 11; i >= 3; i -= 4) {
    outR |= (r >>> i) & 0x3f;
    outR <<= 6;
  }
  outR |= ((r & 0x1f) << 1) | (r >>> 31);

  out[off + 0] = outL >>> 0;
  out[off + 1] = outR >>> 0;
};

var sTable = [
  14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1,
  3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8,
  4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7,
  15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13,

  15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14,
  9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5,
  0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2,
  5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9,

  10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10,
  1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1,
  13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7,
  11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12,

  7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3,
  1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9,
  10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8,
  15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14,

  2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1,
  8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6,
  4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13,
  15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3,

  12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5,
  0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8,
  9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10,
  7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13,

  4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10,
  3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6,
  1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7,
  10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12,

  13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4,
  10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2,
  7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13,
  0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11
];

exports.substitute = function substitute(inL, inR) {
  var out = 0;
  for (var i = 0; i < 4; i++) {
    var b = (inL >>> (18 - i * 6)) & 0x3f;
    var sb = sTable[i * 0x40 + b];

    out <<= 4;
    out |= sb;
  }
  for (var i = 0; i < 4; i++) {
    var b = (inR >>> (18 - i * 6)) & 0x3f;
    var sb = sTable[4 * 0x40 + i * 0x40 + b];

    out <<= 4;
    out |= sb;
  }
  return out >>> 0;
};

var permuteTable = [
  16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22,
  30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7
];

exports.permute = function permute(num) {
  var out = 0;
  for (var i = 0; i < permuteTable.length; i++) {
    out <<= 1;
    out |= (num >>> permuteTable[i]) & 0x1;
  }
  return out >>> 0;
};

exports.padSplit = function padSplit(num, size, group) {
  var str = num.toString(2);
  while (str.length < size)
    str = '0' + str;

  var out = [];
  for (var i = 0; i < size; i += group)
    out.push(str.slice(i, i + group));
  return out.join(' ');
};


/***/ }),

/***/ 13195:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var generatePrime = __webpack_require__(26937)
var primes = __webpack_require__(54828)

var DH = __webpack_require__(34055)

function getDiffieHellman (mod) {
  var prime = new Buffer(primes[mod].prime, 'hex')
  var gen = new Buffer(primes[mod].gen, 'hex')

  return new DH(prime, gen)
}

var ENCODINGS = {
  'binary': true, 'hex': true, 'base64': true
}

function createDiffieHellman (prime, enc, generator, genc) {
  if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) {
    return createDiffieHellman(prime, 'binary', enc, generator)
  }

  enc = enc || 'binary'
  genc = genc || 'binary'
  generator = generator || new Buffer([2])

  if (!Buffer.isBuffer(generator)) {
    generator = new Buffer(generator, genc)
  }

  if (typeof prime === 'number') {
    return new DH(generatePrime(prime, generator), generator, true)
  }

  if (!Buffer.isBuffer(prime)) {
    prime = new Buffer(prime, enc)
  }

  return new DH(prime, generator, true)
}

exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman
exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman


/***/ }),

/***/ 34055:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var BN = __webpack_require__(89991);
var MillerRabin = __webpack_require__(7427);
var millerRabin = new MillerRabin();
var TWENTYFOUR = new BN(24);
var ELEVEN = new BN(11);
var TEN = new BN(10);
var THREE = new BN(3);
var SEVEN = new BN(7);
var primes = __webpack_require__(26937);
var randomBytes = __webpack_require__(66290);
module.exports = DH;

function setPublicKey(pub, enc) {
  enc = enc || 'utf8';
  if (!Buffer.isBuffer(pub)) {
    pub = new Buffer(pub, enc);
  }
  this._pub = new BN(pub);
  return this;
}

function setPrivateKey(priv, enc) {
  enc = enc || 'utf8';
  if (!Buffer.isBuffer(priv)) {
    priv = new Buffer(priv, enc);
  }
  this._priv = new BN(priv);
  return this;
}

var primeCache = {};
function checkPrime(prime, generator) {
  var gen = generator.toString('hex');
  var hex = [gen, prime.toString(16)].join('_');
  if (hex in primeCache) {
    return primeCache[hex];
  }
  var error = 0;

  if (prime.isEven() ||
    !primes.simpleSieve ||
    !primes.fermatTest(prime) ||
    !millerRabin.test(prime)) {
    //not a prime so +1
    error += 1;

    if (gen === '02' || gen === '05') {
      // we'd be able to check the generator
      // it would fail so +8
      error += 8;
    } else {
      //we wouldn't be able to test the generator
      // so +4
      error += 4;
    }
    primeCache[hex] = error;
    return error;
  }
  if (!millerRabin.test(prime.shrn(1))) {
    //not a safe prime
    error += 2;
  }
  var rem;
  switch (gen) {
    case '02':
      if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) {
        // unsuidable generator
        error += 8;
      }
      break;
    case '05':
      rem = prime.mod(TEN);
      if (rem.cmp(THREE) && rem.cmp(SEVEN)) {
        // prime mod 10 needs to equal 3 or 7
        error += 8;
      }
      break;
    default:
      error += 4;
  }
  primeCache[hex] = error;
  return error;
}

function DH(prime, generator, malleable) {
  this.setGenerator(generator);
  this.__prime = new BN(prime);
  this._prime = BN.mont(this.__prime);
  this._primeLen = prime.length;
  this._pub = undefined;
  this._priv = undefined;
  this._primeCode = undefined;
  if (malleable) {
    this.setPublicKey = setPublicKey;
    this.setPrivateKey = setPrivateKey;
  } else {
    this._primeCode = 8;
  }
}
Object.defineProperty(DH.prototype, 'verifyError', {
  enumerable: true,
  get: function () {
    if (typeof this._primeCode !== 'number') {
      this._primeCode = checkPrime(this.__prime, this.__gen);
    }
    return this._primeCode;
  }
});
DH.prototype.generateKeys = function () {
  if (!this._priv) {
    this._priv = new BN(randomBytes(this._primeLen));
  }
  this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed();
  return this.getPublicKey();
};

DH.prototype.computeSecret = function (other) {
  other = new BN(other);
  other = other.toRed(this._prime);
  var secret = other.redPow(this._priv).fromRed();
  var out = new Buffer(secret.toArray());
  var prime = this.getPrime();
  if (out.length < prime.length) {
    var front = new Buffer(prime.length - out.length);
    front.fill(0);
    out = Buffer.concat([front, out]);
  }
  return out;
};

DH.prototype.getPublicKey = function getPublicKey(enc) {
  return formatReturnValue(this._pub, enc);
};

DH.prototype.getPrivateKey = function getPrivateKey(enc) {
  return formatReturnValue(this._priv, enc);
};

DH.prototype.getPrime = function (enc) {
  return formatReturnValue(this.__prime, enc);
};

DH.prototype.getGenerator = function (enc) {
  return formatReturnValue(this._gen, enc);
};

DH.prototype.setGenerator = function (gen, enc) {
  enc = enc || 'utf8';
  if (!Buffer.isBuffer(gen)) {
    gen = new Buffer(gen, enc);
  }
  this.__gen = gen;
  this._gen = new BN(gen);
  return this;
};

function formatReturnValue(bn, enc) {
  var buf = new Buffer(bn.toArray());
  if (!enc) {
    return buf;
  } else {
    return buf.toString(enc);
  }
}


/***/ }),

/***/ 26937:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var randomBytes = __webpack_require__(66290);
module.exports = findPrime;
findPrime.simpleSieve = simpleSieve;
findPrime.fermatTest = fermatTest;
var BN = __webpack_require__(89991);
var TWENTYFOUR = new BN(24);
var MillerRabin = __webpack_require__(7427);
var millerRabin = new MillerRabin();
var ONE = new BN(1);
var TWO = new BN(2);
var FIVE = new BN(5);
var SIXTEEN = new BN(16);
var EIGHT = new BN(8);
var TEN = new BN(10);
var THREE = new BN(3);
var SEVEN = new BN(7);
var ELEVEN = new BN(11);
var FOUR = new BN(4);
var TWELVE = new BN(12);
var primes = null;

function _getPrimes() {
  if (primes !== null)
    return primes;

  var limit = 0x100000;
  var res = [];
  res[0] = 2;
  for (var i = 1, k = 3; k < limit; k += 2) {
    var sqrt = Math.ceil(Math.sqrt(k));
    for (var j = 0; j < i && res[j] <= sqrt; j++)
      if (k % res[j] === 0)
        break;

    if (i !== j && res[j] <= sqrt)
      continue;

    res[i++] = k;
  }
  primes = res;
  return res;
}

function simpleSieve(p) {
  var primes = _getPrimes();

  for (var i = 0; i < primes.length; i++)
    if (p.modn(primes[i]) === 0) {
      if (p.cmpn(primes[i]) === 0) {
        return true;
      } else {
        return false;
      }
    }

  return true;
}

function fermatTest(p) {
  var red = BN.mont(p);
  return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0;
}

function findPrime(bits, gen) {
  if (bits < 16) {
    // this is what openssl does
    if (gen === 2 || gen === 5) {
      return new BN([0x8c, 0x7b]);
    } else {
      return new BN([0x8c, 0x27]);
    }
  }
  gen = new BN(gen);

  var num, n2;

  while (true) {
    num = new BN(randomBytes(Math.ceil(bits / 8)));
    while (num.bitLength() > bits) {
      num.ishrn(1);
    }
    if (num.isEven()) {
      num.iadd(ONE);
    }
    if (!num.testn(1)) {
      num.iadd(TWO);
    }
    if (!gen.cmp(TWO)) {
      while (num.mod(TWENTYFOUR).cmp(ELEVEN)) {
        num.iadd(FOUR);
      }
    } else if (!gen.cmp(FIVE)) {
      while (num.mod(TEN).cmp(THREE)) {
        num.iadd(FOUR);
      }
    }
    n2 = num.shrn(1);
    if (simpleSieve(n2) && simpleSieve(num) &&
      fermatTest(n2) && fermatTest(num) &&
      millerRabin.test(n2) && millerRabin.test(num)) {
      return num;
    }
  }

}


/***/ }),

/***/ 74198:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";


var elliptic = exports;

elliptic.version = (__webpack_require__(13453)/* .version */ .rE);
elliptic.utils = __webpack_require__(78944);
elliptic.rand = __webpack_require__(35973);
elliptic.curve = __webpack_require__(89817);
elliptic.curves = __webpack_require__(16745);

// Protocols
elliptic.ec = __webpack_require__(87474);
elliptic.eddsa = __webpack_require__(32261);


/***/ }),

/***/ 24716:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var BN = __webpack_require__(89991);
var utils = __webpack_require__(78944);
var getNAF = utils.getNAF;
var getJSF = utils.getJSF;
var assert = utils.assert;

function BaseCurve(type, conf) {
  this.type = type;
  this.p = new BN(conf.p, 16);

  // Use Montgomery, when there is no fast reduction for the prime
  this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);

  // Useful for many curves
  this.zero = new BN(0).toRed(this.red);
  this.one = new BN(1).toRed(this.red);
  this.two = new BN(2).toRed(this.red);

  // Curve configuration, optional
  this.n = conf.n && new BN(conf.n, 16);
  this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);

  // Temporary arrays
  this._wnafT1 = new Array(4);
  this._wnafT2 = new Array(4);
  this._wnafT3 = new Array(4);
  this._wnafT4 = new Array(4);

  this._bitLength = this.n ? this.n.bitLength() : 0;

  // Generalized Greg Maxwell's trick
  var adjustCount = this.n && this.p.div(this.n);
  if (!adjustCount || adjustCount.cmpn(100) > 0) {
    this.redN = null;
  } else {
    this._maxwellTrick = true;
    this.redN = this.n.toRed(this.red);
  }
}
module.exports = BaseCurve;

BaseCurve.prototype.point = function point() {
  throw new Error('Not implemented');
};

BaseCurve.prototype.validate = function validate() {
  throw new Error('Not implemented');
};

BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
  assert(p.precomputed);
  var doubles = p._getDoubles();

  var naf = getNAF(k, 1, this._bitLength);
  var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
  I /= 3;

  // Translate into more windowed form
  var repr = [];
  var j;
  var nafW;
  for (j = 0; j < naf.length; j += doubles.step) {
    nafW = 0;
    for (var l = j + doubles.step - 1; l >= j; l--)
      nafW = (nafW << 1) + naf[l];
    repr.push(nafW);
  }

  var a = this.jpoint(null, null, null);
  var b = this.jpoint(null, null, null);
  for (var i = I; i > 0; i--) {
    for (j = 0; j < repr.length; j++) {
      nafW = repr[j];
      if (nafW === i)
        b = b.mixedAdd(doubles.points[j]);
      else if (nafW === -i)
        b = b.mixedAdd(doubles.points[j].neg());
    }
    a = a.add(b);
  }
  return a.toP();
};

BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
  var w = 4;

  // Precompute window
  var nafPoints = p._getNAFPoints(w);
  w = nafPoints.wnd;
  var wnd = nafPoints.points;

  // Get NAF form
  var naf = getNAF(k, w, this._bitLength);

  // Add `this`*(N+1) for every w-NAF index
  var acc = this.jpoint(null, null, null);
  for (var i = naf.length - 1; i >= 0; i--) {
    // Count zeroes
    for (var l = 0; i >= 0 && naf[i] === 0; i--)
      l++;
    if (i >= 0)
      l++;
    acc = acc.dblp(l);

    if (i < 0)
      break;
    var z = naf[i];
    assert(z !== 0);
    if (p.type === 'affine') {
      // J +- P
      if (z > 0)
        acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
      else
        acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
    } else {
      // J +- J
      if (z > 0)
        acc = acc.add(wnd[(z - 1) >> 1]);
      else
        acc = acc.add(wnd[(-z - 1) >> 1].neg());
    }
  }
  return p.type === 'affine' ? acc.toP() : acc;
};

BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
  points,
  coeffs,
  len,
  jacobianResult) {
  var wndWidth = this._wnafT1;
  var wnd = this._wnafT2;
  var naf = this._wnafT3;

  // Fill all arrays
  var max = 0;
  var i;
  var j;
  var p;
  for (i = 0; i < len; i++) {
    p = points[i];
    var nafPoints = p._getNAFPoints(defW);
    wndWidth[i] = nafPoints.wnd;
    wnd[i] = nafPoints.points;
  }

  // Comb small window NAFs
  for (i = len - 1; i >= 1; i -= 2) {
    var a = i - 1;
    var b = i;
    if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
      naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength);
      naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength);
      max = Math.max(naf[a].length, max);
      max = Math.max(naf[b].length, max);
      continue;
    }

    var comb = [
      points[a], /* 1 */
      null, /* 3 */
      null, /* 5 */
      points[b], /* 7 */
    ];

    // Try to avoid Projective points, if possible
    if (points[a].y.cmp(points[b].y) === 0) {
      comb[1] = points[a].add(points[b]);
      comb[2] = points[a].toJ().mixedAdd(points[b].neg());
    } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
      comb[1] = points[a].toJ().mixedAdd(points[b]);
      comb[2] = points[a].add(points[b].neg());
    } else {
      comb[1] = points[a].toJ().mixedAdd(points[b]);
      comb[2] = points[a].toJ().mixedAdd(points[b].neg());
    }

    var index = [
      -3, /* -1 -1 */
      -1, /* -1 0 */
      -5, /* -1 1 */
      -7, /* 0 -1 */
      0, /* 0 0 */
      7, /* 0 1 */
      5, /* 1 -1 */
      1, /* 1 0 */
      3,  /* 1 1 */
    ];

    var jsf = getJSF(coeffs[a], coeffs[b]);
    max = Math.max(jsf[0].length, max);
    naf[a] = new Array(max);
    naf[b] = new Array(max);
    for (j = 0; j < max; j++) {
      var ja = jsf[0][j] | 0;
      var jb = jsf[1][j] | 0;

      naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
      naf[b][j] = 0;
      wnd[a] = comb;
    }
  }

  var acc = this.jpoint(null, null, null);
  var tmp = this._wnafT4;
  for (i = max; i >= 0; i--) {
    var k = 0;

    while (i >= 0) {
      var zero = true;
      for (j = 0; j < len; j++) {
        tmp[j] = naf[j][i] | 0;
        if (tmp[j] !== 0)
          zero = false;
      }
      if (!zero)
        break;
      k++;
      i--;
    }
    if (i >= 0)
      k++;
    acc = acc.dblp(k);
    if (i < 0)
      break;

    for (j = 0; j < len; j++) {
      var z = tmp[j];
      p;
      if (z === 0)
        continue;
      else if (z > 0)
        p = wnd[j][(z - 1) >> 1];
      else if (z < 0)
        p = wnd[j][(-z - 1) >> 1].neg();

      if (p.type === 'affine')
        acc = acc.mixedAdd(p);
      else
        acc = acc.add(p);
    }
  }
  // Zeroify references
  for (i = 0; i < len; i++)
    wnd[i] = null;

  if (jacobianResult)
    return acc;
  else
    return acc.toP();
};

function BasePoint(curve, type) {
  this.curve = curve;
  this.type = type;
  this.precomputed = null;
}
BaseCurve.BasePoint = BasePoint;

BasePoint.prototype.eq = function eq(/*other*/) {
  throw new Error('Not implemented');
};

BasePoint.prototype.validate = function validate() {
  return this.curve.validate(this);
};

BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
  bytes = utils.toArray(bytes, enc);

  var len = this.p.byteLength();

  // uncompressed, hybrid-odd, hybrid-even
  if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
      bytes.length - 1 === 2 * len) {
    if (bytes[0] === 0x06)
      assert(bytes[bytes.length - 1] % 2 === 0);
    else if (bytes[0] === 0x07)
      assert(bytes[bytes.length - 1] % 2 === 1);

    var res =  this.point(bytes.slice(1, 1 + len),
      bytes.slice(1 + len, 1 + 2 * len));

    return res;
  } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
              bytes.length - 1 === len) {
    return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
  }
  throw new Error('Unknown point format');
};

BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
  return this.encode(enc, true);
};

BasePoint.prototype._encode = function _encode(compact) {
  var len = this.curve.p.byteLength();
  var x = this.getX().toArray('be', len);

  if (compact)
    return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);

  return [ 0x04 ].concat(x, this.getY().toArray('be', len));
};

BasePoint.prototype.encode = function encode(enc, compact) {
  return utils.encode(this._encode(compact), enc);
};

BasePoint.prototype.precompute = function precompute(power) {
  if (this.precomputed)
    return this;

  var precomputed = {
    doubles: null,
    naf: null,
    beta: null,
  };
  precomputed.naf = this._getNAFPoints(8);
  precomputed.doubles = this._getDoubles(4, power);
  precomputed.beta = this._getBeta();
  this.precomputed = precomputed;

  return this;
};

BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
  if (!this.precomputed)
    return false;

  var doubles = this.precomputed.doubles;
  if (!doubles)
    return false;

  return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
};

BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
  if (this.precomputed && this.precomputed.doubles)
    return this.precomputed.doubles;

  var doubles = [ this ];
  var acc = this;
  for (var i = 0; i < power; i += step) {
    for (var j = 0; j < step; j++)
      acc = acc.dbl();
    doubles.push(acc);
  }
  return {
    step: step,
    points: doubles,
  };
};

BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
  if (this.precomputed && this.precomputed.naf)
    return this.precomputed.naf;

  var res = [ this ];
  var max = (1 << wnd) - 1;
  var dbl = max === 1 ? null : this.dbl();
  for (var i = 1; i < max; i++)
    res[i] = res[i - 1].add(dbl);
  return {
    wnd: wnd,
    points: res,
  };
};

BasePoint.prototype._getBeta = function _getBeta() {
  return null;
};

BasePoint.prototype.dblp = function dblp(k) {
  var r = this;
  for (var i = 0; i < k; i++)
    r = r.dbl();
  return r;
};


/***/ }),

/***/ 54161:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var utils = __webpack_require__(78944);
var BN = __webpack_require__(89991);
var inherits = __webpack_require__(72116);
var Base = __webpack_require__(24716);

var assert = utils.assert;

function EdwardsCurve(conf) {
  // NOTE: Important as we are creating point in Base.call()
  this.twisted = (conf.a | 0) !== 1;
  this.mOneA = this.twisted && (conf.a | 0) === -1;
  this.extended = this.mOneA;

  Base.call(this, 'edwards', conf);

  this.a = new BN(conf.a, 16).umod(this.red.m);
  this.a = this.a.toRed(this.red);
  this.c = new BN(conf.c, 16).toRed(this.red);
  this.c2 = this.c.redSqr();
  this.d = new BN(conf.d, 16).toRed(this.red);
  this.dd = this.d.redAdd(this.d);

  assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);
  this.oneC = (conf.c | 0) === 1;
}
inherits(EdwardsCurve, Base);
module.exports = EdwardsCurve;

EdwardsCurve.prototype._mulA = function _mulA(num) {
  if (this.mOneA)
    return num.redNeg();
  else
    return this.a.redMul(num);
};

EdwardsCurve.prototype._mulC = function _mulC(num) {
  if (this.oneC)
    return num;
  else
    return this.c.redMul(num);
};

// Just for compatibility with Short curve
EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
  return this.point(x, y, z, t);
};

EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
  x = new BN(x, 16);
  if (!x.red)
    x = x.toRed(this.red);

  var x2 = x.redSqr();
  var rhs = this.c2.redSub(this.a.redMul(x2));
  var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));

  var y2 = rhs.redMul(lhs.redInvm());
  var y = y2.redSqrt();
  if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
    throw new Error('invalid point');

  var isOdd = y.fromRed().isOdd();
  if (odd && !isOdd || !odd && isOdd)
    y = y.redNeg();

  return this.point(x, y);
};

EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
  y = new BN(y, 16);
  if (!y.red)
    y = y.toRed(this.red);

  // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)
  var y2 = y.redSqr();
  var lhs = y2.redSub(this.c2);
  var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);
  var x2 = lhs.redMul(rhs.redInvm());

  if (x2.cmp(this.zero) === 0) {
    if (odd)
      throw new Error('invalid point');
    else
      return this.point(this.zero, y);
  }

  var x = x2.redSqrt();
  if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
    throw new Error('invalid point');

  if (x.fromRed().isOdd() !== odd)
    x = x.redNeg();

  return this.point(x, y);
};

EdwardsCurve.prototype.validate = function validate(point) {
  if (point.isInfinity())
    return true;

  // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
  point.normalize();

  var x2 = point.x.redSqr();
  var y2 = point.y.redSqr();
  var lhs = x2.redMul(this.a).redAdd(y2);
  var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));

  return lhs.cmp(rhs) === 0;
};

function Point(curve, x, y, z, t) {
  Base.BasePoint.call(this, curve, 'projective');
  if (x === null && y === null && z === null) {
    this.x = this.curve.zero;
    this.y = this.curve.one;
    this.z = this.curve.one;
    this.t = this.curve.zero;
    this.zOne = true;
  } else {
    this.x = new BN(x, 16);
    this.y = new BN(y, 16);
    this.z = z ? new BN(z, 16) : this.curve.one;
    this.t = t && new BN(t, 16);
    if (!this.x.red)
      this.x = this.x.toRed(this.curve.red);
    if (!this.y.red)
      this.y = this.y.toRed(this.curve.red);
    if (!this.z.red)
      this.z = this.z.toRed(this.curve.red);
    if (this.t && !this.t.red)
      this.t = this.t.toRed(this.curve.red);
    this.zOne = this.z === this.curve.one;

    // Use extended coordinates
    if (this.curve.extended && !this.t) {
      this.t = this.x.redMul(this.y);
      if (!this.zOne)
        this.t = this.t.redMul(this.z.redInvm());
    }
  }
}
inherits(Point, Base.BasePoint);

EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
  return Point.fromJSON(this, obj);
};

EdwardsCurve.prototype.point = function point(x, y, z, t) {
  return new Point(this, x, y, z, t);
};

Point.fromJSON = function fromJSON(curve, obj) {
  return new Point(curve, obj[0], obj[1], obj[2]);
};

Point.prototype.inspect = function inspect() {
  if (this.isInfinity())
    return '<EC Point Infinity>';
  return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
      ' y: ' + this.y.fromRed().toString(16, 2) +
      ' z: ' + this.z.fromRed().toString(16, 2) + '>';
};

Point.prototype.isInfinity = function isInfinity() {
  // XXX This code assumes that zero is always zero in red
  return this.x.cmpn(0) === 0 &&
    (this.y.cmp(this.z) === 0 ||
    (this.zOne && this.y.cmp(this.curve.c) === 0));
};

Point.prototype._extDbl = function _extDbl() {
  // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
  //     #doubling-dbl-2008-hwcd
  // 4M + 4S

  // A = X1^2
  var a = this.x.redSqr();
  // B = Y1^2
  var b = this.y.redSqr();
  // C = 2 * Z1^2
  var c = this.z.redSqr();
  c = c.redIAdd(c);
  // D = a * A
  var d = this.curve._mulA(a);
  // E = (X1 + Y1)^2 - A - B
  var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
  // G = D + B
  var g = d.redAdd(b);
  // F = G - C
  var f = g.redSub(c);
  // H = D - B
  var h = d.redSub(b);
  // X3 = E * F
  var nx = e.redMul(f);
  // Y3 = G * H
  var ny = g.redMul(h);
  // T3 = E * H
  var nt = e.redMul(h);
  // Z3 = F * G
  var nz = f.redMul(g);
  return this.curve.point(nx, ny, nz, nt);
};

Point.prototype._projDbl = function _projDbl() {
  // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
  //     #doubling-dbl-2008-bbjlp
  //     #doubling-dbl-2007-bl
  // and others
  // Generally 3M + 4S or 2M + 4S

  // B = (X1 + Y1)^2
  var b = this.x.redAdd(this.y).redSqr();
  // C = X1^2
  var c = this.x.redSqr();
  // D = Y1^2
  var d = this.y.redSqr();

  var nx;
  var ny;
  var nz;
  var e;
  var h;
  var j;
  if (this.curve.twisted) {
    // E = a * C
    e = this.curve._mulA(c);
    // F = E + D
    var f = e.redAdd(d);
    if (this.zOne) {
      // X3 = (B - C - D) * (F - 2)
      nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
      // Y3 = F * (E - D)
      ny = f.redMul(e.redSub(d));
      // Z3 = F^2 - 2 * F
      nz = f.redSqr().redSub(f).redSub(f);
    } else {
      // H = Z1^2
      h = this.z.redSqr();
      // J = F - 2 * H
      j = f.redSub(h).redISub(h);
      // X3 = (B-C-D)*J
      nx = b.redSub(c).redISub(d).redMul(j);
      // Y3 = F * (E - D)
      ny = f.redMul(e.redSub(d));
      // Z3 = F * J
      nz = f.redMul(j);
    }
  } else {
    // E = C + D
    e = c.redAdd(d);
    // H = (c * Z1)^2
    h = this.curve._mulC(this.z).redSqr();
    // J = E - 2 * H
    j = e.redSub(h).redSub(h);
    // X3 = c * (B - E) * J
    nx = this.curve._mulC(b.redISub(e)).redMul(j);
    // Y3 = c * E * (C - D)
    ny = this.curve._mulC(e).redMul(c.redISub(d));
    // Z3 = E * J
    nz = e.redMul(j);
  }
  return this.curve.point(nx, ny, nz);
};

Point.prototype.dbl = function dbl() {
  if (this.isInfinity())
    return this;

  // Double in extended coordinates
  if (this.curve.extended)
    return this._extDbl();
  else
    return this._projDbl();
};

Point.prototype._extAdd = function _extAdd(p) {
  // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
  //     #addition-add-2008-hwcd-3
  // 8M

  // A = (Y1 - X1) * (Y2 - X2)
  var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
  // B = (Y1 + X1) * (Y2 + X2)
  var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
  // C = T1 * k * T2
  var c = this.t.redMul(this.curve.dd).redMul(p.t);
  // D = Z1 * 2 * Z2
  var d = this.z.redMul(p.z.redAdd(p.z));
  // E = B - A
  var e = b.redSub(a);
  // F = D - C
  var f = d.redSub(c);
  // G = D + C
  var g = d.redAdd(c);
  // H = B + A
  var h = b.redAdd(a);
  // X3 = E * F
  var nx = e.redMul(f);
  // Y3 = G * H
  var ny = g.redMul(h);
  // T3 = E * H
  var nt = e.redMul(h);
  // Z3 = F * G
  var nz = f.redMul(g);
  return this.curve.point(nx, ny, nz, nt);
};

Point.prototype._projAdd = function _projAdd(p) {
  // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
  //     #addition-add-2008-bbjlp
  //     #addition-add-2007-bl
  // 10M + 1S

  // A = Z1 * Z2
  var a = this.z.redMul(p.z);
  // B = A^2
  var b = a.redSqr();
  // C = X1 * X2
  var c = this.x.redMul(p.x);
  // D = Y1 * Y2
  var d = this.y.redMul(p.y);
  // E = d * C * D
  var e = this.curve.d.redMul(c).redMul(d);
  // F = B - E
  var f = b.redSub(e);
  // G = B + E
  var g = b.redAdd(e);
  // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
  var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
  var nx = a.redMul(f).redMul(tmp);
  var ny;
  var nz;
  if (this.curve.twisted) {
    // Y3 = A * G * (D - a * C)
    ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
    // Z3 = F * G
    nz = f.redMul(g);
  } else {
    // Y3 = A * G * (D - C)
    ny = a.redMul(g).redMul(d.redSub(c));
    // Z3 = c * F * G
    nz = this.curve._mulC(f).redMul(g);
  }
  return this.curve.point(nx, ny, nz);
};

Point.prototype.add = function add(p) {
  if (this.isInfinity())
    return p;
  if (p.isInfinity())
    return this;

  if (this.curve.extended)
    return this._extAdd(p);
  else
    return this._projAdd(p);
};

Point.prototype.mul = function mul(k) {
  if (this._hasDoubles(k))
    return this.curve._fixedNafMul(this, k);
  else
    return this.curve._wnafMul(this, k);
};

Point.prototype.mulAdd = function mulAdd(k1, p, k2) {
  return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);
};

Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) {
  return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);
};

Point.prototype.normalize = function normalize() {
  if (this.zOne)
    return this;

  // Normalize coordinates
  var zi = this.z.redInvm();
  this.x = this.x.redMul(zi);
  this.y = this.y.redMul(zi);
  if (this.t)
    this.t = this.t.redMul(zi);
  this.z = this.curve.one;
  this.zOne = true;
  return this;
};

Point.prototype.neg = function neg() {
  return this.curve.point(this.x.redNeg(),
    this.y,
    this.z,
    this.t && this.t.redNeg());
};

Point.prototype.getX = function getX() {
  this.normalize();
  return this.x.fromRed();
};

Point.prototype.getY = function getY() {
  this.normalize();
  return this.y.fromRed();
};

Point.prototype.eq = function eq(other) {
  return this === other ||
         this.getX().cmp(other.getX()) === 0 &&
         this.getY().cmp(other.getY()) === 0;
};

Point.prototype.eqXToP = function eqXToP(x) {
  var rx = x.toRed(this.curve.red).redMul(this.z);
  if (this.x.cmp(rx) === 0)
    return true;

  var xc = x.clone();
  var t = this.curve.redN.redMul(this.z);
  for (;;) {
    xc.iadd(this.curve.n);
    if (xc.cmp(this.curve.p) >= 0)
      return false;

    rx.redIAdd(t);
    if (this.x.cmp(rx) === 0)
      return true;
  }
};

// Compatibility with BaseCurve
Point.prototype.toP = Point.prototype.normalize;
Point.prototype.mixedAdd = Point.prototype.add;


/***/ }),

/***/ 89817:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";


var curve = exports;

curve.base = __webpack_require__(24716);
curve.short = __webpack_require__(56715);
curve.mont = __webpack_require__(36691);
curve.edwards = __webpack_require__(54161);


/***/ }),

/***/ 36691:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var BN = __webpack_require__(89991);
var inherits = __webpack_require__(72116);
var Base = __webpack_require__(24716);

var utils = __webpack_require__(78944);

function MontCurve(conf) {
  Base.call(this, 'mont', conf);

  this.a = new BN(conf.a, 16).toRed(this.red);
  this.b = new BN(conf.b, 16).toRed(this.red);
  this.i4 = new BN(4).toRed(this.red).redInvm();
  this.two = new BN(2).toRed(this.red);
  this.a24 = this.i4.redMul(this.a.redAdd(this.two));
}
inherits(MontCurve, Base);
module.exports = MontCurve;

MontCurve.prototype.validate = function validate(point) {
  var x = point.normalize().x;
  var x2 = x.redSqr();
  var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
  var y = rhs.redSqrt();

  return y.redSqr().cmp(rhs) === 0;
};

function Point(curve, x, z) {
  Base.BasePoint.call(this, curve, 'projective');
  if (x === null && z === null) {
    this.x = this.curve.one;
    this.z = this.curve.zero;
  } else {
    this.x = new BN(x, 16);
    this.z = new BN(z, 16);
    if (!this.x.red)
      this.x = this.x.toRed(this.curve.red);
    if (!this.z.red)
      this.z = this.z.toRed(this.curve.red);
  }
}
inherits(Point, Base.BasePoint);

MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
  return this.point(utils.toArray(bytes, enc), 1);
};

MontCurve.prototype.point = function point(x, z) {
  return new Point(this, x, z);
};

MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
  return Point.fromJSON(this, obj);
};

Point.prototype.precompute = function precompute() {
  // No-op
};

Point.prototype._encode = function _encode() {
  return this.getX().toArray('be', this.curve.p.byteLength());
};

Point.fromJSON = function fromJSON(curve, obj) {
  return new Point(curve, obj[0], obj[1] || curve.one);
};

Point.prototype.inspect = function inspect() {
  if (this.isInfinity())
    return '<EC Point Infinity>';
  return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
      ' z: ' + this.z.fromRed().toString(16, 2) + '>';
};

Point.prototype.isInfinity = function isInfinity() {
  // XXX This code assumes that zero is always zero in red
  return this.z.cmpn(0) === 0;
};

Point.prototype.dbl = function dbl() {
  // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
  // 2M + 2S + 4A

  // A = X1 + Z1
  var a = this.x.redAdd(this.z);
  // AA = A^2
  var aa = a.redSqr();
  // B = X1 - Z1
  var b = this.x.redSub(this.z);
  // BB = B^2
  var bb = b.redSqr();
  // C = AA - BB
  var c = aa.redSub(bb);
  // X3 = AA * BB
  var nx = aa.redMul(bb);
  // Z3 = C * (BB + A24 * C)
  var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
  return this.curve.point(nx, nz);
};

Point.prototype.add = function add() {
  throw new Error('Not supported on Montgomery curve');
};

Point.prototype.diffAdd = function diffAdd(p, diff) {
  // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
  // 4M + 2S + 6A

  // A = X2 + Z2
  var a = this.x.redAdd(this.z);
  // B = X2 - Z2
  var b = this.x.redSub(this.z);
  // C = X3 + Z3
  var c = p.x.redAdd(p.z);
  // D = X3 - Z3
  var d = p.x.redSub(p.z);
  // DA = D * A
  var da = d.redMul(a);
  // CB = C * B
  var cb = c.redMul(b);
  // X5 = Z1 * (DA + CB)^2
  var nx = diff.z.redMul(da.redAdd(cb).redSqr());
  // Z5 = X1 * (DA - CB)^2
  var nz = diff.x.redMul(da.redISub(cb).redSqr());
  return this.curve.point(nx, nz);
};

Point.prototype.mul = function mul(k) {
  var t = k.clone();
  var a = this; // (N / 2) * Q + Q
  var b = this.curve.point(null, null); // (N / 2) * Q
  var c = this; // Q

  for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))
    bits.push(t.andln(1));

  for (var i = bits.length - 1; i >= 0; i--) {
    if (bits[i] === 0) {
      // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
      a = a.diffAdd(b, c);
      // N * Q = 2 * ((N / 2) * Q + Q))
      b = b.dbl();
    } else {
      // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
      b = a.diffAdd(b, c);
      // N * Q + Q = 2 * ((N / 2) * Q + Q)
      a = a.dbl();
    }
  }
  return b;
};

Point.prototype.mulAdd = function mulAdd() {
  throw new Error('Not supported on Montgomery curve');
};

Point.prototype.jumlAdd = function jumlAdd() {
  throw new Error('Not supported on Montgomery curve');
};

Point.prototype.eq = function eq(other) {
  return this.getX().cmp(other.getX()) === 0;
};

Point.prototype.normalize = function normalize() {
  this.x = this.x.redMul(this.z.redInvm());
  this.z = this.curve.one;
  return this;
};

Point.prototype.getX = function getX() {
  // Normalize coordinates
  this.normalize();

  return this.x.fromRed();
};


/***/ }),

/***/ 56715:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var utils = __webpack_require__(78944);
var BN = __webpack_require__(89991);
var inherits = __webpack_require__(72116);
var Base = __webpack_require__(24716);

var assert = utils.assert;

function ShortCurve(conf) {
  Base.call(this, 'short', conf);

  this.a = new BN(conf.a, 16).toRed(this.red);
  this.b = new BN(conf.b, 16).toRed(this.red);
  this.tinv = this.two.redInvm();

  this.zeroA = this.a.fromRed().cmpn(0) === 0;
  this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;

  // If the curve is endomorphic, precalculate beta and lambda
  this.endo = this._getEndomorphism(conf);
  this._endoWnafT1 = new Array(4);
  this._endoWnafT2 = new Array(4);
}
inherits(ShortCurve, Base);
module.exports = ShortCurve;

ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
  // No efficient endomorphism
  if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
    return;

  // Compute beta and lambda, that lambda * P = (beta * Px; Py)
  var beta;
  var lambda;
  if (conf.beta) {
    beta = new BN(conf.beta, 16).toRed(this.red);
  } else {
    var betas = this._getEndoRoots(this.p);
    // Choose the smallest beta
    beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
    beta = beta.toRed(this.red);
  }
  if (conf.lambda) {
    lambda = new BN(conf.lambda, 16);
  } else {
    // Choose the lambda that is matching selected beta
    var lambdas = this._getEndoRoots(this.n);
    if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
      lambda = lambdas[0];
    } else {
      lambda = lambdas[1];
      assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
    }
  }

  // Get basis vectors, used for balanced length-two representation
  var basis;
  if (conf.basis) {
    basis = conf.basis.map(function(vec) {
      return {
        a: new BN(vec.a, 16),
        b: new BN(vec.b, 16),
      };
    });
  } else {
    basis = this._getEndoBasis(lambda);
  }

  return {
    beta: beta,
    lambda: lambda,
    basis: basis,
  };
};

ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
  // Find roots of for x^2 + x + 1 in F
  // Root = (-1 +- Sqrt(-3)) / 2
  //
  var red = num === this.p ? this.red : BN.mont(num);
  var tinv = new BN(2).toRed(red).redInvm();
  var ntinv = tinv.redNeg();

  var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);

  var l1 = ntinv.redAdd(s).fromRed();
  var l2 = ntinv.redSub(s).fromRed();
  return [ l1, l2 ];
};

ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
  // aprxSqrt >= sqrt(this.n)
  var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));

  // 3.74
  // Run EGCD, until r(L + 1) < aprxSqrt
  var u = lambda;
  var v = this.n.clone();
  var x1 = new BN(1);
  var y1 = new BN(0);
  var x2 = new BN(0);
  var y2 = new BN(1);

  // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
  var a0;
  var b0;
  // First vector
  var a1;
  var b1;
  // Second vector
  var a2;
  var b2;

  var prevR;
  var i = 0;
  var r;
  var x;
  while (u.cmpn(0) !== 0) {
    var q = v.div(u);
    r = v.sub(q.mul(u));
    x = x2.sub(q.mul(x1));
    var y = y2.sub(q.mul(y1));

    if (!a1 && r.cmp(aprxSqrt) < 0) {
      a0 = prevR.neg();
      b0 = x1;
      a1 = r.neg();
      b1 = x;
    } else if (a1 && ++i === 2) {
      break;
    }
    prevR = r;

    v = u;
    u = r;
    x2 = x1;
    x1 = x;
    y2 = y1;
    y1 = y;
  }
  a2 = r.neg();
  b2 = x;

  var len1 = a1.sqr().add(b1.sqr());
  var len2 = a2.sqr().add(b2.sqr());
  if (len2.cmp(len1) >= 0) {
    a2 = a0;
    b2 = b0;
  }

  // Normalize signs
  if (a1.negative) {
    a1 = a1.neg();
    b1 = b1.neg();
  }
  if (a2.negative) {
    a2 = a2.neg();
    b2 = b2.neg();
  }

  return [
    { a: a1, b: b1 },
    { a: a2, b: b2 },
  ];
};

ShortCurve.prototype._endoSplit = function _endoSplit(k) {
  var basis = this.endo.basis;
  var v1 = basis[0];
  var v2 = basis[1];

  var c1 = v2.b.mul(k).divRound(this.n);
  var c2 = v1.b.neg().mul(k).divRound(this.n);

  var p1 = c1.mul(v1.a);
  var p2 = c2.mul(v2.a);
  var q1 = c1.mul(v1.b);
  var q2 = c2.mul(v2.b);

  // Calculate answer
  var k1 = k.sub(p1).sub(p2);
  var k2 = q1.add(q2).neg();
  return { k1: k1, k2: k2 };
};

ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
  x = new BN(x, 16);
  if (!x.red)
    x = x.toRed(this.red);

  var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
  var y = y2.redSqrt();
  if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
    throw new Error('invalid point');

  // XXX Is there any way to tell if the number is odd without converting it
  // to non-red form?
  var isOdd = y.fromRed().isOdd();
  if (odd && !isOdd || !odd && isOdd)
    y = y.redNeg();

  return this.point(x, y);
};

ShortCurve.prototype.validate = function validate(point) {
  if (point.inf)
    return true;

  var x = point.x;
  var y = point.y;

  var ax = this.a.redMul(x);
  var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
  return y.redSqr().redISub(rhs).cmpn(0) === 0;
};

ShortCurve.prototype._endoWnafMulAdd =
    function _endoWnafMulAdd(points, coeffs, jacobianResult) {
      var npoints = this._endoWnafT1;
      var ncoeffs = this._endoWnafT2;
      for (var i = 0; i < points.length; i++) {
        var split = this._endoSplit(coeffs[i]);
        var p = points[i];
        var beta = p._getBeta();

        if (split.k1.negative) {
          split.k1.ineg();
          p = p.neg(true);
        }
        if (split.k2.negative) {
          split.k2.ineg();
          beta = beta.neg(true);
        }

        npoints[i * 2] = p;
        npoints[i * 2 + 1] = beta;
        ncoeffs[i * 2] = split.k1;
        ncoeffs[i * 2 + 1] = split.k2;
      }
      var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);

      // Clean-up references to points and coefficients
      for (var j = 0; j < i * 2; j++) {
        npoints[j] = null;
        ncoeffs[j] = null;
      }
      return res;
    };

function Point(curve, x, y, isRed) {
  Base.BasePoint.call(this, curve, 'affine');
  if (x === null && y === null) {
    this.x = null;
    this.y = null;
    this.inf = true;
  } else {
    this.x = new BN(x, 16);
    this.y = new BN(y, 16);
    // Force redgomery representation when loading from JSON
    if (isRed) {
      this.x.forceRed(this.curve.red);
      this.y.forceRed(this.curve.red);
    }
    if (!this.x.red)
      this.x = this.x.toRed(this.curve.red);
    if (!this.y.red)
      this.y = this.y.toRed(this.curve.red);
    this.inf = false;
  }
}
inherits(Point, Base.BasePoint);

ShortCurve.prototype.point = function point(x, y, isRed) {
  return new Point(this, x, y, isRed);
};

ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
  return Point.fromJSON(this, obj, red);
};

Point.prototype._getBeta = function _getBeta() {
  if (!this.curve.endo)
    return;

  var pre = this.precomputed;
  if (pre && pre.beta)
    return pre.beta;

  var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
  if (pre) {
    var curve = this.curve;
    var endoMul = function(p) {
      return curve.point(p.x.redMul(curve.endo.beta), p.y);
    };
    pre.beta = beta;
    beta.precomputed = {
      beta: null,
      naf: pre.naf && {
        wnd: pre.naf.wnd,
        points: pre.naf.points.map(endoMul),
      },
      doubles: pre.doubles && {
        step: pre.doubles.step,
        points: pre.doubles.points.map(endoMul),
      },
    };
  }
  return beta;
};

Point.prototype.toJSON = function toJSON() {
  if (!this.precomputed)
    return [ this.x, this.y ];

  return [ this.x, this.y, this.precomputed && {
    doubles: this.precomputed.doubles && {
      step: this.precomputed.doubles.step,
      points: this.precomputed.doubles.points.slice(1),
    },
    naf: this.precomputed.naf && {
      wnd: this.precomputed.naf.wnd,
      points: this.precomputed.naf.points.slice(1),
    },
  } ];
};

Point.fromJSON = function fromJSON(curve, obj, red) {
  if (typeof obj === 'string')
    obj = JSON.parse(obj);
  var res = curve.point(obj[0], obj[1], red);
  if (!obj[2])
    return res;

  function obj2point(obj) {
    return curve.point(obj[0], obj[1], red);
  }

  var pre = obj[2];
  res.precomputed = {
    beta: null,
    doubles: pre.doubles && {
      step: pre.doubles.step,
      points: [ res ].concat(pre.doubles.points.map(obj2point)),
    },
    naf: pre.naf && {
      wnd: pre.naf.wnd,
      points: [ res ].concat(pre.naf.points.map(obj2point)),
    },
  };
  return res;
};

Point.prototype.inspect = function inspect() {
  if (this.isInfinity())
    return '<EC Point Infinity>';
  return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
      ' y: ' + this.y.fromRed().toString(16, 2) + '>';
};

Point.prototype.isInfinity = function isInfinity() {
  return this.inf;
};

Point.prototype.add = function add(p) {
  // O + P = P
  if (this.inf)
    return p;

  // P + O = P
  if (p.inf)
    return this;

  // P + P = 2P
  if (this.eq(p))
    return this.dbl();

  // P + (-P) = O
  if (this.neg().eq(p))
    return this.curve.point(null, null);

  // P + Q = O
  if (this.x.cmp(p.x) === 0)
    return this.curve.point(null, null);

  var c = this.y.redSub(p.y);
  if (c.cmpn(0) !== 0)
    c = c.redMul(this.x.redSub(p.x).redInvm());
  var nx = c.redSqr().redISub(this.x).redISub(p.x);
  var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
  return this.curve.point(nx, ny);
};

Point.prototype.dbl = function dbl() {
  if (this.inf)
    return this;

  // 2P = O
  var ys1 = this.y.redAdd(this.y);
  if (ys1.cmpn(0) === 0)
    return this.curve.point(null, null);

  var a = this.curve.a;

  var x2 = this.x.redSqr();
  var dyinv = ys1.redInvm();
  var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);

  var nx = c.redSqr().redISub(this.x.redAdd(this.x));
  var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
  return this.curve.point(nx, ny);
};

Point.prototype.getX = function getX() {
  return this.x.fromRed();
};

Point.prototype.getY = function getY() {
  return this.y.fromRed();
};

Point.prototype.mul = function mul(k) {
  k = new BN(k, 16);
  if (this.isInfinity())
    return this;
  else if (this._hasDoubles(k))
    return this.curve._fixedNafMul(this, k);
  else if (this.curve.endo)
    return this.curve._endoWnafMulAdd([ this ], [ k ]);
  else
    return this.curve._wnafMul(this, k);
};

Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
  var points = [ this, p2 ];
  var coeffs = [ k1, k2 ];
  if (this.curve.endo)
    return this.curve._endoWnafMulAdd(points, coeffs);
  else
    return this.curve._wnafMulAdd(1, points, coeffs, 2);
};

Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
  var points = [ this, p2 ];
  var coeffs = [ k1, k2 ];
  if (this.curve.endo)
    return this.curve._endoWnafMulAdd(points, coeffs, true);
  else
    return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
};

Point.prototype.eq = function eq(p) {
  return this === p ||
         this.inf === p.inf &&
             (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
};

Point.prototype.neg = function neg(_precompute) {
  if (this.inf)
    return this;

  var res = this.curve.point(this.x, this.y.redNeg());
  if (_precompute && this.precomputed) {
    var pre = this.precomputed;
    var negate = function(p) {
      return p.neg();
    };
    res.precomputed = {
      naf: pre.naf && {
        wnd: pre.naf.wnd,
        points: pre.naf.points.map(negate),
      },
      doubles: pre.doubles && {
        step: pre.doubles.step,
        points: pre.doubles.points.map(negate),
      },
    };
  }
  return res;
};

Point.prototype.toJ = function toJ() {
  if (this.inf)
    return this.curve.jpoint(null, null, null);

  var res = this.curve.jpoint(this.x, this.y, this.curve.one);
  return res;
};

function JPoint(curve, x, y, z) {
  Base.BasePoint.call(this, curve, 'jacobian');
  if (x === null && y === null && z === null) {
    this.x = this.curve.one;
    this.y = this.curve.one;
    this.z = new BN(0);
  } else {
    this.x = new BN(x, 16);
    this.y = new BN(y, 16);
    this.z = new BN(z, 16);
  }
  if (!this.x.red)
    this.x = this.x.toRed(this.curve.red);
  if (!this.y.red)
    this.y = this.y.toRed(this.curve.red);
  if (!this.z.red)
    this.z = this.z.toRed(this.curve.red);

  this.zOne = this.z === this.curve.one;
}
inherits(JPoint, Base.BasePoint);

ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
  return new JPoint(this, x, y, z);
};

JPoint.prototype.toP = function toP() {
  if (this.isInfinity())
    return this.curve.point(null, null);

  var zinv = this.z.redInvm();
  var zinv2 = zinv.redSqr();
  var ax = this.x.redMul(zinv2);
  var ay = this.y.redMul(zinv2).redMul(zinv);

  return this.curve.point(ax, ay);
};

JPoint.prototype.neg = function neg() {
  return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
};

JPoint.prototype.add = function add(p) {
  // O + P = P
  if (this.isInfinity())
    return p;

  // P + O = P
  if (p.isInfinity())
    return this;

  // 12M + 4S + 7A
  var pz2 = p.z.redSqr();
  var z2 = this.z.redSqr();
  var u1 = this.x.redMul(pz2);
  var u2 = p.x.redMul(z2);
  var s1 = this.y.redMul(pz2.redMul(p.z));
  var s2 = p.y.redMul(z2.redMul(this.z));

  var h = u1.redSub(u2);
  var r = s1.redSub(s2);
  if (h.cmpn(0) === 0) {
    if (r.cmpn(0) !== 0)
      return this.curve.jpoint(null, null, null);
    else
      return this.dbl();
  }

  var h2 = h.redSqr();
  var h3 = h2.redMul(h);
  var v = u1.redMul(h2);

  var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
  var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
  var nz = this.z.redMul(p.z).redMul(h);

  return this.curve.jpoint(nx, ny, nz);
};

JPoint.prototype.mixedAdd = function mixedAdd(p) {
  // O + P = P
  if (this.isInfinity())
    return p.toJ();

  // P + O = P
  if (p.isInfinity())
    return this;

  // 8M + 3S + 7A
  var z2 = this.z.redSqr();
  var u1 = this.x;
  var u2 = p.x.redMul(z2);
  var s1 = this.y;
  var s2 = p.y.redMul(z2).redMul(this.z);

  var h = u1.redSub(u2);
  var r = s1.redSub(s2);
  if (h.cmpn(0) === 0) {
    if (r.cmpn(0) !== 0)
      return this.curve.jpoint(null, null, null);
    else
      return this.dbl();
  }

  var h2 = h.redSqr();
  var h3 = h2.redMul(h);
  var v = u1.redMul(h2);

  var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
  var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
  var nz = this.z.redMul(h);

  return this.curve.jpoint(nx, ny, nz);
};

JPoint.prototype.dblp = function dblp(pow) {
  if (pow === 0)
    return this;
  if (this.isInfinity())
    return this;
  if (!pow)
    return this.dbl();

  var i;
  if (this.curve.zeroA || this.curve.threeA) {
    var r = this;
    for (i = 0; i < pow; i++)
      r = r.dbl();
    return r;
  }

  // 1M + 2S + 1A + N * (4S + 5M + 8A)
  // N = 1 => 6M + 6S + 9A
  var a = this.curve.a;
  var tinv = this.curve.tinv;

  var jx = this.x;
  var jy = this.y;
  var jz = this.z;
  var jz4 = jz.redSqr().redSqr();

  // Reuse results
  var jyd = jy.redAdd(jy);
  for (i = 0; i < pow; i++) {
    var jx2 = jx.redSqr();
    var jyd2 = jyd.redSqr();
    var jyd4 = jyd2.redSqr();
    var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));

    var t1 = jx.redMul(jyd2);
    var nx = c.redSqr().redISub(t1.redAdd(t1));
    var t2 = t1.redISub(nx);
    var dny = c.redMul(t2);
    dny = dny.redIAdd(dny).redISub(jyd4);
    var nz = jyd.redMul(jz);
    if (i + 1 < pow)
      jz4 = jz4.redMul(jyd4);

    jx = nx;
    jz = nz;
    jyd = dny;
  }

  return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
};

JPoint.prototype.dbl = function dbl() {
  if (this.isInfinity())
    return this;

  if (this.curve.zeroA)
    return this._zeroDbl();
  else if (this.curve.threeA)
    return this._threeDbl();
  else
    return this._dbl();
};

JPoint.prototype._zeroDbl = function _zeroDbl() {
  var nx;
  var ny;
  var nz;
  // Z = 1
  if (this.zOne) {
    // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
    //     #doubling-mdbl-2007-bl
    // 1M + 5S + 14A

    // XX = X1^2
    var xx = this.x.redSqr();
    // YY = Y1^2
    var yy = this.y.redSqr();
    // YYYY = YY^2
    var yyyy = yy.redSqr();
    // S = 2 * ((X1 + YY)^2 - XX - YYYY)
    var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
    s = s.redIAdd(s);
    // M = 3 * XX + a; a = 0
    var m = xx.redAdd(xx).redIAdd(xx);
    // T = M ^ 2 - 2*S
    var t = m.redSqr().redISub(s).redISub(s);

    // 8 * YYYY
    var yyyy8 = yyyy.redIAdd(yyyy);
    yyyy8 = yyyy8.redIAdd(yyyy8);
    yyyy8 = yyyy8.redIAdd(yyyy8);

    // X3 = T
    nx = t;
    // Y3 = M * (S - T) - 8 * YYYY
    ny = m.redMul(s.redISub(t)).redISub(yyyy8);
    // Z3 = 2*Y1
    nz = this.y.redAdd(this.y);
  } else {
    // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
    //     #doubling-dbl-2009-l
    // 2M + 5S + 13A

    // A = X1^2
    var a = this.x.redSqr();
    // B = Y1^2
    var b = this.y.redSqr();
    // C = B^2
    var c = b.redSqr();
    // D = 2 * ((X1 + B)^2 - A - C)
    var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
    d = d.redIAdd(d);
    // E = 3 * A
    var e = a.redAdd(a).redIAdd(a);
    // F = E^2
    var f = e.redSqr();

    // 8 * C
    var c8 = c.redIAdd(c);
    c8 = c8.redIAdd(c8);
    c8 = c8.redIAdd(c8);

    // X3 = F - 2 * D
    nx = f.redISub(d).redISub(d);
    // Y3 = E * (D - X3) - 8 * C
    ny = e.redMul(d.redISub(nx)).redISub(c8);
    // Z3 = 2 * Y1 * Z1
    nz = this.y.redMul(this.z);
    nz = nz.redIAdd(nz);
  }

  return this.curve.jpoint(nx, ny, nz);
};

JPoint.prototype._threeDbl = function _threeDbl() {
  var nx;
  var ny;
  var nz;
  // Z = 1
  if (this.zOne) {
    // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
    //     #doubling-mdbl-2007-bl
    // 1M + 5S + 15A

    // XX = X1^2
    var xx = this.x.redSqr();
    // YY = Y1^2
    var yy = this.y.redSqr();
    // YYYY = YY^2
    var yyyy = yy.redSqr();
    // S = 2 * ((X1 + YY)^2 - XX - YYYY)
    var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
    s = s.redIAdd(s);
    // M = 3 * XX + a
    var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
    // T = M^2 - 2 * S
    var t = m.redSqr().redISub(s).redISub(s);
    // X3 = T
    nx = t;
    // Y3 = M * (S - T) - 8 * YYYY
    var yyyy8 = yyyy.redIAdd(yyyy);
    yyyy8 = yyyy8.redIAdd(yyyy8);
    yyyy8 = yyyy8.redIAdd(yyyy8);
    ny = m.redMul(s.redISub(t)).redISub(yyyy8);
    // Z3 = 2 * Y1
    nz = this.y.redAdd(this.y);
  } else {
    // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
    // 3M + 5S

    // delta = Z1^2
    var delta = this.z.redSqr();
    // gamma = Y1^2
    var gamma = this.y.redSqr();
    // beta = X1 * gamma
    var beta = this.x.redMul(gamma);
    // alpha = 3 * (X1 - delta) * (X1 + delta)
    var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
    alpha = alpha.redAdd(alpha).redIAdd(alpha);
    // X3 = alpha^2 - 8 * beta
    var beta4 = beta.redIAdd(beta);
    beta4 = beta4.redIAdd(beta4);
    var beta8 = beta4.redAdd(beta4);
    nx = alpha.redSqr().redISub(beta8);
    // Z3 = (Y1 + Z1)^2 - gamma - delta
    nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
    // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
    var ggamma8 = gamma.redSqr();
    ggamma8 = ggamma8.redIAdd(ggamma8);
    ggamma8 = ggamma8.redIAdd(ggamma8);
    ggamma8 = ggamma8.redIAdd(ggamma8);
    ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
  }

  return this.curve.jpoint(nx, ny, nz);
};

JPoint.prototype._dbl = function _dbl() {
  var a = this.curve.a;

  // 4M + 6S + 10A
  var jx = this.x;
  var jy = this.y;
  var jz = this.z;
  var jz4 = jz.redSqr().redSqr();

  var jx2 = jx.redSqr();
  var jy2 = jy.redSqr();

  var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));

  var jxd4 = jx.redAdd(jx);
  jxd4 = jxd4.redIAdd(jxd4);
  var t1 = jxd4.redMul(jy2);
  var nx = c.redSqr().redISub(t1.redAdd(t1));
  var t2 = t1.redISub(nx);

  var jyd8 = jy2.redSqr();
  jyd8 = jyd8.redIAdd(jyd8);
  jyd8 = jyd8.redIAdd(jyd8);
  jyd8 = jyd8.redIAdd(jyd8);
  var ny = c.redMul(t2).redISub(jyd8);
  var nz = jy.redAdd(jy).redMul(jz);

  return this.curve.jpoint(nx, ny, nz);
};

JPoint.prototype.trpl = function trpl() {
  if (!this.curve.zeroA)
    return this.dbl().add(this);

  // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
  // 5M + 10S + ...

  // XX = X1^2
  var xx = this.x.redSqr();
  // YY = Y1^2
  var yy = this.y.redSqr();
  // ZZ = Z1^2
  var zz = this.z.redSqr();
  // YYYY = YY^2
  var yyyy = yy.redSqr();
  // M = 3 * XX + a * ZZ2; a = 0
  var m = xx.redAdd(xx).redIAdd(xx);
  // MM = M^2
  var mm = m.redSqr();
  // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
  var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
  e = e.redIAdd(e);
  e = e.redAdd(e).redIAdd(e);
  e = e.redISub(mm);
  // EE = E^2
  var ee = e.redSqr();
  // T = 16*YYYY
  var t = yyyy.redIAdd(yyyy);
  t = t.redIAdd(t);
  t = t.redIAdd(t);
  t = t.redIAdd(t);
  // U = (M + E)^2 - MM - EE - T
  var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
  // X3 = 4 * (X1 * EE - 4 * YY * U)
  var yyu4 = yy.redMul(u);
  yyu4 = yyu4.redIAdd(yyu4);
  yyu4 = yyu4.redIAdd(yyu4);
  var nx = this.x.redMul(ee).redISub(yyu4);
  nx = nx.redIAdd(nx);
  nx = nx.redIAdd(nx);
  // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
  var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
  ny = ny.redIAdd(ny);
  ny = ny.redIAdd(ny);
  ny = ny.redIAdd(ny);
  // Z3 = (Z1 + E)^2 - ZZ - EE
  var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);

  return this.curve.jpoint(nx, ny, nz);
};

JPoint.prototype.mul = function mul(k, kbase) {
  k = new BN(k, kbase);

  return this.curve._wnafMul(this, k);
};

JPoint.prototype.eq = function eq(p) {
  if (p.type === 'affine')
    return this.eq(p.toJ());

  if (this === p)
    return true;

  // x1 * z2^2 == x2 * z1^2
  var z2 = this.z.redSqr();
  var pz2 = p.z.redSqr();
  if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
    return false;

  // y1 * z2^3 == y2 * z1^3
  var z3 = z2.redMul(this.z);
  var pz3 = pz2.redMul(p.z);
  return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
};

JPoint.prototype.eqXToP = function eqXToP(x) {
  var zs = this.z.redSqr();
  var rx = x.toRed(this.curve.red).redMul(zs);
  if (this.x.cmp(rx) === 0)
    return true;

  var xc = x.clone();
  var t = this.curve.redN.redMul(zs);
  for (;;) {
    xc.iadd(this.curve.n);
    if (xc.cmp(this.curve.p) >= 0)
      return false;

    rx.redIAdd(t);
    if (this.x.cmp(rx) === 0)
      return true;
  }
};

JPoint.prototype.inspect = function inspect() {
  if (this.isInfinity())
    return '<EC JPoint Infinity>';
  return '<EC JPoint x: ' + this.x.toString(16, 2) +
      ' y: ' + this.y.toString(16, 2) +
      ' z: ' + this.z.toString(16, 2) + '>';
};

JPoint.prototype.isInfinity = function isInfinity() {
  // XXX This code assumes that zero is always zero in red
  return this.z.cmpn(0) === 0;
};


/***/ }),

/***/ 16745:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";


var curves = exports;

var hash = __webpack_require__(94294);
var curve = __webpack_require__(89817);
var utils = __webpack_require__(78944);

var assert = utils.assert;

function PresetCurve(options) {
  if (options.type === 'short')
    this.curve = new curve.short(options);
  else if (options.type === 'edwards')
    this.curve = new curve.edwards(options);
  else
    this.curve = new curve.mont(options);
  this.g = this.curve.g;
  this.n = this.curve.n;
  this.hash = options.hash;

  assert(this.g.validate(), 'Invalid curve');
  assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');
}
curves.PresetCurve = PresetCurve;

function defineCurve(name, options) {
  Object.defineProperty(curves, name, {
    configurable: true,
    enumerable: true,
    get: function() {
      var curve = new PresetCurve(options);
      Object.defineProperty(curves, name, {
        configurable: true,
        enumerable: true,
        value: curve,
      });
      return curve;
    },
  });
}

defineCurve('p192', {
  type: 'short',
  prime: 'p192',
  p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
  a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
  b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
  n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
  hash: hash.sha256,
  gRed: false,
  g: [
    '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
    '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811',
  ],
});

defineCurve('p224', {
  type: 'short',
  prime: 'p224',
  p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
  a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
  b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
  n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
  hash: hash.sha256,
  gRed: false,
  g: [
    'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
    'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34',
  ],
});

defineCurve('p256', {
  type: 'short',
  prime: null,
  p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
  a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
  b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
  n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
  hash: hash.sha256,
  gRed: false,
  g: [
    '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
    '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5',
  ],
});

defineCurve('p384', {
  type: 'short',
  prime: null,
  p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
     'fffffffe ffffffff 00000000 00000000 ffffffff',
  a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
     'fffffffe ffffffff 00000000 00000000 fffffffc',
  b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
     '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
  n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
     'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
  hash: hash.sha384,
  gRed: false,
  g: [
    'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
    '5502f25d bf55296c 3a545e38 72760ab7',
    '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
    '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f',
  ],
});

defineCurve('p521', {
  type: 'short',
  prime: null,
  p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
     'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
     'ffffffff ffffffff ffffffff ffffffff ffffffff',
  a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
     'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
     'ffffffff ffffffff ffffffff ffffffff fffffffc',
  b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
     '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
     '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
  n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
     'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
     'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
  hash: hash.sha512,
  gRed: false,
  g: [
    '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
    '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
    'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
    '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
    '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
    '3fad0761 353c7086 a272c240 88be9476 9fd16650',
  ],
});

defineCurve('curve25519', {
  type: 'mont',
  prime: 'p25519',
  p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
  a: '76d06',
  b: '1',
  n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
  hash: hash.sha256,
  gRed: false,
  g: [
    '9',
  ],
});

defineCurve('ed25519', {
  type: 'edwards',
  prime: 'p25519',
  p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
  a: '-1',
  c: '1',
  // -121665 * (121666^(-1)) (mod P)
  d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
  n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
  hash: hash.sha256,
  gRed: false,
  g: [
    '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',

    // 4/5
    '6666666666666666666666666666666666666666666666666666666666666658',
  ],
});

var pre;
try {
  pre = __webpack_require__(11160);
} catch (e) {
  pre = undefined;
}

defineCurve('secp256k1', {
  type: 'short',
  prime: 'k256',
  p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
  a: '0',
  b: '7',
  n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
  h: '1',
  hash: hash.sha256,

  // Precomputed endomorphism
  beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
  lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
  basis: [
    {
      a: '3086d221a7d46bcde86c90e49284eb15',
      b: '-e4437ed6010e88286f547fa90abfe4c3',
    },
    {
      a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
      b: '3086d221a7d46bcde86c90e49284eb15',
    },
  ],

  gRed: false,
  g: [
    '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
    '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
    pre,
  ],
});


/***/ }),

/***/ 87474:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var BN = __webpack_require__(89991);
var HmacDRBG = __webpack_require__(38336);
var utils = __webpack_require__(78944);
var curves = __webpack_require__(16745);
var rand = __webpack_require__(35973);
var assert = utils.assert;

var KeyPair = __webpack_require__(2621);
var Signature = __webpack_require__(51044);

function EC(options) {
  if (!(this instanceof EC))
    return new EC(options);

  // Shortcut `elliptic.ec(curve-name)`
  if (typeof options === 'string') {
    assert(Object.prototype.hasOwnProperty.call(curves, options),
      'Unknown curve ' + options);

    options = curves[options];
  }

  // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
  if (options instanceof curves.PresetCurve)
    options = { curve: options };

  this.curve = options.curve.curve;
  this.n = this.curve.n;
  this.nh = this.n.ushrn(1);
  this.g = this.curve.g;

  // Point on curve
  this.g = options.curve.g;
  this.g.precompute(options.curve.n.bitLength() + 1);

  // Hash for function for DRBG
  this.hash = options.hash || options.curve.hash;
}
module.exports = EC;

EC.prototype.keyPair = function keyPair(options) {
  return new KeyPair(this, options);
};

EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
  return KeyPair.fromPrivate(this, priv, enc);
};

EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
  return KeyPair.fromPublic(this, pub, enc);
};

EC.prototype.genKeyPair = function genKeyPair(options) {
  if (!options)
    options = {};

  // Instantiate Hmac_DRBG
  var drbg = new HmacDRBG({
    hash: this.hash,
    pers: options.pers,
    persEnc: options.persEnc || 'utf8',
    entropy: options.entropy || rand(this.hash.hmacStrength),
    entropyEnc: options.entropy && options.entropyEnc || 'utf8',
    nonce: this.n.toArray(),
  });

  var bytes = this.n.byteLength();
  var ns2 = this.n.sub(new BN(2));
  for (;;) {
    var priv = new BN(drbg.generate(bytes));
    if (priv.cmp(ns2) > 0)
      continue;

    priv.iaddn(1);
    return this.keyFromPrivate(priv);
  }
};

EC.prototype._truncateToN = function _truncateToN(msg, truncOnly, bitLength) {
  var byteLength;
  if (BN.isBN(msg) || typeof msg === 'number') {
    msg = new BN(msg, 16);
    byteLength = msg.byteLength();
  } else if (typeof msg === 'object') {
    // BN assumes an array-like input and asserts length
    byteLength = msg.length;
    msg = new BN(msg, 16);
  } else {
    // BN converts the value to string
    var str = msg.toString();
    // HEX encoding
    byteLength = (str.length + 1) >>> 1;
    msg = new BN(str, 16);
  }
  // Allow overriding
  if (typeof bitLength !== 'number') {
    bitLength = byteLength * 8;
  }
  var delta = bitLength - this.n.bitLength();
  if (delta > 0)
    msg = msg.ushrn(delta);
  if (!truncOnly && msg.cmp(this.n) >= 0)
    return msg.sub(this.n);
  else
    return msg;
};

EC.prototype.sign = function sign(msg, key, enc, options) {
  if (typeof enc === 'object') {
    options = enc;
    enc = null;
  }
  if (!options)
    options = {};

  if (typeof msg !== 'string' && typeof msg !== 'number' && !BN.isBN(msg)) {
    assert(typeof msg === 'object' && msg && typeof msg.length === 'number',
      'Expected message to be an array-like, a hex string, or a BN instance');
    assert((msg.length >>> 0) === msg.length); // non-negative 32-bit integer
    for (var i = 0; i < msg.length; i++) assert((msg[i] & 255) === msg[i]);
  }

  key = this.keyFromPrivate(key, enc);
  msg = this._truncateToN(msg, false, options.msgBitLength);

  // Would fail further checks, but let's make the error message clear
  assert(!msg.isNeg(), 'Can not sign a negative message');

  // Zero-extend key to provide enough entropy
  var bytes = this.n.byteLength();
  var bkey = key.getPrivate().toArray('be', bytes);

  // Zero-extend nonce to have the same byte size as N
  var nonce = msg.toArray('be', bytes);

  // Recheck nonce to be bijective to msg
  assert((new BN(nonce)).eq(msg), 'Can not sign message');

  // Instantiate Hmac_DRBG
  var drbg = new HmacDRBG({
    hash: this.hash,
    entropy: bkey,
    nonce: nonce,
    pers: options.pers,
    persEnc: options.persEnc || 'utf8',
  });

  // Number of bytes to generate
  var ns1 = this.n.sub(new BN(1));

  for (var iter = 0; ; iter++) {
    var k = options.k ?
      options.k(iter) :
      new BN(drbg.generate(this.n.byteLength()));
    k = this._truncateToN(k, true);
    if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
      continue;

    var kp = this.g.mul(k);
    if (kp.isInfinity())
      continue;

    var kpX = kp.getX();
    var r = kpX.umod(this.n);
    if (r.cmpn(0) === 0)
      continue;

    var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
    s = s.umod(this.n);
    if (s.cmpn(0) === 0)
      continue;

    var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
                        (kpX.cmp(r) !== 0 ? 2 : 0);

    // Use complement of `s`, if it is > `n / 2`
    if (options.canonical && s.cmp(this.nh) > 0) {
      s = this.n.sub(s);
      recoveryParam ^= 1;
    }

    return new Signature({ r: r, s: s, recoveryParam: recoveryParam });
  }
};

EC.prototype.verify = function verify(msg, signature, key, enc, options) {
  if (!options)
    options = {};

  msg = this._truncateToN(msg, false, options.msgBitLength);
  key = this.keyFromPublic(key, enc);
  signature = new Signature(signature, 'hex');

  // Perform primitive values validation
  var r = signature.r;
  var s = signature.s;
  if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
    return false;
  if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
    return false;

  // Validate signature
  var sinv = s.invm(this.n);
  var u1 = sinv.mul(msg).umod(this.n);
  var u2 = sinv.mul(r).umod(this.n);
  var p;

  if (!this.curve._maxwellTrick) {
    p = this.g.mulAdd(u1, key.getPublic(), u2);
    if (p.isInfinity())
      return false;

    return p.getX().umod(this.n).cmp(r) === 0;
  }

  // NOTE: Greg Maxwell's trick, inspired by:
  // https://git.io/vad3K

  p = this.g.jmulAdd(u1, key.getPublic(), u2);
  if (p.isInfinity())
    return false;

  // Compare `p.x` of Jacobian point with `r`,
  // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
  // inverse of `p.z^2`
  return p.eqXToP(r);
};

EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
  assert((3 & j) === j, 'The recovery param is more than two bits');
  signature = new Signature(signature, enc);

  var n = this.n;
  var e = new BN(msg);
  var r = signature.r;
  var s = signature.s;

  // A set LSB signifies that the y-coordinate is odd
  var isYOdd = j & 1;
  var isSecondKey = j >> 1;
  if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
    throw new Error('Unable to find sencond key candinate');

  // 1.1. Let x = r + jn.
  if (isSecondKey)
    r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
  else
    r = this.curve.pointFromX(r, isYOdd);

  var rInv = signature.r.invm(n);
  var s1 = n.sub(e).mul(rInv).umod(n);
  var s2 = s.mul(rInv).umod(n);

  // 1.6.1 Compute Q = r^-1 (sR -  eG)
  //               Q = r^-1 (sR + -eG)
  return this.g.mulAdd(s1, r, s2);
};

EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
  signature = new Signature(signature, enc);
  if (signature.recoveryParam !== null)
    return signature.recoveryParam;

  for (var i = 0; i < 4; i++) {
    var Qprime;
    try {
      Qprime = this.recoverPubKey(e, signature, i);
    } catch (e) {
      continue;
    }

    if (Qprime.eq(Q))
      return i;
  }
  throw new Error('Unable to find valid recovery factor');
};


/***/ }),

/***/ 2621:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var BN = __webpack_require__(89991);
var utils = __webpack_require__(78944);
var assert = utils.assert;

function KeyPair(ec, options) {
  this.ec = ec;
  this.priv = null;
  this.pub = null;

  // KeyPair(ec, { priv: ..., pub: ... })
  if (options.priv)
    this._importPrivate(options.priv, options.privEnc);
  if (options.pub)
    this._importPublic(options.pub, options.pubEnc);
}
module.exports = KeyPair;

KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
  if (pub instanceof KeyPair)
    return pub;

  return new KeyPair(ec, {
    pub: pub,
    pubEnc: enc,
  });
};

KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
  if (priv instanceof KeyPair)
    return priv;

  return new KeyPair(ec, {
    priv: priv,
    privEnc: enc,
  });
};

KeyPair.prototype.validate = function validate() {
  var pub = this.getPublic();

  if (pub.isInfinity())
    return { result: false, reason: 'Invalid public key' };
  if (!pub.validate())
    return { result: false, reason: 'Public key is not a point' };
  if (!pub.mul(this.ec.curve.n).isInfinity())
    return { result: false, reason: 'Public key * N != O' };

  return { result: true, reason: null };
};

KeyPair.prototype.getPublic = function getPublic(compact, enc) {
  // compact is optional argument
  if (typeof compact === 'string') {
    enc = compact;
    compact = null;
  }

  if (!this.pub)
    this.pub = this.ec.g.mul(this.priv);

  if (!enc)
    return this.pub;

  return this.pub.encode(enc, compact);
};

KeyPair.prototype.getPrivate = function getPrivate(enc) {
  if (enc === 'hex')
    return this.priv.toString(16, 2);
  else
    return this.priv;
};

KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
  this.priv = new BN(key, enc || 16);

  // Ensure that the priv won't be bigger than n, otherwise we may fail
  // in fixed multiplication method
  this.priv = this.priv.umod(this.ec.curve.n);
};

KeyPair.prototype._importPublic = function _importPublic(key, enc) {
  if (key.x || key.y) {
    // Montgomery points only have an `x` coordinate.
    // Weierstrass/Edwards points on the other hand have both `x` and
    // `y` coordinates.
    if (this.ec.curve.type === 'mont') {
      assert(key.x, 'Need x coordinate');
    } else if (this.ec.curve.type === 'short' ||
               this.ec.curve.type === 'edwards') {
      assert(key.x && key.y, 'Need both x and y coordinate');
    }
    this.pub = this.ec.curve.point(key.x, key.y);
    return;
  }
  this.pub = this.ec.curve.decodePoint(key, enc);
};

// ECDH
KeyPair.prototype.derive = function derive(pub) {
  if(!pub.validate()) {
    assert(pub.validate(), 'public point not validated');
  }
  return pub.mul(this.priv).getX();
};

// ECDSA
KeyPair.prototype.sign = function sign(msg, enc, options) {
  return this.ec.sign(msg, this, enc, options);
};

KeyPair.prototype.verify = function verify(msg, signature, options) {
  return this.ec.verify(msg, signature, this, undefined, options);
};

KeyPair.prototype.inspect = function inspect() {
  return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
         ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
};


/***/ }),

/***/ 51044:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var BN = __webpack_require__(89991);

var utils = __webpack_require__(78944);
var assert = utils.assert;

function Signature(options, enc) {
  if (options instanceof Signature)
    return options;

  if (this._importDER(options, enc))
    return;

  assert(options.r && options.s, 'Signature without r or s');
  this.r = new BN(options.r, 16);
  this.s = new BN(options.s, 16);
  if (options.recoveryParam === undefined)
    this.recoveryParam = null;
  else
    this.recoveryParam = options.recoveryParam;
}
module.exports = Signature;

function Position() {
  this.place = 0;
}

function getLength(buf, p) {
  var initial = buf[p.place++];
  if (!(initial & 0x80)) {
    return initial;
  }
  var octetLen = initial & 0xf;

  // Indefinite length or overflow
  if (octetLen === 0 || octetLen > 4) {
    return false;
  }

  if(buf[p.place] === 0x00) {
    return false;
  }

  var val = 0;
  for (var i = 0, off = p.place; i < octetLen; i++, off++) {
    val <<= 8;
    val |= buf[off];
    val >>>= 0;
  }

  // Leading zeroes
  if (val <= 0x7f) {
    return false;
  }

  p.place = off;
  return val;
}

function rmPadding(buf) {
  var i = 0;
  var len = buf.length - 1;
  while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
    i++;
  }
  if (i === 0) {
    return buf;
  }
  return buf.slice(i);
}

Signature.prototype._importDER = function _importDER(data, enc) {
  data = utils.toArray(data, enc);
  var p = new Position();
  if (data[p.place++] !== 0x30) {
    return false;
  }
  var len = getLength(data, p);
  if (len === false) {
    return false;
  }
  if ((len + p.place) !== data.length) {
    return false;
  }
  if (data[p.place++] !== 0x02) {
    return false;
  }
  var rlen = getLength(data, p);
  if (rlen === false) {
    return false;
  }
  if ((data[p.place] & 128) !== 0) {
    return false;
  }
  var r = data.slice(p.place, rlen + p.place);
  p.place += rlen;
  if (data[p.place++] !== 0x02) {
    return false;
  }
  var slen = getLength(data, p);
  if (slen === false) {
    return false;
  }
  if (data.length !== slen + p.place) {
    return false;
  }
  if ((data[p.place] & 128) !== 0) {
    return false;
  }
  var s = data.slice(p.place, slen + p.place);
  if (r[0] === 0) {
    if (r[1] & 0x80) {
      r = r.slice(1);
    } else {
      // Leading zeroes
      return false;
    }
  }
  if (s[0] === 0) {
    if (s[1] & 0x80) {
      s = s.slice(1);
    } else {
      // Leading zeroes
      return false;
    }
  }

  this.r = new BN(r);
  this.s = new BN(s);
  this.recoveryParam = null;

  return true;
};

function constructLength(arr, len) {
  if (len < 0x80) {
    arr.push(len);
    return;
  }
  var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
  arr.push(octets | 0x80);
  while (--octets) {
    arr.push((len >>> (octets << 3)) & 0xff);
  }
  arr.push(len);
}

Signature.prototype.toDER = function toDER(enc) {
  var r = this.r.toArray();
  var s = this.s.toArray();

  // Pad values
  if (r[0] & 0x80)
    r = [ 0 ].concat(r);
  // Pad values
  if (s[0] & 0x80)
    s = [ 0 ].concat(s);

  r = rmPadding(r);
  s = rmPadding(s);

  while (!s[0] && !(s[1] & 0x80)) {
    s = s.slice(1);
  }
  var arr = [ 0x02 ];
  constructLength(arr, r.length);
  arr = arr.concat(r);
  arr.push(0x02);
  constructLength(arr, s.length);
  var backHalf = arr.concat(s);
  var res = [ 0x30 ];
  constructLength(res, backHalf.length);
  res = res.concat(backHalf);
  return utils.encode(res, enc);
};


/***/ }),

/***/ 32261:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var hash = __webpack_require__(94294);
var curves = __webpack_require__(16745);
var utils = __webpack_require__(78944);
var assert = utils.assert;
var parseBytes = utils.parseBytes;
var KeyPair = __webpack_require__(47798);
var Signature = __webpack_require__(10251);

function EDDSA(curve) {
  assert(curve === 'ed25519', 'only tested with ed25519 so far');

  if (!(this instanceof EDDSA))
    return new EDDSA(curve);

  curve = curves[curve].curve;
  this.curve = curve;
  this.g = curve.g;
  this.g.precompute(curve.n.bitLength() + 1);

  this.pointClass = curve.point().constructor;
  this.encodingLength = Math.ceil(curve.n.bitLength() / 8);
  this.hash = hash.sha512;
}

module.exports = EDDSA;

/**
* @param {Array|String} message - message bytes
* @param {Array|String|KeyPair} secret - secret bytes or a keypair
* @returns {Signature} - signature
*/
EDDSA.prototype.sign = function sign(message, secret) {
  message = parseBytes(message);
  var key = this.keyFromSecret(secret);
  var r = this.hashInt(key.messagePrefix(), message);
  var R = this.g.mul(r);
  var Rencoded = this.encodePoint(R);
  var s_ = this.hashInt(Rencoded, key.pubBytes(), message)
    .mul(key.priv());
  var S = r.add(s_).umod(this.curve.n);
  return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });
};

/**
* @param {Array} message - message bytes
* @param {Array|String|Signature} sig - sig bytes
* @param {Array|String|Point|KeyPair} pub - public key
* @returns {Boolean} - true if public key matches sig of message
*/
EDDSA.prototype.verify = function verify(message, sig, pub) {
  message = parseBytes(message);
  sig = this.makeSignature(sig);
  if (sig.S().gte(sig.eddsa.curve.n) || sig.S().isNeg()) {
    return false;
  }
  var key = this.keyFromPublic(pub);
  var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);
  var SG = this.g.mul(sig.S());
  var RplusAh = sig.R().add(key.pub().mul(h));
  return RplusAh.eq(SG);
};

EDDSA.prototype.hashInt = function hashInt() {
  var hash = this.hash();
  for (var i = 0; i < arguments.length; i++)
    hash.update(arguments[i]);
  return utils.intFromLE(hash.digest()).umod(this.curve.n);
};

EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
  return KeyPair.fromPublic(this, pub);
};

EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
  return KeyPair.fromSecret(this, secret);
};

EDDSA.prototype.makeSignature = function makeSignature(sig) {
  if (sig instanceof Signature)
    return sig;
  return new Signature(this, sig);
};

/**
* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
*
* EDDSA defines methods for encoding and decoding points and integers. These are
* helper convenience methods, that pass along to utility functions implied
* parameters.
*
*/
EDDSA.prototype.encodePoint = function encodePoint(point) {
  var enc = point.getY().toArray('le', this.encodingLength);
  enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;
  return enc;
};

EDDSA.prototype.decodePoint = function decodePoint(bytes) {
  bytes = utils.parseBytes(bytes);

  var lastIx = bytes.length - 1;
  var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);
  var xIsOdd = (bytes[lastIx] & 0x80) !== 0;

  var y = utils.intFromLE(normed);
  return this.curve.pointFromY(y, xIsOdd);
};

EDDSA.prototype.encodeInt = function encodeInt(num) {
  return num.toArray('le', this.encodingLength);
};

EDDSA.prototype.decodeInt = function decodeInt(bytes) {
  return utils.intFromLE(bytes);
};

EDDSA.prototype.isPoint = function isPoint(val) {
  return val instanceof this.pointClass;
};


/***/ }),

/***/ 47798:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var utils = __webpack_require__(78944);
var assert = utils.assert;
var parseBytes = utils.parseBytes;
var cachedProperty = utils.cachedProperty;

/**
* @param {EDDSA} eddsa - instance
* @param {Object} params - public/private key parameters
*
* @param {Array<Byte>} [params.secret] - secret seed bytes
* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)
* @param {Array<Byte>} [params.pub] - public key point encoded as bytes
*
*/
function KeyPair(eddsa, params) {
  this.eddsa = eddsa;
  this._secret = parseBytes(params.secret);
  if (eddsa.isPoint(params.pub))
    this._pub = params.pub;
  else
    this._pubBytes = parseBytes(params.pub);
}

KeyPair.fromPublic = function fromPublic(eddsa, pub) {
  if (pub instanceof KeyPair)
    return pub;
  return new KeyPair(eddsa, { pub: pub });
};

KeyPair.fromSecret = function fromSecret(eddsa, secret) {
  if (secret instanceof KeyPair)
    return secret;
  return new KeyPair(eddsa, { secret: secret });
};

KeyPair.prototype.secret = function secret() {
  return this._secret;
};

cachedProperty(KeyPair, 'pubBytes', function pubBytes() {
  return this.eddsa.encodePoint(this.pub());
});

cachedProperty(KeyPair, 'pub', function pub() {
  if (this._pubBytes)
    return this.eddsa.decodePoint(this._pubBytes);
  return this.eddsa.g.mul(this.priv());
});

cachedProperty(KeyPair, 'privBytes', function privBytes() {
  var eddsa = this.eddsa;
  var hash = this.hash();
  var lastIx = eddsa.encodingLength - 1;

  var a = hash.slice(0, eddsa.encodingLength);
  a[0] &= 248;
  a[lastIx] &= 127;
  a[lastIx] |= 64;

  return a;
});

cachedProperty(KeyPair, 'priv', function priv() {
  return this.eddsa.decodeInt(this.privBytes());
});

cachedProperty(KeyPair, 'hash', function hash() {
  return this.eddsa.hash().update(this.secret()).digest();
});

cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {
  return this.hash().slice(this.eddsa.encodingLength);
});

KeyPair.prototype.sign = function sign(message) {
  assert(this._secret, 'KeyPair can only verify');
  return this.eddsa.sign(message, this);
};

KeyPair.prototype.verify = function verify(message, sig) {
  return this.eddsa.verify(message, sig, this);
};

KeyPair.prototype.getSecret = function getSecret(enc) {
  assert(this._secret, 'KeyPair is public only');
  return utils.encode(this.secret(), enc);
};

KeyPair.prototype.getPublic = function getPublic(enc) {
  return utils.encode(this.pubBytes(), enc);
};

module.exports = KeyPair;


/***/ }),

/***/ 10251:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var BN = __webpack_require__(89991);
var utils = __webpack_require__(78944);
var assert = utils.assert;
var cachedProperty = utils.cachedProperty;
var parseBytes = utils.parseBytes;

/**
* @param {EDDSA} eddsa - eddsa instance
* @param {Array<Bytes>|Object} sig -
* @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
* @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
* @param {Array<Bytes>} [sig.Rencoded] - R point encoded
* @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
*/
function Signature(eddsa, sig) {
  this.eddsa = eddsa;

  if (typeof sig !== 'object')
    sig = parseBytes(sig);

  if (Array.isArray(sig)) {
    assert(sig.length === eddsa.encodingLength * 2, 'Signature has invalid size');
    sig = {
      R: sig.slice(0, eddsa.encodingLength),
      S: sig.slice(eddsa.encodingLength),
    };
  }

  assert(sig.R && sig.S, 'Signature without R or S');

  if (eddsa.isPoint(sig.R))
    this._R = sig.R;
  if (sig.S instanceof BN)
    this._S = sig.S;

  this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
  this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
}

cachedProperty(Signature, 'S', function S() {
  return this.eddsa.decodeInt(this.Sencoded());
});

cachedProperty(Signature, 'R', function R() {
  return this.eddsa.decodePoint(this.Rencoded());
});

cachedProperty(Signature, 'Rencoded', function Rencoded() {
  return this.eddsa.encodePoint(this.R());
});

cachedProperty(Signature, 'Sencoded', function Sencoded() {
  return this.eddsa.encodeInt(this.S());
});

Signature.prototype.toBytes = function toBytes() {
  return this.Rencoded().concat(this.Sencoded());
};

Signature.prototype.toHex = function toHex() {
  return utils.encode(this.toBytes(), 'hex').toUpperCase();
};

module.exports = Signature;


/***/ }),

/***/ 11160:
/***/ ((module) => {

module.exports = {
  doubles: {
    step: 4,
    points: [
      [
        'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
        'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821',
      ],
      [
        '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
        '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf',
      ],
      [
        '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
        'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695',
      ],
      [
        '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
        '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9',
      ],
      [
        '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
        '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36',
      ],
      [
        '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
        '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f',
      ],
      [
        'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
        '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999',
      ],
      [
        '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
        'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09',
      ],
      [
        'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
        '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d',
      ],
      [
        'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
        'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088',
      ],
      [
        'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
        '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d',
      ],
      [
        '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
        '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8',
      ],
      [
        '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
        '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a',
      ],
      [
        '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
        '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453',
      ],
      [
        '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
        '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160',
      ],
      [
        '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
        '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0',
      ],
      [
        '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
        '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6',
      ],
      [
        '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
        '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589',
      ],
      [
        '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
        'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17',
      ],
      [
        'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
        '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda',
      ],
      [
        'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
        '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd',
      ],
      [
        '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
        '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2',
      ],
      [
        '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
        '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6',
      ],
      [
        'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
        '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f',
      ],
      [
        '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
        'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01',
      ],
      [
        'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
        '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3',
      ],
      [
        'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
        'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f',
      ],
      [
        'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
        '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7',
      ],
      [
        'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
        'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78',
      ],
      [
        'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
        '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1',
      ],
      [
        '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
        'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150',
      ],
      [
        '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
        '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82',
      ],
      [
        'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
        '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc',
      ],
      [
        '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
        'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b',
      ],
      [
        'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
        '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51',
      ],
      [
        'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
        '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45',
      ],
      [
        'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
        'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120',
      ],
      [
        '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
        '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84',
      ],
      [
        '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
        '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d',
      ],
      [
        '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
        'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d',
      ],
      [
        '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
        '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8',
      ],
      [
        'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
        '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8',
      ],
      [
        '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
        '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac',
      ],
      [
        '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
        'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f',
      ],
      [
        '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
        '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962',
      ],
      [
        'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
        '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907',
      ],
      [
        '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
        'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec',
      ],
      [
        'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
        'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d',
      ],
      [
        'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
        '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414',
      ],
      [
        '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
        'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd',
      ],
      [
        '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
        'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0',
      ],
      [
        'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
        '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811',
      ],
      [
        'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
        '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1',
      ],
      [
        'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
        '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c',
      ],
      [
        '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
        'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73',
      ],
      [
        '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
        '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd',
      ],
      [
        'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
        'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405',
      ],
      [
        '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
        'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589',
      ],
      [
        '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
        '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e',
      ],
      [
        '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
        '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27',
      ],
      [
        'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
        'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1',
      ],
      [
        '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
        '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482',
      ],
      [
        '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
        '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945',
      ],
      [
        'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
        '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573',
      ],
      [
        'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
        'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82',
      ],
    ],
  },
  naf: {
    wnd: 7,
    points: [
      [
        'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
        '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672',
      ],
      [
        '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
        'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6',
      ],
      [
        '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
        '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da',
      ],
      [
        'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
        'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37',
      ],
      [
        '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
        'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b',
      ],
      [
        'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
        'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81',
      ],
      [
        'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
        '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58',
      ],
      [
        'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
        '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77',
      ],
      [
        '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
        '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a',
      ],
      [
        '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
        '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c',
      ],
      [
        '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
        '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67',
      ],
      [
        '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
        '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402',
      ],
      [
        'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
        'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55',
      ],
      [
        'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
        '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482',
      ],
      [
        '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
        'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82',
      ],
      [
        '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
        'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396',
      ],
      [
        '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
        '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49',
      ],
      [
        '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
        '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf',
      ],
      [
        '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
        '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a',
      ],
      [
        '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
        'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7',
      ],
      [
        'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
        'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933',
      ],
      [
        '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
        '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a',
      ],
      [
        '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
        '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6',
      ],
      [
        'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
        'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37',
      ],
      [
        '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
        '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e',
      ],
      [
        'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
        'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6',
      ],
      [
        'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
        'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476',
      ],
      [
        '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
        '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40',
      ],
      [
        '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
        '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61',
      ],
      [
        '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
        '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683',
      ],
      [
        'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
        '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5',
      ],
      [
        '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
        '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b',
      ],
      [
        'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
        '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417',
      ],
      [
        '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
        'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868',
      ],
      [
        '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
        'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a',
      ],
      [
        'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
        'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6',
      ],
      [
        '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
        '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996',
      ],
      [
        '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
        'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e',
      ],
      [
        'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
        'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d',
      ],
      [
        '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
        '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2',
      ],
      [
        '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
        'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e',
      ],
      [
        '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
        '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437',
      ],
      [
        '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
        'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311',
      ],
      [
        'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
        '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4',
      ],
      [
        '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
        '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575',
      ],
      [
        '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
        'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d',
      ],
      [
        '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
        'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d',
      ],
      [
        'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
        'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629',
      ],
      [
        'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
        'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06',
      ],
      [
        '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
        '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374',
      ],
      [
        '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
        '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee',
      ],
      [
        'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
        '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1',
      ],
      [
        'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
        'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b',
      ],
      [
        '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
        '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661',
      ],
      [
        '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
        '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6',
      ],
      [
        'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
        '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e',
      ],
      [
        '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
        '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d',
      ],
      [
        'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
        'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc',
      ],
      [
        '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
        'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4',
      ],
      [
        '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
        '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c',
      ],
      [
        'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
        '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b',
      ],
      [
        'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
        '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913',
      ],
      [
        '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
        '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154',
      ],
      [
        '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
        '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865',
      ],
      [
        '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
        'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc',
      ],
      [
        '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
        'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224',
      ],
      [
        '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
        '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e',
      ],
      [
        '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
        '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6',
      ],
      [
        '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
        '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511',
      ],
      [
        '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
        'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b',
      ],
      [
        'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
        'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2',
      ],
      [
        '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
        'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c',
      ],
      [
        'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
        '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3',
      ],
      [
        'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
        '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d',
      ],
      [
        'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
        '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700',
      ],
      [
        'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
        '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4',
      ],
      [
        '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
        'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196',
      ],
      [
        '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
        '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4',
      ],
      [
        '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
        'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257',
      ],
      [
        'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
        'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13',
      ],
      [
        'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
        '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096',
      ],
      [
        'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
        'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38',
      ],
      [
        'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
        '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f',
      ],
      [
        '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
        '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448',
      ],
      [
        'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
        '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a',
      ],
      [
        'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
        '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4',
      ],
      [
        '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
        '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437',
      ],
      [
        '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
        'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7',
      ],
      [
        'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
        '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d',
      ],
      [
        'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
        '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a',
      ],
      [
        'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
        '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54',
      ],
      [
        '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
        '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77',
      ],
      [
        'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
        'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517',
      ],
      [
        '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
        'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10',
      ],
      [
        'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
        'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125',
      ],
      [
        'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
        '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e',
      ],
      [
        '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
        'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1',
      ],
      [
        'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
        '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2',
      ],
      [
        'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
        '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423',
      ],
      [
        'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
        '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8',
      ],
      [
        '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
        'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758',
      ],
      [
        '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
        'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375',
      ],
      [
        'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
        '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d',
      ],
      [
        '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
        'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec',
      ],
      [
        '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
        '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0',
      ],
      [
        '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
        'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c',
      ],
      [
        'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
        'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4',
      ],
      [
        '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
        'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f',
      ],
      [
        '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
        '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649',
      ],
      [
        '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
        'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826',
      ],
      [
        '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
        '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5',
      ],
      [
        'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
        'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87',
      ],
      [
        '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
        '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b',
      ],
      [
        'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
        '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc',
      ],
      [
        '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
        '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c',
      ],
      [
        'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
        'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f',
      ],
      [
        'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
        '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a',
      ],
      [
        'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
        'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46',
      ],
      [
        '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
        'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f',
      ],
      [
        '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
        '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03',
      ],
      [
        '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
        'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08',
      ],
      [
        '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
        '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8',
      ],
      [
        '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
        '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373',
      ],
      [
        '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
        'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3',
      ],
      [
        '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
        '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8',
      ],
      [
        '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
        '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1',
      ],
      [
        '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
        '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9',
      ],
    ],
  },
};


/***/ }),

/***/ 78944:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";


var utils = exports;
var BN = __webpack_require__(89991);
var minAssert = __webpack_require__(2481);
var minUtils = __webpack_require__(44086);

utils.assert = minAssert;
utils.toArray = minUtils.toArray;
utils.zero2 = minUtils.zero2;
utils.toHex = minUtils.toHex;
utils.encode = minUtils.encode;

// Represent num in a w-NAF form
function getNAF(num, w, bits) {
  var naf = new Array(Math.max(num.bitLength(), bits) + 1);
  var i;
  for (i = 0; i < naf.length; i += 1) {
    naf[i] = 0;
  }

  var ws = 1 << (w + 1);
  var k = num.clone();

  for (i = 0; i < naf.length; i++) {
    var z;
    var mod = k.andln(ws - 1);
    if (k.isOdd()) {
      if (mod > (ws >> 1) - 1)
        z = (ws >> 1) - mod;
      else
        z = mod;
      k.isubn(z);
    } else {
      z = 0;
    }

    naf[i] = z;
    k.iushrn(1);
  }

  return naf;
}
utils.getNAF = getNAF;

// Represent k1, k2 in a Joint Sparse Form
function getJSF(k1, k2) {
  var jsf = [
    [],
    [],
  ];

  k1 = k1.clone();
  k2 = k2.clone();
  var d1 = 0;
  var d2 = 0;
  var m8;
  while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
    // First phase
    var m14 = (k1.andln(3) + d1) & 3;
    var m24 = (k2.andln(3) + d2) & 3;
    if (m14 === 3)
      m14 = -1;
    if (m24 === 3)
      m24 = -1;
    var u1;
    if ((m14 & 1) === 0) {
      u1 = 0;
    } else {
      m8 = (k1.andln(7) + d1) & 7;
      if ((m8 === 3 || m8 === 5) && m24 === 2)
        u1 = -m14;
      else
        u1 = m14;
    }
    jsf[0].push(u1);

    var u2;
    if ((m24 & 1) === 0) {
      u2 = 0;
    } else {
      m8 = (k2.andln(7) + d2) & 7;
      if ((m8 === 3 || m8 === 5) && m14 === 2)
        u2 = -m24;
      else
        u2 = m24;
    }
    jsf[1].push(u2);

    // Second phase
    if (2 * d1 === u1 + 1)
      d1 = 1 - d1;
    if (2 * d2 === u2 + 1)
      d2 = 1 - d2;
    k1.iushrn(1);
    k2.iushrn(1);
  }

  return jsf;
}
utils.getJSF = getJSF;

function cachedProperty(obj, name, computer) {
  var key = '_' + name;
  obj.prototype[name] = function cachedProperty() {
    return this[key] !== undefined ? this[key] :
      this[key] = computer.call(this);
  };
}
utils.cachedProperty = cachedProperty;

function parseBytes(bytes) {
  return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
    bytes;
}
utils.parseBytes = parseBytes;

function intFromLE(bytes) {
  return new BN(bytes, 'hex', 'le');
}
utils.intFromLE = intFromLE;



/***/ }),

/***/ 50608:
/***/ (function(module) {

(function webpackUniversalModuleDefinition(root, factory) {
/* istanbul ignore next */
	if(true)
		module.exports = factory();
	else {}
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __nested_webpack_require_583__(moduleId) {

/******/ 		// Check if module is in cache
/* istanbul ignore if */
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __nested_webpack_require_583__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}


/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__nested_webpack_require_583__.m = modules;

/******/ 	// expose the module cache
/******/ 	__nested_webpack_require_583__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__nested_webpack_require_583__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __nested_webpack_require_583__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __nested_webpack_require_1808__) {

	"use strict";
	/*
	  Copyright JS Foundation and other contributors, https://js.foundation/

	  Redistribution and use in source and binary forms, with or without
	  modification, are permitted provided that the following conditions are met:

	    * Redistributions of source code must retain the above copyright
	      notice, this list of conditions and the following disclaimer.
	    * Redistributions in binary form must reproduce the above copyright
	      notice, this list of conditions and the following disclaimer in the
	      documentation and/or other materials provided with the distribution.

	  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
	  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
	  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
	  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
	  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
	  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
	  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
	  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
	  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
	  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	var comment_handler_1 = __nested_webpack_require_1808__(1);
	var jsx_parser_1 = __nested_webpack_require_1808__(3);
	var parser_1 = __nested_webpack_require_1808__(8);
	var tokenizer_1 = __nested_webpack_require_1808__(15);
	function parse(code, options, delegate) {
	    var commentHandler = null;
	    var proxyDelegate = function (node, metadata) {
	        if (delegate) {
	            delegate(node, metadata);
	        }
	        if (commentHandler) {
	            commentHandler.visit(node, metadata);
	        }
	    };
	    var parserDelegate = (typeof delegate === 'function') ? proxyDelegate : null;
	    var collectComment = false;
	    if (options) {
	        collectComment = (typeof options.comment === 'boolean' && options.comment);
	        var attachComment = (typeof options.attachComment === 'boolean' && options.attachComment);
	        if (collectComment || attachComment) {
	            commentHandler = new comment_handler_1.CommentHandler();
	            commentHandler.attach = attachComment;
	            options.comment = true;
	            parserDelegate = proxyDelegate;
	        }
	    }
	    var isModule = false;
	    if (options && typeof options.sourceType === 'string') {
	        isModule = (options.sourceType === 'module');
	    }
	    var parser;
	    if (options && typeof options.jsx === 'boolean' && options.jsx) {
	        parser = new jsx_parser_1.JSXParser(code, options, parserDelegate);
	    }
	    else {
	        parser = new parser_1.Parser(code, options, parserDelegate);
	    }
	    var program = isModule ? parser.parseModule() : parser.parseScript();
	    var ast = program;
	    if (collectComment && commentHandler) {
	        ast.comments = commentHandler.comments;
	    }
	    if (parser.config.tokens) {
	        ast.tokens = parser.tokens;
	    }
	    if (parser.config.tolerant) {
	        ast.errors = parser.errorHandler.errors;
	    }
	    return ast;
	}
	exports.parse = parse;
	function parseModule(code, options, delegate) {
	    var parsingOptions = options || {};
	    parsingOptions.sourceType = 'module';
	    return parse(code, parsingOptions, delegate);
	}
	exports.parseModule = parseModule;
	function parseScript(code, options, delegate) {
	    var parsingOptions = options || {};
	    parsingOptions.sourceType = 'script';
	    return parse(code, parsingOptions, delegate);
	}
	exports.parseScript = parseScript;
	function tokenize(code, options, delegate) {
	    var tokenizer = new tokenizer_1.Tokenizer(code, options);
	    var tokens;
	    tokens = [];
	    try {
	        while (true) {
	            var token = tokenizer.getNextToken();
	            if (!token) {
	                break;
	            }
	            if (delegate) {
	                token = delegate(token);
	            }
	            tokens.push(token);
	        }
	    }
	    catch (e) {
	        tokenizer.errorHandler.tolerate(e);
	    }
	    if (tokenizer.errorHandler.tolerant) {
	        tokens.errors = tokenizer.errors();
	    }
	    return tokens;
	}
	exports.tokenize = tokenize;
	var syntax_1 = __nested_webpack_require_1808__(2);
	exports.Syntax = syntax_1.Syntax;
	// Sync with *.json manifests.
	exports.version = '4.0.1';


/***/ },
/* 1 */
/***/ function(module, exports, __nested_webpack_require_6456__) {

	"use strict";
	Object.defineProperty(exports, "__esModule", { value: true });
	var syntax_1 = __nested_webpack_require_6456__(2);
	var CommentHandler = (function () {
	    function CommentHandler() {
	        this.attach = false;
	        this.comments = [];
	        this.stack = [];
	        this.leading = [];
	        this.trailing = [];
	    }
	    CommentHandler.prototype.insertInnerComments = function (node, metadata) {
	        //  innnerComments for properties empty block
	        //  `function a() {/** comments **\/}`
	        if (node.type === syntax_1.Syntax.BlockStatement && node.body.length === 0) {
	            var innerComments = [];
	            for (var i = this.leading.length - 1; i >= 0; --i) {
	                var entry = this.leading[i];
	                if (metadata.end.offset >= entry.start) {
	                    innerComments.unshift(entry.comment);
	                    this.leading.splice(i, 1);
	                    this.trailing.splice(i, 1);
	                }
	            }
	            if (innerComments.length) {
	                node.innerComments = innerComments;
	            }
	        }
	    };
	    CommentHandler.prototype.findTrailingComments = function (metadata) {
	        var trailingComments = [];
	        if (this.trailing.length > 0) {
	            for (var i = this.trailing.length - 1; i >= 0; --i) {
	                var entry_1 = this.trailing[i];
	                if (entry_1.start >= metadata.end.offset) {
	                    trailingComments.unshift(entry_1.comment);
	                }
	            }
	            this.trailing.length = 0;
	            return trailingComments;
	        }
	        var entry = this.stack[this.stack.length - 1];
	        if (entry && entry.node.trailingComments) {
	            var firstComment = entry.node.trailingComments[0];
	            if (firstComment && firstComment.range[0] >= metadata.end.offset) {
	                trailingComments = entry.node.trailingComments;
	                delete entry.node.trailingComments;
	            }
	        }
	        return trailingComments;
	    };
	    CommentHandler.prototype.findLeadingComments = function (metadata) {
	        var leadingComments = [];
	        var target;
	        while (this.stack.length > 0) {
	            var entry = this.stack[this.stack.length - 1];
	            if (entry && entry.start >= metadata.start.offset) {
	                target = entry.node;
	                this.stack.pop();
	            }
	            else {
	                break;
	            }
	        }
	        if (target) {
	            var count = target.leadingComments ? target.leadingComments.length : 0;
	            for (var i = count - 1; i >= 0; --i) {
	                var comment = target.leadingComments[i];
	                if (comment.range[1] <= metadata.start.offset) {
	                    leadingComments.unshift(comment);
	                    target.leadingComments.splice(i, 1);
	                }
	            }
	            if (target.leadingComments && target.leadingComments.length === 0) {
	                delete target.leadingComments;
	            }
	            return leadingComments;
	        }
	        for (var i = this.leading.length - 1; i >= 0; --i) {
	            var entry = this.leading[i];
	            if (entry.start <= metadata.start.offset) {
	                leadingComments.unshift(entry.comment);
	                this.leading.splice(i, 1);
	            }
	        }
	        return leadingComments;
	    };
	    CommentHandler.prototype.visitNode = function (node, metadata) {
	        if (node.type === syntax_1.Syntax.Program && node.body.length > 0) {
	            return;
	        }
	        this.insertInnerComments(node, metadata);
	        var trailingComments = this.findTrailingComments(metadata);
	        var leadingComments = this.findLeadingComments(metadata);
	        if (leadingComments.length > 0) {
	            node.leadingComments = leadingComments;
	        }
	        if (trailingComments.length > 0) {
	            node.trailingComments = trailingComments;
	        }
	        this.stack.push({
	            node: node,
	            start: metadata.start.offset
	        });
	    };
	    CommentHandler.prototype.visitComment = function (node, metadata) {
	        var type = (node.type[0] === 'L') ? 'Line' : 'Block';
	        var comment = {
	            type: type,
	            value: node.value
	        };
	        if (node.range) {
	            comment.range = node.range;
	        }
	        if (node.loc) {
	            comment.loc = node.loc;
	        }
	        this.comments.push(comment);
	        if (this.attach) {
	            var entry = {
	                comment: {
	                    type: type,
	                    value: node.value,
	                    range: [metadata.start.offset, metadata.end.offset]
	                },
	                start: metadata.start.offset
	            };
	            if (node.loc) {
	                entry.comment.loc = node.loc;
	            }
	            node.type = type;
	            this.leading.push(entry);
	            this.trailing.push(entry);
	        }
	    };
	    CommentHandler.prototype.visit = function (node, metadata) {
	        if (node.type === 'LineComment') {
	            this.visitComment(node, metadata);
	        }
	        else if (node.type === 'BlockComment') {
	            this.visitComment(node, metadata);
	        }
	        else if (this.attach) {
	            this.visitNode(node, metadata);
	        }
	    };
	    return CommentHandler;
	}());
	exports.CommentHandler = CommentHandler;


/***/ },
/* 2 */
/***/ function(module, exports) {

	"use strict";
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.Syntax = {
	    AssignmentExpression: 'AssignmentExpression',
	    AssignmentPattern: 'AssignmentPattern',
	    ArrayExpression: 'ArrayExpression',
	    ArrayPattern: 'ArrayPattern',
	    ArrowFunctionExpression: 'ArrowFunctionExpression',
	    AwaitExpression: 'AwaitExpression',
	    BlockStatement: 'BlockStatement',
	    BinaryExpression: 'BinaryExpression',
	    BreakStatement: 'BreakStatement',
	    CallExpression: 'CallExpression',
	    CatchClause: 'CatchClause',
	    ClassBody: 'ClassBody',
	    ClassDeclaration: 'ClassDeclaration',
	    ClassExpression: 'ClassExpression',
	    ConditionalExpression: 'ConditionalExpression',
	    ContinueStatement: 'ContinueStatement',
	    DoWhileStatement: 'DoWhileStatement',
	    DebuggerStatement: 'DebuggerStatement',
	    EmptyStatement: 'EmptyStatement',
	    ExportAllDeclaration: 'ExportAllDeclaration',
	    ExportDefaultDeclaration: 'ExportDefaultDeclaration',
	    ExportNamedDeclaration: 'ExportNamedDeclaration',
	    ExportSpecifier: 'ExportSpecifier',
	    ExpressionStatement: 'ExpressionStatement',
	    ForStatement: 'ForStatement',
	    ForOfStatement: 'ForOfStatement',
	    ForInStatement: 'ForInStatement',
	    FunctionDeclaration: 'FunctionDeclaration',
	    FunctionExpression: 'FunctionExpression',
	    Identifier: 'Identifier',
	    IfStatement: 'IfStatement',
	    ImportDeclaration: 'ImportDeclaration',
	    ImportDefaultSpecifier: 'ImportDefaultSpecifier',
	    ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
	    ImportSpecifier: 'ImportSpecifier',
	    Literal: 'Literal',
	    LabeledStatement: 'LabeledStatement',
	    LogicalExpression: 'LogicalExpression',
	    MemberExpression: 'MemberExpression',
	    MetaProperty: 'MetaProperty',
	    MethodDefinition: 'MethodDefinition',
	    NewExpression: 'NewExpression',
	    ObjectExpression: 'ObjectExpression',
	    ObjectPattern: 'ObjectPattern',
	    Program: 'Program',
	    Property: 'Property',
	    RestElement: 'RestElement',
	    ReturnStatement: 'ReturnStatement',
	    SequenceExpression: 'SequenceExpression',
	    SpreadElement: 'SpreadElement',
	    Super: 'Super',
	    SwitchCase: 'SwitchCase',
	    SwitchStatement: 'SwitchStatement',
	    TaggedTemplateExpression: 'TaggedTemplateExpression',
	    TemplateElement: 'TemplateElement',
	    TemplateLiteral: 'TemplateLiteral',
	    ThisExpression: 'ThisExpression',
	    ThrowStatement: 'ThrowStatement',
	    TryStatement: 'TryStatement',
	    UnaryExpression: 'UnaryExpression',
	    UpdateExpression: 'UpdateExpression',
	    VariableDeclaration: 'VariableDeclaration',
	    VariableDeclarator: 'VariableDeclarator',
	    WhileStatement: 'WhileStatement',
	    WithStatement: 'WithStatement',
	    YieldExpression: 'YieldExpression'
	};


/***/ },
/* 3 */
/***/ function(module, exports, __nested_webpack_require_15019__) {

	"use strict";
/* istanbul ignore next */
	var __extends = (this && this.__extends) || (function () {
	    var extendStatics = Object.setPrototypeOf ||
	        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
	        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
	    return function (d, b) {
	        extendStatics(d, b);
	        function __() { this.constructor = d; }
	        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
	    };
	})();
	Object.defineProperty(exports, "__esModule", { value: true });
	var character_1 = __nested_webpack_require_15019__(4);
	var JSXNode = __nested_webpack_require_15019__(5);
	var jsx_syntax_1 = __nested_webpack_require_15019__(6);
	var Node = __nested_webpack_require_15019__(7);
	var parser_1 = __nested_webpack_require_15019__(8);
	var token_1 = __nested_webpack_require_15019__(13);
	var xhtml_entities_1 = __nested_webpack_require_15019__(14);
	token_1.TokenName[100 /* Identifier */] = 'JSXIdentifier';
	token_1.TokenName[101 /* Text */] = 'JSXText';
	// Fully qualified element name, e.g. <svg:path> returns "svg:path"
	function getQualifiedElementName(elementName) {
	    var qualifiedName;
	    switch (elementName.type) {
	        case jsx_syntax_1.JSXSyntax.JSXIdentifier:
	            var id = elementName;
	            qualifiedName = id.name;
	            break;
	        case jsx_syntax_1.JSXSyntax.JSXNamespacedName:
	            var ns = elementName;
	            qualifiedName = getQualifiedElementName(ns.namespace) + ':' +
	                getQualifiedElementName(ns.name);
	            break;
	        case jsx_syntax_1.JSXSyntax.JSXMemberExpression:
	            var expr = elementName;
	            qualifiedName = getQualifiedElementName(expr.object) + '.' +
	                getQualifiedElementName(expr.property);
	            break;
	        /* istanbul ignore next */
	        default:
	            break;
	    }
	    return qualifiedName;
	}
	var JSXParser = (function (_super) {
	    __extends(JSXParser, _super);
	    function JSXParser(code, options, delegate) {
	        return _super.call(this, code, options, delegate) || this;
	    }
	    JSXParser.prototype.parsePrimaryExpression = function () {
	        return this.match('<') ? this.parseJSXRoot() : _super.prototype.parsePrimaryExpression.call(this);
	    };
	    JSXParser.prototype.startJSX = function () {
	        // Unwind the scanner before the lookahead token.
	        this.scanner.index = this.startMarker.index;
	        this.scanner.lineNumber = this.startMarker.line;
	        this.scanner.lineStart = this.startMarker.index - this.startMarker.column;
	    };
	    JSXParser.prototype.finishJSX = function () {
	        // Prime the next lookahead.
	        this.nextToken();
	    };
	    JSXParser.prototype.reenterJSX = function () {
	        this.startJSX();
	        this.expectJSX('}');
	        // Pop the closing '}' added from the lookahead.
	        if (this.config.tokens) {
	            this.tokens.pop();
	        }
	    };
	    JSXParser.prototype.createJSXNode = function () {
	        this.collectComments();
	        return {
	            index: this.scanner.index,
	            line: this.scanner.lineNumber,
	            column: this.scanner.index - this.scanner.lineStart
	        };
	    };
	    JSXParser.prototype.createJSXChildNode = function () {
	        return {
	            index: this.scanner.index,
	            line: this.scanner.lineNumber,
	            column: this.scanner.index - this.scanner.lineStart
	        };
	    };
	    JSXParser.prototype.scanXHTMLEntity = function (quote) {
	        var result = '&';
	        var valid = true;
	        var terminated = false;
	        var numeric = false;
	        var hex = false;
	        while (!this.scanner.eof() && valid && !terminated) {
	            var ch = this.scanner.source[this.scanner.index];
	            if (ch === quote) {
	                break;
	            }
	            terminated = (ch === ';');
	            result += ch;
	            ++this.scanner.index;
	            if (!terminated) {
	                switch (result.length) {
	                    case 2:
	                        // e.g. '&#123;'
	                        numeric = (ch === '#');
	                        break;
	                    case 3:
	                        if (numeric) {
	                            // e.g. '&#x41;'
	                            hex = (ch === 'x');
	                            valid = hex || character_1.Character.isDecimalDigit(ch.charCodeAt(0));
	                            numeric = numeric && !hex;
	                        }
	                        break;
	                    default:
	                        valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0)));
	                        valid = valid && !(hex && !character_1.Character.isHexDigit(ch.charCodeAt(0)));
	                        break;
	                }
	            }
	        }
	        if (valid && terminated && result.length > 2) {
	            // e.g. '&#x41;' becomes just '#x41'
	            var str = result.substr(1, result.length - 2);
	            if (numeric && str.length > 1) {
	                result = String.fromCharCode(parseInt(str.substr(1), 10));
	            }
	            else if (hex && str.length > 2) {
	                result = String.fromCharCode(parseInt('0' + str.substr(1), 16));
	            }
	            else if (!numeric && !hex && xhtml_entities_1.XHTMLEntities[str]) {
	                result = xhtml_entities_1.XHTMLEntities[str];
	            }
	        }
	        return result;
	    };
	    // Scan the next JSX token. This replaces Scanner#lex when in JSX mode.
	    JSXParser.prototype.lexJSX = function () {
	        var cp = this.scanner.source.charCodeAt(this.scanner.index);
	        // < > / : = { }
	        if (cp === 60 || cp === 62 || cp === 47 || cp === 58 || cp === 61 || cp === 123 || cp === 125) {
	            var value = this.scanner.source[this.scanner.index++];
	            return {
	                type: 7 /* Punctuator */,
	                value: value,
	                lineNumber: this.scanner.lineNumber,
	                lineStart: this.scanner.lineStart,
	                start: this.scanner.index - 1,
	                end: this.scanner.index
	            };
	        }
	        // " '
	        if (cp === 34 || cp === 39) {
	            var start = this.scanner.index;
	            var quote = this.scanner.source[this.scanner.index++];
	            var str = '';
	            while (!this.scanner.eof()) {
	                var ch = this.scanner.source[this.scanner.index++];
	                if (ch === quote) {
	                    break;
	                }
	                else if (ch === '&') {
	                    str += this.scanXHTMLEntity(quote);
	                }
	                else {
	                    str += ch;
	                }
	            }
	            return {
	                type: 8 /* StringLiteral */,
	                value: str,
	                lineNumber: this.scanner.lineNumber,
	                lineStart: this.scanner.lineStart,
	                start: start,
	                end: this.scanner.index
	            };
	        }
	        // ... or .
	        if (cp === 46) {
	            var n1 = this.scanner.source.charCodeAt(this.scanner.index + 1);
	            var n2 = this.scanner.source.charCodeAt(this.scanner.index + 2);
	            var value = (n1 === 46 && n2 === 46) ? '...' : '.';
	            var start = this.scanner.index;
	            this.scanner.index += value.length;
	            return {
	                type: 7 /* Punctuator */,
	                value: value,
	                lineNumber: this.scanner.lineNumber,
	                lineStart: this.scanner.lineStart,
	                start: start,
	                end: this.scanner.index
	            };
	        }
	        // `
	        if (cp === 96) {
	            // Only placeholder, since it will be rescanned as a real assignment expression.
	            return {
	                type: 10 /* Template */,
	                value: '',
	                lineNumber: this.scanner.lineNumber,
	                lineStart: this.scanner.lineStart,
	                start: this.scanner.index,
	                end: this.scanner.index
	            };
	        }
	        // Identifer can not contain backslash (char code 92).
	        if (character_1.Character.isIdentifierStart(cp) && (cp !== 92)) {
	            var start = this.scanner.index;
	            ++this.scanner.index;
	            while (!this.scanner.eof()) {
	                var ch = this.scanner.source.charCodeAt(this.scanner.index);
	                if (character_1.Character.isIdentifierPart(ch) && (ch !== 92)) {
	                    ++this.scanner.index;
	                }
	                else if (ch === 45) {
	                    // Hyphen (char code 45) can be part of an identifier.
	                    ++this.scanner.index;
	                }
	                else {
	                    break;
	                }
	            }
	            var id = this.scanner.source.slice(start, this.scanner.index);
	            return {
	                type: 100 /* Identifier */,
	                value: id,
	                lineNumber: this.scanner.lineNumber,
	                lineStart: this.scanner.lineStart,
	                start: start,
	                end: this.scanner.index
	            };
	        }
	        return this.scanner.lex();
	    };
	    JSXParser.prototype.nextJSXToken = function () {
	        this.collectComments();
	        this.startMarker.index = this.scanner.index;
	        this.startMarker.line = this.scanner.lineNumber;
	        this.startMarker.column = this.scanner.index - this.scanner.lineStart;
	        var token = this.lexJSX();
	        this.lastMarker.index = this.scanner.index;
	        this.lastMarker.line = this.scanner.lineNumber;
	        this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
	        if (this.config.tokens) {
	            this.tokens.push(this.convertToken(token));
	        }
	        return token;
	    };
	    JSXParser.prototype.nextJSXText = function () {
	        this.startMarker.index = this.scanner.index;
	        this.startMarker.line = this.scanner.lineNumber;
	        this.startMarker.column = this.scanner.index - this.scanner.lineStart;
	        var start = this.scanner.index;
	        var text = '';
	        while (!this.scanner.eof()) {
	            var ch = this.scanner.source[this.scanner.index];
	            if (ch === '{' || ch === '<') {
	                break;
	            }
	            ++this.scanner.index;
	            text += ch;
	            if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
	                ++this.scanner.lineNumber;
	                if (ch === '\r' && this.scanner.source[this.scanner.index] === '\n') {
	                    ++this.scanner.index;
	                }
	                this.scanner.lineStart = this.scanner.index;
	            }
	        }
	        this.lastMarker.index = this.scanner.index;
	        this.lastMarker.line = this.scanner.lineNumber;
	        this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
	        var token = {
	            type: 101 /* Text */,
	            value: text,
	            lineNumber: this.scanner.lineNumber,
	            lineStart: this.scanner.lineStart,
	            start: start,
	            end: this.scanner.index
	        };
	        if ((text.length > 0) && this.config.tokens) {
	            this.tokens.push(this.convertToken(token));
	        }
	        return token;
	    };
	    JSXParser.prototype.peekJSXToken = function () {
	        var state = this.scanner.saveState();
	        this.scanner.scanComments();
	        var next = this.lexJSX();
	        this.scanner.restoreState(state);
	        return next;
	    };
	    // Expect the next JSX token to match the specified punctuator.
	    // If not, an exception will be thrown.
	    JSXParser.prototype.expectJSX = function (value) {
	        var token = this.nextJSXToken();
	        if (token.type !== 7 /* Punctuator */ || token.value !== value) {
	            this.throwUnexpectedToken(token);
	        }
	    };
	    // Return true if the next JSX token matches the specified punctuator.
	    JSXParser.prototype.matchJSX = function (value) {
	        var next = this.peekJSXToken();
	        return next.type === 7 /* Punctuator */ && next.value === value;
	    };
	    JSXParser.prototype.parseJSXIdentifier = function () {
	        var node = this.createJSXNode();
	        var token = this.nextJSXToken();
	        if (token.type !== 100 /* Identifier */) {
	            this.throwUnexpectedToken(token);
	        }
	        return this.finalize(node, new JSXNode.JSXIdentifier(token.value));
	    };
	    JSXParser.prototype.parseJSXElementName = function () {
	        var node = this.createJSXNode();
	        var elementName = this.parseJSXIdentifier();
	        if (this.matchJSX(':')) {
	            var namespace = elementName;
	            this.expectJSX(':');
	            var name_1 = this.parseJSXIdentifier();
	            elementName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_1));
	        }
	        else if (this.matchJSX('.')) {
	            while (this.matchJSX('.')) {
	                var object = elementName;
	                this.expectJSX('.');
	                var property = this.parseJSXIdentifier();
	                elementName = this.finalize(node, new JSXNode.JSXMemberExpression(object, property));
	            }
	        }
	        return elementName;
	    };
	    JSXParser.prototype.parseJSXAttributeName = function () {
	        var node = this.createJSXNode();
	        var attributeName;
	        var identifier = this.parseJSXIdentifier();
	        if (this.matchJSX(':')) {
	            var namespace = identifier;
	            this.expectJSX(':');
	            var name_2 = this.parseJSXIdentifier();
	            attributeName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_2));
	        }
	        else {
	            attributeName = identifier;
	        }
	        return attributeName;
	    };
	    JSXParser.prototype.parseJSXStringLiteralAttribute = function () {
	        var node = this.createJSXNode();
	        var token = this.nextJSXToken();
	        if (token.type !== 8 /* StringLiteral */) {
	            this.throwUnexpectedToken(token);
	        }
	        var raw = this.getTokenRaw(token);
	        return this.finalize(node, new Node.Literal(token.value, raw));
	    };
	    JSXParser.prototype.parseJSXExpressionAttribute = function () {
	        var node = this.createJSXNode();
	        this.expectJSX('{');
	        this.finishJSX();
	        if (this.match('}')) {
	            this.tolerateError('JSX attributes must only be assigned a non-empty expression');
	        }
	        var expression = this.parseAssignmentExpression();
	        this.reenterJSX();
	        return this.finalize(node, new JSXNode.JSXExpressionContainer(expression));
	    };
	    JSXParser.prototype.parseJSXAttributeValue = function () {
	        return this.matchJSX('{') ? this.parseJSXExpressionAttribute() :
	            this.matchJSX('<') ? this.parseJSXElement() : this.parseJSXStringLiteralAttribute();
	    };
	    JSXParser.prototype.parseJSXNameValueAttribute = function () {
	        var node = this.createJSXNode();
	        var name = this.parseJSXAttributeName();
	        var value = null;
	        if (this.matchJSX('=')) {
	            this.expectJSX('=');
	            value = this.parseJSXAttributeValue();
	        }
	        return this.finalize(node, new JSXNode.JSXAttribute(name, value));
	    };
	    JSXParser.prototype.parseJSXSpreadAttribute = function () {
	        var node = this.createJSXNode();
	        this.expectJSX('{');
	        this.expectJSX('...');
	        this.finishJSX();
	        var argument = this.parseAssignmentExpression();
	        this.reenterJSX();
	        return this.finalize(node, new JSXNode.JSXSpreadAttribute(argument));
	    };
	    JSXParser.prototype.parseJSXAttributes = function () {
	        var attributes = [];
	        while (!this.matchJSX('/') && !this.matchJSX('>')) {
	            var attribute = this.matchJSX('{') ? this.parseJSXSpreadAttribute() :
	                this.parseJSXNameValueAttribute();
	            attributes.push(attribute);
	        }
	        return attributes;
	    };
	    JSXParser.prototype.parseJSXOpeningElement = function () {
	        var node = this.createJSXNode();
	        this.expectJSX('<');
	        var name = this.parseJSXElementName();
	        var attributes = this.parseJSXAttributes();
	        var selfClosing = this.matchJSX('/');
	        if (selfClosing) {
	            this.expectJSX('/');
	        }
	        this.expectJSX('>');
	        return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes));
	    };
	    JSXParser.prototype.parseJSXBoundaryElement = function () {
	        var node = this.createJSXNode();
	        this.expectJSX('<');
	        if (this.matchJSX('/')) {
	            this.expectJSX('/');
	            var name_3 = this.parseJSXElementName();
	            this.expectJSX('>');
	            return this.finalize(node, new JSXNode.JSXClosingElement(name_3));
	        }
	        var name = this.parseJSXElementName();
	        var attributes = this.parseJSXAttributes();
	        var selfClosing = this.matchJSX('/');
	        if (selfClosing) {
	            this.expectJSX('/');
	        }
	        this.expectJSX('>');
	        return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes));
	    };
	    JSXParser.prototype.parseJSXEmptyExpression = function () {
	        var node = this.createJSXChildNode();
	        this.collectComments();
	        this.lastMarker.index = this.scanner.index;
	        this.lastMarker.line = this.scanner.lineNumber;
	        this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
	        return this.finalize(node, new JSXNode.JSXEmptyExpression());
	    };
	    JSXParser.prototype.parseJSXExpressionContainer = function () {
	        var node = this.createJSXNode();
	        this.expectJSX('{');
	        var expression;
	        if (this.matchJSX('}')) {
	            expression = this.parseJSXEmptyExpression();
	            this.expectJSX('}');
	        }
	        else {
	            this.finishJSX();
	            expression = this.parseAssignmentExpression();
	            this.reenterJSX();
	        }
	        return this.finalize(node, new JSXNode.JSXExpressionContainer(expression));
	    };
	    JSXParser.prototype.parseJSXChildren = function () {
	        var children = [];
	        while (!this.scanner.eof()) {
	            var node = this.createJSXChildNode();
	            var token = this.nextJSXText();
	            if (token.start < token.end) {
	                var raw = this.getTokenRaw(token);
	                var child = this.finalize(node, new JSXNode.JSXText(token.value, raw));
	                children.push(child);
	            }
	            if (this.scanner.source[this.scanner.index] === '{') {
	                var container = this.parseJSXExpressionContainer();
	                children.push(container);
	            }
	            else {
	                break;
	            }
	        }
	        return children;
	    };
	    JSXParser.prototype.parseComplexJSXElement = function (el) {
	        var stack = [];
	        while (!this.scanner.eof()) {
	            el.children = el.children.concat(this.parseJSXChildren());
	            var node = this.createJSXChildNode();
	            var element = this.parseJSXBoundaryElement();
	            if (element.type === jsx_syntax_1.JSXSyntax.JSXOpeningElement) {
	                var opening = element;
	                if (opening.selfClosing) {
	                    var child = this.finalize(node, new JSXNode.JSXElement(opening, [], null));
	                    el.children.push(child);
	                }
	                else {
	                    stack.push(el);
	                    el = { node: node, opening: opening, closing: null, children: [] };
	                }
	            }
	            if (element.type === jsx_syntax_1.JSXSyntax.JSXClosingElement) {
	                el.closing = element;
	                var open_1 = getQualifiedElementName(el.opening.name);
	                var close_1 = getQualifiedElementName(el.closing.name);
	                if (open_1 !== close_1) {
	                    this.tolerateError('Expected corresponding JSX closing tag for %0', open_1);
	                }
	                if (stack.length > 0) {
	                    var child = this.finalize(el.node, new JSXNode.JSXElement(el.opening, el.children, el.closing));
	                    el = stack[stack.length - 1];
	                    el.children.push(child);
	                    stack.pop();
	                }
	                else {
	                    break;
	                }
	            }
	        }
	        return el;
	    };
	    JSXParser.prototype.parseJSXElement = function () {
	        var node = this.createJSXNode();
	        var opening = this.parseJSXOpeningElement();
	        var children = [];
	        var closing = null;
	        if (!opening.selfClosing) {
	            var el = this.parseComplexJSXElement({ node: node, opening: opening, closing: closing, children: children });
	            children = el.children;
	            closing = el.closing;
	        }
	        return this.finalize(node, new JSXNode.JSXElement(opening, children, closing));
	    };
	    JSXParser.prototype.parseJSXRoot = function () {
	        // Pop the opening '<' added from the lookahead.
	        if (this.config.tokens) {
	            this.tokens.pop();
	        }
	        this.startJSX();
	        var element = this.parseJSXElement();
	        this.finishJSX();
	        return element;
	    };
	    JSXParser.prototype.isStartOfExpression = function () {
	        return _super.prototype.isStartOfExpression.call(this) || this.match('<');
	    };
	    return JSXParser;
	}(parser_1.Parser));
	exports.JSXParser = JSXParser;


/***/ },
/* 4 */
/***/ function(module, exports) {

	"use strict";
	Object.defineProperty(exports, "__esModule", { value: true });
	// See also tools/generate-unicode-regex.js.
	var Regex = {
	    // Unicode v8.0.0 NonAsciiIdentifierStart:
	    NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,
	    // Unicode v8.0.0 NonAsciiIdentifierPart:
	    NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
	};
	exports.Character = {
	    /* tslint:disable:no-bitwise */
	    fromCodePoint: function (cp) {
	        return (cp < 0x10000) ? String.fromCharCode(cp) :
	            String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) +
	                String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023));
	    },
	    // https://tc39.github.io/ecma262/#sec-white-space
	    isWhiteSpace: function (cp) {
	        return (cp === 0x20) || (cp === 0x09) || (cp === 0x0B) || (cp === 0x0C) || (cp === 0xA0) ||
	            (cp >= 0x1680 && [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(cp) >= 0);
	    },
	    // https://tc39.github.io/ecma262/#sec-line-terminators
	    isLineTerminator: function (cp) {
	        return (cp === 0x0A) || (cp === 0x0D) || (cp === 0x2028) || (cp === 0x2029);
	    },
	    // https://tc39.github.io/ecma262/#sec-names-and-keywords
	    isIdentifierStart: function (cp) {
	        return (cp === 0x24) || (cp === 0x5F) ||
	            (cp >= 0x41 && cp <= 0x5A) ||
	            (cp >= 0x61 && cp <= 0x7A) ||
	            (cp === 0x5C) ||
	            ((cp >= 0x80) && Regex.NonAsciiIdentifierStart.test(exports.Character.fromCodePoint(cp)));
	    },
	    isIdentifierPart: function (cp) {
	        return (cp === 0x24) || (cp === 0x5F) ||
	            (cp >= 0x41 && cp <= 0x5A) ||
	            (cp >= 0x61 && cp <= 0x7A) ||
	            (cp >= 0x30 && cp <= 0x39) ||
	            (cp === 0x5C) ||
	            ((cp >= 0x80) && Regex.NonAsciiIdentifierPart.test(exports.Character.fromCodePoint(cp)));
	    },
	    // https://tc39.github.io/ecma262/#sec-literals-numeric-literals
	    isDecimalDigit: function (cp) {
	        return (cp >= 0x30 && cp <= 0x39); // 0..9
	    },
	    isHexDigit: function (cp) {
	        return (cp >= 0x30 && cp <= 0x39) ||
	            (cp >= 0x41 && cp <= 0x46) ||
	            (cp >= 0x61 && cp <= 0x66); // a..f
	    },
	    isOctalDigit: function (cp) {
	        return (cp >= 0x30 && cp <= 0x37); // 0..7
	    }
	};


/***/ },
/* 5 */
/***/ function(module, exports, __nested_webpack_require_54354__) {

	"use strict";
	Object.defineProperty(exports, "__esModule", { value: true });
	var jsx_syntax_1 = __nested_webpack_require_54354__(6);
	/* tslint:disable:max-classes-per-file */
	var JSXClosingElement = (function () {
	    function JSXClosingElement(name) {
	        this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement;
	        this.name = name;
	    }
	    return JSXClosingElement;
	}());
	exports.JSXClosingElement = JSXClosingElement;
	var JSXElement = (function () {
	    function JSXElement(openingElement, children, closingElement) {
	        this.type = jsx_syntax_1.JSXSyntax.JSXElement;
	        this.openingElement = openingElement;
	        this.children = children;
	        this.closingElement = closingElement;
	    }
	    return JSXElement;
	}());
	exports.JSXElement = JSXElement;
	var JSXEmptyExpression = (function () {
	    function JSXEmptyExpression() {
	        this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression;
	    }
	    return JSXEmptyExpression;
	}());
	exports.JSXEmptyExpression = JSXEmptyExpression;
	var JSXExpressionContainer = (function () {
	    function JSXExpressionContainer(expression) {
	        this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer;
	        this.expression = expression;
	    }
	    return JSXExpressionContainer;
	}());
	exports.JSXExpressionContainer = JSXExpressionContainer;
	var JSXIdentifier = (function () {
	    function JSXIdentifier(name) {
	        this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier;
	        this.name = name;
	    }
	    return JSXIdentifier;
	}());
	exports.JSXIdentifier = JSXIdentifier;
	var JSXMemberExpression = (function () {
	    function JSXMemberExpression(object, property) {
	        this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression;
	        this.object = object;
	        this.property = property;
	    }
	    return JSXMemberExpression;
	}());
	exports.JSXMemberExpression = JSXMemberExpression;
	var JSXAttribute = (function () {
	    function JSXAttribute(name, value) {
	        this.type = jsx_syntax_1.JSXSyntax.JSXAttribute;
	        this.name = name;
	        this.value = value;
	    }
	    return JSXAttribute;
	}());
	exports.JSXAttribute = JSXAttribute;
	var JSXNamespacedName = (function () {
	    function JSXNamespacedName(namespace, name) {
	        this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName;
	        this.namespace = namespace;
	        this.name = name;
	    }
	    return JSXNamespacedName;
	}());
	exports.JSXNamespacedName = JSXNamespacedName;
	var JSXOpeningElement = (function () {
	    function JSXOpeningElement(name, selfClosing, attributes) {
	        this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement;
	        this.name = name;
	        this.selfClosing = selfClosing;
	        this.attributes = attributes;
	    }
	    return JSXOpeningElement;
	}());
	exports.JSXOpeningElement = JSXOpeningElement;
	var JSXSpreadAttribute = (function () {
	    function JSXSpreadAttribute(argument) {
	        this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute;
	        this.argument = argument;
	    }
	    return JSXSpreadAttribute;
	}());
	exports.JSXSpreadAttribute = JSXSpreadAttribute;
	var JSXText = (function () {
	    function JSXText(value, raw) {
	        this.type = jsx_syntax_1.JSXSyntax.JSXText;
	        this.value = value;
	        this.raw = raw;
	    }
	    return JSXText;
	}());
	exports.JSXText = JSXText;


/***/ },
/* 6 */
/***/ function(module, exports) {

	"use strict";
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.JSXSyntax = {
	    JSXAttribute: 'JSXAttribute',
	    JSXClosingElement: 'JSXClosingElement',
	    JSXElement: 'JSXElement',
	    JSXEmptyExpression: 'JSXEmptyExpression',
	    JSXExpressionContainer: 'JSXExpressionContainer',
	    JSXIdentifier: 'JSXIdentifier',
	    JSXMemberExpression: 'JSXMemberExpression',
	    JSXNamespacedName: 'JSXNamespacedName',
	    JSXOpeningElement: 'JSXOpeningElement',
	    JSXSpreadAttribute: 'JSXSpreadAttribute',
	    JSXText: 'JSXText'
	};


/***/ },
/* 7 */
/***/ function(module, exports, __nested_webpack_require_58416__) {

	"use strict";
	Object.defineProperty(exports, "__esModule", { value: true });
	var syntax_1 = __nested_webpack_require_58416__(2);
	/* tslint:disable:max-classes-per-file */
	var ArrayExpression = (function () {
	    function ArrayExpression(elements) {
	        this.type = syntax_1.Syntax.ArrayExpression;
	        this.elements = elements;
	    }
	    return ArrayExpression;
	}());
	exports.ArrayExpression = ArrayExpression;
	var ArrayPattern = (function () {
	    function ArrayPattern(elements) {
	        this.type = syntax_1.Syntax.ArrayPattern;
	        this.elements = elements;
	    }
	    return ArrayPattern;
	}());
	exports.ArrayPattern = ArrayPattern;
	var ArrowFunctionExpression = (function () {
	    function ArrowFunctionExpression(params, body, expression) {
	        this.type = syntax_1.Syntax.ArrowFunctionExpression;
	        this.id = null;
	        this.params = params;
	        this.body = body;
	        this.generator = false;
	        this.expression = expression;
	        this.async = false;
	    }
	    return ArrowFunctionExpression;
	}());
	exports.ArrowFunctionExpression = ArrowFunctionExpression;
	var AssignmentExpression = (function () {
	    function AssignmentExpression(operator, left, right) {
	        this.type = syntax_1.Syntax.AssignmentExpression;
	        this.operator = operator;
	        this.left = left;
	        this.right = right;
	    }
	    return AssignmentExpression;
	}());
	exports.AssignmentExpression = AssignmentExpression;
	var AssignmentPattern = (function () {
	    function AssignmentPattern(left, right) {
	        this.type = syntax_1.Syntax.AssignmentPattern;
	        this.left = left;
	        this.right = right;
	    }
	    return AssignmentPattern;
	}());
	exports.AssignmentPattern = AssignmentPattern;
	var AsyncArrowFunctionExpression = (function () {
	    function AsyncArrowFunctionExpression(params, body, expression) {
	        this.type = syntax_1.Syntax.ArrowFunctionExpression;
	        this.id = null;
	        this.params = params;
	        this.body = body;
	        this.generator = false;
	        this.expression = expression;
	        this.async = true;
	    }
	    return AsyncArrowFunctionExpression;
	}());
	exports.AsyncArrowFunctionExpression = AsyncArrowFunctionExpression;
	var AsyncFunctionDeclaration = (function () {
	    function AsyncFunctionDeclaration(id, params, body) {
	        this.type = syntax_1.Syntax.FunctionDeclaration;
	        this.id = id;
	        this.params = params;
	        this.body = body;
	        this.generator = false;
	        this.expression = false;
	        this.async = true;
	    }
	    return AsyncFunctionDeclaration;
	}());
	exports.AsyncFunctionDeclaration = AsyncFunctionDeclaration;
	var AsyncFunctionExpression = (function () {
	    function AsyncFunctionExpression(id, params, body) {
	        this.type = syntax_1.Syntax.FunctionExpression;
	        this.id = id;
	        this.params = params;
	        this.body = body;
	        this.generator = false;
	        this.expression = false;
	        this.async = true;
	    }
	    return AsyncFunctionExpression;
	}());
	exports.AsyncFunctionExpression = AsyncFunctionExpression;
	var AwaitExpression = (function () {
	    function AwaitExpression(argument) {
	        this.type = syntax_1.Syntax.AwaitExpression;
	        this.argument = argument;
	    }
	    return AwaitExpression;
	}());
	exports.AwaitExpression = AwaitExpression;
	var BinaryExpression = (function () {
	    function BinaryExpression(operator, left, right) {
	        var logical = (operator === '||' || operator === '&&');
	        this.type = logical ? syntax_1.Syntax.LogicalExpression : syntax_1.Syntax.BinaryExpression;
	        this.operator = operator;
	        this.left = left;
	        this.right = right;
	    }
	    return BinaryExpression;
	}());
	exports.BinaryExpression = BinaryExpression;
	var BlockStatement = (function () {
	    function BlockStatement(body) {
	        this.type = syntax_1.Syntax.BlockStatement;
	        this.body = body;
	    }
	    return BlockStatement;
	}());
	exports.BlockStatement = BlockStatement;
	var BreakStatement = (function () {
	    function BreakStatement(label) {
	        this.type = syntax_1.Syntax.BreakStatement;
	        this.label = label;
	    }
	    return BreakStatement;
	}());
	exports.BreakStatement = BreakStatement;
	var CallExpression = (function () {
	    function CallExpression(callee, args) {
	        this.type = syntax_1.Syntax.CallExpression;
	        this.callee = callee;
	        this.arguments = args;
	    }
	    return CallExpression;
	}());
	exports.CallExpression = CallExpression;
	var CatchClause = (function () {
	    function CatchClause(param, body) {
	        this.type = syntax_1.Syntax.CatchClause;
	        this.param = param;
	        this.body = body;
	    }
	    return CatchClause;
	}());
	exports.CatchClause = CatchClause;
	var ClassBody = (function () {
	    function ClassBody(body) {
	        this.type = syntax_1.Syntax.ClassBody;
	        this.body = body;
	    }
	    return ClassBody;
	}());
	exports.ClassBody = ClassBody;
	var ClassDeclaration = (function () {
	    function ClassDeclaration(id, superClass, body) {
	        this.type = syntax_1.Syntax.ClassDeclaration;
	        this.id = id;
	        this.superClass = superClass;
	        this.body = body;
	    }
	    return ClassDeclaration;
	}());
	exports.ClassDeclaration = ClassDeclaration;
	var ClassExpression = (function () {
	    function ClassExpression(id, superClass, body) {
	        this.type = syntax_1.Syntax.ClassExpression;
	        this.id = id;
	        this.superClass = superClass;
	        this.body = body;
	    }
	    return ClassExpression;
	}());
	exports.ClassExpression = ClassExpression;
	var ComputedMemberExpression = (function () {
	    function ComputedMemberExpression(object, property) {
	        this.type = syntax_1.Syntax.MemberExpression;
	        this.computed = true;
	        this.object = object;
	        this.property = property;
	    }
	    return ComputedMemberExpression;
	}());
	exports.ComputedMemberExpression = ComputedMemberExpression;
	var ConditionalExpression = (function () {
	    function ConditionalExpression(test, consequent, alternate) {
	        this.type = syntax_1.Syntax.ConditionalExpression;
	        this.test = test;
	        this.consequent = consequent;
	        this.alternate = alternate;
	    }
	    return ConditionalExpression;
	}());
	exports.ConditionalExpression = ConditionalExpression;
	var ContinueStatement = (function () {
	    function ContinueStatement(label) {
	        this.type = syntax_1.Syntax.ContinueStatement;
	        this.label = label;
	    }
	    return ContinueStatement;
	}());
	exports.ContinueStatement = ContinueStatement;
	var DebuggerStatement = (function () {
	    function DebuggerStatement() {
	        this.type = syntax_1.Syntax.DebuggerStatement;
	    }
	    return DebuggerStatement;
	}());
	exports.DebuggerStatement = DebuggerStatement;
	var Directive = (function () {
	    function Directive(expression, directive) {
	        this.type = syntax_1.Syntax.ExpressionStatement;
	        this.expression = expression;
	        this.directive = directive;
	    }
	    return Directive;
	}());
	exports.Directive = Directive;
	var DoWhileStatement = (function () {
	    function DoWhileStatement(body, test) {
	        this.type = syntax_1.Syntax.DoWhileStatement;
	        this.body = body;
	        this.test = test;
	    }
	    return DoWhileStatement;
	}());
	exports.DoWhileStatement = DoWhileStatement;
	var EmptyStatement = (function () {
	    function EmptyStatement() {
	        this.type = syntax_1.Syntax.EmptyStatement;
	    }
	    return EmptyStatement;
	}());
	exports.EmptyStatement = EmptyStatement;
	var ExportAllDeclaration = (function () {
	    function ExportAllDeclaration(source) {
	        this.type = syntax_1.Syntax.ExportAllDeclaration;
	        this.source = source;
	    }
	    return ExportAllDeclaration;
	}());
	exports.ExportAllDeclaration = ExportAllDeclaration;
	var ExportDefaultDeclaration = (function () {
	    function ExportDefaultDeclaration(declaration) {
	        this.type = syntax_1.Syntax.ExportDefaultDeclaration;
	        this.declaration = declaration;
	    }
	    return ExportDefaultDeclaration;
	}());
	exports.ExportDefaultDeclaration = ExportDefaultDeclaration;
	var ExportNamedDeclaration = (function () {
	    function ExportNamedDeclaration(declaration, specifiers, source) {
	        this.type = syntax_1.Syntax.ExportNamedDeclaration;
	        this.declaration = declaration;
	        this.specifiers = specifiers;
	        this.source = source;
	    }
	    return ExportNamedDeclaration;
	}());
	exports.ExportNamedDeclaration = ExportNamedDeclaration;
	var ExportSpecifier = (function () {
	    function ExportSpecifier(local, exported) {
	        this.type = syntax_1.Syntax.ExportSpecifier;
	        this.exported = exported;
	        this.local = local;
	    }
	    return ExportSpecifier;
	}());
	exports.ExportSpecifier = ExportSpecifier;
	var ExpressionStatement = (function () {
	    function ExpressionStatement(expression) {
	        this.type = syntax_1.Syntax.ExpressionStatement;
	        this.expression = expression;
	    }
	    return ExpressionStatement;
	}());
	exports.ExpressionStatement = ExpressionStatement;
	var ForInStatement = (function () {
	    function ForInStatement(left, right, body) {
	        this.type = syntax_1.Syntax.ForInStatement;
	        this.left = left;
	        this.right = right;
	        this.body = body;
	        this.each = false;
	    }
	    return ForInStatement;
	}());
	exports.ForInStatement = ForInStatement;
	var ForOfStatement = (function () {
	    function ForOfStatement(left, right, body) {
	        this.type = syntax_1.Syntax.ForOfStatement;
	        this.left = left;
	        this.right = right;
	        this.body = body;
	    }
	    return ForOfStatement;
	}());
	exports.ForOfStatement = ForOfStatement;
	var ForStatement = (function () {
	    function ForStatement(init, test, update, body) {
	        this.type = syntax_1.Syntax.ForStatement;
	        this.init = init;
	        this.test = test;
	        this.update = update;
	        this.body = body;
	    }
	    return ForStatement;
	}());
	exports.ForStatement = ForStatement;
	var FunctionDeclaration = (function () {
	    function FunctionDeclaration(id, params, body, generator) {
	        this.type = syntax_1.Syntax.FunctionDeclaration;
	        this.id = id;
	        this.params = params;
	        this.body = body;
	        this.generator = generator;
	        this.expression = false;
	        this.async = false;
	    }
	    return FunctionDeclaration;
	}());
	exports.FunctionDeclaration = FunctionDeclaration;
	var FunctionExpression = (function () {
	    function FunctionExpression(id, params, body, generator) {
	        this.type = syntax_1.Syntax.FunctionExpression;
	        this.id = id;
	        this.params = params;
	        this.body = body;
	        this.generator = generator;
	        this.expression = false;
	        this.async = false;
	    }
	    return FunctionExpression;
	}());
	exports.FunctionExpression = FunctionExpression;
	var Identifier = (function () {
	    function Identifier(name) {
	        this.type = syntax_1.Syntax.Identifier;
	        this.name = name;
	    }
	    return Identifier;
	}());
	exports.Identifier = Identifier;
	var IfStatement = (function () {
	    function IfStatement(test, consequent, alternate) {
	        this.type = syntax_1.Syntax.IfStatement;
	        this.test = test;
	        this.consequent = consequent;
	        this.alternate = alternate;
	    }
	    return IfStatement;
	}());
	exports.IfStatement = IfStatement;
	var ImportDeclaration = (function () {
	    function ImportDeclaration(specifiers, source) {
	        this.type = syntax_1.Syntax.ImportDeclaration;
	        this.specifiers = specifiers;
	        this.source = source;
	    }
	    return ImportDeclaration;
	}());
	exports.ImportDeclaration = ImportDeclaration;
	var ImportDefaultSpecifier = (function () {
	    function ImportDefaultSpecifier(local) {
	        this.type = syntax_1.Syntax.ImportDefaultSpecifier;
	        this.local = local;
	    }
	    return ImportDefaultSpecifier;
	}());
	exports.ImportDefaultSpecifier = ImportDefaultSpecifier;
	var ImportNamespaceSpecifier = (function () {
	    function ImportNamespaceSpecifier(local) {
	        this.type = syntax_1.Syntax.ImportNamespaceSpecifier;
	        this.local = local;
	    }
	    return ImportNamespaceSpecifier;
	}());
	exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier;
	var ImportSpecifier = (function () {
	    function ImportSpecifier(local, imported) {
	        this.type = syntax_1.Syntax.ImportSpecifier;
	        this.local = local;
	        this.imported = imported;
	    }
	    return ImportSpecifier;
	}());
	exports.ImportSpecifier = ImportSpecifier;
	var LabeledStatement = (function () {
	    function LabeledStatement(label, body) {
	        this.type = syntax_1.Syntax.LabeledStatement;
	        this.label = label;
	        this.body = body;
	    }
	    return LabeledStatement;
	}());
	exports.LabeledStatement = LabeledStatement;
	var Literal = (function () {
	    function Literal(value, raw) {
	        this.type = syntax_1.Syntax.Literal;
	        this.value = value;
	        this.raw = raw;
	    }
	    return Literal;
	}());
	exports.Literal = Literal;
	var MetaProperty = (function () {
	    function MetaProperty(meta, property) {
	        this.type = syntax_1.Syntax.MetaProperty;
	        this.meta = meta;
	        this.property = property;
	    }
	    return MetaProperty;
	}());
	exports.MetaProperty = MetaProperty;
	var MethodDefinition = (function () {
	    function MethodDefinition(key, computed, value, kind, isStatic) {
	        this.type = syntax_1.Syntax.MethodDefinition;
	        this.key = key;
	        this.computed = computed;
	        this.value = value;
	        this.kind = kind;
	        this.static = isStatic;
	    }
	    return MethodDefinition;
	}());
	exports.MethodDefinition = MethodDefinition;
	var Module = (function () {
	    function Module(body) {
	        this.type = syntax_1.Syntax.Program;
	        this.body = body;
	        this.sourceType = 'module';
	    }
	    return Module;
	}());
	exports.Module = Module;
	var NewExpression = (function () {
	    function NewExpression(callee, args) {
	        this.type = syntax_1.Syntax.NewExpression;
	        this.callee = callee;
	        this.arguments = args;
	    }
	    return NewExpression;
	}());
	exports.NewExpression = NewExpression;
	var ObjectExpression = (function () {
	    function ObjectExpression(properties) {
	        this.type = syntax_1.Syntax.ObjectExpression;
	        this.properties = properties;
	    }
	    return ObjectExpression;
	}());
	exports.ObjectExpression = ObjectExpression;
	var ObjectPattern = (function () {
	    function ObjectPattern(properties) {
	        this.type = syntax_1.Syntax.ObjectPattern;
	        this.properties = properties;
	    }
	    return ObjectPattern;
	}());
	exports.ObjectPattern = ObjectPattern;
	var Property = (function () {
	    function Property(kind, key, computed, value, method, shorthand) {
	        this.type = syntax_1.Syntax.Property;
	        this.key = key;
	        this.computed = computed;
	        this.value = value;
	        this.kind = kind;
	        this.method = method;
	        this.shorthand = shorthand;
	    }
	    return Property;
	}());
	exports.Property = Property;
	var RegexLiteral = (function () {
	    function RegexLiteral(value, raw, pattern, flags) {
	        this.type = syntax_1.Syntax.Literal;
	        this.value = value;
	        this.raw = raw;
	        this.regex = { pattern: pattern, flags: flags };
	    }
	    return RegexLiteral;
	}());
	exports.RegexLiteral = RegexLiteral;
	var RestElement = (function () {
	    function RestElement(argument) {
	        this.type = syntax_1.Syntax.RestElement;
	        this.argument = argument;
	    }
	    return RestElement;
	}());
	exports.RestElement = RestElement;
	var ReturnStatement = (function () {
	    function ReturnStatement(argument) {
	        this.type = syntax_1.Syntax.ReturnStatement;
	        this.argument = argument;
	    }
	    return ReturnStatement;
	}());
	exports.ReturnStatement = ReturnStatement;
	var Script = (function () {
	    function Script(body) {
	        this.type = syntax_1.Syntax.Program;
	        this.body = body;
	        this.sourceType = 'script';
	    }
	    return Script;
	}());
	exports.Script = Script;
	var SequenceExpression = (function () {
	    function SequenceExpression(expressions) {
	        this.type = syntax_1.Syntax.SequenceExpression;
	        this.expressions = expressions;
	    }
	    return SequenceExpression;
	}());
	exports.SequenceExpression = SequenceExpression;
	var SpreadElement = (function () {
	    function SpreadElement(argument) {
	        this.type = syntax_1.Syntax.SpreadElement;
	        this.argument = argument;
	    }
	    return SpreadElement;
	}());
	exports.SpreadElement = SpreadElement;
	var StaticMemberExpression = (function () {
	    function StaticMemberExpression(object, property) {
	        this.type = syntax_1.Syntax.MemberExpression;
	        this.computed = false;
	        this.object = object;
	        this.property = property;
	    }
	    return StaticMemberExpression;
	}());
	exports.StaticMemberExpression = StaticMemberExpression;
	var Super = (function () {
	    function Super() {
	        this.type = syntax_1.Syntax.Super;
	    }
	    return Super;
	}());
	exports.Super = Super;
	var SwitchCase = (function () {
	    function SwitchCase(test, consequent) {
	        this.type = syntax_1.Syntax.SwitchCase;
	        this.test = test;
	        this.consequent = consequent;
	    }
	    return SwitchCase;
	}());
	exports.SwitchCase = SwitchCase;
	var SwitchStatement = (function () {
	    function SwitchStatement(discriminant, cases) {
	        this.type = syntax_1.Syntax.SwitchStatement;
	        this.discriminant = discriminant;
	        this.cases = cases;
	    }
	    return SwitchStatement;
	}());
	exports.SwitchStatement = SwitchStatement;
	var TaggedTemplateExpression = (function () {
	    function TaggedTemplateExpression(tag, quasi) {
	        this.type = syntax_1.Syntax.TaggedTemplateExpression;
	        this.tag = tag;
	        this.quasi = quasi;
	    }
	    return TaggedTemplateExpression;
	}());
	exports.TaggedTemplateExpression = TaggedTemplateExpression;
	var TemplateElement = (function () {
	    function TemplateElement(value, tail) {
	        this.type = syntax_1.Syntax.TemplateElement;
	        this.value = value;
	        this.tail = tail;
	    }
	    return TemplateElement;
	}());
	exports.TemplateElement = TemplateElement;
	var TemplateLiteral = (function () {
	    function TemplateLiteral(quasis, expressions) {
	        this.type = syntax_1.Syntax.TemplateLiteral;
	        this.quasis = quasis;
	        this.expressions = expressions;
	    }
	    return TemplateLiteral;
	}());
	exports.TemplateLiteral = TemplateLiteral;
	var ThisExpression = (function () {
	    function ThisExpression() {
	        this.type = syntax_1.Syntax.ThisExpression;
	    }
	    return ThisExpression;
	}());
	exports.ThisExpression = ThisExpression;
	var ThrowStatement = (function () {
	    function ThrowStatement(argument) {
	        this.type = syntax_1.Syntax.ThrowStatement;
	        this.argument = argument;
	    }
	    return ThrowStatement;
	}());
	exports.ThrowStatement = ThrowStatement;
	var TryStatement = (function () {
	    function TryStatement(block, handler, finalizer) {
	        this.type = syntax_1.Syntax.TryStatement;
	        this.block = block;
	        this.handler = handler;
	        this.finalizer = finalizer;
	    }
	    return TryStatement;
	}());
	exports.TryStatement = TryStatement;
	var UnaryExpression = (function () {
	    function UnaryExpression(operator, argument) {
	        this.type = syntax_1.Syntax.UnaryExpression;
	        this.operator = operator;
	        this.argument = argument;
	        this.prefix = true;
	    }
	    return UnaryExpression;
	}());
	exports.UnaryExpression = UnaryExpression;
	var UpdateExpression = (function () {
	    function UpdateExpression(operator, argument, prefix) {
	        this.type = syntax_1.Syntax.UpdateExpression;
	        this.operator = operator;
	        this.argument = argument;
	        this.prefix = prefix;
	    }
	    return UpdateExpression;
	}());
	exports.UpdateExpression = UpdateExpression;
	var VariableDeclaration = (function () {
	    function VariableDeclaration(declarations, kind) {
	        this.type = syntax_1.Syntax.VariableDeclaration;
	        this.declarations = declarations;
	        this.kind = kind;
	    }
	    return VariableDeclaration;
	}());
	exports.VariableDeclaration = VariableDeclaration;
	var VariableDeclarator = (function () {
	    function VariableDeclarator(id, init) {
	        this.type = syntax_1.Syntax.VariableDeclarator;
	        this.id = id;
	        this.init = init;
	    }
	    return VariableDeclarator;
	}());
	exports.VariableDeclarator = VariableDeclarator;
	var WhileStatement = (function () {
	    function WhileStatement(test, body) {
	        this.type = syntax_1.Syntax.WhileStatement;
	        this.test = test;
	        this.body = body;
	    }
	    return WhileStatement;
	}());
	exports.WhileStatement = WhileStatement;
	var WithStatement = (function () {
	    function WithStatement(object, body) {
	        this.type = syntax_1.Syntax.WithStatement;
	        this.object = object;
	        this.body = body;
	    }
	    return WithStatement;
	}());
	exports.WithStatement = WithStatement;
	var YieldExpression = (function () {
	    function YieldExpression(argument, delegate) {
	        this.type = syntax_1.Syntax.YieldExpression;
	        this.argument = argument;
	        this.delegate = delegate;
	    }
	    return YieldExpression;
	}());
	exports.YieldExpression = YieldExpression;


/***/ },
/* 8 */
/***/ function(module, exports, __nested_webpack_require_80491__) {

	"use strict";
	Object.defineProperty(exports, "__esModule", { value: true });
	var assert_1 = __nested_webpack_require_80491__(9);
	var error_handler_1 = __nested_webpack_require_80491__(10);
	var messages_1 = __nested_webpack_require_80491__(11);
	var Node = __nested_webpack_require_80491__(7);
	var scanner_1 = __nested_webpack_require_80491__(12);
	var syntax_1 = __nested_webpack_require_80491__(2);
	var token_1 = __nested_webpack_require_80491__(13);
	var ArrowParameterPlaceHolder = 'ArrowParameterPlaceHolder';
	var Parser = (function () {
	    function Parser(code, options, delegate) {
	        if (options === void 0) { options = {}; }
	        this.config = {
	            range: (typeof options.range === 'boolean') && options.range,
	            loc: (typeof options.loc === 'boolean') && options.loc,
	            source: null,
	            tokens: (typeof options.tokens === 'boolean') && options.tokens,
	            comment: (typeof options.comment === 'boolean') && options.comment,
	            tolerant: (typeof options.tolerant === 'boolean') && options.tolerant
	        };
	        if (this.config.loc && options.source && options.source !== null) {
	            this.config.source = String(options.source);
	        }
	        this.delegate = delegate;
	        this.errorHandler = new error_handler_1.ErrorHandler();
	        this.errorHandler.tolerant = this.config.tolerant;
	        this.scanner = new scanner_1.Scanner(code, this.errorHandler);
	        this.scanner.trackComment = this.config.comment;
	        this.operatorPrecedence = {
	            ')': 0,
	            ';': 0,
	            ',': 0,
	            '=': 0,
	            ']': 0,
	            '||': 1,
	            '&&': 2,
	            '|': 3,
	            '^': 4,
	            '&': 5,
	            '==': 6,
	            '!=': 6,
	            '===': 6,
	            '!==': 6,
	            '<': 7,
	            '>': 7,
	            '<=': 7,
	            '>=': 7,
	            '<<': 8,
	            '>>': 8,
	            '>>>': 8,
	            '+': 9,
	            '-': 9,
	            '*': 11,
	            '/': 11,
	            '%': 11
	        };
	        this.lookahead = {
	            type: 2 /* EOF */,
	            value: '',
	            lineNumber: this.scanner.lineNumber,
	            lineStart: 0,
	            start: 0,
	            end: 0
	        };
	        this.hasLineTerminator = false;
	        this.context = {
	            isModule: false,
	            await: false,
	            allowIn: true,
	            allowStrictDirective: true,
	            allowYield: true,
	            firstCoverInitializedNameError: null,
	            isAssignmentTarget: false,
	            isBindingElement: false,
	            inFunctionBody: false,
	            inIteration: false,
	            inSwitch: false,
	            labelSet: {},
	            strict: false
	        };
	        this.tokens = [];
	        this.startMarker = {
	            index: 0,
	            line: this.scanner.lineNumber,
	            column: 0
	        };
	        this.lastMarker = {
	            index: 0,
	            line: this.scanner.lineNumber,
	            column: 0
	        };
	        this.nextToken();
	        this.lastMarker = {
	            index: this.scanner.index,
	            line: this.scanner.lineNumber,
	            column: this.scanner.index - this.scanner.lineStart
	        };
	    }
	    Parser.prototype.throwError = function (messageFormat) {
	        var values = [];
	        for (var _i = 1; _i < arguments.length; _i++) {
	            values[_i - 1] = arguments[_i];
	        }
	        var args = Array.prototype.slice.call(arguments, 1);
	        var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) {
	            assert_1.assert(idx < args.length, 'Message reference must be in range');
	            return args[idx];
	        });
	        var index = this.lastMarker.index;
	        var line = this.lastMarker.line;
	        var column = this.lastMarker.column + 1;
	        throw this.errorHandler.createError(index, line, column, msg);
	    };
	    Parser.prototype.tolerateError = function (messageFormat) {
	        var values = [];
	        for (var _i = 1; _i < arguments.length; _i++) {
	            values[_i - 1] = arguments[_i];
	        }
	        var args = Array.prototype.slice.call(arguments, 1);
	        var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) {
	            assert_1.assert(idx < args.length, 'Message reference must be in range');
	            return args[idx];
	        });
	        var index = this.lastMarker.index;
	        var line = this.scanner.lineNumber;
	        var column = this.lastMarker.column + 1;
	        this.errorHandler.tolerateError(index, line, column, msg);
	    };
	    // Throw an exception because of the token.
	    Parser.prototype.unexpectedTokenError = function (token, message) {
	        var msg = message || messages_1.Messages.UnexpectedToken;
	        var value;
	        if (token) {
	            if (!message) {
	                msg = (token.type === 2 /* EOF */) ? messages_1.Messages.UnexpectedEOS :
	                    (token.type === 3 /* Identifier */) ? messages_1.Messages.UnexpectedIdentifier :
	                        (token.type === 6 /* NumericLiteral */) ? messages_1.Messages.UnexpectedNumber :
	                            (token.type === 8 /* StringLiteral */) ? messages_1.Messages.UnexpectedString :
	                                (token.type === 10 /* Template */) ? messages_1.Messages.UnexpectedTemplate :
	                                    messages_1.Messages.UnexpectedToken;
	                if (token.type === 4 /* Keyword */) {
	                    if (this.scanner.isFutureReservedWord(token.value)) {
	                        msg = messages_1.Messages.UnexpectedReserved;
	                    }
	                    else if (this.context.strict && this.scanner.isStrictModeReservedWord(token.value)) {
	                        msg = messages_1.Messages.StrictReservedWord;
	                    }
	                }
	            }
	            value = token.value;
	        }
	        else {
	            value = 'ILLEGAL';
	        }
	        msg = msg.replace('%0', value);
	        if (token && typeof token.lineNumber === 'number') {
	            var index = token.start;
	            var line = token.lineNumber;
	            var lastMarkerLineStart = this.lastMarker.index - this.lastMarker.column;
	            var column = token.start - lastMarkerLineStart + 1;
	            return this.errorHandler.createError(index, line, column, msg);
	        }
	        else {
	            var index = this.lastMarker.index;
	            var line = this.lastMarker.line;
	            var column = this.lastMarker.column + 1;
	            return this.errorHandler.createError(index, line, column, msg);
	        }
	    };
	    Parser.prototype.throwUnexpectedToken = function (token, message) {
	        throw this.unexpectedTokenError(token, message);
	    };
	    Parser.prototype.tolerateUnexpectedToken = function (token, message) {
	        this.errorHandler.tolerate(this.unexpectedTokenError(token, message));
	    };
	    Parser.prototype.collectComments = function () {
	        if (!this.config.comment) {
	            this.scanner.scanComments();
	        }
	        else {
	            var comments = this.scanner.scanComments();
	            if (comments.length > 0 && this.delegate) {
	                for (var i = 0; i < comments.length; ++i) {
	                    var e = comments[i];
	                    var node = void 0;
	                    node = {
	                        type: e.multiLine ? 'BlockComment' : 'LineComment',
	                        value: this.scanner.source.slice(e.slice[0], e.slice[1])
	                    };
	                    if (this.config.range) {
	                        node.range = e.range;
	                    }
	                    if (this.config.loc) {
	                        node.loc = e.loc;
	                    }
	                    var metadata = {
	                        start: {
	                            line: e.loc.start.line,
	                            column: e.loc.start.column,
	                            offset: e.range[0]
	                        },
	                        end: {
	                            line: e.loc.end.line,
	                            column: e.loc.end.column,
	                            offset: e.range[1]
	                        }
	                    };
	                    this.delegate(node, metadata);
	                }
	            }
	        }
	    };
	    // From internal representation to an external structure
	    Parser.prototype.getTokenRaw = function (token) {
	        return this.scanner.source.slice(token.start, token.end);
	    };
	    Parser.prototype.convertToken = function (token) {
	        var t = {
	            type: token_1.TokenName[token.type],
	            value: this.getTokenRaw(token)
	        };
	        if (this.config.range) {
	            t.range = [token.start, token.end];
	        }
	        if (this.config.loc) {
	            t.loc = {
	                start: {
	                    line: this.startMarker.line,
	                    column: this.startMarker.column
	                },
	                end: {
	                    line: this.scanner.lineNumber,
	                    column: this.scanner.index - this.scanner.lineStart
	                }
	            };
	        }
	        if (token.type === 9 /* RegularExpression */) {
	            var pattern = token.pattern;
	            var flags = token.flags;
	            t.regex = { pattern: pattern, flags: flags };
	        }
	        return t;
	    };
	    Parser.prototype.nextToken = function () {
	        var token = this.lookahead;
	        this.lastMarker.index = this.scanner.index;
	        this.lastMarker.line = this.scanner.lineNumber;
	        this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
	        this.collectComments();
	        if (this.scanner.index !== this.startMarker.index) {
	            this.startMarker.index = this.scanner.index;
	            this.startMarker.line = this.scanner.lineNumber;
	            this.startMarker.column = this.scanner.index - this.scanner.lineStart;
	        }
	        var next = this.scanner.lex();
	        this.hasLineTerminator = (token.lineNumber !== next.lineNumber);
	        if (next && this.context.strict && next.type === 3 /* Identifier */) {
	            if (this.scanner.isStrictModeReservedWord(next.value)) {
	                next.type = 4 /* Keyword */;
	            }
	        }
	        this.lookahead = next;
	        if (this.config.tokens && next.type !== 2 /* EOF */) {
	            this.tokens.push(this.convertToken(next));
	        }
	        return token;
	    };
	    Parser.prototype.nextRegexToken = function () {
	        this.collectComments();
	        var token = this.scanner.scanRegExp();
	        if (this.config.tokens) {
	            // Pop the previous token, '/' or '/='
	            // This is added from the lookahead token.
	            this.tokens.pop();
	            this.tokens.push(this.convertToken(token));
	        }
	        // Prime the next lookahead.
	        this.lookahead = token;
	        this.nextToken();
	        return token;
	    };
	    Parser.prototype.createNode = function () {
	        return {
	            index: this.startMarker.index,
	            line: this.startMarker.line,
	            column: this.startMarker.column
	        };
	    };
	    Parser.prototype.startNode = function (token, lastLineStart) {
	        if (lastLineStart === void 0) { lastLineStart = 0; }
	        var column = token.start - token.lineStart;
	        var line = token.lineNumber;
	        if (column < 0) {
	            column += lastLineStart;
	            line--;
	        }
	        return {
	            index: token.start,
	            line: line,
	            column: column
	        };
	    };
	    Parser.prototype.finalize = function (marker, node) {
	        if (this.config.range) {
	            node.range = [marker.index, this.lastMarker.index];
	        }
	        if (this.config.loc) {
	            node.loc = {
	                start: {
	                    line: marker.line,
	                    column: marker.column,
	                },
	                end: {
	                    line: this.lastMarker.line,
	                    column: this.lastMarker.column
	                }
	            };
	            if (this.config.source) {
	                node.loc.source = this.config.source;
	            }
	        }
	        if (this.delegate) {
	            var metadata = {
	                start: {
	                    line: marker.line,
	                    column: marker.column,
	                    offset: marker.index
	                },
	                end: {
	                    line: this.lastMarker.line,
	                    column: this.lastMarker.column,
	                    offset: this.lastMarker.index
	                }
	            };
	            this.delegate(node, metadata);
	        }
	        return node;
	    };
	    // Expect the next token to match the specified punctuator.
	    // If not, an exception will be thrown.
	    Parser.prototype.expect = function (value) {
	        var token = this.nextToken();
	        if (token.type !== 7 /* Punctuator */ || token.value !== value) {
	            this.throwUnexpectedToken(token);
	        }
	    };
	    // Quietly expect a comma when in tolerant mode, otherwise delegates to expect().
	    Parser.prototype.expectCommaSeparator = function () {
	        if (this.config.tolerant) {
	            var token = this.lookahead;
	            if (token.type === 7 /* Punctuator */ && token.value === ',') {
	                this.nextToken();
	            }
	            else if (token.type === 7 /* Punctuator */ && token.value === ';') {
	                this.nextToken();
	                this.tolerateUnexpectedToken(token);
	            }
	            else {
	                this.tolerateUnexpectedToken(token, messages_1.Messages.UnexpectedToken);
	            }
	        }
	        else {
	            this.expect(',');
	        }
	    };
	    // Expect the next token to match the specified keyword.
	    // If not, an exception will be thrown.
	    Parser.prototype.expectKeyword = function (keyword) {
	        var token = this.nextToken();
	        if (token.type !== 4 /* Keyword */ || token.value !== keyword) {
	            this.throwUnexpectedToken(token);
	        }
	    };
	    // Return true if the next token matches the specified punctuator.
	    Parser.prototype.match = function (value) {
	        return this.lookahead.type === 7 /* Punctuator */ && this.lookahead.value === value;
	    };
	    // Return true if the next token matches the specified keyword
	    Parser.prototype.matchKeyword = function (keyword) {
	        return this.lookahead.type === 4 /* Keyword */ && this.lookahead.value === keyword;
	    };
	    // Return true if the next token matches the specified contextual keyword
	    // (where an identifier is sometimes a keyword depending on the context)
	    Parser.prototype.matchContextualKeyword = function (keyword) {
	        return this.lookahead.type === 3 /* Identifier */ && this.lookahead.value === keyword;
	    };
	    // Return true if the next token is an assignment operator
	    Parser.prototype.matchAssign = function () {
	        if (this.lookahead.type !== 7 /* Punctuator */) {
	            return false;
	        }
	        var op = this.lookahead.value;
	        return op === '=' ||
	            op === '*=' ||
	            op === '**=' ||
	            op === '/=' ||
	            op === '%=' ||
	            op === '+=' ||
	            op === '-=' ||
	            op === '<<=' ||
	            op === '>>=' ||
	            op === '>>>=' ||
	            op === '&=' ||
	            op === '^=' ||
	            op === '|=';
	    };
	    // Cover grammar support.
	    //
	    // When an assignment expression position starts with an left parenthesis, the determination of the type
	    // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead)
	    // or the first comma. This situation also defers the determination of all the expressions nested in the pair.
	    //
	    // There are three productions that can be parsed in a parentheses pair that needs to be determined
	    // after the outermost pair is closed. They are:
	    //
	    //   1. AssignmentExpression
	    //   2. BindingElements
	    //   3. AssignmentTargets
	    //
	    // In order to avoid exponential backtracking, we use two flags to denote if the production can be
	    // binding element or assignment target.
	    //
	    // The three productions have the relationship:
	    //
	    //   BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression
	    //
	    // with a single exception that CoverInitializedName when used directly in an Expression, generates
	    // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the
	    // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair.
	    //
	    // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not
	    // effect the current flags. This means the production the parser parses is only used as an expression. Therefore
	    // the CoverInitializedName check is conducted.
	    //
	    // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates
	    // the flags outside of the parser. This means the production the parser parses is used as a part of a potential
	    // pattern. The CoverInitializedName check is deferred.
	    Parser.prototype.isolateCoverGrammar = function (parseFunction) {
	        var previousIsBindingElement = this.context.isBindingElement;
	        var previousIsAssignmentTarget = this.context.isAssignmentTarget;
	        var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError;
	        this.context.isBindingElement = true;
	        this.context.isAssignmentTarget = true;
	        this.context.firstCoverInitializedNameError = null;
	        var result = parseFunction.call(this);
	        if (this.context.firstCoverInitializedNameError !== null) {
	            this.throwUnexpectedToken(this.context.firstCoverInitializedNameError);
	        }
	        this.context.isBindingElement = previousIsBindingElement;
	        this.context.isAssignmentTarget = previousIsAssignmentTarget;
	        this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError;
	        return result;
	    };
	    Parser.prototype.inheritCoverGrammar = function (parseFunction) {
	        var previousIsBindingElement = this.context.isBindingElement;
	        var previousIsAssignmentTarget = this.context.isAssignmentTarget;
	        var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError;
	        this.context.isBindingElement = true;
	        this.context.isAssignmentTarget = true;
	        this.context.firstCoverInitializedNameError = null;
	        var result = parseFunction.call(this);
	        this.context.isBindingElement = this.context.isBindingElement && previousIsBindingElement;
	        this.context.isAssignmentTarget = this.context.isAssignmentTarget && previousIsAssignmentTarget;
	        this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError || this.context.firstCoverInitializedNameError;
	        return result;
	    };
	    Parser.prototype.consumeSemicolon = function () {
	        if (this.match(';')) {
	            this.nextToken();
	        }
	        else if (!this.hasLineTerminator) {
	            if (this.lookahead.type !== 2 /* EOF */ && !this.match('}')) {
	                this.throwUnexpectedToken(this.lookahead);
	            }
	            this.lastMarker.index = this.startMarker.index;
	            this.lastMarker.line = this.startMarker.line;
	            this.lastMarker.column = this.startMarker.column;
	        }
	    };
	    // https://tc39.github.io/ecma262/#sec-primary-expression
	    Parser.prototype.parsePrimaryExpression = function () {
	        var node = this.createNode();
	        var expr;
	        var token, raw;
	        switch (this.lookahead.type) {
	            case 3 /* Identifier */:
	                if ((this.context.isModule || this.context.await) && this.lookahead.value === 'await') {
	                    this.tolerateUnexpectedToken(this.lookahead);
	                }
	                expr = this.matchAsyncFunction() ? this.parseFunctionExpression() : this.finalize(node, new Node.Identifier(this.nextToken().value));
	                break;
	            case 6 /* NumericLiteral */:
	            case 8 /* StringLiteral */:
	                if (this.context.strict && this.lookahead.octal) {
	                    this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.StrictOctalLiteral);
	                }
	                this.context.isAssignmentTarget = false;
	                this.context.isBindingElement = false;
	                token = this.nextToken();
	                raw = this.getTokenRaw(token);
	                expr = this.finalize(node, new Node.Literal(token.value, raw));
	                break;
	            case 1 /* BooleanLiteral */:
	                this.context.isAssignmentTarget = false;
	                this.context.isBindingElement = false;
	                token = this.nextToken();
	                raw = this.getTokenRaw(token);
	                expr = this.finalize(node, new Node.Literal(token.value === 'true', raw));
	                break;
	            case 5 /* NullLiteral */:
	                this.context.isAssignmentTarget = false;
	                this.context.isBindingElement = false;
	                token = this.nextToken();
	                raw = this.getTokenRaw(token);
	                expr = this.finalize(node, new Node.Literal(null, raw));
	                break;
	            case 10 /* Template */:
	                expr = this.parseTemplateLiteral();
	                break;
	            case 7 /* Punctuator */:
	                switch (this.lookahead.value) {
	                    case '(':
	                        this.context.isBindingElement = false;
	                        expr = this.inheritCoverGrammar(this.parseGroupExpression);
	                        break;
	                    case '[':
	                        expr = this.inheritCoverGrammar(this.parseArrayInitializer);
	                        break;
	                    case '{':
	                        expr = this.inheritCoverGrammar(this.parseObjectInitializer);
	                        break;
	                    case '/':
	                    case '/=':
	                        this.context.isAssignmentTarget = false;
	                        this.context.isBindingElement = false;
	                        this.scanner.index = this.startMarker.index;
	                        token = this.nextRegexToken();
	                        raw = this.getTokenRaw(token);
	                        expr = this.finalize(node, new Node.RegexLiteral(token.regex, raw, token.pattern, token.flags));
	                        break;
	                    default:
	                        expr = this.throwUnexpectedToken(this.nextToken());
	                }
	                break;
	            case 4 /* Keyword */:
	                if (!this.context.strict && this.context.allowYield && this.matchKeyword('yield')) {
	                    expr = this.parseIdentifierName();
	                }
	                else if (!this.context.strict && this.matchKeyword('let')) {
	                    expr = this.finalize(node, new Node.Identifier(this.nextToken().value));
	                }
	                else {
	                    this.context.isAssignmentTarget = false;
	                    this.context.isBindingElement = false;
	                    if (this.matchKeyword('function')) {
	                        expr = this.parseFunctionExpression();
	                    }
	                    else if (this.matchKeyword('this')) {
	                        this.nextToken();
	                        expr = this.finalize(node, new Node.ThisExpression());
	                    }
	                    else if (this.matchKeyword('class')) {
	                        expr = this.parseClassExpression();
	                    }
	                    else {
	                        expr = this.throwUnexpectedToken(this.nextToken());
	                    }
	                }
	                break;
	            default:
	                expr = this.throwUnexpectedToken(this.nextToken());
	        }
	        return expr;
	    };
	    // https://tc39.github.io/ecma262/#sec-array-initializer
	    Parser.prototype.parseSpreadElement = function () {
	        var node = this.createNode();
	        this.expect('...');
	        var arg = this.inheritCoverGrammar(this.parseAssignmentExpression);
	        return this.finalize(node, new Node.SpreadElement(arg));
	    };
	    Parser.prototype.parseArrayInitializer = function () {
	        var node = this.createNode();
	        var elements = [];
	        this.expect('[');
	        while (!this.match(']')) {
	            if (this.match(',')) {
	                this.nextToken();
	                elements.push(null);
	            }
	            else if (this.match('...')) {
	                var element = this.parseSpreadElement();
	                if (!this.match(']')) {
	                    this.context.isAssignmentTarget = false;
	                    this.context.isBindingElement = false;
	                    this.expect(',');
	                }
	                elements.push(element);
	            }
	            else {
	                elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
	                if (!this.match(']')) {
	                    this.expect(',');
	                }
	            }
	        }
	        this.expect(']');
	        return this.finalize(node, new Node.ArrayExpression(elements));
	    };
	    // https://tc39.github.io/ecma262/#sec-object-initializer
	    Parser.prototype.parsePropertyMethod = function (params) {
	        this.context.isAssignmentTarget = false;
	        this.context.isBindingElement = false;
	        var previousStrict = this.context.strict;
	        var previousAllowStrictDirective = this.context.allowStrictDirective;
	        this.context.allowStrictDirective = params.simple;
	        var body = this.isolateCoverGrammar(this.parseFunctionSourceElements);
	        if (this.context.strict && params.firstRestricted) {
	            this.tolerateUnexpectedToken(params.firstRestricted, params.message);
	        }
	        if (this.context.strict && params.stricted) {
	            this.tolerateUnexpectedToken(params.stricted, params.message);
	        }
	        this.context.strict = previousStrict;
	        this.context.allowStrictDirective = previousAllowStrictDirective;
	        return body;
	    };
	    Parser.prototype.parsePropertyMethodFunction = function () {
	        var isGenerator = false;
	        var node = this.createNode();
	        var previousAllowYield = this.context.allowYield;
	        this.context.allowYield = true;
	        var params = this.parseFormalParameters();
	        var method = this.parsePropertyMethod(params);
	        this.context.allowYield = previousAllowYield;
	        return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator));
	    };
	    Parser.prototype.parsePropertyMethodAsyncFunction = function () {
	        var node = this.createNode();
	        var previousAllowYield = this.context.allowYield;
	        var previousAwait = this.context.await;
	        this.context.allowYield = false;
	        this.context.await = true;
	        var params = this.parseFormalParameters();
	        var method = this.parsePropertyMethod(params);
	        this.context.allowYield = previousAllowYield;
	        this.context.await = previousAwait;
	        return this.finalize(node, new Node.AsyncFunctionExpression(null, params.params, method));
	    };
	    Parser.prototype.parseObjectPropertyKey = function () {
	        var node = this.createNode();
	        var token = this.nextToken();
	        var key;
	        switch (token.type) {
	            case 8 /* StringLiteral */:
	            case 6 /* NumericLiteral */:
	                if (this.context.strict && token.octal) {
	                    this.tolerateUnexpectedToken(token, messages_1.Messages.StrictOctalLiteral);
	                }
	                var raw = this.getTokenRaw(token);
	                key = this.finalize(node, new Node.Literal(token.value, raw));
	                break;
	            case 3 /* Identifier */:
	            case 1 /* BooleanLiteral */:
	            case 5 /* NullLiteral */:
	            case 4 /* Keyword */:
	                key = this.finalize(node, new Node.Identifier(token.value));
	                break;
	            case 7 /* Punctuator */:
	                if (token.value === '[') {
	                    key = this.isolateCoverGrammar(this.parseAssignmentExpression);
	                    this.expect(']');
	                }
	                else {
	                    key = this.throwUnexpectedToken(token);
	                }
	                break;
	            default:
	                key = this.throwUnexpectedToken(token);
	        }
	        return key;
	    };
	    Parser.prototype.isPropertyKey = function (key, value) {
	        return (key.type === syntax_1.Syntax.Identifier && key.name === value) ||
	            (key.type === syntax_1.Syntax.Literal && key.value === value);
	    };
	    Parser.prototype.parseObjectProperty = function (hasProto) {
	        var node = this.createNode();
	        var token = this.lookahead;
	        var kind;
	        var key = null;
	        var value = null;
	        var computed = false;
	        var method = false;
	        var shorthand = false;
	        var isAsync = false;
	        if (token.type === 3 /* Identifier */) {
	            var id = token.value;
	            this.nextToken();
	            computed = this.match('[');
	            isAsync = !this.hasLineTerminator && (id === 'async') &&
	                !this.match(':') && !this.match('(') && !this.match('*') && !this.match(',');
	            key = isAsync ? this.parseObjectPropertyKey() : this.finalize(node, new Node.Identifier(id));
	        }
	        else if (this.match('*')) {
	            this.nextToken();
	        }
	        else {
	            computed = this.match('[');
	            key = this.parseObjectPropertyKey();
	        }
	        var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
	        if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'get' && lookaheadPropertyKey) {
	            kind = 'get';
	            computed = this.match('[');
	            key = this.parseObjectPropertyKey();
	            this.context.allowYield = false;
	            value = this.parseGetterMethod();
	        }
	        else if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'set' && lookaheadPropertyKey) {
	            kind = 'set';
	            computed = this.match('[');
	            key = this.parseObjectPropertyKey();
	            value = this.parseSetterMethod();
	        }
	        else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) {
	            kind = 'init';
	            computed = this.match('[');
	            key = this.parseObjectPropertyKey();
	            value = this.parseGeneratorMethod();
	            method = true;
	        }
	        else {
	            if (!key) {
	                this.throwUnexpectedToken(this.lookahead);
	            }
	            kind = 'init';
	            if (this.match(':') && !isAsync) {
	                if (!computed && this.isPropertyKey(key, '__proto__')) {
	                    if (hasProto.value) {
	                        this.tolerateError(messages_1.Messages.DuplicateProtoProperty);
	                    }
	                    hasProto.value = true;
	                }
	                this.nextToken();
	                value = this.inheritCoverGrammar(this.parseAssignmentExpression);
	            }
	            else if (this.match('(')) {
	                value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
	                method = true;
	            }
	            else if (token.type === 3 /* Identifier */) {
	                var id = this.finalize(node, new Node.Identifier(token.value));
	                if (this.match('=')) {
	                    this.context.firstCoverInitializedNameError = this.lookahead;
	                    this.nextToken();
	                    shorthand = true;
	                    var init = this.isolateCoverGrammar(this.parseAssignmentExpression);
	                    value = this.finalize(node, new Node.AssignmentPattern(id, init));
	                }
	                else {
	                    shorthand = true;
	                    value = id;
	                }
	            }
	            else {
	                this.throwUnexpectedToken(this.nextToken());
	            }
	        }
	        return this.finalize(node, new Node.Property(kind, key, computed, value, method, shorthand));
	    };
	    Parser.prototype.parseObjectInitializer = function () {
	        var node = this.createNode();
	        this.expect('{');
	        var properties = [];
	        var hasProto = { value: false };
	        while (!this.match('}')) {
	            properties.push(this.parseObjectProperty(hasProto));
	            if (!this.match('}')) {
	                this.expectCommaSeparator();
	            }
	        }
	        this.expect('}');
	        return this.finalize(node, new Node.ObjectExpression(properties));
	    };
	    // https://tc39.github.io/ecma262/#sec-template-literals
	    Parser.prototype.parseTemplateHead = function () {
	        assert_1.assert(this.lookahead.head, 'Template literal must start with a template head');
	        var node = this.createNode();
	        var token = this.nextToken();
	        var raw = token.value;
	        var cooked = token.cooked;
	        return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail));
	    };
	    Parser.prototype.parseTemplateElement = function () {
	        if (this.lookahead.type !== 10 /* Template */) {
	            this.throwUnexpectedToken();
	        }
	        var node = this.createNode();
	        var token = this.nextToken();
	        var raw = token.value;
	        var cooked = token.cooked;
	        return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail));
	    };
	    Parser.prototype.parseTemplateLiteral = function () {
	        var node = this.createNode();
	        var expressions = [];
	        var quasis = [];
	        var quasi = this.parseTemplateHead();
	        quasis.push(quasi);
	        while (!quasi.tail) {
	            expressions.push(this.parseExpression());
	            quasi = this.parseTemplateElement();
	            quasis.push(quasi);
	        }
	        return this.finalize(node, new Node.TemplateLiteral(quasis, expressions));
	    };
	    // https://tc39.github.io/ecma262/#sec-grouping-operator
	    Parser.prototype.reinterpretExpressionAsPattern = function (expr) {
	        switch (expr.type) {
	            case syntax_1.Syntax.Identifier:
	            case syntax_1.Syntax.MemberExpression:
	            case syntax_1.Syntax.RestElement:
	            case syntax_1.Syntax.AssignmentPattern:
	                break;
	            case syntax_1.Syntax.SpreadElement:
	                expr.type = syntax_1.Syntax.RestElement;
	                this.reinterpretExpressionAsPattern(expr.argument);
	                break;
	            case syntax_1.Syntax.ArrayExpression:
	                expr.type = syntax_1.Syntax.ArrayPattern;
	                for (var i = 0; i < expr.elements.length; i++) {
	                    if (expr.elements[i] !== null) {
	                        this.reinterpretExpressionAsPattern(expr.elements[i]);
	                    }
	                }
	                break;
	            case syntax_1.Syntax.ObjectExpression:
	                expr.type = syntax_1.Syntax.ObjectPattern;
	                for (var i = 0; i < expr.properties.length; i++) {
	                    this.reinterpretExpressionAsPattern(expr.properties[i].value);
	                }
	                break;
	            case syntax_1.Syntax.AssignmentExpression:
	                expr.type = syntax_1.Syntax.AssignmentPattern;
	                delete expr.operator;
	                this.reinterpretExpressionAsPattern(expr.left);
	                break;
	            default:
	                // Allow other node type for tolerant parsing.
	                break;
	        }
	    };
	    Parser.prototype.parseGroupExpression = function () {
	        var expr;
	        this.expect('(');
	        if (this.match(')')) {
	            this.nextToken();
	            if (!this.match('=>')) {
	                this.expect('=>');
	            }
	            expr = {
	                type: ArrowParameterPlaceHolder,
	                params: [],
	                async: false
	            };
	        }
	        else {
	            var startToken = this.lookahead;
	            var params = [];
	            if (this.match('...')) {
	                expr = this.parseRestElement(params);
	                this.expect(')');
	                if (!this.match('=>')) {
	                    this.expect('=>');
	                }
	                expr = {
	                    type: ArrowParameterPlaceHolder,
	                    params: [expr],
	                    async: false
	                };
	            }
	            else {
	                var arrow = false;
	                this.context.isBindingElement = true;
	                expr = this.inheritCoverGrammar(this.parseAssignmentExpression);
	                if (this.match(',')) {
	                    var expressions = [];
	                    this.context.isAssignmentTarget = false;
	                    expressions.push(expr);
	                    while (this.lookahead.type !== 2 /* EOF */) {
	                        if (!this.match(',')) {
	                            break;
	                        }
	                        this.nextToken();
	                        if (this.match(')')) {
	                            this.nextToken();
	                            for (var i = 0; i < expressions.length; i++) {
	                                this.reinterpretExpressionAsPattern(expressions[i]);
	                            }
	                            arrow = true;
	                            expr = {
	                                type: ArrowParameterPlaceHolder,
	                                params: expressions,
	                                async: false
	                            };
	                        }
	                        else if (this.match('...')) {
	                            if (!this.context.isBindingElement) {
	                                this.throwUnexpectedToken(this.lookahead);
	                            }
	                            expressions.push(this.parseRestElement(params));
	                            this.expect(')');
	                            if (!this.match('=>')) {
	                                this.expect('=>');
	                            }
	                            this.context.isBindingElement = false;
	                            for (var i = 0; i < expressions.length; i++) {
	                                this.reinterpretExpressionAsPattern(expressions[i]);
	                            }
	                            arrow = true;
	                            expr = {
	                                type: ArrowParameterPlaceHolder,
	                                params: expressions,
	                                async: false
	                            };
	                        }
	                        else {
	                            expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
	                        }
	                        if (arrow) {
	                            break;
	                        }
	                    }
	                    if (!arrow) {
	                        expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions));
	                    }
	                }
	                if (!arrow) {
	                    this.expect(')');
	                    if (this.match('=>')) {
	                        if (expr.type === syntax_1.Syntax.Identifier && expr.name === 'yield') {
	                            arrow = true;
	                            expr = {
	                                type: ArrowParameterPlaceHolder,
	                                params: [expr],
	                                async: false
	                            };
	                        }
	                        if (!arrow) {
	                            if (!this.context.isBindingElement) {
	                                this.throwUnexpectedToken(this.lookahead);
	                            }
	                            if (expr.type === syntax_1.Syntax.SequenceExpression) {
	                                for (var i = 0; i < expr.expressions.length; i++) {
	                                    this.reinterpretExpressionAsPattern(expr.expressions[i]);
	                                }
	                            }
	                            else {
	                                this.reinterpretExpressionAsPattern(expr);
	                            }
	                            var parameters = (expr.type === syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr]);
	                            expr = {
	                                type: ArrowParameterPlaceHolder,
	                                params: parameters,
	                                async: false
	                            };
	                        }
	                    }
	                    this.context.isBindingElement = false;
	                }
	            }
	        }
	        return expr;
	    };
	    // https://tc39.github.io/ecma262/#sec-left-hand-side-expressions
	    Parser.prototype.parseArguments = function () {
	        this.expect('(');
	        var args = [];
	        if (!this.match(')')) {
	            while (true) {
	                var expr = this.match('...') ? this.parseSpreadElement() :
	                    this.isolateCoverGrammar(this.parseAssignmentExpression);
	                args.push(expr);
	                if (this.match(')')) {
	                    break;
	                }
	                this.expectCommaSeparator();
	                if (this.match(')')) {
	                    break;
	                }
	            }
	        }
	        this.expect(')');
	        return args;
	    };
	    Parser.prototype.isIdentifierName = function (token) {
	        return token.type === 3 /* Identifier */ ||
	            token.type === 4 /* Keyword */ ||
	            token.type === 1 /* BooleanLiteral */ ||
	            token.type === 5 /* NullLiteral */;
	    };
	    Parser.prototype.parseIdentifierName = function () {
	        var node = this.createNode();
	        var token = this.nextToken();
	        if (!this.isIdentifierName(token)) {
	            this.throwUnexpectedToken(token);
	        }
	        return this.finalize(node, new Node.Identifier(token.value));
	    };
	    Parser.prototype.parseNewExpression = function () {
	        var node = this.createNode();
	        var id = this.parseIdentifierName();
	        assert_1.assert(id.name === 'new', 'New expression must start with `new`');
	        var expr;
	        if (this.match('.')) {
	            this.nextToken();
	            if (this.lookahead.type === 3 /* Identifier */ && this.context.inFunctionBody && this.lookahead.value === 'target') {
	                var property = this.parseIdentifierName();
	                expr = new Node.MetaProperty(id, property);
	            }
	            else {
	                this.throwUnexpectedToken(this.lookahead);
	            }
	        }
	        else {
	            var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression);
	            var args = this.match('(') ? this.parseArguments() : [];
	            expr = new Node.NewExpression(callee, args);
	            this.context.isAssignmentTarget = false;
	            this.context.isBindingElement = false;
	        }
	        return this.finalize(node, expr);
	    };
	    Parser.prototype.parseAsyncArgument = function () {
	        var arg = this.parseAssignmentExpression();
	        this.context.firstCoverInitializedNameError = null;
	        return arg;
	    };
	    Parser.prototype.parseAsyncArguments = function () {
	        this.expect('(');
	        var args = [];
	        if (!this.match(')')) {
	            while (true) {
	                var expr = this.match('...') ? this.parseSpreadElement() :
	                    this.isolateCoverGrammar(this.parseAsyncArgument);
	                args.push(expr);
	                if (this.match(')')) {
	                    break;
	                }
	                this.expectCommaSeparator();
	                if (this.match(')')) {
	                    break;
	                }
	            }
	        }
	        this.expect(')');
	        return args;
	    };
	    Parser.prototype.parseLeftHandSideExpressionAllowCall = function () {
	        var startToken = this.lookahead;
	        var maybeAsync = this.matchContextualKeyword('async');
	        var previousAllowIn = this.context.allowIn;
	        this.context.allowIn = true;
	        var expr;
	        if (this.matchKeyword('super') && this.context.inFunctionBody) {
	            expr = this.createNode();
	            this.nextToken();
	            expr = this.finalize(expr, new Node.Super());
	            if (!this.match('(') && !this.match('.') && !this.match('[')) {
	                this.throwUnexpectedToken(this.lookahead);
	            }
	        }
	        else {
	            expr = this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression);
	        }
	        while (true) {
	            if (this.match('.')) {
	                this.context.isBindingElement = false;
	                this.context.isAssignmentTarget = true;
	                this.expect('.');
	                var property = this.parseIdentifierName();
	                expr = this.finalize(this.startNode(startToken), new Node.StaticMemberExpression(expr, property));
	            }
	            else if (this.match('(')) {
	                var asyncArrow = maybeAsync && (startToken.lineNumber === this.lookahead.lineNumber);
	                this.context.isBindingElement = false;
	                this.context.isAssignmentTarget = false;
	                var args = asyncArrow ? this.parseAsyncArguments() : this.parseArguments();
	                expr = this.finalize(this.startNode(startToken), new Node.CallExpression(expr, args));
	                if (asyncArrow && this.match('=>')) {
	                    for (var i = 0; i < args.length; ++i) {
	                        this.reinterpretExpressionAsPattern(args[i]);
	                    }
	                    expr = {
	                        type: ArrowParameterPlaceHolder,
	                        params: args,
	                        async: true
	                    };
	                }
	            }
	            else if (this.match('[')) {
	                this.context.isBindingElement = false;
	                this.context.isAssignmentTarget = true;
	                this.expect('[');
	                var property = this.isolateCoverGrammar(this.parseExpression);
	                this.expect(']');
	                expr = this.finalize(this.startNode(startToken), new Node.ComputedMemberExpression(expr, property));
	            }
	            else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) {
	                var quasi = this.parseTemplateLiteral();
	                expr = this.finalize(this.startNode(startToken), new Node.TaggedTemplateExpression(expr, quasi));
	            }
	            else {
	                break;
	            }
	        }
	        this.context.allowIn = previousAllowIn;
	        return expr;
	    };
	    Parser.prototype.parseSuper = function () {
	        var node = this.createNode();
	        this.expectKeyword('super');
	        if (!this.match('[') && !this.match('.')) {
	            this.throwUnexpectedToken(this.lookahead);
	        }
	        return this.finalize(node, new Node.Super());
	    };
	    Parser.prototype.parseLeftHandSideExpression = function () {
	        assert_1.assert(this.context.allowIn, 'callee of new expression always allow in keyword.');
	        var node = this.startNode(this.lookahead);
	        var expr = (this.matchKeyword('super') && this.context.inFunctionBody) ? this.parseSuper() :
	            this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression);
	        while (true) {
	            if (this.match('[')) {
	                this.context.isBindingElement = false;
	                this.context.isAssignmentTarget = true;
	                this.expect('[');
	                var property = this.isolateCoverGrammar(this.parseExpression);
	                this.expect(']');
	                expr = this.finalize(node, new Node.ComputedMemberExpression(expr, property));
	            }
	            else if (this.match('.')) {
	                this.context.isBindingElement = false;
	                this.context.isAssignmentTarget = true;
	                this.expect('.');
	                var property = this.parseIdentifierName();
	                expr = this.finalize(node, new Node.StaticMemberExpression(expr, property));
	            }
	            else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) {
	                var quasi = this.parseTemplateLiteral();
	                expr = this.finalize(node, new Node.TaggedTemplateExpression(expr, quasi));
	            }
	            else {
	                break;
	            }
	        }
	        return expr;
	    };
	    // https://tc39.github.io/ecma262/#sec-update-expressions
	    Parser.prototype.parseUpdateExpression = function () {
	        var expr;
	        var startToken = this.lookahead;
	        if (this.match('++') || this.match('--')) {
	            var node = this.startNode(startToken);
	            var token = this.nextToken();
	            expr = this.inheritCoverGrammar(this.parseUnaryExpression);
	            if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
	                this.tolerateError(messages_1.Messages.StrictLHSPrefix);
	            }
	            if (!this.context.isAssignmentTarget) {
	                this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
	            }
	            var prefix = true;
	            expr = this.finalize(node, new Node.UpdateExpression(token.value, expr, prefix));
	            this.context.isAssignmentTarget = false;
	            this.context.isBindingElement = false;
	        }
	        else {
	            expr = this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
	            if (!this.hasLineTerminator && this.lookahead.type === 7 /* Punctuator */) {
	                if (this.match('++') || this.match('--')) {
	                    if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
	                        this.tolerateError(messages_1.Messages.StrictLHSPostfix);
	                    }
	                    if (!this.context.isAssignmentTarget) {
	                        this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
	                    }
	                    this.context.isAssignmentTarget = false;
	                    this.context.isBindingElement = false;
	                    var operator = this.nextToken().value;
	                    var prefix = false;
	                    expr = this.finalize(this.startNode(startToken), new Node.UpdateExpression(operator, expr, prefix));
	                }
	            }
	        }
	        return expr;
	    };
	    // https://tc39.github.io/ecma262/#sec-unary-operators
	    Parser.prototype.parseAwaitExpression = function () {
	        var node = this.createNode();
	        this.nextToken();
	        var argument = this.parseUnaryExpression();
	        return this.finalize(node, new Node.AwaitExpression(argument));
	    };
	    Parser.prototype.parseUnaryExpression = function () {
	        var expr;
	        if (this.match('+') || this.match('-') || this.match('~') || this.match('!') ||
	            this.matchKeyword('delete') || this.matchKeyword('void') || this.matchKeyword('typeof')) {
	            var node = this.startNode(this.lookahead);
	            var token = this.nextToken();
	            expr = this.inheritCoverGrammar(this.parseUnaryExpression);
	            expr = this.finalize(node, new Node.UnaryExpression(token.value, expr));
	            if (this.context.strict && expr.operator === 'delete' && expr.argument.type === syntax_1.Syntax.Identifier) {
	                this.tolerateError(messages_1.Messages.StrictDelete);
	            }
	            this.context.isAssignmentTarget = false;
	            this.context.isBindingElement = false;
	        }
	        else if (this.context.await && this.matchContextualKeyword('await')) {
	            expr = this.parseAwaitExpression();
	        }
	        else {
	            expr = this.parseUpdateExpression();
	        }
	        return expr;
	    };
	    Parser.prototype.parseExponentiationExpression = function () {
	        var startToken = this.lookahead;
	        var expr = this.inheritCoverGrammar(this.parseUnaryExpression);
	        if (expr.type !== syntax_1.Syntax.UnaryExpression && this.match('**')) {
	            this.nextToken();
	            this.context.isAssignmentTarget = false;
	            this.context.isBindingElement = false;
	            var left = expr;
	            var right = this.isolateCoverGrammar(this.parseExponentiationExpression);
	            expr = this.finalize(this.startNode(startToken), new Node.BinaryExpression('**', left, right));
	        }
	        return expr;
	    };
	    // https://tc39.github.io/ecma262/#sec-exp-operator
	    // https://tc39.github.io/ecma262/#sec-multiplicative-operators
	    // https://tc39.github.io/ecma262/#sec-additive-operators
	    // https://tc39.github.io/ecma262/#sec-bitwise-shift-operators
	    // https://tc39.github.io/ecma262/#sec-relational-operators
	    // https://tc39.github.io/ecma262/#sec-equality-operators
	    // https://tc39.github.io/ecma262/#sec-binary-bitwise-operators
	    // https://tc39.github.io/ecma262/#sec-binary-logical-operators
	    Parser.prototype.binaryPrecedence = function (token) {
	        var op = token.value;
	        var precedence;
	        if (token.type === 7 /* Punctuator */) {
	            precedence = this.operatorPrecedence[op] || 0;
	        }
	        else if (token.type === 4 /* Keyword */) {
	            precedence = (op === 'instanceof' || (this.context.allowIn && op === 'in')) ? 7 : 0;
	        }
	        else {
	            precedence = 0;
	        }
	        return precedence;
	    };
	    Parser.prototype.parseBinaryExpression = function () {
	        var startToken = this.lookahead;
	        var expr = this.inheritCoverGrammar(this.parseExponentiationExpression);
	        var token = this.lookahead;
	        var prec = this.binaryPrecedence(token);
	        if (prec > 0) {
	            this.nextToken();
	            this.context.isAssignmentTarget = false;
	            this.context.isBindingElement = false;
	            var markers = [startToken, this.lookahead];
	            var left = expr;
	            var right = this.isolateCoverGrammar(this.parseExponentiationExpression);
	            var stack = [left, token.value, right];
	            var precedences = [prec];
	            while (true) {
	                prec = this.binaryPrecedence(this.lookahead);
	                if (prec <= 0) {
	                    break;
	                }
	                // Reduce: make a binary expression from the three topmost entries.
	                while ((stack.length > 2) && (prec <= precedences[precedences.length - 1])) {
	                    right = stack.pop();
	                    var operator = stack.pop();
	                    precedences.pop();
	                    left = stack.pop();
	                    markers.pop();
	                    var node = this.startNode(markers[markers.length - 1]);
	                    stack.push(this.finalize(node, new Node.BinaryExpression(operator, left, right)));
	                }
	                // Shift.
	                stack.push(this.nextToken().value);
	                precedences.push(prec);
	                markers.push(this.lookahead);
	                stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression));
	            }
	            // Final reduce to clean-up the stack.
	            var i = stack.length - 1;
	            expr = stack[i];
	            var lastMarker = markers.pop();
	            while (i > 1) {
	                var marker = markers.pop();
	                var lastLineStart = lastMarker && lastMarker.lineStart;
	                var node = this.startNode(marker, lastLineStart);
	                var operator = stack[i - 1];
	                expr = this.finalize(node, new Node.BinaryExpression(operator, stack[i - 2], expr));
	                i -= 2;
	                lastMarker = marker;
	            }
	        }
	        return expr;
	    };
	    // https://tc39.github.io/ecma262/#sec-conditional-operator
	    Parser.prototype.parseConditionalExpression = function () {
	        var startToken = this.lookahead;
	        var expr = this.inheritCoverGrammar(this.parseBinaryExpression);
	        if (this.match('?')) {
	            this.nextToken();
	            var previousAllowIn = this.context.allowIn;
	            this.context.allowIn = true;
	            var consequent = this.isolateCoverGrammar(this.parseAssignmentExpression);
	            this.context.allowIn = previousAllowIn;
	            this.expect(':');
	            var alternate = this.isolateCoverGrammar(this.parseAssignmentExpression);
	            expr = this.finalize(this.startNode(startToken), new Node.ConditionalExpression(expr, consequent, alternate));
	            this.context.isAssignmentTarget = false;
	            this.context.isBindingElement = false;
	        }
	        return expr;
	    };
	    // https://tc39.github.io/ecma262/#sec-assignment-operators
	    Parser.prototype.checkPatternParam = function (options, param) {
	        switch (param.type) {
	            case syntax_1.Syntax.Identifier:
	                this.validateParam(options, param, param.name);
	                break;
	            case syntax_1.Syntax.RestElement:
	                this.checkPatternParam(options, param.argument);
	                break;
	            case syntax_1.Syntax.AssignmentPattern:
	                this.checkPatternParam(options, param.left);
	                break;
	            case syntax_1.Syntax.ArrayPattern:
	                for (var i = 0; i < param.elements.length; i++) {
	                    if (param.elements[i] !== null) {
	                        this.checkPatternParam(options, param.elements[i]);
	                    }
	                }
	                break;
	            case syntax_1.Syntax.ObjectPattern:
	                for (var i = 0; i < param.properties.length; i++) {
	                    this.checkPatternParam(options, param.properties[i].value);
	                }
	                break;
	            default:
	                break;
	        }
	        options.simple = options.simple && (param instanceof Node.Identifier);
	    };
	    Parser.prototype.reinterpretAsCoverFormalsList = function (expr) {
	        var params = [expr];
	        var options;
	        var asyncArrow = false;
	        switch (expr.type) {
	            case syntax_1.Syntax.Identifier:
	                break;
	            case ArrowParameterPlaceHolder:
	                params = expr.params;
	                asyncArrow = expr.async;
	                break;
	            default:
	                return null;
	        }
	        options = {
	            simple: true,
	            paramSet: {}
	        };
	        for (var i = 0; i < params.length; ++i) {
	            var param = params[i];
	            if (param.type === syntax_1.Syntax.AssignmentPattern) {
	                if (param.right.type === syntax_1.Syntax.YieldExpression) {
	                    if (param.right.argument) {
	                        this.throwUnexpectedToken(this.lookahead);
	                    }
	                    param.right.type = syntax_1.Syntax.Identifier;
	                    param.right.name = 'yield';
	                    delete param.right.argument;
	                    delete param.right.delegate;
	                }
	            }
	            else if (asyncArrow && param.type === syntax_1.Syntax.Identifier && param.name === 'await') {
	                this.throwUnexpectedToken(this.lookahead);
	            }
	            this.checkPatternParam(options, param);
	            params[i] = param;
	        }
	        if (this.context.strict || !this.context.allowYield) {
	            for (var i = 0; i < params.length; ++i) {
	                var param = params[i];
	                if (param.type === syntax_1.Syntax.YieldExpression) {
	                    this.throwUnexpectedToken(this.lookahead);
	                }
	            }
	        }
	        if (options.message === messages_1.Messages.StrictParamDupe) {
	            var token = this.context.strict ? options.stricted : options.firstRestricted;
	            this.throwUnexpectedToken(token, options.message);
	        }
	        return {
	            simple: options.simple,
	            params: params,
	            stricted: options.stricted,
	            firstRestricted: options.firstRestricted,
	            message: options.message
	        };
	    };
	    Parser.prototype.parseAssignmentExpression = function () {
	        var expr;
	        if (!this.context.allowYield && this.matchKeyword('yield')) {
	            expr = this.parseYieldExpression();
	        }
	        else {
	            var startToken = this.lookahead;
	            var token = startToken;
	            expr = this.parseConditionalExpression();
	            if (token.type === 3 /* Identifier */ && (token.lineNumber === this.lookahead.lineNumber) && token.value === 'async') {
	                if (this.lookahead.type === 3 /* Identifier */ || this.matchKeyword('yield')) {
	                    var arg = this.parsePrimaryExpression();
	                    this.reinterpretExpressionAsPattern(arg);
	                    expr = {
	                        type: ArrowParameterPlaceHolder,
	                        params: [arg],
	                        async: true
	                    };
	                }
	            }
	            if (expr.type === ArrowParameterPlaceHolder || this.match('=>')) {
	                // https://tc39.github.io/ecma262/#sec-arrow-function-definitions
	                this.context.isAssignmentTarget = false;
	                this.context.isBindingElement = false;
	                var isAsync = expr.async;
	                var list = this.reinterpretAsCoverFormalsList(expr);
	                if (list) {
	                    if (this.hasLineTerminator) {
	                        this.tolerateUnexpectedToken(this.lookahead);
	                    }
	                    this.context.firstCoverInitializedNameError = null;
	                    var previousStrict = this.context.strict;
	                    var previousAllowStrictDirective = this.context.allowStrictDirective;
	                    this.context.allowStrictDirective = list.simple;
	                    var previousAllowYield = this.context.allowYield;
	                    var previousAwait = this.context.await;
	                    this.context.allowYield = true;
	                    this.context.await = isAsync;
	                    var node = this.startNode(startToken);
	                    this.expect('=>');
	                    var body = void 0;
	                    if (this.match('{')) {
	                        var previousAllowIn = this.context.allowIn;
	                        this.context.allowIn = true;
	                        body = this.parseFunctionSourceElements();
	                        this.context.allowIn = previousAllowIn;
	                    }
	                    else {
	                        body = this.isolateCoverGrammar(this.parseAssignmentExpression);
	                    }
	                    var expression = body.type !== syntax_1.Syntax.BlockStatement;
	                    if (this.context.strict && list.firstRestricted) {
	                        this.throwUnexpectedToken(list.firstRestricted, list.message);
	                    }
	                    if (this.context.strict && list.stricted) {
	                        this.tolerateUnexpectedToken(list.stricted, list.message);
	                    }
	                    expr = isAsync ? this.finalize(node, new Node.AsyncArrowFunctionExpression(list.params, body, expression)) :
	                        this.finalize(node, new Node.ArrowFunctionExpression(list.params, body, expression));
	                    this.context.strict = previousStrict;
	                    this.context.allowStrictDirective = previousAllowStrictDirective;
	                    this.context.allowYield = previousAllowYield;
	                    this.context.await = previousAwait;
	                }
	            }
	            else {
	                if (this.matchAssign()) {
	                    if (!this.context.isAssignmentTarget) {
	                        this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
	                    }
	                    if (this.context.strict && expr.type === syntax_1.Syntax.Identifier) {
	                        var id = expr;
	                        if (this.scanner.isRestrictedWord(id.name)) {
	                            this.tolerateUnexpectedToken(token, messages_1.Messages.StrictLHSAssignment);
	                        }
	                        if (this.scanner.isStrictModeReservedWord(id.name)) {
	                            this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
	                        }
	                    }
	                    if (!this.match('=')) {
	                        this.context.isAssignmentTarget = false;
	                        this.context.isBindingElement = false;
	                    }
	                    else {
	                        this.reinterpretExpressionAsPattern(expr);
	                    }
	                    token = this.nextToken();
	                    var operator = token.value;
	                    var right = this.isolateCoverGrammar(this.parseAssignmentExpression);
	                    expr = this.finalize(this.startNode(startToken), new Node.AssignmentExpression(operator, expr, right));
	                    this.context.firstCoverInitializedNameError = null;
	                }
	            }
	        }
	        return expr;
	    };
	    // https://tc39.github.io/ecma262/#sec-comma-operator
	    Parser.prototype.parseExpression = function () {
	        var startToken = this.lookahead;
	        var expr = this.isolateCoverGrammar(this.parseAssignmentExpression);
	        if (this.match(',')) {
	            var expressions = [];
	            expressions.push(expr);
	            while (this.lookahead.type !== 2 /* EOF */) {
	                if (!this.match(',')) {
	                    break;
	                }
	                this.nextToken();
	                expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
	            }
	            expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions));
	        }
	        return expr;
	    };
	    // https://tc39.github.io/ecma262/#sec-block
	    Parser.prototype.parseStatementListItem = function () {
	        var statement;
	        this.context.isAssignmentTarget = true;
	        this.context.isBindingElement = true;
	        if (this.lookahead.type === 4 /* Keyword */) {
	            switch (this.lookahead.value) {
	                case 'export':
	                    if (!this.context.isModule) {
	                        this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalExportDeclaration);
	                    }
	                    statement = this.parseExportDeclaration();
	                    break;
	                case 'import':
	                    if (!this.context.isModule) {
	                        this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalImportDeclaration);
	                    }
	                    statement = this.parseImportDeclaration();
	                    break;
	                case 'const':
	                    statement = this.parseLexicalDeclaration({ inFor: false });
	                    break;
	                case 'function':
	                    statement = this.parseFunctionDeclaration();
	                    break;
	                case 'class':
	                    statement = this.parseClassDeclaration();
	                    break;
	                case 'let':
	                    statement = this.isLexicalDeclaration() ? this.parseLexicalDeclaration({ inFor: false }) : this.parseStatement();
	                    break;
	                default:
	                    statement = this.parseStatement();
	                    break;
	            }
	        }
	        else {
	            statement = this.parseStatement();
	        }
	        return statement;
	    };
	    Parser.prototype.parseBlock = function () {
	        var node = this.createNode();
	        this.expect('{');
	        var block = [];
	        while (true) {
	            if (this.match('}')) {
	                break;
	            }
	            block.push(this.parseStatementListItem());
	        }
	        this.expect('}');
	        return this.finalize(node, new Node.BlockStatement(block));
	    };
	    // https://tc39.github.io/ecma262/#sec-let-and-const-declarations
	    Parser.prototype.parseLexicalBinding = function (kind, options) {
	        var node = this.createNode();
	        var params = [];
	        var id = this.parsePattern(params, kind);
	        if (this.context.strict && id.type === syntax_1.Syntax.Identifier) {
	            if (this.scanner.isRestrictedWord(id.name)) {
	                this.tolerateError(messages_1.Messages.StrictVarName);
	            }
	        }
	        var init = null;
	        if (kind === 'const') {
	            if (!this.matchKeyword('in') && !this.matchContextualKeyword('of')) {
	                if (this.match('=')) {
	                    this.nextToken();
	                    init = this.isolateCoverGrammar(this.parseAssignmentExpression);
	                }
	                else {
	                    this.throwError(messages_1.Messages.DeclarationMissingInitializer, 'const');
	                }
	            }
	        }
	        else if ((!options.inFor && id.type !== syntax_1.Syntax.Identifier) || this.match('=')) {
	            this.expect('=');
	            init = this.isolateCoverGrammar(this.parseAssignmentExpression);
	        }
	        return this.finalize(node, new Node.VariableDeclarator(id, init));
	    };
	    Parser.prototype.parseBindingList = function (kind, options) {
	        var list = [this.parseLexicalBinding(kind, options)];
	        while (this.match(',')) {
	            this.nextToken();
	            list.push(this.parseLexicalBinding(kind, options));
	        }
	        return list;
	    };
	    Parser.prototype.isLexicalDeclaration = function () {
	        var state = this.scanner.saveState();
	        this.scanner.scanComments();
	        var next = this.scanner.lex();
	        this.scanner.restoreState(state);
	        return (next.type === 3 /* Identifier */) ||
	            (next.type === 7 /* Punctuator */ && next.value === '[') ||
	            (next.type === 7 /* Punctuator */ && next.value === '{') ||
	            (next.type === 4 /* Keyword */ && next.value === 'let') ||
	            (next.type === 4 /* Keyword */ && next.value === 'yield');
	    };
	    Parser.prototype.parseLexicalDeclaration = function (options) {
	        var node = this.createNode();
	        var kind = this.nextToken().value;
	        assert_1.assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const');
	        var declarations = this.parseBindingList(kind, options);
	        this.consumeSemicolon();
	        return this.finalize(node, new Node.VariableDeclaration(declarations, kind));
	    };
	    // https://tc39.github.io/ecma262/#sec-destructuring-binding-patterns
	    Parser.prototype.parseBindingRestElement = function (params, kind) {
	        var node = this.createNode();
	        this.expect('...');
	        var arg = this.parsePattern(params, kind);
	        return this.finalize(node, new Node.RestElement(arg));
	    };
	    Parser.prototype.parseArrayPattern = function (params, kind) {
	        var node = this.createNode();
	        this.expect('[');
	        var elements = [];
	        while (!this.match(']')) {
	            if (this.match(',')) {
	                this.nextToken();
	                elements.push(null);
	            }
	            else {
	                if (this.match('...')) {
	                    elements.push(this.parseBindingRestElement(params, kind));
	                    break;
	                }
	                else {
	                    elements.push(this.parsePatternWithDefault(params, kind));
	                }
	                if (!this.match(']')) {
	                    this.expect(',');
	                }
	            }
	        }
	        this.expect(']');
	        return this.finalize(node, new Node.ArrayPattern(elements));
	    };
	    Parser.prototype.parsePropertyPattern = function (params, kind) {
	        var node = this.createNode();
	        var computed = false;
	        var shorthand = false;
	        var method = false;
	        var key;
	        var value;
	        if (this.lookahead.type === 3 /* Identifier */) {
	            var keyToken = this.lookahead;
	            key = this.parseVariableIdentifier();
	            var init = this.finalize(node, new Node.Identifier(keyToken.value));
	            if (this.match('=')) {
	                params.push(keyToken);
	                shorthand = true;
	                this.nextToken();
	                var expr = this.parseAssignmentExpression();
	                value = this.finalize(this.startNode(keyToken), new Node.AssignmentPattern(init, expr));
	            }
	            else if (!this.match(':')) {
	                params.push(keyToken);
	                shorthand = true;
	                value = init;
	            }
	            else {
	                this.expect(':');
	                value = this.parsePatternWithDefault(params, kind);
	            }
	        }
	        else {
	            computed = this.match('[');
	            key = this.parseObjectPropertyKey();
	            this.expect(':');
	            value = this.parsePatternWithDefault(params, kind);
	        }
	        return this.finalize(node, new Node.Property('init', key, computed, value, method, shorthand));
	    };
	    Parser.prototype.parseObjectPattern = function (params, kind) {
	        var node = this.createNode();
	        var properties = [];
	        this.expect('{');
	        while (!this.match('}')) {
	            properties.push(this.parsePropertyPattern(params, kind));
	            if (!this.match('}')) {
	                this.expect(',');
	            }
	        }
	        this.expect('}');
	        return this.finalize(node, new Node.ObjectPattern(properties));
	    };
	    Parser.prototype.parsePattern = function (params, kind) {
	        var pattern;
	        if (this.match('[')) {
	            pattern = this.parseArrayPattern(params, kind);
	        }
	        else if (this.match('{')) {
	            pattern = this.parseObjectPattern(params, kind);
	        }
	        else {
	            if (this.matchKeyword('let') && (kind === 'const' || kind === 'let')) {
	                this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.LetInLexicalBinding);
	            }
	            params.push(this.lookahead);
	            pattern = this.parseVariableIdentifier(kind);
	        }
	        return pattern;
	    };
	    Parser.prototype.parsePatternWithDefault = function (params, kind) {
	        var startToken = this.lookahead;
	        var pattern = this.parsePattern(params, kind);
	        if (this.match('=')) {
	            this.nextToken();
	            var previousAllowYield = this.context.allowYield;
	            this.context.allowYield = true;
	            var right = this.isolateCoverGrammar(this.parseAssignmentExpression);
	            this.context.allowYield = previousAllowYield;
	            pattern = this.finalize(this.startNode(startToken), new Node.AssignmentPattern(pattern, right));
	        }
	        return pattern;
	    };
	    // https://tc39.github.io/ecma262/#sec-variable-statement
	    Parser.prototype.parseVariableIdentifier = function (kind) {
	        var node = this.createNode();
	        var token = this.nextToken();
	        if (token.type === 4 /* Keyword */ && token.value === 'yield') {
	            if (this.context.strict) {
	                this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
	            }
	            else if (!this.context.allowYield) {
	                this.throwUnexpectedToken(token);
	            }
	        }
	        else if (token.type !== 3 /* Identifier */) {
	            if (this.context.strict && token.type === 4 /* Keyword */ && this.scanner.isStrictModeReservedWord(token.value)) {
	                this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
	            }
	            else {
	                if (this.context.strict || token.value !== 'let' || kind !== 'var') {
	                    this.throwUnexpectedToken(token);
	                }
	            }
	        }
	        else if ((this.context.isModule || this.context.await) && token.type === 3 /* Identifier */ && token.value === 'await') {
	            this.tolerateUnexpectedToken(token);
	        }
	        return this.finalize(node, new Node.Identifier(token.value));
	    };
	    Parser.prototype.parseVariableDeclaration = function (options) {
	        var node = this.createNode();
	        var params = [];
	        var id = this.parsePattern(params, 'var');
	        if (this.context.strict && id.type === syntax_1.Syntax.Identifier) {
	            if (this.scanner.isRestrictedWord(id.name)) {
	                this.tolerateError(messages_1.Messages.StrictVarName);
	            }
	        }
	        var init = null;
	        if (this.match('=')) {
	            this.nextToken();
	            init = this.isolateCoverGrammar(this.parseAssignmentExpression);
	        }
	        else if (id.type !== syntax_1.Syntax.Identifier && !options.inFor) {
	            this.expect('=');
	        }
	        return this.finalize(node, new Node.VariableDeclarator(id, init));
	    };
	    Parser.prototype.parseVariableDeclarationList = function (options) {
	        var opt = { inFor: options.inFor };
	        var list = [];
	        list.push(this.parseVariableDeclaration(opt));
	        while (this.match(',')) {
	            this.nextToken();
	            list.push(this.parseVariableDeclaration(opt));
	        }
	        return list;
	    };
	    Parser.prototype.parseVariableStatement = function () {
	        var node = this.createNode();
	        this.expectKeyword('var');
	        var declarations = this.parseVariableDeclarationList({ inFor: false });
	        this.consumeSemicolon();
	        return this.finalize(node, new Node.VariableDeclaration(declarations, 'var'));
	    };
	    // https://tc39.github.io/ecma262/#sec-empty-statement
	    Parser.prototype.parseEmptyStatement = function () {
	        var node = this.createNode();
	        this.expect(';');
	        return this.finalize(node, new Node.EmptyStatement());
	    };
	    // https://tc39.github.io/ecma262/#sec-expression-statement
	    Parser.prototype.parseExpressionStatement = function () {
	        var node = this.createNode();
	        var expr = this.parseExpression();
	        this.consumeSemicolon();
	        return this.finalize(node, new Node.ExpressionStatement(expr));
	    };
	    // https://tc39.github.io/ecma262/#sec-if-statement
	    Parser.prototype.parseIfClause = function () {
	        if (this.context.strict && this.matchKeyword('function')) {
	            this.tolerateError(messages_1.Messages.StrictFunction);
	        }
	        return this.parseStatement();
	    };
	    Parser.prototype.parseIfStatement = function () {
	        var node = this.createNode();
	        var consequent;
	        var alternate = null;
	        this.expectKeyword('if');
	        this.expect('(');
	        var test = this.parseExpression();
	        if (!this.match(')') && this.config.tolerant) {
	            this.tolerateUnexpectedToken(this.nextToken());
	            consequent = this.finalize(this.createNode(), new Node.EmptyStatement());
	        }
	        else {
	            this.expect(')');
	            consequent = this.parseIfClause();
	            if (this.matchKeyword('else')) {
	                this.nextToken();
	                alternate = this.parseIfClause();
	            }
	        }
	        return this.finalize(node, new Node.IfStatement(test, consequent, alternate));
	    };
	    // https://tc39.github.io/ecma262/#sec-do-while-statement
	    Parser.prototype.parseDoWhileStatement = function () {
	        var node = this.createNode();
	        this.expectKeyword('do');
	        var previousInIteration = this.context.inIteration;
	        this.context.inIteration = true;
	        var body = this.parseStatement();
	        this.context.inIteration = previousInIteration;
	        this.expectKeyword('while');
	        this.expect('(');
	        var test = this.parseExpression();
	        if (!this.match(')') && this.config.tolerant) {
	            this.tolerateUnexpectedToken(this.nextToken());
	        }
	        else {
	            this.expect(')');
	            if (this.match(';')) {
	                this.nextToken();
	            }
	        }
	        return this.finalize(node, new Node.DoWhileStatement(body, test));
	    };
	    // https://tc39.github.io/ecma262/#sec-while-statement
	    Parser.prototype.parseWhileStatement = function () {
	        var node = this.createNode();
	        var body;
	        this.expectKeyword('while');
	        this.expect('(');
	        var test = this.parseExpression();
	        if (!this.match(')') && this.config.tolerant) {
	            this.tolerateUnexpectedToken(this.nextToken());
	            body = this.finalize(this.createNode(), new Node.EmptyStatement());
	        }
	        else {
	            this.expect(')');
	            var previousInIteration = this.context.inIteration;
	            this.context.inIteration = true;
	            body = this.parseStatement();
	            this.context.inIteration = previousInIteration;
	        }
	        return this.finalize(node, new Node.WhileStatement(test, body));
	    };
	    // https://tc39.github.io/ecma262/#sec-for-statement
	    // https://tc39.github.io/ecma262/#sec-for-in-and-for-of-statements
	    Parser.prototype.parseForStatement = function () {
	        var init = null;
	        var test = null;
	        var update = null;
	        var forIn = true;
	        var left, right;
	        var node = this.createNode();
	        this.expectKeyword('for');
	        this.expect('(');
	        if (this.match(';')) {
	            this.nextToken();
	        }
	        else {
	            if (this.matchKeyword('var')) {
	                init = this.createNode();
	                this.nextToken();
	                var previousAllowIn = this.context.allowIn;
	                this.context.allowIn = false;
	                var declarations = this.parseVariableDeclarationList({ inFor: true });
	                this.context.allowIn = previousAllowIn;
	                if (declarations.length === 1 && this.matchKeyword('in')) {
	                    var decl = declarations[0];
	                    if (decl.init && (decl.id.type === syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern || this.context.strict)) {
	                        this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, 'for-in');
	                    }
	                    init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var'));
	                    this.nextToken();
	                    left = init;
	                    right = this.parseExpression();
	                    init = null;
	                }
	                else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) {
	                    init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var'));
	                    this.nextToken();
	                    left = init;
	                    right = this.parseAssignmentExpression();
	                    init = null;
	                    forIn = false;
	                }
	                else {
	                    init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var'));
	                    this.expect(';');
	                }
	            }
	            else if (this.matchKeyword('const') || this.matchKeyword('let')) {
	                init = this.createNode();
	                var kind = this.nextToken().value;
	                if (!this.context.strict && this.lookahead.value === 'in') {
	                    init = this.finalize(init, new Node.Identifier(kind));
	                    this.nextToken();
	                    left = init;
	                    right = this.parseExpression();
	                    init = null;
	                }
	                else {
	                    var previousAllowIn = this.context.allowIn;
	                    this.context.allowIn = false;
	                    var declarations = this.parseBindingList(kind, { inFor: true });
	                    this.context.allowIn = previousAllowIn;
	                    if (declarations.length === 1 && declarations[0].init === null && this.matchKeyword('in')) {
	                        init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
	                        this.nextToken();
	                        left = init;
	                        right = this.parseExpression();
	                        init = null;
	                    }
	                    else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) {
	                        init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
	                        this.nextToken();
	                        left = init;
	                        right = this.parseAssignmentExpression();
	                        init = null;
	                        forIn = false;
	                    }
	                    else {
	                        this.consumeSemicolon();
	                        init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
	                    }
	                }
	            }
	            else {
	                var initStartToken = this.lookahead;
	                var previousAllowIn = this.context.allowIn;
	                this.context.allowIn = false;
	                init = this.inheritCoverGrammar(this.parseAssignmentExpression);
	                this.context.allowIn = previousAllowIn;
	                if (this.matchKeyword('in')) {
	                    if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) {
	                        this.tolerateError(messages_1.Messages.InvalidLHSInForIn);
	                    }
	                    this.nextToken();
	                    this.reinterpretExpressionAsPattern(init);
	                    left = init;
	                    right = this.parseExpression();
	                    init = null;
	                }
	                else if (this.matchContextualKeyword('of')) {
	                    if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) {
	                        this.tolerateError(messages_1.Messages.InvalidLHSInForLoop);
	                    }
	                    this.nextToken();
	                    this.reinterpretExpressionAsPattern(init);
	                    left = init;
	                    right = this.parseAssignmentExpression();
	                    init = null;
	                    forIn = false;
	                }
	                else {
	                    if (this.match(',')) {
	                        var initSeq = [init];
	                        while (this.match(',')) {
	                            this.nextToken();
	                            initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
	                        }
	                        init = this.finalize(this.startNode(initStartToken), new Node.SequenceExpression(initSeq));
	                    }
	                    this.expect(';');
	                }
	            }
	        }
	        if (typeof left === 'undefined') {
	            if (!this.match(';')) {
	                test = this.parseExpression();
	            }
	            this.expect(';');
	            if (!this.match(')')) {
	                update = this.parseExpression();
	            }
	        }
	        var body;
	        if (!this.match(')') && this.config.tolerant) {
	            this.tolerateUnexpectedToken(this.nextToken());
	            body = this.finalize(this.createNode(), new Node.EmptyStatement());
	        }
	        else {
	            this.expect(')');
	            var previousInIteration = this.context.inIteration;
	            this.context.inIteration = true;
	            body = this.isolateCoverGrammar(this.parseStatement);
	            this.context.inIteration = previousInIteration;
	        }
	        return (typeof left === 'undefined') ?
	            this.finalize(node, new Node.ForStatement(init, test, update, body)) :
	            forIn ? this.finalize(node, new Node.ForInStatement(left, right, body)) :
	                this.finalize(node, new Node.ForOfStatement(left, right, body));
	    };
	    // https://tc39.github.io/ecma262/#sec-continue-statement
	    Parser.prototype.parseContinueStatement = function () {
	        var node = this.createNode();
	        this.expectKeyword('continue');
	        var label = null;
	        if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) {
	            var id = this.parseVariableIdentifier();
	            label = id;
	            var key = '$' + id.name;
	            if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
	                this.throwError(messages_1.Messages.UnknownLabel, id.name);
	            }
	        }
	        this.consumeSemicolon();
	        if (label === null && !this.context.inIteration) {
	            this.throwError(messages_1.Messages.IllegalContinue);
	        }
	        return this.finalize(node, new Node.ContinueStatement(label));
	    };
	    // https://tc39.github.io/ecma262/#sec-break-statement
	    Parser.prototype.parseBreakStatement = function () {
	        var node = this.createNode();
	        this.expectKeyword('break');
	        var label = null;
	        if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) {
	            var id = this.parseVariableIdentifier();
	            var key = '$' + id.name;
	            if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
	                this.throwError(messages_1.Messages.UnknownLabel, id.name);
	            }
	            label = id;
	        }
	        this.consumeSemicolon();
	        if (label === null && !this.context.inIteration && !this.context.inSwitch) {
	            this.throwError(messages_1.Messages.IllegalBreak);
	        }
	        return this.finalize(node, new Node.BreakStatement(label));
	    };
	    // https://tc39.github.io/ecma262/#sec-return-statement
	    Parser.prototype.parseReturnStatement = function () {
	        if (!this.context.inFunctionBody) {
	            this.tolerateError(messages_1.Messages.IllegalReturn);
	        }
	        var node = this.createNode();
	        this.expectKeyword('return');
	        var hasArgument = (!this.match(';') && !this.match('}') &&
	            !this.hasLineTerminator && this.lookahead.type !== 2 /* EOF */) ||
	            this.lookahead.type === 8 /* StringLiteral */ ||
	            this.lookahead.type === 10 /* Template */;
	        var argument = hasArgument ? this.parseExpression() : null;
	        this.consumeSemicolon();
	        return this.finalize(node, new Node.ReturnStatement(argument));
	    };
	    // https://tc39.github.io/ecma262/#sec-with-statement
	    Parser.prototype.parseWithStatement = function () {
	        if (this.context.strict) {
	            this.tolerateError(messages_1.Messages.StrictModeWith);
	        }
	        var node = this.createNode();
	        var body;
	        this.expectKeyword('with');
	        this.expect('(');
	        var object = this.parseExpression();
	        if (!this.match(')') && this.config.tolerant) {
	            this.tolerateUnexpectedToken(this.nextToken());
	            body = this.finalize(this.createNode(), new Node.EmptyStatement());
	        }
	        else {
	            this.expect(')');
	            body = this.parseStatement();
	        }
	        return this.finalize(node, new Node.WithStatement(object, body));
	    };
	    // https://tc39.github.io/ecma262/#sec-switch-statement
	    Parser.prototype.parseSwitchCase = function () {
	        var node = this.createNode();
	        var test;
	        if (this.matchKeyword('default')) {
	            this.nextToken();
	            test = null;
	        }
	        else {
	            this.expectKeyword('case');
	            test = this.parseExpression();
	        }
	        this.expect(':');
	        var consequent = [];
	        while (true) {
	            if (this.match('}') || this.matchKeyword('default') || this.matchKeyword('case')) {
	                break;
	            }
	            consequent.push(this.parseStatementListItem());
	        }
	        return this.finalize(node, new Node.SwitchCase(test, consequent));
	    };
	    Parser.prototype.parseSwitchStatement = function () {
	        var node = this.createNode();
	        this.expectKeyword('switch');
	        this.expect('(');
	        var discriminant = this.parseExpression();
	        this.expect(')');
	        var previousInSwitch = this.context.inSwitch;
	        this.context.inSwitch = true;
	        var cases = [];
	        var defaultFound = false;
	        this.expect('{');
	        while (true) {
	            if (this.match('}')) {
	                break;
	            }
	            var clause = this.parseSwitchCase();
	            if (clause.test === null) {
	                if (defaultFound) {
	                    this.throwError(messages_1.Messages.MultipleDefaultsInSwitch);
	                }
	                defaultFound = true;
	            }
	            cases.push(clause);
	        }
	        this.expect('}');
	        this.context.inSwitch = previousInSwitch;
	        return this.finalize(node, new Node.SwitchStatement(discriminant, cases));
	    };
	    // https://tc39.github.io/ecma262/#sec-labelled-statements
	    Parser.prototype.parseLabelledStatement = function () {
	        var node = this.createNode();
	        var expr = this.parseExpression();
	        var statement;
	        if ((expr.type === syntax_1.Syntax.Identifier) && this.match(':')) {
	            this.nextToken();
	            var id = expr;
	            var key = '$' + id.name;
	            if (Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
	                this.throwError(messages_1.Messages.Redeclaration, 'Label', id.name);
	            }
	            this.context.labelSet[key] = true;
	            var body = void 0;
	            if (this.matchKeyword('class')) {
	                this.tolerateUnexpectedToken(this.lookahead);
	                body = this.parseClassDeclaration();
	            }
	            else if (this.matchKeyword('function')) {
	                var token = this.lookahead;
	                var declaration = this.parseFunctionDeclaration();
	                if (this.context.strict) {
	                    this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunction);
	                }
	                else if (declaration.generator) {
	                    this.tolerateUnexpectedToken(token, messages_1.Messages.GeneratorInLegacyContext);
	                }
	                body = declaration;
	            }
	            else {
	                body = this.parseStatement();
	            }
	            delete this.context.labelSet[key];
	            statement = new Node.LabeledStatement(id, body);
	        }
	        else {
	            this.consumeSemicolon();
	            statement = new Node.ExpressionStatement(expr);
	        }
	        return this.finalize(node, statement);
	    };
	    // https://tc39.github.io/ecma262/#sec-throw-statement
	    Parser.prototype.parseThrowStatement = function () {
	        var node = this.createNode();
	        this.expectKeyword('throw');
	        if (this.hasLineTerminator) {
	            this.throwError(messages_1.Messages.NewlineAfterThrow);
	        }
	        var argument = this.parseExpression();
	        this.consumeSemicolon();
	        return this.finalize(node, new Node.ThrowStatement(argument));
	    };
	    // https://tc39.github.io/ecma262/#sec-try-statement
	    Parser.prototype.parseCatchClause = function () {
	        var node = this.createNode();
	        this.expectKeyword('catch');
	        this.expect('(');
	        if (this.match(')')) {
	            this.throwUnexpectedToken(this.lookahead);
	        }
	        var params = [];
	        var param = this.parsePattern(params);
	        var paramMap = {};
	        for (var i = 0; i < params.length; i++) {
	            var key = '$' + params[i].value;
	            if (Object.prototype.hasOwnProperty.call(paramMap, key)) {
	                this.tolerateError(messages_1.Messages.DuplicateBinding, params[i].value);
	            }
	            paramMap[key] = true;
	        }
	        if (this.context.strict && param.type === syntax_1.Syntax.Identifier) {
	            if (this.scanner.isRestrictedWord(param.name)) {
	                this.tolerateError(messages_1.Messages.StrictCatchVariable);
	            }
	        }
	        this.expect(')');
	        var body = this.parseBlock();
	        return this.finalize(node, new Node.CatchClause(param, body));
	    };
	    Parser.prototype.parseFinallyClause = function () {
	        this.expectKeyword('finally');
	        return this.parseBlock();
	    };
	    Parser.prototype.parseTryStatement = function () {
	        var node = this.createNode();
	        this.expectKeyword('try');
	        var block = this.parseBlock();
	        var handler = this.matchKeyword('catch') ? this.parseCatchClause() : null;
	        var finalizer = this.matchKeyword('finally') ? this.parseFinallyClause() : null;
	        if (!handler && !finalizer) {
	            this.throwError(messages_1.Messages.NoCatchOrFinally);
	        }
	        return this.finalize(node, new Node.TryStatement(block, handler, finalizer));
	    };
	    // https://tc39.github.io/ecma262/#sec-debugger-statement
	    Parser.prototype.parseDebuggerStatement = function () {
	        var node = this.createNode();
	        this.expectKeyword('debugger');
	        this.consumeSemicolon();
	        return this.finalize(node, new Node.DebuggerStatement());
	    };
	    // https://tc39.github.io/ecma262/#sec-ecmascript-language-statements-and-declarations
	    Parser.prototype.parseStatement = function () {
	        var statement;
	        switch (this.lookahead.type) {
	            case 1 /* BooleanLiteral */:
	            case 5 /* NullLiteral */:
	            case 6 /* NumericLiteral */:
	            case 8 /* StringLiteral */:
	            case 10 /* Template */:
	            case 9 /* RegularExpression */:
	                statement = this.parseExpressionStatement();
	                break;
	            case 7 /* Punctuator */:
	                var value = this.lookahead.value;
	                if (value === '{') {
	                    statement = this.parseBlock();
	                }
	                else if (value === '(') {
	                    statement = this.parseExpressionStatement();
	                }
	                else if (value === ';') {
	                    statement = this.parseEmptyStatement();
	                }
	                else {
	                    statement = this.parseExpressionStatement();
	                }
	                break;
	            case 3 /* Identifier */:
	                statement = this.matchAsyncFunction() ? this.parseFunctionDeclaration() : this.parseLabelledStatement();
	                break;
	            case 4 /* Keyword */:
	                switch (this.lookahead.value) {
	                    case 'break':
	                        statement = this.parseBreakStatement();
	                        break;
	                    case 'continue':
	                        statement = this.parseContinueStatement();
	                        break;
	                    case 'debugger':
	                        statement = this.parseDebuggerStatement();
	                        break;
	                    case 'do':
	                        statement = this.parseDoWhileStatement();
	                        break;
	                    case 'for':
	                        statement = this.parseForStatement();
	                        break;
	                    case 'function':
	                        statement = this.parseFunctionDeclaration();
	                        break;
	                    case 'if':
	                        statement = this.parseIfStatement();
	                        break;
	                    case 'return':
	                        statement = this.parseReturnStatement();
	                        break;
	                    case 'switch':
	                        statement = this.parseSwitchStatement();
	                        break;
	                    case 'throw':
	                        statement = this.parseThrowStatement();
	                        break;
	                    case 'try':
	                        statement = this.parseTryStatement();
	                        break;
	                    case 'var':
	                        statement = this.parseVariableStatement();
	                        break;
	                    case 'while':
	                        statement = this.parseWhileStatement();
	                        break;
	                    case 'with':
	                        statement = this.parseWithStatement();
	                        break;
	                    default:
	                        statement = this.parseExpressionStatement();
	                        break;
	                }
	                break;
	            default:
	                statement = this.throwUnexpectedToken(this.lookahead);
	        }
	        return statement;
	    };
	    // https://tc39.github.io/ecma262/#sec-function-definitions
	    Parser.prototype.parseFunctionSourceElements = function () {
	        var node = this.createNode();
	        this.expect('{');
	        var body = this.parseDirectivePrologues();
	        var previousLabelSet = this.context.labelSet;
	        var previousInIteration = this.context.inIteration;
	        var previousInSwitch = this.context.inSwitch;
	        var previousInFunctionBody = this.context.inFunctionBody;
	        this.context.labelSet = {};
	        this.context.inIteration = false;
	        this.context.inSwitch = false;
	        this.context.inFunctionBody = true;
	        while (this.lookahead.type !== 2 /* EOF */) {
	            if (this.match('}')) {
	                break;
	            }
	            body.push(this.parseStatementListItem());
	        }
	        this.expect('}');
	        this.context.labelSet = previousLabelSet;
	        this.context.inIteration = previousInIteration;
	        this.context.inSwitch = previousInSwitch;
	        this.context.inFunctionBody = previousInFunctionBody;
	        return this.finalize(node, new Node.BlockStatement(body));
	    };
	    Parser.prototype.validateParam = function (options, param, name) {
	        var key = '$' + name;
	        if (this.context.strict) {
	            if (this.scanner.isRestrictedWord(name)) {
	                options.stricted = param;
	                options.message = messages_1.Messages.StrictParamName;
	            }
	            if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
	                options.stricted = param;
	                options.message = messages_1.Messages.StrictParamDupe;
	            }
	        }
	        else if (!options.firstRestricted) {
	            if (this.scanner.isRestrictedWord(name)) {
	                options.firstRestricted = param;
	                options.message = messages_1.Messages.StrictParamName;
	            }
	            else if (this.scanner.isStrictModeReservedWord(name)) {
	                options.firstRestricted = param;
	                options.message = messages_1.Messages.StrictReservedWord;
	            }
	            else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
	                options.stricted = param;
	                options.message = messages_1.Messages.StrictParamDupe;
	            }
	        }
	        /* istanbul ignore next */
	        if (typeof Object.defineProperty === 'function') {
	            Object.defineProperty(options.paramSet, key, { value: true, enumerable: true, writable: true, configurable: true });
	        }
	        else {
	            options.paramSet[key] = true;
	        }
	    };
	    Parser.prototype.parseRestElement = function (params) {
	        var node = this.createNode();
	        this.expect('...');
	        var arg = this.parsePattern(params);
	        if (this.match('=')) {
	            this.throwError(messages_1.Messages.DefaultRestParameter);
	        }
	        if (!this.match(')')) {
	            this.throwError(messages_1.Messages.ParameterAfterRestParameter);
	        }
	        return this.finalize(node, new Node.RestElement(arg));
	    };
	    Parser.prototype.parseFormalParameter = function (options) {
	        var params = [];
	        var param = this.match('...') ? this.parseRestElement(params) : this.parsePatternWithDefault(params);
	        for (var i = 0; i < params.length; i++) {
	            this.validateParam(options, params[i], params[i].value);
	        }
	        options.simple = options.simple && (param instanceof Node.Identifier);
	        options.params.push(param);
	    };
	    Parser.prototype.parseFormalParameters = function (firstRestricted) {
	        var options;
	        options = {
	            simple: true,
	            params: [],
	            firstRestricted: firstRestricted
	        };
	        this.expect('(');
	        if (!this.match(')')) {
	            options.paramSet = {};
	            while (this.lookahead.type !== 2 /* EOF */) {
	                this.parseFormalParameter(options);
	                if (this.match(')')) {
	                    break;
	                }
	                this.expect(',');
	                if (this.match(')')) {
	                    break;
	                }
	            }
	        }
	        this.expect(')');
	        return {
	            simple: options.simple,
	            params: options.params,
	            stricted: options.stricted,
	            firstRestricted: options.firstRestricted,
	            message: options.message
	        };
	    };
	    Parser.prototype.matchAsyncFunction = function () {
	        var match = this.matchContextualKeyword('async');
	        if (match) {
	            var state = this.scanner.saveState();
	            this.scanner.scanComments();
	            var next = this.scanner.lex();
	            this.scanner.restoreState(state);
	            match = (state.lineNumber === next.lineNumber) && (next.type === 4 /* Keyword */) && (next.value === 'function');
	        }
	        return match;
	    };
	    Parser.prototype.parseFunctionDeclaration = function (identifierIsOptional) {
	        var node = this.createNode();
	        var isAsync = this.matchContextualKeyword('async');
	        if (isAsync) {
	            this.nextToken();
	        }
	        this.expectKeyword('function');
	        var isGenerator = isAsync ? false : this.match('*');
	        if (isGenerator) {
	            this.nextToken();
	        }
	        var message;
	        var id = null;
	        var firstRestricted = null;
	        if (!identifierIsOptional || !this.match('(')) {
	            var token = this.lookahead;
	            id = this.parseVariableIdentifier();
	            if (this.context.strict) {
	                if (this.scanner.isRestrictedWord(token.value)) {
	                    this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName);
	                }
	            }
	            else {
	                if (this.scanner.isRestrictedWord(token.value)) {
	                    firstRestricted = token;
	                    message = messages_1.Messages.StrictFunctionName;
	                }
	                else if (this.scanner.isStrictModeReservedWord(token.value)) {
	                    firstRestricted = token;
	                    message = messages_1.Messages.StrictReservedWord;
	                }
	            }
	        }
	        var previousAllowAwait = this.context.await;
	        var previousAllowYield = this.context.allowYield;
	        this.context.await = isAsync;
	        this.context.allowYield = !isGenerator;
	        var formalParameters = this.parseFormalParameters(firstRestricted);
	        var params = formalParameters.params;
	        var stricted = formalParameters.stricted;
	        firstRestricted = formalParameters.firstRestricted;
	        if (formalParameters.message) {
	            message = formalParameters.message;
	        }
	        var previousStrict = this.context.strict;
	        var previousAllowStrictDirective = this.context.allowStrictDirective;
	        this.context.allowStrictDirective = formalParameters.simple;
	        var body = this.parseFunctionSourceElements();
	        if (this.context.strict && firstRestricted) {
	            this.throwUnexpectedToken(firstRestricted, message);
	        }
	        if (this.context.strict && stricted) {
	            this.tolerateUnexpectedToken(stricted, message);
	        }
	        this.context.strict = previousStrict;
	        this.context.allowStrictDirective = previousAllowStrictDirective;
	        this.context.await = previousAllowAwait;
	        this.context.allowYield = previousAllowYield;
	        return isAsync ? this.finalize(node, new Node.AsyncFunctionDeclaration(id, params, body)) :
	            this.finalize(node, new Node.FunctionDeclaration(id, params, body, isGenerator));
	    };
	    Parser.prototype.parseFunctionExpression = function () {
	        var node = this.createNode();
	        var isAsync = this.matchContextualKeyword('async');
	        if (isAsync) {
	            this.nextToken();
	        }
	        this.expectKeyword('function');
	        var isGenerator = isAsync ? false : this.match('*');
	        if (isGenerator) {
	            this.nextToken();
	        }
	        var message;
	        var id = null;
	        var firstRestricted;
	        var previousAllowAwait = this.context.await;
	        var previousAllowYield = this.context.allowYield;
	        this.context.await = isAsync;
	        this.context.allowYield = !isGenerator;
	        if (!this.match('(')) {
	            var token = this.lookahead;
	            id = (!this.context.strict && !isGenerator && this.matchKeyword('yield')) ? this.parseIdentifierName() : this.parseVariableIdentifier();
	            if (this.context.strict) {
	                if (this.scanner.isRestrictedWord(token.value)) {
	                    this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName);
	                }
	            }
	            else {
	                if (this.scanner.isRestrictedWord(token.value)) {
	                    firstRestricted = token;
	                    message = messages_1.Messages.StrictFunctionName;
	                }
	                else if (this.scanner.isStrictModeReservedWord(token.value)) {
	                    firstRestricted = token;
	                    message = messages_1.Messages.StrictReservedWord;
	                }
	            }
	        }
	        var formalParameters = this.parseFormalParameters(firstRestricted);
	        var params = formalParameters.params;
	        var stricted = formalParameters.stricted;
	        firstRestricted = formalParameters.firstRestricted;
	        if (formalParameters.message) {
	            message = formalParameters.message;
	        }
	        var previousStrict = this.context.strict;
	        var previousAllowStrictDirective = this.context.allowStrictDirective;
	        this.context.allowStrictDirective = formalParameters.simple;
	        var body = this.parseFunctionSourceElements();
	        if (this.context.strict && firstRestricted) {
	            this.throwUnexpectedToken(firstRestricted, message);
	        }
	        if (this.context.strict && stricted) {
	            this.tolerateUnexpectedToken(stricted, message);
	        }
	        this.context.strict = previousStrict;
	        this.context.allowStrictDirective = previousAllowStrictDirective;
	        this.context.await = previousAllowAwait;
	        this.context.allowYield = previousAllowYield;
	        return isAsync ? this.finalize(node, new Node.AsyncFunctionExpression(id, params, body)) :
	            this.finalize(node, new Node.FunctionExpression(id, params, body, isGenerator));
	    };
	    // https://tc39.github.io/ecma262/#sec-directive-prologues-and-the-use-strict-directive
	    Parser.prototype.parseDirective = function () {
	        var token = this.lookahead;
	        var node = this.createNode();
	        var expr = this.parseExpression();
	        var directive = (expr.type === syntax_1.Syntax.Literal) ? this.getTokenRaw(token).slice(1, -1) : null;
	        this.consumeSemicolon();
	        return this.finalize(node, directive ? new Node.Directive(expr, directive) : new Node.ExpressionStatement(expr));
	    };
	    Parser.prototype.parseDirectivePrologues = function () {
	        var firstRestricted = null;
	        var body = [];
	        while (true) {
	            var token = this.lookahead;
	            if (token.type !== 8 /* StringLiteral */) {
	                break;
	            }
	            var statement = this.parseDirective();
	            body.push(statement);
	            var directive = statement.directive;
	            if (typeof directive !== 'string') {
	                break;
	            }
	            if (directive === 'use strict') {
	                this.context.strict = true;
	                if (firstRestricted) {
	                    this.tolerateUnexpectedToken(firstRestricted, messages_1.Messages.StrictOctalLiteral);
	                }
	                if (!this.context.allowStrictDirective) {
	                    this.tolerateUnexpectedToken(token, messages_1.Messages.IllegalLanguageModeDirective);
	                }
	            }
	            else {
	                if (!firstRestricted && token.octal) {
	                    firstRestricted = token;
	                }
	            }
	        }
	        return body;
	    };
	    // https://tc39.github.io/ecma262/#sec-method-definitions
	    Parser.prototype.qualifiedPropertyName = function (token) {
	        switch (token.type) {
	            case 3 /* Identifier */:
	            case 8 /* StringLiteral */:
	            case 1 /* BooleanLiteral */:
	            case 5 /* NullLiteral */:
	            case 6 /* NumericLiteral */:
	            case 4 /* Keyword */:
	                return true;
	            case 7 /* Punctuator */:
	                return token.value === '[';
	            default:
	                break;
	        }
	        return false;
	    };
	    Parser.prototype.parseGetterMethod = function () {
	        var node = this.createNode();
	        var isGenerator = false;
	        var previousAllowYield = this.context.allowYield;
	        this.context.allowYield = !isGenerator;
	        var formalParameters = this.parseFormalParameters();
	        if (formalParameters.params.length > 0) {
	            this.tolerateError(messages_1.Messages.BadGetterArity);
	        }
	        var method = this.parsePropertyMethod(formalParameters);
	        this.context.allowYield = previousAllowYield;
	        return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator));
	    };
	    Parser.prototype.parseSetterMethod = function () {
	        var node = this.createNode();
	        var isGenerator = false;
	        var previousAllowYield = this.context.allowYield;
	        this.context.allowYield = !isGenerator;
	        var formalParameters = this.parseFormalParameters();
	        if (formalParameters.params.length !== 1) {
	            this.tolerateError(messages_1.Messages.BadSetterArity);
	        }
	        else if (formalParameters.params[0] instanceof Node.RestElement) {
	            this.tolerateError(messages_1.Messages.BadSetterRestParameter);
	        }
	        var method = this.parsePropertyMethod(formalParameters);
	        this.context.allowYield = previousAllowYield;
	        return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator));
	    };
	    Parser.prototype.parseGeneratorMethod = function () {
	        var node = this.createNode();
	        var isGenerator = true;
	        var previousAllowYield = this.context.allowYield;
	        this.context.allowYield = true;
	        var params = this.parseFormalParameters();
	        this.context.allowYield = false;
	        var method = this.parsePropertyMethod(params);
	        this.context.allowYield = previousAllowYield;
	        return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator));
	    };
	    // https://tc39.github.io/ecma262/#sec-generator-function-definitions
	    Parser.prototype.isStartOfExpression = function () {
	        var start = true;
	        var value = this.lookahead.value;
	        switch (this.lookahead.type) {
	            case 7 /* Punctuator */:
	                start = (value === '[') || (value === '(') || (value === '{') ||
	                    (value === '+') || (value === '-') ||
	                    (value === '!') || (value === '~') ||
	                    (value === '++') || (value === '--') ||
	                    (value === '/') || (value === '/='); // regular expression literal
	                break;
	            case 4 /* Keyword */:
	                start = (value === 'class') || (value === 'delete') ||
	                    (value === 'function') || (value === 'let') || (value === 'new') ||
	                    (value === 'super') || (value === 'this') || (value === 'typeof') ||
	                    (value === 'void') || (value === 'yield');
	                break;
	            default:
	                break;
	        }
	        return start;
	    };
	    Parser.prototype.parseYieldExpression = function () {
	        var node = this.createNode();
	        this.expectKeyword('yield');
	        var argument = null;
	        var delegate = false;
	        if (!this.hasLineTerminator) {
	            var previousAllowYield = this.context.allowYield;
	            this.context.allowYield = false;
	            delegate = this.match('*');
	            if (delegate) {
	                this.nextToken();
	                argument = this.parseAssignmentExpression();
	            }
	            else if (this.isStartOfExpression()) {
	                argument = this.parseAssignmentExpression();
	            }
	            this.context.allowYield = previousAllowYield;
	        }
	        return this.finalize(node, new Node.YieldExpression(argument, delegate));
	    };
	    // https://tc39.github.io/ecma262/#sec-class-definitions
	    Parser.prototype.parseClassElement = function (hasConstructor) {
	        var token = this.lookahead;
	        var node = this.createNode();
	        var kind = '';
	        var key = null;
	        var value = null;
	        var computed = false;
	        var method = false;
	        var isStatic = false;
	        var isAsync = false;
	        if (this.match('*')) {
	            this.nextToken();
	        }
	        else {
	            computed = this.match('[');
	            key = this.parseObjectPropertyKey();
	            var id = key;
	            if (id.name === 'static' && (this.qualifiedPropertyName(this.lookahead) || this.match('*'))) {
	                token = this.lookahead;
	                isStatic = true;
	                computed = this.match('[');
	                if (this.match('*')) {
	                    this.nextToken();
	                }
	                else {
	                    key = this.parseObjectPropertyKey();
	                }
	            }
	            if ((token.type === 3 /* Identifier */) && !this.hasLineTerminator && (token.value === 'async')) {
	                var punctuator = this.lookahead.value;
	                if (punctuator !== ':' && punctuator !== '(' && punctuator !== '*') {
	                    isAsync = true;
	                    token = this.lookahead;
	                    key = this.parseObjectPropertyKey();
	                    if (token.type === 3 /* Identifier */ && token.value === 'constructor') {
	                        this.tolerateUnexpectedToken(token, messages_1.Messages.ConstructorIsAsync);
	                    }
	                }
	            }
	        }
	        var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
	        if (token.type === 3 /* Identifier */) {
	            if (token.value === 'get' && lookaheadPropertyKey) {
	                kind = 'get';
	                computed = this.match('[');
	                key = this.parseObjectPropertyKey();
	                this.context.allowYield = false;
	                value = this.parseGetterMethod();
	            }
	            else if (token.value === 'set' && lookaheadPropertyKey) {
	                kind = 'set';
	                computed = this.match('[');
	                key = this.parseObjectPropertyKey();
	                value = this.parseSetterMethod();
	            }
	        }
	        else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) {
	            kind = 'init';
	            computed = this.match('[');
	            key = this.parseObjectPropertyKey();
	            value = this.parseGeneratorMethod();
	            method = true;
	        }
	        if (!kind && key && this.match('(')) {
	            kind = 'init';
	            value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
	            method = true;
	        }
	        if (!kind) {
	            this.throwUnexpectedToken(this.lookahead);
	        }
	        if (kind === 'init') {
	            kind = 'method';
	        }
	        if (!computed) {
	            if (isStatic && this.isPropertyKey(key, 'prototype')) {
	                this.throwUnexpectedToken(token, messages_1.Messages.StaticPrototype);
	            }
	            if (!isStatic && this.isPropertyKey(key, 'constructor')) {
	                if (kind !== 'method' || !method || (value && value.generator)) {
	                    this.throwUnexpectedToken(token, messages_1.Messages.ConstructorSpecialMethod);
	                }
	                if (hasConstructor.value) {
	                    this.throwUnexpectedToken(token, messages_1.Messages.DuplicateConstructor);
	                }
	                else {
	                    hasConstructor.value = true;
	                }
	                kind = 'constructor';
	            }
	        }
	        return this.finalize(node, new Node.MethodDefinition(key, computed, value, kind, isStatic));
	    };
	    Parser.prototype.parseClassElementList = function () {
	        var body = [];
	        var hasConstructor = { value: false };
	        this.expect('{');
	        while (!this.match('}')) {
	            if (this.match(';')) {
	                this.nextToken();
	            }
	            else {
	                body.push(this.parseClassElement(hasConstructor));
	            }
	        }
	        this.expect('}');
	        return body;
	    };
	    Parser.prototype.parseClassBody = function () {
	        var node = this.createNode();
	        var elementList = this.parseClassElementList();
	        return this.finalize(node, new Node.ClassBody(elementList));
	    };
	    Parser.prototype.parseClassDeclaration = function (identifierIsOptional) {
	        var node = this.createNode();
	        var previousStrict = this.context.strict;
	        this.context.strict = true;
	        this.expectKeyword('class');
	        var id = (identifierIsOptional && (this.lookahead.type !== 3 /* Identifier */)) ? null : this.parseVariableIdentifier();
	        var superClass = null;
	        if (this.matchKeyword('extends')) {
	            this.nextToken();
	            superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
	        }
	        var classBody = this.parseClassBody();
	        this.context.strict = previousStrict;
	        return this.finalize(node, new Node.ClassDeclaration(id, superClass, classBody));
	    };
	    Parser.prototype.parseClassExpression = function () {
	        var node = this.createNode();
	        var previousStrict = this.context.strict;
	        this.context.strict = true;
	        this.expectKeyword('class');
	        var id = (this.lookahead.type === 3 /* Identifier */) ? this.parseVariableIdentifier() : null;
	        var superClass = null;
	        if (this.matchKeyword('extends')) {
	            this.nextToken();
	            superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
	        }
	        var classBody = this.parseClassBody();
	        this.context.strict = previousStrict;
	        return this.finalize(node, new Node.ClassExpression(id, superClass, classBody));
	    };
	    // https://tc39.github.io/ecma262/#sec-scripts
	    // https://tc39.github.io/ecma262/#sec-modules
	    Parser.prototype.parseModule = function () {
	        this.context.strict = true;
	        this.context.isModule = true;
	        this.scanner.isModule = true;
	        var node = this.createNode();
	        var body = this.parseDirectivePrologues();
	        while (this.lookahead.type !== 2 /* EOF */) {
	            body.push(this.parseStatementListItem());
	        }
	        return this.finalize(node, new Node.Module(body));
	    };
	    Parser.prototype.parseScript = function () {
	        var node = this.createNode();
	        var body = this.parseDirectivePrologues();
	        while (this.lookahead.type !== 2 /* EOF */) {
	            body.push(this.parseStatementListItem());
	        }
	        return this.finalize(node, new Node.Script(body));
	    };
	    // https://tc39.github.io/ecma262/#sec-imports
	    Parser.prototype.parseModuleSpecifier = function () {
	        var node = this.createNode();
	        if (this.lookahead.type !== 8 /* StringLiteral */) {
	            this.throwError(messages_1.Messages.InvalidModuleSpecifier);
	        }
	        var token = this.nextToken();
	        var raw = this.getTokenRaw(token);
	        return this.finalize(node, new Node.Literal(token.value, raw));
	    };
	    // import {<foo as bar>} ...;
	    Parser.prototype.parseImportSpecifier = function () {
	        var node = this.createNode();
	        var imported;
	        var local;
	        if (this.lookahead.type === 3 /* Identifier */) {
	            imported = this.parseVariableIdentifier();
	            local = imported;
	            if (this.matchContextualKeyword('as')) {
	                this.nextToken();
	                local = this.parseVariableIdentifier();
	            }
	        }
	        else {
	            imported = this.parseIdentifierName();
	            local = imported;
	            if (this.matchContextualKeyword('as')) {
	                this.nextToken();
	                local = this.parseVariableIdentifier();
	            }
	            else {
	                this.throwUnexpectedToken(this.nextToken());
	            }
	        }
	        return this.finalize(node, new Node.ImportSpecifier(local, imported));
	    };
	    // {foo, bar as bas}
	    Parser.prototype.parseNamedImports = function () {
	        this.expect('{');
	        var specifiers = [];
	        while (!this.match('}')) {
	            specifiers.push(this.parseImportSpecifier());
	            if (!this.match('}')) {
	                this.expect(',');
	            }
	        }
	        this.expect('}');
	        return specifiers;
	    };
	    // import <foo> ...;
	    Parser.prototype.parseImportDefaultSpecifier = function () {
	        var node = this.createNode();
	        var local = this.parseIdentifierName();
	        return this.finalize(node, new Node.ImportDefaultSpecifier(local));
	    };
	    // import <* as foo> ...;
	    Parser.prototype.parseImportNamespaceSpecifier = function () {
	        var node = this.createNode();
	        this.expect('*');
	        if (!this.matchContextualKeyword('as')) {
	            this.throwError(messages_1.Messages.NoAsAfterImportNamespace);
	        }
	        this.nextToken();
	        var local = this.parseIdentifierName();
	        return this.finalize(node, new Node.ImportNamespaceSpecifier(local));
	    };
	    Parser.prototype.parseImportDeclaration = function () {
	        if (this.context.inFunctionBody) {
	            this.throwError(messages_1.Messages.IllegalImportDeclaration);
	        }
	        var node = this.createNode();
	        this.expectKeyword('import');
	        var src;
	        var specifiers = [];
	        if (this.lookahead.type === 8 /* StringLiteral */) {
	            // import 'foo';
	            src = this.parseModuleSpecifier();
	        }
	        else {
	            if (this.match('{')) {
	                // import {bar}
	                specifiers = specifiers.concat(this.parseNamedImports());
	            }
	            else if (this.match('*')) {
	                // import * as foo
	                specifiers.push(this.parseImportNamespaceSpecifier());
	            }
	            else if (this.isIdentifierName(this.lookahead) && !this.matchKeyword('default')) {
	                // import foo
	                specifiers.push(this.parseImportDefaultSpecifier());
	                if (this.match(',')) {
	                    this.nextToken();
	                    if (this.match('*')) {
	                        // import foo, * as foo
	                        specifiers.push(this.parseImportNamespaceSpecifier());
	                    }
	                    else if (this.match('{')) {
	                        // import foo, {bar}
	                        specifiers = specifiers.concat(this.parseNamedImports());
	                    }
	                    else {
	                        this.throwUnexpectedToken(this.lookahead);
	                    }
	                }
	            }
	            else {
	                this.throwUnexpectedToken(this.nextToken());
	            }
	            if (!this.matchContextualKeyword('from')) {
	                var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
	                this.throwError(message, this.lookahead.value);
	            }
	            this.nextToken();
	            src = this.parseModuleSpecifier();
	        }
	        this.consumeSemicolon();
	        return this.finalize(node, new Node.ImportDeclaration(specifiers, src));
	    };
	    // https://tc39.github.io/ecma262/#sec-exports
	    Parser.prototype.parseExportSpecifier = function () {
	        var node = this.createNode();
	        var local = this.parseIdentifierName();
	        var exported = local;
	        if (this.matchContextualKeyword('as')) {
	            this.nextToken();
	            exported = this.parseIdentifierName();
	        }
	        return this.finalize(node, new Node.ExportSpecifier(local, exported));
	    };
	    Parser.prototype.parseExportDeclaration = function () {
	        if (this.context.inFunctionBody) {
	            this.throwError(messages_1.Messages.IllegalExportDeclaration);
	        }
	        var node = this.createNode();
	        this.expectKeyword('export');
	        var exportDeclaration;
	        if (this.matchKeyword('default')) {
	            // export default ...
	            this.nextToken();
	            if (this.matchKeyword('function')) {
	                // export default function foo () {}
	                // export default function () {}
	                var declaration = this.parseFunctionDeclaration(true);
	                exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
	            }
	            else if (this.matchKeyword('class')) {
	                // export default class foo {}
	                var declaration = this.parseClassDeclaration(true);
	                exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
	            }
	            else if (this.matchContextualKeyword('async')) {
	                // export default async function f () {}
	                // export default async function () {}
	                // export default async x => x
	                var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression();
	                exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
	            }
	            else {
	                if (this.matchContextualKeyword('from')) {
	                    this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value);
	                }
	                // export default {};
	                // export default [];
	                // export default (1 + 2);
	                var declaration = this.match('{') ? this.parseObjectInitializer() :
	                    this.match('[') ? this.parseArrayInitializer() : this.parseAssignmentExpression();
	                this.consumeSemicolon();
	                exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
	            }
	        }
	        else if (this.match('*')) {
	            // export * from 'foo';
	            this.nextToken();
	            if (!this.matchContextualKeyword('from')) {
	                var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
	                this.throwError(message, this.lookahead.value);
	            }
	            this.nextToken();
	            var src = this.parseModuleSpecifier();
	            this.consumeSemicolon();
	            exportDeclaration = this.finalize(node, new Node.ExportAllDeclaration(src));
	        }
	        else if (this.lookahead.type === 4 /* Keyword */) {
	            // export var f = 1;
	            var declaration = void 0;
	            switch (this.lookahead.value) {
	                case 'let':
	                case 'const':
	                    declaration = this.parseLexicalDeclaration({ inFor: false });
	                    break;
	                case 'var':
	                case 'class':
	                case 'function':
	                    declaration = this.parseStatementListItem();
	                    break;
	                default:
	                    this.throwUnexpectedToken(this.lookahead);
	            }
	            exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null));
	        }
	        else if (this.matchAsyncFunction()) {
	            var declaration = this.parseFunctionDeclaration();
	            exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null));
	        }
	        else {
	            var specifiers = [];
	            var source = null;
	            var isExportFromIdentifier = false;
	            this.expect('{');
	            while (!this.match('}')) {
	                isExportFromIdentifier = isExportFromIdentifier || this.matchKeyword('default');
	                specifiers.push(this.parseExportSpecifier());
	                if (!this.match('}')) {
	                    this.expect(',');
	                }
	            }
	            this.expect('}');
	            if (this.matchContextualKeyword('from')) {
	                // export {default} from 'foo';
	                // export {foo} from 'foo';
	                this.nextToken();
	                source = this.parseModuleSpecifier();
	                this.consumeSemicolon();
	            }
	            else if (isExportFromIdentifier) {
	                // export {default}; // missing fromClause
	                var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
	                this.throwError(message, this.lookahead.value);
	            }
	            else {
	                // export {foo};
	                this.consumeSemicolon();
	            }
	            exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(null, specifiers, source));
	        }
	        return exportDeclaration;
	    };
	    return Parser;
	}());
	exports.Parser = Parser;


/***/ },
/* 9 */
/***/ function(module, exports) {

	"use strict";
	// Ensure the condition is true, otherwise throw an error.
	// This is only to have a better contract semantic, i.e. another safety net
	// to catch a logic error. The condition shall be fulfilled in normal case.
	// Do NOT use this to enforce a certain condition on any user input.
	Object.defineProperty(exports, "__esModule", { value: true });
	function assert(condition, message) {
	    /* istanbul ignore if */
	    if (!condition) {
	        throw new Error('ASSERT: ' + message);
	    }
	}
	exports.assert = assert;


/***/ },
/* 10 */
/***/ function(module, exports) {

	"use strict";
	/* tslint:disable:max-classes-per-file */
	Object.defineProperty(exports, "__esModule", { value: true });
	var ErrorHandler = (function () {
	    function ErrorHandler() {
	        this.errors = [];
	        this.tolerant = false;
	    }
	    ErrorHandler.prototype.recordError = function (error) {
	        this.errors.push(error);
	    };
	    ErrorHandler.prototype.tolerate = function (error) {
	        if (this.tolerant) {
	            this.recordError(error);
	        }
	        else {
	            throw error;
	        }
	    };
	    ErrorHandler.prototype.constructError = function (msg, column) {
	        var error = new Error(msg);
	        try {
	            throw error;
	        }
	        catch (base) {
	            /* istanbul ignore else */
	            if (Object.create && Object.defineProperty) {
	                error = Object.create(base);
	                Object.defineProperty(error, 'column', { value: column });
	            }
	        }
	        /* istanbul ignore next */
	        return error;
	    };
	    ErrorHandler.prototype.createError = function (index, line, col, description) {
	        var msg = 'Line ' + line + ': ' + description;
	        var error = this.constructError(msg, col);
	        error.index = index;
	        error.lineNumber = line;
	        error.description = description;
	        return error;
	    };
	    ErrorHandler.prototype.throwError = function (index, line, col, description) {
	        throw this.createError(index, line, col, description);
	    };
	    ErrorHandler.prototype.tolerateError = function (index, line, col, description) {
	        var error = this.createError(index, line, col, description);
	        if (this.tolerant) {
	            this.recordError(error);
	        }
	        else {
	            throw error;
	        }
	    };
	    return ErrorHandler;
	}());
	exports.ErrorHandler = ErrorHandler;


/***/ },
/* 11 */
/***/ function(module, exports) {

	"use strict";
	Object.defineProperty(exports, "__esModule", { value: true });
	// Error messages should be identical to V8.
	exports.Messages = {
	    BadGetterArity: 'Getter must not have any formal parameters',
	    BadSetterArity: 'Setter must have exactly one formal parameter',
	    BadSetterRestParameter: 'Setter function argument must not be a rest parameter',
	    ConstructorIsAsync: 'Class constructor may not be an async method',
	    ConstructorSpecialMethod: 'Class constructor may not be an accessor',
	    DeclarationMissingInitializer: 'Missing initializer in %0 declaration',
	    DefaultRestParameter: 'Unexpected token =',
	    DuplicateBinding: 'Duplicate binding %0',
	    DuplicateConstructor: 'A class may only have one constructor',
	    DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals',
	    ForInOfLoopInitializer: '%0 loop variable declaration may not have an initializer',
	    GeneratorInLegacyContext: 'Generator declarations are not allowed in legacy contexts',
	    IllegalBreak: 'Illegal break statement',
	    IllegalContinue: 'Illegal continue statement',
	    IllegalExportDeclaration: 'Unexpected token',
	    IllegalImportDeclaration: 'Unexpected token',
	    IllegalLanguageModeDirective: 'Illegal \'use strict\' directive in function with non-simple parameter list',
	    IllegalReturn: 'Illegal return statement',
	    InvalidEscapedReservedWord: 'Keyword must not contain escaped characters',
	    InvalidHexEscapeSequence: 'Invalid hexadecimal escape sequence',
	    InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
	    InvalidLHSInForIn: 'Invalid left-hand side in for-in',
	    InvalidLHSInForLoop: 'Invalid left-hand side in for-loop',
	    InvalidModuleSpecifier: 'Unexpected token',
	    InvalidRegExp: 'Invalid regular expression',
	    LetInLexicalBinding: 'let is disallowed as a lexically bound name',
	    MissingFromClause: 'Unexpected token',
	    MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
	    NewlineAfterThrow: 'Illegal newline after throw',
	    NoAsAfterImportNamespace: 'Unexpected token',
	    NoCatchOrFinally: 'Missing catch or finally after try',
	    ParameterAfterRestParameter: 'Rest parameter must be last formal parameter',
	    Redeclaration: '%0 \'%1\' has already been declared',
	    StaticPrototype: 'Classes may not have static property named prototype',
	    StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
	    StrictDelete: 'Delete of an unqualified identifier in strict mode.',
	    StrictFunction: 'In strict mode code, functions can only be declared at top level or inside a block',
	    StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
	    StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
	    StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
	    StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
	    StrictModeWith: 'Strict mode code may not include a with statement',
	    StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
	    StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
	    StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
	    StrictReservedWord: 'Use of future reserved word in strict mode',
	    StrictVarName: 'Variable name may not be eval or arguments in strict mode',
	    TemplateOctalLiteral: 'Octal literals are not allowed in template strings.',
	    UnexpectedEOS: 'Unexpected end of input',
	    UnexpectedIdentifier: 'Unexpected identifier',
	    UnexpectedNumber: 'Unexpected number',
	    UnexpectedReserved: 'Unexpected reserved word',
	    UnexpectedString: 'Unexpected string',
	    UnexpectedTemplate: 'Unexpected quasi %0',
	    UnexpectedToken: 'Unexpected token %0',
	    UnexpectedTokenIllegal: 'Unexpected token ILLEGAL',
	    UnknownLabel: 'Undefined label \'%0\'',
	    UnterminatedRegExp: 'Invalid regular expression: missing /'
	};


/***/ },
/* 12 */
/***/ function(module, exports, __nested_webpack_require_226595__) {

	"use strict";
	Object.defineProperty(exports, "__esModule", { value: true });
	var assert_1 = __nested_webpack_require_226595__(9);
	var character_1 = __nested_webpack_require_226595__(4);
	var messages_1 = __nested_webpack_require_226595__(11);
	function hexValue(ch) {
	    return '0123456789abcdef'.indexOf(ch.toLowerCase());
	}
	function octalValue(ch) {
	    return '01234567'.indexOf(ch);
	}
	var Scanner = (function () {
	    function Scanner(code, handler) {
	        this.source = code;
	        this.errorHandler = handler;
	        this.trackComment = false;
	        this.isModule = false;
	        this.length = code.length;
	        this.index = 0;
	        this.lineNumber = (code.length > 0) ? 1 : 0;
	        this.lineStart = 0;
	        this.curlyStack = [];
	    }
	    Scanner.prototype.saveState = function () {
	        return {
	            index: this.index,
	            lineNumber: this.lineNumber,
	            lineStart: this.lineStart
	        };
	    };
	    Scanner.prototype.restoreState = function (state) {
	        this.index = state.index;
	        this.lineNumber = state.lineNumber;
	        this.lineStart = state.lineStart;
	    };
	    Scanner.prototype.eof = function () {
	        return this.index >= this.length;
	    };
	    Scanner.prototype.throwUnexpectedToken = function (message) {
	        if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; }
	        return this.errorHandler.throwError(this.index, this.lineNumber, this.index - this.lineStart + 1, message);
	    };
	    Scanner.prototype.tolerateUnexpectedToken = function (message) {
	        if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; }
	        this.errorHandler.tolerateError(this.index, this.lineNumber, this.index - this.lineStart + 1, message);
	    };
	    // https://tc39.github.io/ecma262/#sec-comments
	    Scanner.prototype.skipSingleLineComment = function (offset) {
	        var comments = [];
	        var start, loc;
	        if (this.trackComment) {
	            comments = [];
	            start = this.index - offset;
	            loc = {
	                start: {
	                    line: this.lineNumber,
	                    column: this.index - this.lineStart - offset
	                },
	                end: {}
	            };
	        }
	        while (!this.eof()) {
	            var ch = this.source.charCodeAt(this.index);
	            ++this.index;
	            if (character_1.Character.isLineTerminator(ch)) {
	                if (this.trackComment) {
	                    loc.end = {
	                        line: this.lineNumber,
	                        column: this.index - this.lineStart - 1
	                    };
	                    var entry = {
	                        multiLine: false,
	                        slice: [start + offset, this.index - 1],
	                        range: [start, this.index - 1],
	                        loc: loc
	                    };
	                    comments.push(entry);
	                }
	                if (ch === 13 && this.source.charCodeAt(this.index) === 10) {
	                    ++this.index;
	                }
	                ++this.lineNumber;
	                this.lineStart = this.index;
	                return comments;
	            }
	        }
	        if (this.trackComment) {
	            loc.end = {
	                line: this.lineNumber,
	                column: this.index - this.lineStart
	            };
	            var entry = {
	                multiLine: false,
	                slice: [start + offset, this.index],
	                range: [start, this.index],
	                loc: loc
	            };
	            comments.push(entry);
	        }
	        return comments;
	    };
	    Scanner.prototype.skipMultiLineComment = function () {
	        var comments = [];
	        var start, loc;
	        if (this.trackComment) {
	            comments = [];
	            start = this.index - 2;
	            loc = {
	                start: {
	                    line: this.lineNumber,
	                    column: this.index - this.lineStart - 2
	                },
	                end: {}
	            };
	        }
	        while (!this.eof()) {
	            var ch = this.source.charCodeAt(this.index);
	            if (character_1.Character.isLineTerminator(ch)) {
	                if (ch === 0x0D && this.source.charCodeAt(this.index + 1) === 0x0A) {
	                    ++this.index;
	                }
	                ++this.lineNumber;
	                ++this.index;
	                this.lineStart = this.index;
	            }
	            else if (ch === 0x2A) {
	                // Block comment ends with '*/'.
	                if (this.source.charCodeAt(this.index + 1) === 0x2F) {
	                    this.index += 2;
	                    if (this.trackComment) {
	                        loc.end = {
	                            line: this.lineNumber,
	                            column: this.index - this.lineStart
	                        };
	                        var entry = {
	                            multiLine: true,
	                            slice: [start + 2, this.index - 2],
	                            range: [start, this.index],
	                            loc: loc
	                        };
	                        comments.push(entry);
	                    }
	                    return comments;
	                }
	                ++this.index;
	            }
	            else {
	                ++this.index;
	            }
	        }
	        // Ran off the end of the file - the whole thing is a comment
	        if (this.trackComment) {
	            loc.end = {
	                line: this.lineNumber,
	                column: this.index - this.lineStart
	            };
	            var entry = {
	                multiLine: true,
	                slice: [start + 2, this.index],
	                range: [start, this.index],
	                loc: loc
	            };
	            comments.push(entry);
	        }
	        this.tolerateUnexpectedToken();
	        return comments;
	    };
	    Scanner.prototype.scanComments = function () {
	        var comments;
	        if (this.trackComment) {
	            comments = [];
	        }
	        var start = (this.index === 0);
	        while (!this.eof()) {
	            var ch = this.source.charCodeAt(this.index);
	            if (character_1.Character.isWhiteSpace(ch)) {
	                ++this.index;
	            }
	            else if (character_1.Character.isLineTerminator(ch)) {
	                ++this.index;
	                if (ch === 0x0D && this.source.charCodeAt(this.index) === 0x0A) {
	                    ++this.index;
	                }
	                ++this.lineNumber;
	                this.lineStart = this.index;
	                start = true;
	            }
	            else if (ch === 0x2F) {
	                ch = this.source.charCodeAt(this.index + 1);
	                if (ch === 0x2F) {
	                    this.index += 2;
	                    var comment = this.skipSingleLineComment(2);
	                    if (this.trackComment) {
	                        comments = comments.concat(comment);
	                    }
	                    start = true;
	                }
	                else if (ch === 0x2A) {
	                    this.index += 2;
	                    var comment = this.skipMultiLineComment();
	                    if (this.trackComment) {
	                        comments = comments.concat(comment);
	                    }
	                }
	                else {
	                    break;
	                }
	            }
	            else if (start && ch === 0x2D) {
	                // U+003E is '>'
	                if ((this.source.charCodeAt(this.index + 1) === 0x2D) && (this.source.charCodeAt(this.index + 2) === 0x3E)) {
	                    // '-->' is a single-line comment
	                    this.index += 3;
	                    var comment = this.skipSingleLineComment(3);
	                    if (this.trackComment) {
	                        comments = comments.concat(comment);
	                    }
	                }
	                else {
	                    break;
	                }
	            }
	            else if (ch === 0x3C && !this.isModule) {
	                if (this.source.slice(this.index + 1, this.index + 4) === '!--') {
	                    this.index += 4; // `<!--`
	                    var comment = this.skipSingleLineComment(4);
	                    if (this.trackComment) {
	                        comments = comments.concat(comment);
	                    }
	                }
	                else {
	                    break;
	                }
	            }
	            else {
	                break;
	            }
	        }
	        return comments;
	    };
	    // https://tc39.github.io/ecma262/#sec-future-reserved-words
	    Scanner.prototype.isFutureReservedWord = function (id) {
	        switch (id) {
	            case 'enum':
	            case 'export':
	            case 'import':
	            case 'super':
	                return true;
	            default:
	                return false;
	        }
	    };
	    Scanner.prototype.isStrictModeReservedWord = function (id) {
	        switch (id) {
	            case 'implements':
	            case 'interface':
	            case 'package':
	            case 'private':
	            case 'protected':
	            case 'public':
	            case 'static':
	            case 'yield':
	            case 'let':
	                return true;
	            default:
	                return false;
	        }
	    };
	    Scanner.prototype.isRestrictedWord = function (id) {
	        return id === 'eval' || id === 'arguments';
	    };
	    // https://tc39.github.io/ecma262/#sec-keywords
	    Scanner.prototype.isKeyword = function (id) {
	        switch (id.length) {
	            case 2:
	                return (id === 'if') || (id === 'in') || (id === 'do');
	            case 3:
	                return (id === 'var') || (id === 'for') || (id === 'new') ||
	                    (id === 'try') || (id === 'let');
	            case 4:
	                return (id === 'this') || (id === 'else') || (id === 'case') ||
	                    (id === 'void') || (id === 'with') || (id === 'enum');
	            case 5:
	                return (id === 'while') || (id === 'break') || (id === 'catch') ||
	                    (id === 'throw') || (id === 'const') || (id === 'yield') ||
	                    (id === 'class') || (id === 'super');
	            case 6:
	                return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
	                    (id === 'switch') || (id === 'export') || (id === 'import');
	            case 7:
	                return (id === 'default') || (id === 'finally') || (id === 'extends');
	            case 8:
	                return (id === 'function') || (id === 'continue') || (id === 'debugger');
	            case 10:
	                return (id === 'instanceof');
	            default:
	                return false;
	        }
	    };
	    Scanner.prototype.codePointAt = function (i) {
	        var cp = this.source.charCodeAt(i);
	        if (cp >= 0xD800 && cp <= 0xDBFF) {
	            var second = this.source.charCodeAt(i + 1);
	            if (second >= 0xDC00 && second <= 0xDFFF) {
	                var first = cp;
	                cp = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
	            }
	        }
	        return cp;
	    };
	    Scanner.prototype.scanHexEscape = function (prefix) {
	        var len = (prefix === 'u') ? 4 : 2;
	        var code = 0;
	        for (var i = 0; i < len; ++i) {
	            if (!this.eof() && character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
	                code = code * 16 + hexValue(this.source[this.index++]);
	            }
	            else {
	                return null;
	            }
	        }
	        return String.fromCharCode(code);
	    };
	    Scanner.prototype.scanUnicodeCodePointEscape = function () {
	        var ch = this.source[this.index];
	        var code = 0;
	        // At least, one hex digit is required.
	        if (ch === '}') {
	            this.throwUnexpectedToken();
	        }
	        while (!this.eof()) {
	            ch = this.source[this.index++];
	            if (!character_1.Character.isHexDigit(ch.charCodeAt(0))) {
	                break;
	            }
	            code = code * 16 + hexValue(ch);
	        }
	        if (code > 0x10FFFF || ch !== '}') {
	            this.throwUnexpectedToken();
	        }
	        return character_1.Character.fromCodePoint(code);
	    };
	    Scanner.prototype.getIdentifier = function () {
	        var start = this.index++;
	        while (!this.eof()) {
	            var ch = this.source.charCodeAt(this.index);
	            if (ch === 0x5C) {
	                // Blackslash (U+005C) marks Unicode escape sequence.
	                this.index = start;
	                return this.getComplexIdentifier();
	            }
	            else if (ch >= 0xD800 && ch < 0xDFFF) {
	                // Need to handle surrogate pairs.
	                this.index = start;
	                return this.getComplexIdentifier();
	            }
	            if (character_1.Character.isIdentifierPart(ch)) {
	                ++this.index;
	            }
	            else {
	                break;
	            }
	        }
	        return this.source.slice(start, this.index);
	    };
	    Scanner.prototype.getComplexIdentifier = function () {
	        var cp = this.codePointAt(this.index);
	        var id = character_1.Character.fromCodePoint(cp);
	        this.index += id.length;
	        // '\u' (U+005C, U+0075) denotes an escaped character.
	        var ch;
	        if (cp === 0x5C) {
	            if (this.source.charCodeAt(this.index) !== 0x75) {
	                this.throwUnexpectedToken();
	            }
	            ++this.index;
	            if (this.source[this.index] === '{') {
	                ++this.index;
	                ch = this.scanUnicodeCodePointEscape();
	            }
	            else {
	                ch = this.scanHexEscape('u');
	                if (ch === null || ch === '\\' || !character_1.Character.isIdentifierStart(ch.charCodeAt(0))) {
	                    this.throwUnexpectedToken();
	                }
	            }
	            id = ch;
	        }
	        while (!this.eof()) {
	            cp = this.codePointAt(this.index);
	            if (!character_1.Character.isIdentifierPart(cp)) {
	                break;
	            }
	            ch = character_1.Character.fromCodePoint(cp);
	            id += ch;
	            this.index += ch.length;
	            // '\u' (U+005C, U+0075) denotes an escaped character.
	            if (cp === 0x5C) {
	                id = id.substr(0, id.length - 1);
	                if (this.source.charCodeAt(this.index) !== 0x75) {
	                    this.throwUnexpectedToken();
	                }
	                ++this.index;
	                if (this.source[this.index] === '{') {
	                    ++this.index;
	                    ch = this.scanUnicodeCodePointEscape();
	                }
	                else {
	                    ch = this.scanHexEscape('u');
	                    if (ch === null || ch === '\\' || !character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
	                        this.throwUnexpectedToken();
	                    }
	                }
	                id += ch;
	            }
	        }
	        return id;
	    };
	    Scanner.prototype.octalToDecimal = function (ch) {
	        // \0 is not octal escape sequence
	        var octal = (ch !== '0');
	        var code = octalValue(ch);
	        if (!this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
	            octal = true;
	            code = code * 8 + octalValue(this.source[this.index++]);
	            // 3 digits are only allowed when string starts
	            // with 0, 1, 2, 3
	            if ('0123'.indexOf(ch) >= 0 && !this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
	                code = code * 8 + octalValue(this.source[this.index++]);
	            }
	        }
	        return {
	            code: code,
	            octal: octal
	        };
	    };
	    // https://tc39.github.io/ecma262/#sec-names-and-keywords
	    Scanner.prototype.scanIdentifier = function () {
	        var type;
	        var start = this.index;
	        // Backslash (U+005C) starts an escaped character.
	        var id = (this.source.charCodeAt(start) === 0x5C) ? this.getComplexIdentifier() : this.getIdentifier();
	        // There is no keyword or literal with only one character.
	        // Thus, it must be an identifier.
	        if (id.length === 1) {
	            type = 3 /* Identifier */;
	        }
	        else if (this.isKeyword(id)) {
	            type = 4 /* Keyword */;
	        }
	        else if (id === 'null') {
	            type = 5 /* NullLiteral */;
	        }
	        else if (id === 'true' || id === 'false') {
	            type = 1 /* BooleanLiteral */;
	        }
	        else {
	            type = 3 /* Identifier */;
	        }
	        if (type !== 3 /* Identifier */ && (start + id.length !== this.index)) {
	            var restore = this.index;
	            this.index = start;
	            this.tolerateUnexpectedToken(messages_1.Messages.InvalidEscapedReservedWord);
	            this.index = restore;
	        }
	        return {
	            type: type,
	            value: id,
	            lineNumber: this.lineNumber,
	            lineStart: this.lineStart,
	            start: start,
	            end: this.index
	        };
	    };
	    // https://tc39.github.io/ecma262/#sec-punctuators
	    Scanner.prototype.scanPunctuator = function () {
	        var start = this.index;
	        // Check for most common single-character punctuators.
	        var str = this.source[this.index];
	        switch (str) {
	            case '(':
	            case '{':
	                if (str === '{') {
	                    this.curlyStack.push('{');
	                }
	                ++this.index;
	                break;
	            case '.':
	                ++this.index;
	                if (this.source[this.index] === '.' && this.source[this.index + 1] === '.') {
	                    // Spread operator: ...
	                    this.index += 2;
	                    str = '...';
	                }
	                break;
	            case '}':
	                ++this.index;
	                this.curlyStack.pop();
	                break;
	            case ')':
	            case ';':
	            case ',':
	            case '[':
	            case ']':
	            case ':':
	            case '?':
	            case '~':
	                ++this.index;
	                break;
	            default:
	                // 4-character punctuator.
	                str = this.source.substr(this.index, 4);
	                if (str === '>>>=') {
	                    this.index += 4;
	                }
	                else {
	                    // 3-character punctuators.
	                    str = str.substr(0, 3);
	                    if (str === '===' || str === '!==' || str === '>>>' ||
	                        str === '<<=' || str === '>>=' || str === '**=') {
	                        this.index += 3;
	                    }
	                    else {
	                        // 2-character punctuators.
	                        str = str.substr(0, 2);
	                        if (str === '&&' || str === '||' || str === '==' || str === '!=' ||
	                            str === '+=' || str === '-=' || str === '*=' || str === '/=' ||
	                            str === '++' || str === '--' || str === '<<' || str === '>>' ||
	                            str === '&=' || str === '|=' || str === '^=' || str === '%=' ||
	                            str === '<=' || str === '>=' || str === '=>' || str === '**') {
	                            this.index += 2;
	                        }
	                        else {
	                            // 1-character punctuators.
	                            str = this.source[this.index];
	                            if ('<>=!+-*%&|^/'.indexOf(str) >= 0) {
	                                ++this.index;
	                            }
	                        }
	                    }
	                }
	        }
	        if (this.index === start) {
	            this.throwUnexpectedToken();
	        }
	        return {
	            type: 7 /* Punctuator */,
	            value: str,
	            lineNumber: this.lineNumber,
	            lineStart: this.lineStart,
	            start: start,
	            end: this.index
	        };
	    };
	    // https://tc39.github.io/ecma262/#sec-literals-numeric-literals
	    Scanner.prototype.scanHexLiteral = function (start) {
	        var num = '';
	        while (!this.eof()) {
	            if (!character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
	                break;
	            }
	            num += this.source[this.index++];
	        }
	        if (num.length === 0) {
	            this.throwUnexpectedToken();
	        }
	        if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
	            this.throwUnexpectedToken();
	        }
	        return {
	            type: 6 /* NumericLiteral */,
	            value: parseInt('0x' + num, 16),
	            lineNumber: this.lineNumber,
	            lineStart: this.lineStart,
	            start: start,
	            end: this.index
	        };
	    };
	    Scanner.prototype.scanBinaryLiteral = function (start) {
	        var num = '';
	        var ch;
	        while (!this.eof()) {
	            ch = this.source[this.index];
	            if (ch !== '0' && ch !== '1') {
	                break;
	            }
	            num += this.source[this.index++];
	        }
	        if (num.length === 0) {
	            // only 0b or 0B
	            this.throwUnexpectedToken();
	        }
	        if (!this.eof()) {
	            ch = this.source.charCodeAt(this.index);
	            /* istanbul ignore else */
	            if (character_1.Character.isIdentifierStart(ch) || character_1.Character.isDecimalDigit(ch)) {
	                this.throwUnexpectedToken();
	            }
	        }
	        return {
	            type: 6 /* NumericLiteral */,
	            value: parseInt(num, 2),
	            lineNumber: this.lineNumber,
	            lineStart: this.lineStart,
	            start: start,
	            end: this.index
	        };
	    };
	    Scanner.prototype.scanOctalLiteral = function (prefix, start) {
	        var num = '';
	        var octal = false;
	        if (character_1.Character.isOctalDigit(prefix.charCodeAt(0))) {
	            octal = true;
	            num = '0' + this.source[this.index++];
	        }
	        else {
	            ++this.index;
	        }
	        while (!this.eof()) {
	            if (!character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
	                break;
	            }
	            num += this.source[this.index++];
	        }
	        if (!octal && num.length === 0) {
	            // only 0o or 0O
	            this.throwUnexpectedToken();
	        }
	        if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index)) || character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
	            this.throwUnexpectedToken();
	        }
	        return {
	            type: 6 /* NumericLiteral */,
	            value: parseInt(num, 8),
	            octal: octal,
	            lineNumber: this.lineNumber,
	            lineStart: this.lineStart,
	            start: start,
	            end: this.index
	        };
	    };
	    Scanner.prototype.isImplicitOctalLiteral = function () {
	        // Implicit octal, unless there is a non-octal digit.
	        // (Annex B.1.1 on Numeric Literals)
	        for (var i = this.index + 1; i < this.length; ++i) {
	            var ch = this.source[i];
	            if (ch === '8' || ch === '9') {
	                return false;
	            }
	            if (!character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
	                return true;
	            }
	        }
	        return true;
	    };
	    Scanner.prototype.scanNumericLiteral = function () {
	        var start = this.index;
	        var ch = this.source[start];
	        assert_1.assert(character_1.Character.isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point');
	        var num = '';
	        if (ch !== '.') {
	            num = this.source[this.index++];
	            ch = this.source[this.index];
	            // Hex number starts with '0x'.
	            // Octal number starts with '0'.
	            // Octal number in ES6 starts with '0o'.
	            // Binary number in ES6 starts with '0b'.
	            if (num === '0') {
	                if (ch === 'x' || ch === 'X') {
	                    ++this.index;
	                    return this.scanHexLiteral(start);
	                }
	                if (ch === 'b' || ch === 'B') {
	                    ++this.index;
	                    return this.scanBinaryLiteral(start);
	                }
	                if (ch === 'o' || ch === 'O') {
	                    return this.scanOctalLiteral(ch, start);
	                }
	                if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
	                    if (this.isImplicitOctalLiteral()) {
	                        return this.scanOctalLiteral(ch, start);
	                    }
	                }
	            }
	            while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
	                num += this.source[this.index++];
	            }
	            ch = this.source[this.index];
	        }
	        if (ch === '.') {
	            num += this.source[this.index++];
	            while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
	                num += this.source[this.index++];
	            }
	            ch = this.source[this.index];
	        }
	        if (ch === 'e' || ch === 'E') {
	            num += this.source[this.index++];
	            ch = this.source[this.index];
	            if (ch === '+' || ch === '-') {
	                num += this.source[this.index++];
	            }
	            if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
	                while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
	                    num += this.source[this.index++];
	                }
	            }
	            else {
	                this.throwUnexpectedToken();
	            }
	        }
	        if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
	            this.throwUnexpectedToken();
	        }
	        return {
	            type: 6 /* NumericLiteral */,
	            value: parseFloat(num),
	            lineNumber: this.lineNumber,
	            lineStart: this.lineStart,
	            start: start,
	            end: this.index
	        };
	    };
	    // https://tc39.github.io/ecma262/#sec-literals-string-literals
	    Scanner.prototype.scanStringLiteral = function () {
	        var start = this.index;
	        var quote = this.source[start];
	        assert_1.assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote');
	        ++this.index;
	        var octal = false;
	        var str = '';
	        while (!this.eof()) {
	            var ch = this.source[this.index++];
	            if (ch === quote) {
	                quote = '';
	                break;
	            }
	            else if (ch === '\\') {
	                ch = this.source[this.index++];
	                if (!ch || !character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
	                    switch (ch) {
	                        case 'u':
	                            if (this.source[this.index] === '{') {
	                                ++this.index;
	                                str += this.scanUnicodeCodePointEscape();
	                            }
	                            else {
	                                var unescaped_1 = this.scanHexEscape(ch);
	                                if (unescaped_1 === null) {
	                                    this.throwUnexpectedToken();
	                                }
	                                str += unescaped_1;
	                            }
	                            break;
	                        case 'x':
	                            var unescaped = this.scanHexEscape(ch);
	                            if (unescaped === null) {
	                                this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence);
	                            }
	                            str += unescaped;
	                            break;
	                        case 'n':
	                            str += '\n';
	                            break;
	                        case 'r':
	                            str += '\r';
	                            break;
	                        case 't':
	                            str += '\t';
	                            break;
	                        case 'b':
	                            str += '\b';
	                            break;
	                        case 'f':
	                            str += '\f';
	                            break;
	                        case 'v':
	                            str += '\x0B';
	                            break;
	                        case '8':
	                        case '9':
	                            str += ch;
	                            this.tolerateUnexpectedToken();
	                            break;
	                        default:
	                            if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
	                                var octToDec = this.octalToDecimal(ch);
	                                octal = octToDec.octal || octal;
	                                str += String.fromCharCode(octToDec.code);
	                            }
	                            else {
	                                str += ch;
	                            }
	                            break;
	                    }
	                }
	                else {
	                    ++this.lineNumber;
	                    if (ch === '\r' && this.source[this.index] === '\n') {
	                        ++this.index;
	                    }
	                    this.lineStart = this.index;
	                }
	            }
	            else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
	                break;
	            }
	            else {
	                str += ch;
	            }
	        }
	        if (quote !== '') {
	            this.index = start;
	            this.throwUnexpectedToken();
	        }
	        return {
	            type: 8 /* StringLiteral */,
	            value: str,
	            octal: octal,
	            lineNumber: this.lineNumber,
	            lineStart: this.lineStart,
	            start: start,
	            end: this.index
	        };
	    };
	    // https://tc39.github.io/ecma262/#sec-template-literal-lexical-components
	    Scanner.prototype.scanTemplate = function () {
	        var cooked = '';
	        var terminated = false;
	        var start = this.index;
	        var head = (this.source[start] === '`');
	        var tail = false;
	        var rawOffset = 2;
	        ++this.index;
	        while (!this.eof()) {
	            var ch = this.source[this.index++];
	            if (ch === '`') {
	                rawOffset = 1;
	                tail = true;
	                terminated = true;
	                break;
	            }
	            else if (ch === '$') {
	                if (this.source[this.index] === '{') {
	                    this.curlyStack.push('${');
	                    ++this.index;
	                    terminated = true;
	                    break;
	                }
	                cooked += ch;
	            }
	            else if (ch === '\\') {
	                ch = this.source[this.index++];
	                if (!character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
	                    switch (ch) {
	                        case 'n':
	                            cooked += '\n';
	                            break;
	                        case 'r':
	                            cooked += '\r';
	                            break;
	                        case 't':
	                            cooked += '\t';
	                            break;
	                        case 'u':
	                            if (this.source[this.index] === '{') {
	                                ++this.index;
	                                cooked += this.scanUnicodeCodePointEscape();
	                            }
	                            else {
	                                var restore = this.index;
	                                var unescaped_2 = this.scanHexEscape(ch);
	                                if (unescaped_2 !== null) {
	                                    cooked += unescaped_2;
	                                }
	                                else {
	                                    this.index = restore;
	                                    cooked += ch;
	                                }
	                            }
	                            break;
	                        case 'x':
	                            var unescaped = this.scanHexEscape(ch);
	                            if (unescaped === null) {
	                                this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence);
	                            }
	                            cooked += unescaped;
	                            break;
	                        case 'b':
	                            cooked += '\b';
	                            break;
	                        case 'f':
	                            cooked += '\f';
	                            break;
	                        case 'v':
	                            cooked += '\v';
	                            break;
	                        default:
	                            if (ch === '0') {
	                                if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
	                                    // Illegal: \01 \02 and so on
	                                    this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
	                                }
	                                cooked += '\0';
	                            }
	                            else if (character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
	                                // Illegal: \1 \2
	                                this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
	                            }
	                            else {
	                                cooked += ch;
	                            }
	                            break;
	                    }
	                }
	                else {
	                    ++this.lineNumber;
	                    if (ch === '\r' && this.source[this.index] === '\n') {
	                        ++this.index;
	                    }
	                    this.lineStart = this.index;
	                }
	            }
	            else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
	                ++this.lineNumber;
	                if (ch === '\r' && this.source[this.index] === '\n') {
	                    ++this.index;
	                }
	                this.lineStart = this.index;
	                cooked += '\n';
	            }
	            else {
	                cooked += ch;
	            }
	        }
	        if (!terminated) {
	            this.throwUnexpectedToken();
	        }
	        if (!head) {
	            this.curlyStack.pop();
	        }
	        return {
	            type: 10 /* Template */,
	            value: this.source.slice(start + 1, this.index - rawOffset),
	            cooked: cooked,
	            head: head,
	            tail: tail,
	            lineNumber: this.lineNumber,
	            lineStart: this.lineStart,
	            start: start,
	            end: this.index
	        };
	    };
	    // https://tc39.github.io/ecma262/#sec-literals-regular-expression-literals
	    Scanner.prototype.testRegExp = function (pattern, flags) {
	        // The BMP character to use as a replacement for astral symbols when
	        // translating an ES6 "u"-flagged pattern to an ES5-compatible
	        // approximation.
	        // Note: replacing with '\uFFFF' enables false positives in unlikely
	        // scenarios. For example, `[\u{1044f}-\u{10440}]` is an invalid
	        // pattern that would not be detected by this substitution.
	        var astralSubstitute = '\uFFFF';
	        var tmp = pattern;
	        var self = this;
	        if (flags.indexOf('u') >= 0) {
	            tmp = tmp
	                .replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function ($0, $1, $2) {
	                var codePoint = parseInt($1 || $2, 16);
	                if (codePoint > 0x10FFFF) {
	                    self.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
	                }
	                if (codePoint <= 0xFFFF) {
	                    return String.fromCharCode(codePoint);
	                }
	                return astralSubstitute;
	            })
	                .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, astralSubstitute);
	        }
	        // First, detect invalid regular expressions.
	        try {
	            RegExp(tmp);
	        }
	        catch (e) {
	            this.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
	        }
	        // Return a regular expression object for this pattern-flag pair, or
	        // `null` in case the current environment doesn't support the flags it
	        // uses.
	        try {
	            return new RegExp(pattern, flags);
	        }
	        catch (exception) {
	            /* istanbul ignore next */
	            return null;
	        }
	    };
	    Scanner.prototype.scanRegExpBody = function () {
	        var ch = this.source[this.index];
	        assert_1.assert(ch === '/', 'Regular expression literal must start with a slash');
	        var str = this.source[this.index++];
	        var classMarker = false;
	        var terminated = false;
	        while (!this.eof()) {
	            ch = this.source[this.index++];
	            str += ch;
	            if (ch === '\\') {
	                ch = this.source[this.index++];
	                // https://tc39.github.io/ecma262/#sec-literals-regular-expression-literals
	                if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
	                    this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
	                }
	                str += ch;
	            }
	            else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
	                this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
	            }
	            else if (classMarker) {
	                if (ch === ']') {
	                    classMarker = false;
	                }
	            }
	            else {
	                if (ch === '/') {
	                    terminated = true;
	                    break;
	                }
	                else if (ch === '[') {
	                    classMarker = true;
	                }
	            }
	        }
	        if (!terminated) {
	            this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
	        }
	        // Exclude leading and trailing slash.
	        return str.substr(1, str.length - 2);
	    };
	    Scanner.prototype.scanRegExpFlags = function () {
	        var str = '';
	        var flags = '';
	        while (!this.eof()) {
	            var ch = this.source[this.index];
	            if (!character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
	                break;
	            }
	            ++this.index;
	            if (ch === '\\' && !this.eof()) {
	                ch = this.source[this.index];
	                if (ch === 'u') {
	                    ++this.index;
	                    var restore = this.index;
	                    var char = this.scanHexEscape('u');
	                    if (char !== null) {
	                        flags += char;
	                        for (str += '\\u'; restore < this.index; ++restore) {
	                            str += this.source[restore];
	                        }
	                    }
	                    else {
	                        this.index = restore;
	                        flags += 'u';
	                        str += '\\u';
	                    }
	                    this.tolerateUnexpectedToken();
	                }
	                else {
	                    str += '\\';
	                    this.tolerateUnexpectedToken();
	                }
	            }
	            else {
	                flags += ch;
	                str += ch;
	            }
	        }
	        return flags;
	    };
	    Scanner.prototype.scanRegExp = function () {
	        var start = this.index;
	        var pattern = this.scanRegExpBody();
	        var flags = this.scanRegExpFlags();
	        var value = this.testRegExp(pattern, flags);
	        return {
	            type: 9 /* RegularExpression */,
	            value: '',
	            pattern: pattern,
	            flags: flags,
	            regex: value,
	            lineNumber: this.lineNumber,
	            lineStart: this.lineStart,
	            start: start,
	            end: this.index
	        };
	    };
	    Scanner.prototype.lex = function () {
	        if (this.eof()) {
	            return {
	                type: 2 /* EOF */,
	                value: '',
	                lineNumber: this.lineNumber,
	                lineStart: this.lineStart,
	                start: this.index,
	                end: this.index
	            };
	        }
	        var cp = this.source.charCodeAt(this.index);
	        if (character_1.Character.isIdentifierStart(cp)) {
	            return this.scanIdentifier();
	        }
	        // Very common: ( and ) and ;
	        if (cp === 0x28 || cp === 0x29 || cp === 0x3B) {
	            return this.scanPunctuator();
	        }
	        // String literal starts with single quote (U+0027) or double quote (U+0022).
	        if (cp === 0x27 || cp === 0x22) {
	            return this.scanStringLiteral();
	        }
	        // Dot (.) U+002E can also start a floating-point number, hence the need
	        // to check the next character.
	        if (cp === 0x2E) {
	            if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index + 1))) {
	                return this.scanNumericLiteral();
	            }
	            return this.scanPunctuator();
	        }
	        if (character_1.Character.isDecimalDigit(cp)) {
	            return this.scanNumericLiteral();
	        }
	        // Template literals start with ` (U+0060) for template head
	        // or } (U+007D) for template middle or template tail.
	        if (cp === 0x60 || (cp === 0x7D && this.curlyStack[this.curlyStack.length - 1] === '${')) {
	            return this.scanTemplate();
	        }
	        // Possible identifier start in a surrogate pair.
	        if (cp >= 0xD800 && cp < 0xDFFF) {
	            if (character_1.Character.isIdentifierStart(this.codePointAt(this.index))) {
	                return this.scanIdentifier();
	            }
	        }
	        return this.scanPunctuator();
	    };
	    return Scanner;
	}());
	exports.Scanner = Scanner;


/***/ },
/* 13 */
/***/ function(module, exports) {

	"use strict";
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.TokenName = {};
	exports.TokenName[1 /* BooleanLiteral */] = 'Boolean';
	exports.TokenName[2 /* EOF */] = '<end>';
	exports.TokenName[3 /* Identifier */] = 'Identifier';
	exports.TokenName[4 /* Keyword */] = 'Keyword';
	exports.TokenName[5 /* NullLiteral */] = 'Null';
	exports.TokenName[6 /* NumericLiteral */] = 'Numeric';
	exports.TokenName[7 /* Punctuator */] = 'Punctuator';
	exports.TokenName[8 /* StringLiteral */] = 'String';
	exports.TokenName[9 /* RegularExpression */] = 'RegularExpression';
	exports.TokenName[10 /* Template */] = 'Template';


/***/ },
/* 14 */
/***/ function(module, exports) {

	"use strict";
	// Generated by generate-xhtml-entities.js. DO NOT MODIFY!
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.XHTMLEntities = {
	    quot: '\u0022',
	    amp: '\u0026',
	    apos: '\u0027',
	    gt: '\u003E',
	    nbsp: '\u00A0',
	    iexcl: '\u00A1',
	    cent: '\u00A2',
	    pound: '\u00A3',
	    curren: '\u00A4',
	    yen: '\u00A5',
	    brvbar: '\u00A6',
	    sect: '\u00A7',
	    uml: '\u00A8',
	    copy: '\u00A9',
	    ordf: '\u00AA',
	    laquo: '\u00AB',
	    not: '\u00AC',
	    shy: '\u00AD',
	    reg: '\u00AE',
	    macr: '\u00AF',
	    deg: '\u00B0',
	    plusmn: '\u00B1',
	    sup2: '\u00B2',
	    sup3: '\u00B3',
	    acute: '\u00B4',
	    micro: '\u00B5',
	    para: '\u00B6',
	    middot: '\u00B7',
	    cedil: '\u00B8',
	    sup1: '\u00B9',
	    ordm: '\u00BA',
	    raquo: '\u00BB',
	    frac14: '\u00BC',
	    frac12: '\u00BD',
	    frac34: '\u00BE',
	    iquest: '\u00BF',
	    Agrave: '\u00C0',
	    Aacute: '\u00C1',
	    Acirc: '\u00C2',
	    Atilde: '\u00C3',
	    Auml: '\u00C4',
	    Aring: '\u00C5',
	    AElig: '\u00C6',
	    Ccedil: '\u00C7',
	    Egrave: '\u00C8',
	    Eacute: '\u00C9',
	    Ecirc: '\u00CA',
	    Euml: '\u00CB',
	    Igrave: '\u00CC',
	    Iacute: '\u00CD',
	    Icirc: '\u00CE',
	    Iuml: '\u00CF',
	    ETH: '\u00D0',
	    Ntilde: '\u00D1',
	    Ograve: '\u00D2',
	    Oacute: '\u00D3',
	    Ocirc: '\u00D4',
	    Otilde: '\u00D5',
	    Ouml: '\u00D6',
	    times: '\u00D7',
	    Oslash: '\u00D8',
	    Ugrave: '\u00D9',
	    Uacute: '\u00DA',
	    Ucirc: '\u00DB',
	    Uuml: '\u00DC',
	    Yacute: '\u00DD',
	    THORN: '\u00DE',
	    szlig: '\u00DF',
	    agrave: '\u00E0',
	    aacute: '\u00E1',
	    acirc: '\u00E2',
	    atilde: '\u00E3',
	    auml: '\u00E4',
	    aring: '\u00E5',
	    aelig: '\u00E6',
	    ccedil: '\u00E7',
	    egrave: '\u00E8',
	    eacute: '\u00E9',
	    ecirc: '\u00EA',
	    euml: '\u00EB',
	    igrave: '\u00EC',
	    iacute: '\u00ED',
	    icirc: '\u00EE',
	    iuml: '\u00EF',
	    eth: '\u00F0',
	    ntilde: '\u00F1',
	    ograve: '\u00F2',
	    oacute: '\u00F3',
	    ocirc: '\u00F4',
	    otilde: '\u00F5',
	    ouml: '\u00F6',
	    divide: '\u00F7',
	    oslash: '\u00F8',
	    ugrave: '\u00F9',
	    uacute: '\u00FA',
	    ucirc: '\u00FB',
	    uuml: '\u00FC',
	    yacute: '\u00FD',
	    thorn: '\u00FE',
	    yuml: '\u00FF',
	    OElig: '\u0152',
	    oelig: '\u0153',
	    Scaron: '\u0160',
	    scaron: '\u0161',
	    Yuml: '\u0178',
	    fnof: '\u0192',
	    circ: '\u02C6',
	    tilde: '\u02DC',
	    Alpha: '\u0391',
	    Beta: '\u0392',
	    Gamma: '\u0393',
	    Delta: '\u0394',
	    Epsilon: '\u0395',
	    Zeta: '\u0396',
	    Eta: '\u0397',
	    Theta: '\u0398',
	    Iota: '\u0399',
	    Kappa: '\u039A',
	    Lambda: '\u039B',
	    Mu: '\u039C',
	    Nu: '\u039D',
	    Xi: '\u039E',
	    Omicron: '\u039F',
	    Pi: '\u03A0',
	    Rho: '\u03A1',
	    Sigma: '\u03A3',
	    Tau: '\u03A4',
	    Upsilon: '\u03A5',
	    Phi: '\u03A6',
	    Chi: '\u03A7',
	    Psi: '\u03A8',
	    Omega: '\u03A9',
	    alpha: '\u03B1',
	    beta: '\u03B2',
	    gamma: '\u03B3',
	    delta: '\u03B4',
	    epsilon: '\u03B5',
	    zeta: '\u03B6',
	    eta: '\u03B7',
	    theta: '\u03B8',
	    iota: '\u03B9',
	    kappa: '\u03BA',
	    lambda: '\u03BB',
	    mu: '\u03BC',
	    nu: '\u03BD',
	    xi: '\u03BE',
	    omicron: '\u03BF',
	    pi: '\u03C0',
	    rho: '\u03C1',
	    sigmaf: '\u03C2',
	    sigma: '\u03C3',
	    tau: '\u03C4',
	    upsilon: '\u03C5',
	    phi: '\u03C6',
	    chi: '\u03C7',
	    psi: '\u03C8',
	    omega: '\u03C9',
	    thetasym: '\u03D1',
	    upsih: '\u03D2',
	    piv: '\u03D6',
	    ensp: '\u2002',
	    emsp: '\u2003',
	    thinsp: '\u2009',
	    zwnj: '\u200C',
	    zwj: '\u200D',
	    lrm: '\u200E',
	    rlm: '\u200F',
	    ndash: '\u2013',
	    mdash: '\u2014',
	    lsquo: '\u2018',
	    rsquo: '\u2019',
	    sbquo: '\u201A',
	    ldquo: '\u201C',
	    rdquo: '\u201D',
	    bdquo: '\u201E',
	    dagger: '\u2020',
	    Dagger: '\u2021',
	    bull: '\u2022',
	    hellip: '\u2026',
	    permil: '\u2030',
	    prime: '\u2032',
	    Prime: '\u2033',
	    lsaquo: '\u2039',
	    rsaquo: '\u203A',
	    oline: '\u203E',
	    frasl: '\u2044',
	    euro: '\u20AC',
	    image: '\u2111',
	    weierp: '\u2118',
	    real: '\u211C',
	    trade: '\u2122',
	    alefsym: '\u2135',
	    larr: '\u2190',
	    uarr: '\u2191',
	    rarr: '\u2192',
	    darr: '\u2193',
	    harr: '\u2194',
	    crarr: '\u21B5',
	    lArr: '\u21D0',
	    uArr: '\u21D1',
	    rArr: '\u21D2',
	    dArr: '\u21D3',
	    hArr: '\u21D4',
	    forall: '\u2200',
	    part: '\u2202',
	    exist: '\u2203',
	    empty: '\u2205',
	    nabla: '\u2207',
	    isin: '\u2208',
	    notin: '\u2209',
	    ni: '\u220B',
	    prod: '\u220F',
	    sum: '\u2211',
	    minus: '\u2212',
	    lowast: '\u2217',
	    radic: '\u221A',
	    prop: '\u221D',
	    infin: '\u221E',
	    ang: '\u2220',
	    and: '\u2227',
	    or: '\u2228',
	    cap: '\u2229',
	    cup: '\u222A',
	    int: '\u222B',
	    there4: '\u2234',
	    sim: '\u223C',
	    cong: '\u2245',
	    asymp: '\u2248',
	    ne: '\u2260',
	    equiv: '\u2261',
	    le: '\u2264',
	    ge: '\u2265',
	    sub: '\u2282',
	    sup: '\u2283',
	    nsub: '\u2284',
	    sube: '\u2286',
	    supe: '\u2287',
	    oplus: '\u2295',
	    otimes: '\u2297',
	    perp: '\u22A5',
	    sdot: '\u22C5',
	    lceil: '\u2308',
	    rceil: '\u2309',
	    lfloor: '\u230A',
	    rfloor: '\u230B',
	    loz: '\u25CA',
	    spades: '\u2660',
	    clubs: '\u2663',
	    hearts: '\u2665',
	    diams: '\u2666',
	    lang: '\u27E8',
	    rang: '\u27E9'
	};


/***/ },
/* 15 */
/***/ function(module, exports, __nested_webpack_require_277122__) {

	"use strict";
	Object.defineProperty(exports, "__esModule", { value: true });
	var error_handler_1 = __nested_webpack_require_277122__(10);
	var scanner_1 = __nested_webpack_require_277122__(12);
	var token_1 = __nested_webpack_require_277122__(13);
	var Reader = (function () {
	    function Reader() {
	        this.values = [];
	        this.curly = this.paren = -1;
	    }
	    // A function following one of those tokens is an expression.
	    Reader.prototype.beforeFunctionExpression = function (t) {
	        return ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
	            'return', 'case', 'delete', 'throw', 'void',
	            // assignment operators
	            '=', '+=', '-=', '*=', '**=', '/=', '%=', '<<=', '>>=', '>>>=',
	            '&=', '|=', '^=', ',',
	            // binary/unary operators
	            '+', '-', '*', '**', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
	            '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
	            '<=', '<', '>', '!=', '!=='].indexOf(t) >= 0;
	    };
	    // Determine if forward slash (/) is an operator or part of a regular expression
	    // https://github.com/mozilla/sweet.js/wiki/design
	    Reader.prototype.isRegexStart = function () {
	        var previous = this.values[this.values.length - 1];
	        var regex = (previous !== null);
	        switch (previous) {
	            case 'this':
	            case ']':
	                regex = false;
	                break;
	            case ')':
	                var keyword = this.values[this.paren - 1];
	                regex = (keyword === 'if' || keyword === 'while' || keyword === 'for' || keyword === 'with');
	                break;
	            case '}':
	                // Dividing a function by anything makes little sense,
	                // but we have to check for that.
	                regex = false;
	                if (this.values[this.curly - 3] === 'function') {
	                    // Anonymous function, e.g. function(){} /42
	                    var check = this.values[this.curly - 4];
	                    regex = check ? !this.beforeFunctionExpression(check) : false;
	                }
	                else if (this.values[this.curly - 4] === 'function') {
	                    // Named function, e.g. function f(){} /42/
	                    var check = this.values[this.curly - 5];
	                    regex = check ? !this.beforeFunctionExpression(check) : true;
	                }
	                break;
	            default:
	                break;
	        }
	        return regex;
	    };
	    Reader.prototype.push = function (token) {
	        if (token.type === 7 /* Punctuator */ || token.type === 4 /* Keyword */) {
	            if (token.value === '{') {
	                this.curly = this.values.length;
	            }
	            else if (token.value === '(') {
	                this.paren = this.values.length;
	            }
	            this.values.push(token.value);
	        }
	        else {
	            this.values.push(null);
	        }
	    };
	    return Reader;
	}());
	var Tokenizer = (function () {
	    function Tokenizer(code, config) {
	        this.errorHandler = new error_handler_1.ErrorHandler();
	        this.errorHandler.tolerant = config ? (typeof config.tolerant === 'boolean' && config.tolerant) : false;
	        this.scanner = new scanner_1.Scanner(code, this.errorHandler);
	        this.scanner.trackComment = config ? (typeof config.comment === 'boolean' && config.comment) : false;
	        this.trackRange = config ? (typeof config.range === 'boolean' && config.range) : false;
	        this.trackLoc = config ? (typeof config.loc === 'boolean' && config.loc) : false;
	        this.buffer = [];
	        this.reader = new Reader();
	    }
	    Tokenizer.prototype.errors = function () {
	        return this.errorHandler.errors;
	    };
	    Tokenizer.prototype.getNextToken = function () {
	        if (this.buffer.length === 0) {
	            var comments = this.scanner.scanComments();
	            if (this.scanner.trackComment) {
	                for (var i = 0; i < comments.length; ++i) {
	                    var e = comments[i];
	                    var value = this.scanner.source.slice(e.slice[0], e.slice[1]);
	                    var comment = {
	                        type: e.multiLine ? 'BlockComment' : 'LineComment',
	                        value: value
	                    };
	                    if (this.trackRange) {
	                        comment.range = e.range;
	                    }
	                    if (this.trackLoc) {
	                        comment.loc = e.loc;
	                    }
	                    this.buffer.push(comment);
	                }
	            }
	            if (!this.scanner.eof()) {
	                var loc = void 0;
	                if (this.trackLoc) {
	                    loc = {
	                        start: {
	                            line: this.scanner.lineNumber,
	                            column: this.scanner.index - this.scanner.lineStart
	                        },
	                        end: {}
	                    };
	                }
	                var startRegex = (this.scanner.source[this.scanner.index] === '/') && this.reader.isRegexStart();
	                var token = startRegex ? this.scanner.scanRegExp() : this.scanner.lex();
	                this.reader.push(token);
	                var entry = {
	                    type: token_1.TokenName[token.type],
	                    value: this.scanner.source.slice(token.start, token.end)
	                };
	                if (this.trackRange) {
	                    entry.range = [token.start, token.end];
	                }
	                if (this.trackLoc) {
	                    loc.end = {
	                        line: this.scanner.lineNumber,
	                        column: this.scanner.index - this.scanner.lineStart
	                    };
	                    entry.loc = loc;
	                }
	                if (token.type === 9 /* RegularExpression */) {
	                    var pattern = token.pattern;
	                    var flags = token.flags;
	                    entry.regex = { pattern: pattern, flags: flags };
	                }
	                this.buffer.push(entry);
	            }
	        }
	        return this.buffer.shift();
	    };
	    return Tokenizer;
	}());
	exports.Tokenizer = Tokenizer;


/***/ }
/******/ ])
});
;

/***/ }),

/***/ 93876:
/***/ ((module) => {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.



var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
  ? R.apply
  : function ReflectApply(target, receiver, args) {
    return Function.prototype.apply.call(target, receiver, args);
  }

var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
  ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
  ReflectOwnKeys = function ReflectOwnKeys(target) {
    return Object.getOwnPropertyNames(target)
      .concat(Object.getOwnPropertySymbols(target));
  };
} else {
  ReflectOwnKeys = function ReflectOwnKeys(target) {
    return Object.getOwnPropertyNames(target);
  };
}

function ProcessEmitWarning(warning) {
  if (console && console.warn) console.warn(warning);
}

var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
  return value !== value;
}

function EventEmitter() {
  EventEmitter.init.call(this);
}
module.exports = EventEmitter;
module.exports.once = once;

// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;

EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;

// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;

function checkListener(listener) {
  if (typeof listener !== 'function') {
    throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
  }
}

Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  enumerable: true,
  get: function() {
    return defaultMaxListeners;
  },
  set: function(arg) {
    if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
      throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
    }
    defaultMaxListeners = arg;
  }
});

EventEmitter.init = function() {

  if (this._events === undefined ||
      this._events === Object.getPrototypeOf(this)._events) {
    this._events = Object.create(null);
    this._eventsCount = 0;
  }

  this._maxListeners = this._maxListeners || undefined;
};

// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
    throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
  }
  this._maxListeners = n;
  return this;
};

function _getMaxListeners(that) {
  if (that._maxListeners === undefined)
    return EventEmitter.defaultMaxListeners;
  return that._maxListeners;
}

EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  return _getMaxListeners(this);
};

EventEmitter.prototype.emit = function emit(type) {
  var args = [];
  for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
  var doError = (type === 'error');

  var events = this._events;
  if (events !== undefined)
    doError = (doError && events.error === undefined);
  else if (!doError)
    return false;

  // If there is no 'error' event listener then throw.
  if (doError) {
    var er;
    if (args.length > 0)
      er = args[0];
    if (er instanceof Error) {
      // Note: The comments on the `throw` lines are intentional, they show
      // up in Node's output if this results in an unhandled exception.
      throw er; // Unhandled 'error' event
    }
    // At least give some kind of context to the user
    var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
    err.context = er;
    throw err; // Unhandled 'error' event
  }

  var handler = events[type];

  if (handler === undefined)
    return false;

  if (typeof handler === 'function') {
    ReflectApply(handler, this, args);
  } else {
    var len = handler.length;
    var listeners = arrayClone(handler, len);
    for (var i = 0; i < len; ++i)
      ReflectApply(listeners[i], this, args);
  }

  return true;
};

function _addListener(target, type, listener, prepend) {
  var m;
  var events;
  var existing;

  checkListener(listener);

  events = target._events;
  if (events === undefined) {
    events = target._events = Object.create(null);
    target._eventsCount = 0;
  } else {
    // To avoid recursion in the case that type === "newListener"! Before
    // adding it to the listeners, first emit "newListener".
    if (events.newListener !== undefined) {
      target.emit('newListener', type,
                  listener.listener ? listener.listener : listener);

      // Re-assign `events` because a newListener handler could have caused the
      // this._events to be assigned to a new object
      events = target._events;
    }
    existing = events[type];
  }

  if (existing === undefined) {
    // Optimize the case of one listener. Don't need the extra array object.
    existing = events[type] = listener;
    ++target._eventsCount;
  } else {
    if (typeof existing === 'function') {
      // Adding the second element, need to change to array.
      existing = events[type] =
        prepend ? [listener, existing] : [existing, listener];
      // If we've already got an array, just append.
    } else if (prepend) {
      existing.unshift(listener);
    } else {
      existing.push(listener);
    }

    // Check for listener leak
    m = _getMaxListeners(target);
    if (m > 0 && existing.length > m && !existing.warned) {
      existing.warned = true;
      // No error code for this since it is a Warning
      // eslint-disable-next-line no-restricted-syntax
      var w = new Error('Possible EventEmitter memory leak detected. ' +
                          existing.length + ' ' + String(type) + ' listeners ' +
                          'added. Use emitter.setMaxListeners() to ' +
                          'increase limit');
      w.name = 'MaxListenersExceededWarning';
      w.emitter = target;
      w.type = type;
      w.count = existing.length;
      ProcessEmitWarning(w);
    }
  }

  return target;
}

EventEmitter.prototype.addListener = function addListener(type, listener) {
  return _addListener(this, type, listener, false);
};

EventEmitter.prototype.on = EventEmitter.prototype.addListener;

EventEmitter.prototype.prependListener =
    function prependListener(type, listener) {
      return _addListener(this, type, listener, true);
    };

function onceWrapper() {
  if (!this.fired) {
    this.target.removeListener(this.type, this.wrapFn);
    this.fired = true;
    if (arguments.length === 0)
      return this.listener.call(this.target);
    return this.listener.apply(this.target, arguments);
  }
}

function _onceWrap(target, type, listener) {
  var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  var wrapped = onceWrapper.bind(state);
  wrapped.listener = listener;
  state.wrapFn = wrapped;
  return wrapped;
}

EventEmitter.prototype.once = function once(type, listener) {
  checkListener(listener);
  this.on(type, _onceWrap(this, type, listener));
  return this;
};

EventEmitter.prototype.prependOnceListener =
    function prependOnceListener(type, listener) {
      checkListener(listener);
      this.prependListener(type, _onceWrap(this, type, listener));
      return this;
    };

// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
    function removeListener(type, listener) {
      var list, events, position, i, originalListener;

      checkListener(listener);

      events = this._events;
      if (events === undefined)
        return this;

      list = events[type];
      if (list === undefined)
        return this;

      if (list === listener || list.listener === listener) {
        if (--this._eventsCount === 0)
          this._events = Object.create(null);
        else {
          delete events[type];
          if (events.removeListener)
            this.emit('removeListener', type, list.listener || listener);
        }
      } else if (typeof list !== 'function') {
        position = -1;

        for (i = list.length - 1; i >= 0; i--) {
          if (list[i] === listener || list[i].listener === listener) {
            originalListener = list[i].listener;
            position = i;
            break;
          }
        }

        if (position < 0)
          return this;

        if (position === 0)
          list.shift();
        else {
          spliceOne(list, position);
        }

        if (list.length === 1)
          events[type] = list[0];

        if (events.removeListener !== undefined)
          this.emit('removeListener', type, originalListener || listener);
      }

      return this;
    };

EventEmitter.prototype.off = EventEmitter.prototype.removeListener;

EventEmitter.prototype.removeAllListeners =
    function removeAllListeners(type) {
      var listeners, events, i;

      events = this._events;
      if (events === undefined)
        return this;

      // not listening for removeListener, no need to emit
      if (events.removeListener === undefined) {
        if (arguments.length === 0) {
          this._events = Object.create(null);
          this._eventsCount = 0;
        } else if (events[type] !== undefined) {
          if (--this._eventsCount === 0)
            this._events = Object.create(null);
          else
            delete events[type];
        }
        return this;
      }

      // emit removeListener for all listeners on all events
      if (arguments.length === 0) {
        var keys = Object.keys(events);
        var key;
        for (i = 0; i < keys.length; ++i) {
          key = keys[i];
          if (key === 'removeListener') continue;
          this.removeAllListeners(key);
        }
        this.removeAllListeners('removeListener');
        this._events = Object.create(null);
        this._eventsCount = 0;
        return this;
      }

      listeners = events[type];

      if (typeof listeners === 'function') {
        this.removeListener(type, listeners);
      } else if (listeners !== undefined) {
        // LIFO order
        for (i = listeners.length - 1; i >= 0; i--) {
          this.removeListener(type, listeners[i]);
        }
      }

      return this;
    };

function _listeners(target, type, unwrap) {
  var events = target._events;

  if (events === undefined)
    return [];

  var evlistener = events[type];
  if (evlistener === undefined)
    return [];

  if (typeof evlistener === 'function')
    return unwrap ? [evlistener.listener || evlistener] : [evlistener];

  return unwrap ?
    unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}

EventEmitter.prototype.listeners = function listeners(type) {
  return _listeners(this, type, true);
};

EventEmitter.prototype.rawListeners = function rawListeners(type) {
  return _listeners(this, type, false);
};

EventEmitter.listenerCount = function(emitter, type) {
  if (typeof emitter.listenerCount === 'function') {
    return emitter.listenerCount(type);
  } else {
    return listenerCount.call(emitter, type);
  }
};

EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
  var events = this._events;

  if (events !== undefined) {
    var evlistener = events[type];

    if (typeof evlistener === 'function') {
      return 1;
    } else if (evlistener !== undefined) {
      return evlistener.length;
    }
  }

  return 0;
}

EventEmitter.prototype.eventNames = function eventNames() {
  return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};

function arrayClone(arr, n) {
  var copy = new Array(n);
  for (var i = 0; i < n; ++i)
    copy[i] = arr[i];
  return copy;
}

function spliceOne(list, index) {
  for (; index + 1 < list.length; index++)
    list[index] = list[index + 1];
  list.pop();
}

function unwrapListeners(arr) {
  var ret = new Array(arr.length);
  for (var i = 0; i < ret.length; ++i) {
    ret[i] = arr[i].listener || arr[i];
  }
  return ret;
}

function once(emitter, name) {
  return new Promise(function (resolve, reject) {
    function errorListener(err) {
      emitter.removeListener(name, resolver);
      reject(err);
    }

    function resolver() {
      if (typeof emitter.removeListener === 'function') {
        emitter.removeListener('error', errorListener);
      }
      resolve([].slice.call(arguments));
    };

    eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
    if (name !== 'error') {
      addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
    }
  });
}

function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
  if (typeof emitter.on === 'function') {
    eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
  }
}

function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
  if (typeof emitter.on === 'function') {
    if (flags.once) {
      emitter.once(name, listener);
    } else {
      emitter.on(name, listener);
    }
  } else if (typeof emitter.addEventListener === 'function') {
    // EventTarget does not have `error` event semantics like Node
    // EventEmitters, we do not listen for `error` events here.
    emitter.addEventListener(name, function wrapListener(arg) {
      // IE does not have builtin `{ once: true }` support so we
      // have to do it manually.
      if (flags.once) {
        emitter.removeEventListener(name, wrapListener);
      }
      listener(arg);
    });
  } else {
    throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
  }
}


/***/ }),

/***/ 32615:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var Buffer = (__webpack_require__(60571).Buffer)
var MD5 = __webpack_require__(29160)

/* eslint-disable camelcase */
function EVP_BytesToKey (password, salt, keyBits, ivLen) {
  if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary')
  if (salt) {
    if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary')
    if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length')
  }

  var keyLen = keyBits / 8
  var key = Buffer.alloc(keyLen)
  var iv = Buffer.alloc(ivLen || 0)
  var tmp = Buffer.alloc(0)

  while (keyLen > 0 || ivLen > 0) {
    var hash = new MD5()
    hash.update(tmp)
    hash.update(password)
    if (salt) hash.update(salt)
    tmp = hash.digest()

    var used = 0

    if (keyLen > 0) {
      var keyStart = key.length - keyLen
      used = Math.min(keyLen, tmp.length)
      tmp.copy(key, keyStart, 0, used)
      keyLen -= used
    }

    if (used < tmp.length && ivLen > 0) {
      var ivStart = iv.length - ivLen
      var length = Math.min(ivLen, tmp.length - used)
      tmp.copy(iv, ivStart, used, used + length)
      ivLen -= length
    }
  }

  tmp.fill(0)
  return { key: key, iv: iv }
}

module.exports = EVP_BytesToKey


/***/ }),

/***/ 63871:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var Buffer = (__webpack_require__(60571).Buffer)
var Transform = (__webpack_require__(32891).Transform)
var inherits = __webpack_require__(72116)

function throwIfNotStringOrBuffer (val, prefix) {
  if (!Buffer.isBuffer(val) && typeof val !== 'string') {
    throw new TypeError(prefix + ' must be a string or a buffer')
  }
}

function HashBase (blockSize) {
  Transform.call(this)

  this._block = Buffer.allocUnsafe(blockSize)
  this._blockSize = blockSize
  this._blockOffset = 0
  this._length = [0, 0, 0, 0]

  this._finalized = false
}

inherits(HashBase, Transform)

HashBase.prototype._transform = function (chunk, encoding, callback) {
  var error = null
  try {
    this.update(chunk, encoding)
  } catch (err) {
    error = err
  }

  callback(error)
}

HashBase.prototype._flush = function (callback) {
  var error = null
  try {
    this.push(this.digest())
  } catch (err) {
    error = err
  }

  callback(error)
}

HashBase.prototype.update = function (data, encoding) {
  throwIfNotStringOrBuffer(data, 'Data')
  if (this._finalized) throw new Error('Digest already called')
  if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)

  // consume data
  var block = this._block
  var offset = 0
  while (this._blockOffset + data.length - offset >= this._blockSize) {
    for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
    this._update()
    this._blockOffset = 0
  }
  while (offset < data.length) block[this._blockOffset++] = data[offset++]

  // update length
  for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
    this._length[j] += carry
    carry = (this._length[j] / 0x0100000000) | 0
    if (carry > 0) this._length[j] -= 0x0100000000 * carry
  }

  return this
}

HashBase.prototype._update = function () {
  throw new Error('_update is not implemented')
}

HashBase.prototype.digest = function (encoding) {
  if (this._finalized) throw new Error('Digest already called')
  this._finalized = true

  var digest = this._digest()
  if (encoding !== undefined) digest = digest.toString(encoding)

  // reset state
  this._block.fill(0)
  this._blockOffset = 0
  for (var i = 0; i < 4; ++i) this._length[i] = 0

  return digest
}

HashBase.prototype._digest = function () {
  throw new Error('_digest is not implemented')
}

module.exports = HashBase


/***/ }),

/***/ 94294:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var hash = exports;

hash.utils = __webpack_require__(6048);
hash.common = __webpack_require__(93924);
hash.sha = __webpack_require__(15523);
hash.ripemd = __webpack_require__(56234);
hash.hmac = __webpack_require__(76734);

// Proxy hash functions to the main object
hash.sha1 = hash.sha.sha1;
hash.sha256 = hash.sha.sha256;
hash.sha224 = hash.sha.sha224;
hash.sha384 = hash.sha.sha384;
hash.sha512 = hash.sha.sha512;
hash.ripemd160 = hash.ripemd.ripemd160;


/***/ }),

/***/ 93924:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";


var utils = __webpack_require__(6048);
var assert = __webpack_require__(2481);

function BlockHash() {
  this.pending = null;
  this.pendingTotal = 0;
  this.blockSize = this.constructor.blockSize;
  this.outSize = this.constructor.outSize;
  this.hmacStrength = this.constructor.hmacStrength;
  this.padLength = this.constructor.padLength / 8;
  this.endian = 'big';

  this._delta8 = this.blockSize / 8;
  this._delta32 = this.blockSize / 32;
}
exports.BlockHash = BlockHash;

BlockHash.prototype.update = function update(msg, enc) {
  // Convert message to array, pad it, and join into 32bit blocks
  msg = utils.toArray(msg, enc);
  if (!this.pending)
    this.pending = msg;
  else
    this.pending = this.pending.concat(msg);
  this.pendingTotal += msg.length;

  // Enough data, try updating
  if (this.pending.length >= this._delta8) {
    msg = this.pending;

    // Process pending data in blocks
    var r = msg.length % this._delta8;
    this.pending = msg.slice(msg.length - r, msg.length);
    if (this.pending.length === 0)
      this.pending = null;

    msg = utils.join32(msg, 0, msg.length - r, this.endian);
    for (var i = 0; i < msg.length; i += this._delta32)
      this._update(msg, i, i + this._delta32);
  }

  return this;
};

BlockHash.prototype.digest = function digest(enc) {
  this.update(this._pad());
  assert(this.pending === null);

  return this._digest(enc);
};

BlockHash.prototype._pad = function pad() {
  var len = this.pendingTotal;
  var bytes = this._delta8;
  var k = bytes - ((len + this.padLength) % bytes);
  var res = new Array(k + this.padLength);
  res[0] = 0x80;
  for (var i = 1; i < k; i++)
    res[i] = 0;

  // Append length
  len <<= 3;
  if (this.endian === 'big') {
    for (var t = 8; t < this.padLength; t++)
      res[i++] = 0;

    res[i++] = 0;
    res[i++] = 0;
    res[i++] = 0;
    res[i++] = 0;
    res[i++] = (len >>> 24) & 0xff;
    res[i++] = (len >>> 16) & 0xff;
    res[i++] = (len >>> 8) & 0xff;
    res[i++] = len & 0xff;
  } else {
    res[i++] = len & 0xff;
    res[i++] = (len >>> 8) & 0xff;
    res[i++] = (len >>> 16) & 0xff;
    res[i++] = (len >>> 24) & 0xff;
    res[i++] = 0;
    res[i++] = 0;
    res[i++] = 0;
    res[i++] = 0;

    for (t = 8; t < this.padLength; t++)
      res[i++] = 0;
  }

  return res;
};


/***/ }),

/***/ 76734:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var utils = __webpack_require__(6048);
var assert = __webpack_require__(2481);

function Hmac(hash, key, enc) {
  if (!(this instanceof Hmac))
    return new Hmac(hash, key, enc);
  this.Hash = hash;
  this.blockSize = hash.blockSize / 8;
  this.outSize = hash.outSize / 8;
  this.inner = null;
  this.outer = null;

  this._init(utils.toArray(key, enc));
}
module.exports = Hmac;

Hmac.prototype._init = function init(key) {
  // Shorten key, if needed
  if (key.length > this.blockSize)
    key = new this.Hash().update(key).digest();
  assert(key.length <= this.blockSize);

  // Add padding to key
  for (var i = key.length; i < this.blockSize; i++)
    key.push(0);

  for (i = 0; i < key.length; i++)
    key[i] ^= 0x36;
  this.inner = new this.Hash().update(key);

  // 0x36 ^ 0x5c = 0x6a
  for (i = 0; i < key.length; i++)
    key[i] ^= 0x6a;
  this.outer = new this.Hash().update(key);
};

Hmac.prototype.update = function update(msg, enc) {
  this.inner.update(msg, enc);
  return this;
};

Hmac.prototype.digest = function digest(enc) {
  this.outer.update(this.inner.digest());
  return this.outer.digest(enc);
};


/***/ }),

/***/ 56234:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";


var utils = __webpack_require__(6048);
var common = __webpack_require__(93924);

var rotl32 = utils.rotl32;
var sum32 = utils.sum32;
var sum32_3 = utils.sum32_3;
var sum32_4 = utils.sum32_4;
var BlockHash = common.BlockHash;

function RIPEMD160() {
  if (!(this instanceof RIPEMD160))
    return new RIPEMD160();

  BlockHash.call(this);

  this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
  this.endian = 'little';
}
utils.inherits(RIPEMD160, BlockHash);
exports.ripemd160 = RIPEMD160;

RIPEMD160.blockSize = 512;
RIPEMD160.outSize = 160;
RIPEMD160.hmacStrength = 192;
RIPEMD160.padLength = 64;

RIPEMD160.prototype._update = function update(msg, start) {
  var A = this.h[0];
  var B = this.h[1];
  var C = this.h[2];
  var D = this.h[3];
  var E = this.h[4];
  var Ah = A;
  var Bh = B;
  var Ch = C;
  var Dh = D;
  var Eh = E;
  for (var j = 0; j < 80; j++) {
    var T = sum32(
      rotl32(
        sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),
        s[j]),
      E);
    A = E;
    E = D;
    D = rotl32(C, 10);
    C = B;
    B = T;
    T = sum32(
      rotl32(
        sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
        sh[j]),
      Eh);
    Ah = Eh;
    Eh = Dh;
    Dh = rotl32(Ch, 10);
    Ch = Bh;
    Bh = T;
  }
  T = sum32_3(this.h[1], C, Dh);
  this.h[1] = sum32_3(this.h[2], D, Eh);
  this.h[2] = sum32_3(this.h[3], E, Ah);
  this.h[3] = sum32_3(this.h[4], A, Bh);
  this.h[4] = sum32_3(this.h[0], B, Ch);
  this.h[0] = T;
};

RIPEMD160.prototype._digest = function digest(enc) {
  if (enc === 'hex')
    return utils.toHex32(this.h, 'little');
  else
    return utils.split32(this.h, 'little');
};

function f(j, x, y, z) {
  if (j <= 15)
    return x ^ y ^ z;
  else if (j <= 31)
    return (x & y) | ((~x) & z);
  else if (j <= 47)
    return (x | (~y)) ^ z;
  else if (j <= 63)
    return (x & z) | (y & (~z));
  else
    return x ^ (y | (~z));
}

function K(j) {
  if (j <= 15)
    return 0x00000000;
  else if (j <= 31)
    return 0x5a827999;
  else if (j <= 47)
    return 0x6ed9eba1;
  else if (j <= 63)
    return 0x8f1bbcdc;
  else
    return 0xa953fd4e;
}

function Kh(j) {
  if (j <= 15)
    return 0x50a28be6;
  else if (j <= 31)
    return 0x5c4dd124;
  else if (j <= 47)
    return 0x6d703ef3;
  else if (j <= 63)
    return 0x7a6d76e9;
  else
    return 0x00000000;
}

var r = [
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
  3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
  1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
  4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
];

var rh = [
  5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
  6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
  15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
  8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
  12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
];

var s = [
  11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
  7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
  11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
  11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
  9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
];

var sh = [
  8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
  9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
  9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
  15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
  8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
];


/***/ }),

/***/ 15523:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";


exports.sha1 = __webpack_require__(26191);
exports.sha224 = __webpack_require__(9828);
exports.sha256 = __webpack_require__(69681);
exports.sha384 = __webpack_require__(8069);
exports.sha512 = __webpack_require__(90868);


/***/ }),

/***/ 26191:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var utils = __webpack_require__(6048);
var common = __webpack_require__(93924);
var shaCommon = __webpack_require__(17479);

var rotl32 = utils.rotl32;
var sum32 = utils.sum32;
var sum32_5 = utils.sum32_5;
var ft_1 = shaCommon.ft_1;
var BlockHash = common.BlockHash;

var sha1_K = [
  0x5A827999, 0x6ED9EBA1,
  0x8F1BBCDC, 0xCA62C1D6
];

function SHA1() {
  if (!(this instanceof SHA1))
    return new SHA1();

  BlockHash.call(this);
  this.h = [
    0x67452301, 0xefcdab89, 0x98badcfe,
    0x10325476, 0xc3d2e1f0 ];
  this.W = new Array(80);
}

utils.inherits(SHA1, BlockHash);
module.exports = SHA1;

SHA1.blockSize = 512;
SHA1.outSize = 160;
SHA1.hmacStrength = 80;
SHA1.padLength = 64;

SHA1.prototype._update = function _update(msg, start) {
  var W = this.W;

  for (var i = 0; i < 16; i++)
    W[i] = msg[start + i];

  for(; i < W.length; i++)
    W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);

  var a = this.h[0];
  var b = this.h[1];
  var c = this.h[2];
  var d = this.h[3];
  var e = this.h[4];

  for (i = 0; i < W.length; i++) {
    var s = ~~(i / 20);
    var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);
    e = d;
    d = c;
    c = rotl32(b, 30);
    b = a;
    a = t;
  }

  this.h[0] = sum32(this.h[0], a);
  this.h[1] = sum32(this.h[1], b);
  this.h[2] = sum32(this.h[2], c);
  this.h[3] = sum32(this.h[3], d);
  this.h[4] = sum32(this.h[4], e);
};

SHA1.prototype._digest = function digest(enc) {
  if (enc === 'hex')
    return utils.toHex32(this.h, 'big');
  else
    return utils.split32(this.h, 'big');
};


/***/ }),

/***/ 9828:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var utils = __webpack_require__(6048);
var SHA256 = __webpack_require__(69681);

function SHA224() {
  if (!(this instanceof SHA224))
    return new SHA224();

  SHA256.call(this);
  this.h = [
    0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
    0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
}
utils.inherits(SHA224, SHA256);
module.exports = SHA224;

SHA224.blockSize = 512;
SHA224.outSize = 224;
SHA224.hmacStrength = 192;
SHA224.padLength = 64;

SHA224.prototype._digest = function digest(enc) {
  // Just truncate output
  if (enc === 'hex')
    return utils.toHex32(this.h.slice(0, 7), 'big');
  else
    return utils.split32(this.h.slice(0, 7), 'big');
};



/***/ }),

/***/ 69681:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var utils = __webpack_require__(6048);
var common = __webpack_require__(93924);
var shaCommon = __webpack_require__(17479);
var assert = __webpack_require__(2481);

var sum32 = utils.sum32;
var sum32_4 = utils.sum32_4;
var sum32_5 = utils.sum32_5;
var ch32 = shaCommon.ch32;
var maj32 = shaCommon.maj32;
var s0_256 = shaCommon.s0_256;
var s1_256 = shaCommon.s1_256;
var g0_256 = shaCommon.g0_256;
var g1_256 = shaCommon.g1_256;

var BlockHash = common.BlockHash;

var sha256_K = [
  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
  0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
  0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
  0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
  0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
  0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
  0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
  0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
  0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
  0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
  0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
  0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
];

function SHA256() {
  if (!(this instanceof SHA256))
    return new SHA256();

  BlockHash.call(this);
  this.h = [
    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
    0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
  ];
  this.k = sha256_K;
  this.W = new Array(64);
}
utils.inherits(SHA256, BlockHash);
module.exports = SHA256;

SHA256.blockSize = 512;
SHA256.outSize = 256;
SHA256.hmacStrength = 192;
SHA256.padLength = 64;

SHA256.prototype._update = function _update(msg, start) {
  var W = this.W;

  for (var i = 0; i < 16; i++)
    W[i] = msg[start + i];
  for (; i < W.length; i++)
    W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);

  var a = this.h[0];
  var b = this.h[1];
  var c = this.h[2];
  var d = this.h[3];
  var e = this.h[4];
  var f = this.h[5];
  var g = this.h[6];
  var h = this.h[7];

  assert(this.k.length === W.length);
  for (i = 0; i < W.length; i++) {
    var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);
    var T2 = sum32(s0_256(a), maj32(a, b, c));
    h = g;
    g = f;
    f = e;
    e = sum32(d, T1);
    d = c;
    c = b;
    b = a;
    a = sum32(T1, T2);
  }

  this.h[0] = sum32(this.h[0], a);
  this.h[1] = sum32(this.h[1], b);
  this.h[2] = sum32(this.h[2], c);
  this.h[3] = sum32(this.h[3], d);
  this.h[4] = sum32(this.h[4], e);
  this.h[5] = sum32(this.h[5], f);
  this.h[6] = sum32(this.h[6], g);
  this.h[7] = sum32(this.h[7], h);
};

SHA256.prototype._digest = function digest(enc) {
  if (enc === 'hex')
    return utils.toHex32(this.h, 'big');
  else
    return utils.split32(this.h, 'big');
};


/***/ }),

/***/ 8069:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var utils = __webpack_require__(6048);

var SHA512 = __webpack_require__(90868);

function SHA384() {
  if (!(this instanceof SHA384))
    return new SHA384();

  SHA512.call(this);
  this.h = [
    0xcbbb9d5d, 0xc1059ed8,
    0x629a292a, 0x367cd507,
    0x9159015a, 0x3070dd17,
    0x152fecd8, 0xf70e5939,
    0x67332667, 0xffc00b31,
    0x8eb44a87, 0x68581511,
    0xdb0c2e0d, 0x64f98fa7,
    0x47b5481d, 0xbefa4fa4 ];
}
utils.inherits(SHA384, SHA512);
module.exports = SHA384;

SHA384.blockSize = 1024;
SHA384.outSize = 384;
SHA384.hmacStrength = 192;
SHA384.padLength = 128;

SHA384.prototype._digest = function digest(enc) {
  if (enc === 'hex')
    return utils.toHex32(this.h.slice(0, 12), 'big');
  else
    return utils.split32(this.h.slice(0, 12), 'big');
};


/***/ }),

/***/ 90868:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var utils = __webpack_require__(6048);
var common = __webpack_require__(93924);
var assert = __webpack_require__(2481);

var rotr64_hi = utils.rotr64_hi;
var rotr64_lo = utils.rotr64_lo;
var shr64_hi = utils.shr64_hi;
var shr64_lo = utils.shr64_lo;
var sum64 = utils.sum64;
var sum64_hi = utils.sum64_hi;
var sum64_lo = utils.sum64_lo;
var sum64_4_hi = utils.sum64_4_hi;
var sum64_4_lo = utils.sum64_4_lo;
var sum64_5_hi = utils.sum64_5_hi;
var sum64_5_lo = utils.sum64_5_lo;

var BlockHash = common.BlockHash;

var sha512_K = [
  0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
  0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
  0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
  0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
  0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
  0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
  0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
  0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
  0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
  0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
  0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
  0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
  0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
  0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
  0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
  0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
  0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
  0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
  0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
  0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
  0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
  0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
  0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
  0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
  0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
  0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
  0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
  0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
  0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
  0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
  0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
  0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
  0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
  0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
  0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
  0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
  0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
  0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
  0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
  0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
];

function SHA512() {
  if (!(this instanceof SHA512))
    return new SHA512();

  BlockHash.call(this);
  this.h = [
    0x6a09e667, 0xf3bcc908,
    0xbb67ae85, 0x84caa73b,
    0x3c6ef372, 0xfe94f82b,
    0xa54ff53a, 0x5f1d36f1,
    0x510e527f, 0xade682d1,
    0x9b05688c, 0x2b3e6c1f,
    0x1f83d9ab, 0xfb41bd6b,
    0x5be0cd19, 0x137e2179 ];
  this.k = sha512_K;
  this.W = new Array(160);
}
utils.inherits(SHA512, BlockHash);
module.exports = SHA512;

SHA512.blockSize = 1024;
SHA512.outSize = 512;
SHA512.hmacStrength = 192;
SHA512.padLength = 128;

SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
  var W = this.W;

  // 32 x 32bit words
  for (var i = 0; i < 32; i++)
    W[i] = msg[start + i];
  for (; i < W.length; i += 2) {
    var c0_hi = g1_512_hi(W[i - 4], W[i - 3]);  // i - 2
    var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
    var c1_hi = W[i - 14];  // i - 7
    var c1_lo = W[i - 13];
    var c2_hi = g0_512_hi(W[i - 30], W[i - 29]);  // i - 15
    var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
    var c3_hi = W[i - 32];  // i - 16
    var c3_lo = W[i - 31];

    W[i] = sum64_4_hi(
      c0_hi, c0_lo,
      c1_hi, c1_lo,
      c2_hi, c2_lo,
      c3_hi, c3_lo);
    W[i + 1] = sum64_4_lo(
      c0_hi, c0_lo,
      c1_hi, c1_lo,
      c2_hi, c2_lo,
      c3_hi, c3_lo);
  }
};

SHA512.prototype._update = function _update(msg, start) {
  this._prepareBlock(msg, start);

  var W = this.W;

  var ah = this.h[0];
  var al = this.h[1];
  var bh = this.h[2];
  var bl = this.h[3];
  var ch = this.h[4];
  var cl = this.h[5];
  var dh = this.h[6];
  var dl = this.h[7];
  var eh = this.h[8];
  var el = this.h[9];
  var fh = this.h[10];
  var fl = this.h[11];
  var gh = this.h[12];
  var gl = this.h[13];
  var hh = this.h[14];
  var hl = this.h[15];

  assert(this.k.length === W.length);
  for (var i = 0; i < W.length; i += 2) {
    var c0_hi = hh;
    var c0_lo = hl;
    var c1_hi = s1_512_hi(eh, el);
    var c1_lo = s1_512_lo(eh, el);
    var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
    var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
    var c3_hi = this.k[i];
    var c3_lo = this.k[i + 1];
    var c4_hi = W[i];
    var c4_lo = W[i + 1];

    var T1_hi = sum64_5_hi(
      c0_hi, c0_lo,
      c1_hi, c1_lo,
      c2_hi, c2_lo,
      c3_hi, c3_lo,
      c4_hi, c4_lo);
    var T1_lo = sum64_5_lo(
      c0_hi, c0_lo,
      c1_hi, c1_lo,
      c2_hi, c2_lo,
      c3_hi, c3_lo,
      c4_hi, c4_lo);

    c0_hi = s0_512_hi(ah, al);
    c0_lo = s0_512_lo(ah, al);
    c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
    c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);

    var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
    var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);

    hh = gh;
    hl = gl;

    gh = fh;
    gl = fl;

    fh = eh;
    fl = el;

    eh = sum64_hi(dh, dl, T1_hi, T1_lo);
    el = sum64_lo(dl, dl, T1_hi, T1_lo);

    dh = ch;
    dl = cl;

    ch = bh;
    cl = bl;

    bh = ah;
    bl = al;

    ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
    al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
  }

  sum64(this.h, 0, ah, al);
  sum64(this.h, 2, bh, bl);
  sum64(this.h, 4, ch, cl);
  sum64(this.h, 6, dh, dl);
  sum64(this.h, 8, eh, el);
  sum64(this.h, 10, fh, fl);
  sum64(this.h, 12, gh, gl);
  sum64(this.h, 14, hh, hl);
};

SHA512.prototype._digest = function digest(enc) {
  if (enc === 'hex')
    return utils.toHex32(this.h, 'big');
  else
    return utils.split32(this.h, 'big');
};

function ch64_hi(xh, xl, yh, yl, zh) {
  var r = (xh & yh) ^ ((~xh) & zh);
  if (r < 0)
    r += 0x100000000;
  return r;
}

function ch64_lo(xh, xl, yh, yl, zh, zl) {
  var r = (xl & yl) ^ ((~xl) & zl);
  if (r < 0)
    r += 0x100000000;
  return r;
}

function maj64_hi(xh, xl, yh, yl, zh) {
  var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
  if (r < 0)
    r += 0x100000000;
  return r;
}

function maj64_lo(xh, xl, yh, yl, zh, zl) {
  var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
  if (r < 0)
    r += 0x100000000;
  return r;
}

function s0_512_hi(xh, xl) {
  var c0_hi = rotr64_hi(xh, xl, 28);
  var c1_hi = rotr64_hi(xl, xh, 2);  // 34
  var c2_hi = rotr64_hi(xl, xh, 7);  // 39

  var r = c0_hi ^ c1_hi ^ c2_hi;
  if (r < 0)
    r += 0x100000000;
  return r;
}

function s0_512_lo(xh, xl) {
  var c0_lo = rotr64_lo(xh, xl, 28);
  var c1_lo = rotr64_lo(xl, xh, 2);  // 34
  var c2_lo = rotr64_lo(xl, xh, 7);  // 39

  var r = c0_lo ^ c1_lo ^ c2_lo;
  if (r < 0)
    r += 0x100000000;
  return r;
}

function s1_512_hi(xh, xl) {
  var c0_hi = rotr64_hi(xh, xl, 14);
  var c1_hi = rotr64_hi(xh, xl, 18);
  var c2_hi = rotr64_hi(xl, xh, 9);  // 41

  var r = c0_hi ^ c1_hi ^ c2_hi;
  if (r < 0)
    r += 0x100000000;
  return r;
}

function s1_512_lo(xh, xl) {
  var c0_lo = rotr64_lo(xh, xl, 14);
  var c1_lo = rotr64_lo(xh, xl, 18);
  var c2_lo = rotr64_lo(xl, xh, 9);  // 41

  var r = c0_lo ^ c1_lo ^ c2_lo;
  if (r < 0)
    r += 0x100000000;
  return r;
}

function g0_512_hi(xh, xl) {
  var c0_hi = rotr64_hi(xh, xl, 1);
  var c1_hi = rotr64_hi(xh, xl, 8);
  var c2_hi = shr64_hi(xh, xl, 7);

  var r = c0_hi ^ c1_hi ^ c2_hi;
  if (r < 0)
    r += 0x100000000;
  return r;
}

function g0_512_lo(xh, xl) {
  var c0_lo = rotr64_lo(xh, xl, 1);
  var c1_lo = rotr64_lo(xh, xl, 8);
  var c2_lo = shr64_lo(xh, xl, 7);

  var r = c0_lo ^ c1_lo ^ c2_lo;
  if (r < 0)
    r += 0x100000000;
  return r;
}

function g1_512_hi(xh, xl) {
  var c0_hi = rotr64_hi(xh, xl, 19);
  var c1_hi = rotr64_hi(xl, xh, 29);  // 61
  var c2_hi = shr64_hi(xh, xl, 6);

  var r = c0_hi ^ c1_hi ^ c2_hi;
  if (r < 0)
    r += 0x100000000;
  return r;
}

function g1_512_lo(xh, xl) {
  var c0_lo = rotr64_lo(xh, xl, 19);
  var c1_lo = rotr64_lo(xl, xh, 29);  // 61
  var c2_lo = shr64_lo(xh, xl, 6);

  var r = c0_lo ^ c1_lo ^ c2_lo;
  if (r < 0)
    r += 0x100000000;
  return r;
}


/***/ }),

/***/ 17479:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";


var utils = __webpack_require__(6048);
var rotr32 = utils.rotr32;

function ft_1(s, x, y, z) {
  if (s === 0)
    return ch32(x, y, z);
  if (s === 1 || s === 3)
    return p32(x, y, z);
  if (s === 2)
    return maj32(x, y, z);
}
exports.ft_1 = ft_1;

function ch32(x, y, z) {
  return (x & y) ^ ((~x) & z);
}
exports.ch32 = ch32;

function maj32(x, y, z) {
  return (x & y) ^ (x & z) ^ (y & z);
}
exports.maj32 = maj32;

function p32(x, y, z) {
  return x ^ y ^ z;
}
exports.p32 = p32;

function s0_256(x) {
  return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
}
exports.s0_256 = s0_256;

function s1_256(x) {
  return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
}
exports.s1_256 = s1_256;

function g0_256(x) {
  return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);
}
exports.g0_256 = g0_256;

function g1_256(x) {
  return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);
}
exports.g1_256 = g1_256;


/***/ }),

/***/ 6048:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";


var assert = __webpack_require__(2481);
var inherits = __webpack_require__(72116);

exports.inherits = inherits;

function isSurrogatePair(msg, i) {
  if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) {
    return false;
  }
  if (i < 0 || i + 1 >= msg.length) {
    return false;
  }
  return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00;
}

function toArray(msg, enc) {
  if (Array.isArray(msg))
    return msg.slice();
  if (!msg)
    return [];
  var res = [];
  if (typeof msg === 'string') {
    if (!enc) {
      // Inspired by stringToUtf8ByteArray() in closure-library by Google
      // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
      // Apache License 2.0
      // https://github.com/google/closure-library/blob/master/LICENSE
      var p = 0;
      for (var i = 0; i < msg.length; i++) {
        var c = msg.charCodeAt(i);
        if (c < 128) {
          res[p++] = c;
        } else if (c < 2048) {
          res[p++] = (c >> 6) | 192;
          res[p++] = (c & 63) | 128;
        } else if (isSurrogatePair(msg, i)) {
          c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF);
          res[p++] = (c >> 18) | 240;
          res[p++] = ((c >> 12) & 63) | 128;
          res[p++] = ((c >> 6) & 63) | 128;
          res[p++] = (c & 63) | 128;
        } else {
          res[p++] = (c >> 12) | 224;
          res[p++] = ((c >> 6) & 63) | 128;
          res[p++] = (c & 63) | 128;
        }
      }
    } else if (enc === 'hex') {
      msg = msg.replace(/[^a-z0-9]+/ig, '');
      if (msg.length % 2 !== 0)
        msg = '0' + msg;
      for (i = 0; i < msg.length; i += 2)
        res.push(parseInt(msg[i] + msg[i + 1], 16));
    }
  } else {
    for (i = 0; i < msg.length; i++)
      res[i] = msg[i] | 0;
  }
  return res;
}
exports.toArray = toArray;

function toHex(msg) {
  var res = '';
  for (var i = 0; i < msg.length; i++)
    res += zero2(msg[i].toString(16));
  return res;
}
exports.toHex = toHex;

function htonl(w) {
  var res = (w >>> 24) |
            ((w >>> 8) & 0xff00) |
            ((w << 8) & 0xff0000) |
            ((w & 0xff) << 24);
  return res >>> 0;
}
exports.htonl = htonl;

function toHex32(msg, endian) {
  var res = '';
  for (var i = 0; i < msg.length; i++) {
    var w = msg[i];
    if (endian === 'little')
      w = htonl(w);
    res += zero8(w.toString(16));
  }
  return res;
}
exports.toHex32 = toHex32;

function zero2(word) {
  if (word.length === 1)
    return '0' + word;
  else
    return word;
}
exports.zero2 = zero2;

function zero8(word) {
  if (word.length === 7)
    return '0' + word;
  else if (word.length === 6)
    return '00' + word;
  else if (word.length === 5)
    return '000' + word;
  else if (word.length === 4)
    return '0000' + word;
  else if (word.length === 3)
    return '00000' + word;
  else if (word.length === 2)
    return '000000' + word;
  else if (word.length === 1)
    return '0000000' + word;
  else
    return word;
}
exports.zero8 = zero8;

function join32(msg, start, end, endian) {
  var len = end - start;
  assert(len % 4 === 0);
  var res = new Array(len / 4);
  for (var i = 0, k = start; i < res.length; i++, k += 4) {
    var w;
    if (endian === 'big')
      w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
    else
      w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
    res[i] = w >>> 0;
  }
  return res;
}
exports.join32 = join32;

function split32(msg, endian) {
  var res = new Array(msg.length * 4);
  for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
    var m = msg[i];
    if (endian === 'big') {
      res[k] = m >>> 24;
      res[k + 1] = (m >>> 16) & 0xff;
      res[k + 2] = (m >>> 8) & 0xff;
      res[k + 3] = m & 0xff;
    } else {
      res[k + 3] = m >>> 24;
      res[k + 2] = (m >>> 16) & 0xff;
      res[k + 1] = (m >>> 8) & 0xff;
      res[k] = m & 0xff;
    }
  }
  return res;
}
exports.split32 = split32;

function rotr32(w, b) {
  return (w >>> b) | (w << (32 - b));
}
exports.rotr32 = rotr32;

function rotl32(w, b) {
  return (w << b) | (w >>> (32 - b));
}
exports.rotl32 = rotl32;

function sum32(a, b) {
  return (a + b) >>> 0;
}
exports.sum32 = sum32;

function sum32_3(a, b, c) {
  return (a + b + c) >>> 0;
}
exports.sum32_3 = sum32_3;

function sum32_4(a, b, c, d) {
  return (a + b + c + d) >>> 0;
}
exports.sum32_4 = sum32_4;

function sum32_5(a, b, c, d, e) {
  return (a + b + c + d + e) >>> 0;
}
exports.sum32_5 = sum32_5;

function sum64(buf, pos, ah, al) {
  var bh = buf[pos];
  var bl = buf[pos + 1];

  var lo = (al + bl) >>> 0;
  var hi = (lo < al ? 1 : 0) + ah + bh;
  buf[pos] = hi >>> 0;
  buf[pos + 1] = lo;
}
exports.sum64 = sum64;

function sum64_hi(ah, al, bh, bl) {
  var lo = (al + bl) >>> 0;
  var hi = (lo < al ? 1 : 0) + ah + bh;
  return hi >>> 0;
}
exports.sum64_hi = sum64_hi;

function sum64_lo(ah, al, bh, bl) {
  var lo = al + bl;
  return lo >>> 0;
}
exports.sum64_lo = sum64_lo;

function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
  var carry = 0;
  var lo = al;
  lo = (lo + bl) >>> 0;
  carry += lo < al ? 1 : 0;
  lo = (lo + cl) >>> 0;
  carry += lo < cl ? 1 : 0;
  lo = (lo + dl) >>> 0;
  carry += lo < dl ? 1 : 0;

  var hi = ah + bh + ch + dh + carry;
  return hi >>> 0;
}
exports.sum64_4_hi = sum64_4_hi;

function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
  var lo = al + bl + cl + dl;
  return lo >>> 0;
}
exports.sum64_4_lo = sum64_4_lo;

function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
  var carry = 0;
  var lo = al;
  lo = (lo + bl) >>> 0;
  carry += lo < al ? 1 : 0;
  lo = (lo + cl) >>> 0;
  carry += lo < cl ? 1 : 0;
  lo = (lo + dl) >>> 0;
  carry += lo < dl ? 1 : 0;
  lo = (lo + el) >>> 0;
  carry += lo < el ? 1 : 0;

  var hi = ah + bh + ch + dh + eh + carry;
  return hi >>> 0;
}
exports.sum64_5_hi = sum64_5_hi;

function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
  var lo = al + bl + cl + dl + el;

  return lo >>> 0;
}
exports.sum64_5_lo = sum64_5_lo;

function rotr64_hi(ah, al, num) {
  var r = (al << (32 - num)) | (ah >>> num);
  return r >>> 0;
}
exports.rotr64_hi = rotr64_hi;

function rotr64_lo(ah, al, num) {
  var r = (ah << (32 - num)) | (al >>> num);
  return r >>> 0;
}
exports.rotr64_lo = rotr64_lo;

function shr64_hi(ah, al, num) {
  return ah >>> num;
}
exports.shr64_hi = shr64_hi;

function shr64_lo(ah, al, num) {
  var r = (ah << (32 - num)) | (al >>> num);
  return r >>> 0;
}
exports.shr64_lo = shr64_lo;


/***/ }),

/***/ 38336:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var hash = __webpack_require__(94294);
var utils = __webpack_require__(44086);
var assert = __webpack_require__(2481);

function HmacDRBG(options) {
  if (!(this instanceof HmacDRBG))
    return new HmacDRBG(options);
  this.hash = options.hash;
  this.predResist = !!options.predResist;

  this.outLen = this.hash.outSize;
  this.minEntropy = options.minEntropy || this.hash.hmacStrength;

  this._reseed = null;
  this.reseedInterval = null;
  this.K = null;
  this.V = null;

  var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');
  var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');
  var pers = utils.toArray(options.pers, options.persEnc || 'hex');
  assert(entropy.length >= (this.minEntropy / 8),
         'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
  this._init(entropy, nonce, pers);
}
module.exports = HmacDRBG;

HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
  var seed = entropy.concat(nonce).concat(pers);

  this.K = new Array(this.outLen / 8);
  this.V = new Array(this.outLen / 8);
  for (var i = 0; i < this.V.length; i++) {
    this.K[i] = 0x00;
    this.V[i] = 0x01;
  }

  this._update(seed);
  this._reseed = 1;
  this.reseedInterval = 0x1000000000000;  // 2^48
};

HmacDRBG.prototype._hmac = function hmac() {
  return new hash.hmac(this.hash, this.K);
};

HmacDRBG.prototype._update = function update(seed) {
  var kmac = this._hmac()
                 .update(this.V)
                 .update([ 0x00 ]);
  if (seed)
    kmac = kmac.update(seed);
  this.K = kmac.digest();
  this.V = this._hmac().update(this.V).digest();
  if (!seed)
    return;

  this.K = this._hmac()
               .update(this.V)
               .update([ 0x01 ])
               .update(seed)
               .digest();
  this.V = this._hmac().update(this.V).digest();
};

HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
  // Optional entropy enc
  if (typeof entropyEnc !== 'string') {
    addEnc = add;
    add = entropyEnc;
    entropyEnc = null;
  }

  entropy = utils.toArray(entropy, entropyEnc);
  add = utils.toArray(add, addEnc);

  assert(entropy.length >= (this.minEntropy / 8),
         'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');

  this._update(entropy.concat(add || []));
  this._reseed = 1;
};

HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
  if (this._reseed > this.reseedInterval)
    throw new Error('Reseed is required');

  // Optional encoding
  if (typeof enc !== 'string') {
    addEnc = add;
    add = enc;
    enc = null;
  }

  // Optional additional data
  if (add) {
    add = utils.toArray(add, addEnc || 'hex');
    this._update(add);
  }

  var temp = [];
  while (temp.length < len) {
    this.V = this._hmac().update(this.V).digest();
    temp = temp.concat(this.V);
  }

  var res = temp.slice(0, len);
  this._update(add);
  this._reseed++;
  return utils.encode(res, enc);
};


/***/ }),

/***/ 98319:
/***/ ((__unused_webpack_module, exports) => {

/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  var e, m
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var nBits = -7
  var i = isLE ? (nBytes - 1) : 0
  var d = isLE ? -1 : 1
  var s = buffer[offset + i]

  i += d

  e = s & ((1 << (-nBits)) - 1)
  s >>= (-nBits)
  nBits += eLen
  for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  m = e & ((1 << (-nBits)) - 1)
  e >>= (-nBits)
  nBits += mLen
  for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  if (e === 0) {
    e = 1 - eBias
  } else if (e === eMax) {
    return m ? NaN : ((s ? -1 : 1) * Infinity)
  } else {
    m = m + Math.pow(2, mLen)
    e = e - eBias
  }
  return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}

exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  var e, m, c
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  var i = isLE ? 0 : (nBytes - 1)
  var d = isLE ? 1 : -1
  var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0

  value = Math.abs(value)

  if (isNaN(value) || value === Infinity) {
    m = isNaN(value) ? 1 : 0
    e = eMax
  } else {
    e = Math.floor(Math.log(value) / Math.LN2)
    if (value * (c = Math.pow(2, -e)) < 1) {
      e--
      c *= 2
    }
    if (e + eBias >= 1) {
      value += rt / c
    } else {
      value += rt * Math.pow(2, 1 - eBias)
    }
    if (value * c >= 2) {
      e++
      c /= 2
    }

    if (e + eBias >= eMax) {
      m = 0
      e = eMax
    } else if (e + eBias >= 1) {
      m = ((value * c) - 1) * Math.pow(2, mLen)
      e = e + eBias
    } else {
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
      e = 0
    }
  }

  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}

  e = (e << mLen) | m
  eLen += mLen
  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}

  buffer[offset + i - d] |= s * 128
}


/***/ }),

/***/ 72116:
/***/ ((module) => {

if (typeof Object.create === 'function') {
  // implementation from standard node.js 'util' module
  module.exports = function inherits(ctor, superCtor) {
    if (superCtor) {
      ctor.super_ = superCtor
      ctor.prototype = Object.create(superCtor.prototype, {
        constructor: {
          value: ctor,
          enumerable: false,
          writable: true,
          configurable: true
        }
      })
    }
  };
} else {
  // old school shim for old browsers
  module.exports = function inherits(ctor, superCtor) {
    if (superCtor) {
      ctor.super_ = superCtor
      var TempCtor = function () {}
      TempCtor.prototype = superCtor.prototype
      ctor.prototype = new TempCtor()
      ctor.prototype.constructor = ctor
    }
  }
}


/***/ }),

/***/ 35140:
/***/ ((module) => {

"use strict";


const word = '[a-fA-F\\d:]';
const b = options => options && options.includeBoundaries ?
	`(?:(?<=\\s|^)(?=${word})|(?<=${word})(?=\\s|$))` :
	'';

const v4 = '(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}';

const v6seg = '[a-fA-F\\d]{1,4}';
const v6 = `
(?:
(?:${v6seg}:){7}(?:${v6seg}|:)|                                    // 1:2:3:4:5:6:7::  1:2:3:4:5:6:7:8
(?:${v6seg}:){6}(?:${v4}|:${v6seg}|:)|                             // 1:2:3:4:5:6::    1:2:3:4:5:6::8   1:2:3:4:5:6::8  1:2:3:4:5:6::1.2.3.4
(?:${v6seg}:){5}(?::${v4}|(?::${v6seg}){1,2}|:)|                   // 1:2:3:4:5::      1:2:3:4:5::7:8   1:2:3:4:5::8    1:2:3:4:5::7:1.2.3.4
(?:${v6seg}:){4}(?:(?::${v6seg}){0,1}:${v4}|(?::${v6seg}){1,3}|:)| // 1:2:3:4::        1:2:3:4::6:7:8   1:2:3:4::8      1:2:3:4::6:7:1.2.3.4
(?:${v6seg}:){3}(?:(?::${v6seg}){0,2}:${v4}|(?::${v6seg}){1,4}|:)| // 1:2:3::          1:2:3::5:6:7:8   1:2:3::8        1:2:3::5:6:7:1.2.3.4
(?:${v6seg}:){2}(?:(?::${v6seg}){0,3}:${v4}|(?::${v6seg}){1,5}|:)| // 1:2::            1:2::4:5:6:7:8   1:2::8          1:2::4:5:6:7:1.2.3.4
(?:${v6seg}:){1}(?:(?::${v6seg}){0,4}:${v4}|(?::${v6seg}){1,6}|:)| // 1::              1::3:4:5:6:7:8   1::8            1::3:4:5:6:7:1.2.3.4
(?::(?:(?::${v6seg}){0,5}:${v4}|(?::${v6seg}){1,7}|:))             // ::2:3:4:5:6:7:8  ::2:3:4:5:6:7:8  ::8             ::1.2.3.4
)(?:%[0-9a-zA-Z]{1,})?                                             // %eth0            %1
`.replace(/\s*\/\/.*$/gm, '').replace(/\n/g, '').trim();

// Pre-compile only the exact regexes because adding a global flag make regexes stateful
const v46Exact = new RegExp(`(?:^${v4}$)|(?:^${v6}$)`);
const v4exact = new RegExp(`^${v4}$`);
const v6exact = new RegExp(`^${v6}$`);

const ip = options => options && options.exact ?
	v46Exact :
	new RegExp(`(?:${b(options)}${v4}${b(options)})|(?:${b(options)}${v6}${b(options)})`, 'g');

ip.v4 = options => options && options.exact ? v4exact : new RegExp(`${b(options)}${v4}${b(options)}`, 'g');
ip.v6 = options => options && options.exact ? v6exact : new RegExp(`${b(options)}${v6}${b(options)}`, 'g');

module.exports = ip;


/***/ }),

/***/ 32537:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

const {v4, v6} = __webpack_require__(85220);

const re4 = v4({exact: true});
const re6 = v6({exact: true});

module.exports = str => re4.test(str) ? 4 : (re6.test(str) ? 6 : 0);
module.exports.v4 = str => re4.test(str);
module.exports.v6 = str => re6.test(str);


/***/ }),

/***/ 85183:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

const ipRegex = __webpack_require__(35140);

const isIp = string => ipRegex({exact: true}).test(string);
isIp.v4 = string => ipRegex.v4({exact: true}).test(string);
isIp.v6 = string => ipRegex.v6({exact: true}).test(string);
isIp.version = string => isIp(string) ? (isIp.v4(string) ? 4 : 6) : undefined;

module.exports = isIp;


/***/ }),

/***/ 18093:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
/*!
 * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
 *
 * Copyright (c) 2014-2017, Jon Schlinkert.
 * Released under the MIT License.
 */



var isObject = __webpack_require__(85439);

function isObjectObject(o) {
  return isObject(o) === true
    && Object.prototype.toString.call(o) === '[object Object]';
}

module.exports = function isPlainObject(o) {
  var ctor,prot;

  if (isObjectObject(o) === false) return false;

  // If has modified constructor
  ctor = o.constructor;
  if (typeof ctor !== 'function') return false;

  // If has modified prototype
  prot = ctor.prototype;
  if (isObjectObject(prot) === false) return false;

  // If constructor does not have an Object-specific method
  if (prot.hasOwnProperty('isPrototypeOf') === false) {
    return false;
  }

  // Most likely a plain Object
  return true;
};


/***/ }),

/***/ 57082:
/***/ ((module) => {

var toString = {}.toString;

module.exports = Array.isArray || function (arr) {
  return toString.call(arr) == '[object Array]';
};


/***/ }),

/***/ 85439:
/***/ ((module) => {

"use strict";
/*!
 * isobject <https://github.com/jonschlinkert/isobject>
 *
 * Copyright (c) 2014-2017, Jon Schlinkert.
 * Released under the MIT License.
 */



module.exports = function isObject(val) {
  return val != null && typeof val === 'object' && Array.isArray(val) === false;
};


/***/ }),

/***/ 97420:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";



var yaml = __webpack_require__(61169);


module.exports = yaml;


/***/ }),

/***/ 61169:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";



var loader = __webpack_require__(36279);
var dumper = __webpack_require__(99897);


function deprecated(name) {
  return function () {
    throw new Error('Function ' + name + ' is deprecated and cannot be used.');
  };
}


module.exports.Type = __webpack_require__(26136);
module.exports.Schema = __webpack_require__(92915);
module.exports.FAILSAFE_SCHEMA = __webpack_require__(29899);
module.exports.JSON_SCHEMA = __webpack_require__(33460);
module.exports.CORE_SCHEMA = __webpack_require__(76421);
module.exports.DEFAULT_SAFE_SCHEMA = __webpack_require__(41893);
module.exports.DEFAULT_FULL_SCHEMA = __webpack_require__(41413);
module.exports.load                = loader.load;
module.exports.loadAll             = loader.loadAll;
module.exports.safeLoad            = loader.safeLoad;
module.exports.safeLoadAll         = loader.safeLoadAll;
module.exports.dump                = dumper.dump;
module.exports.safeDump            = dumper.safeDump;
module.exports.YAMLException = __webpack_require__(9643);

// Deprecated schema names from JS-YAML 2.0.x
module.exports.MINIMAL_SCHEMA = __webpack_require__(29899);
module.exports.SAFE_SCHEMA = __webpack_require__(41893);
module.exports.DEFAULT_SCHEMA = __webpack_require__(41413);

// Deprecated functions from JS-YAML 1.x.x
module.exports.scan           = deprecated('scan');
module.exports.parse          = deprecated('parse');
module.exports.compose        = deprecated('compose');
module.exports.addConstructor = deprecated('addConstructor');


/***/ }),

/***/ 19333:
/***/ ((module) => {

"use strict";



function isNothing(subject) {
  return (typeof subject === 'undefined') || (subject === null);
}


function isObject(subject) {
  return (typeof subject === 'object') && (subject !== null);
}


function toArray(sequence) {
  if (Array.isArray(sequence)) return sequence;
  else if (isNothing(sequence)) return [];

  return [ sequence ];
}


function extend(target, source) {
  var index, length, key, sourceKeys;

  if (source) {
    sourceKeys = Object.keys(source);

    for (index = 0, length = sourceKeys.length; index < length; index += 1) {
      key = sourceKeys[index];
      target[key] = source[key];
    }
  }

  return target;
}


function repeat(string, count) {
  var result = '', cycle;

  for (cycle = 0; cycle < count; cycle += 1) {
    result += string;
  }

  return result;
}


function isNegativeZero(number) {
  return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);
}


module.exports.isNothing      = isNothing;
module.exports.isObject       = isObject;
module.exports.toArray        = toArray;
module.exports.repeat         = repeat;
module.exports.isNegativeZero = isNegativeZero;
module.exports.extend         = extend;


/***/ }),

/***/ 99897:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


/*eslint-disable no-use-before-define*/

var common              = __webpack_require__(19333);
var YAMLException       = __webpack_require__(9643);
var DEFAULT_FULL_SCHEMA = __webpack_require__(41413);
var DEFAULT_SAFE_SCHEMA = __webpack_require__(41893);

var _toString       = Object.prototype.toString;
var _hasOwnProperty = Object.prototype.hasOwnProperty;

var CHAR_TAB                  = 0x09; /* Tab */
var CHAR_LINE_FEED            = 0x0A; /* LF */
var CHAR_CARRIAGE_RETURN      = 0x0D; /* CR */
var CHAR_SPACE                = 0x20; /* Space */
var CHAR_EXCLAMATION          = 0x21; /* ! */
var CHAR_DOUBLE_QUOTE         = 0x22; /* " */
var CHAR_SHARP                = 0x23; /* # */
var CHAR_PERCENT              = 0x25; /* % */
var CHAR_AMPERSAND            = 0x26; /* & */
var CHAR_SINGLE_QUOTE         = 0x27; /* ' */
var CHAR_ASTERISK             = 0x2A; /* * */
var CHAR_COMMA                = 0x2C; /* , */
var CHAR_MINUS                = 0x2D; /* - */
var CHAR_COLON                = 0x3A; /* : */
var CHAR_EQUALS               = 0x3D; /* = */
var CHAR_GREATER_THAN         = 0x3E; /* > */
var CHAR_QUESTION             = 0x3F; /* ? */
var CHAR_COMMERCIAL_AT        = 0x40; /* @ */
var CHAR_LEFT_SQUARE_BRACKET  = 0x5B; /* [ */
var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
var CHAR_GRAVE_ACCENT         = 0x60; /* ` */
var CHAR_LEFT_CURLY_BRACKET   = 0x7B; /* { */
var CHAR_VERTICAL_LINE        = 0x7C; /* | */
var CHAR_RIGHT_CURLY_BRACKET  = 0x7D; /* } */

var ESCAPE_SEQUENCES = {};

ESCAPE_SEQUENCES[0x00]   = '\\0';
ESCAPE_SEQUENCES[0x07]   = '\\a';
ESCAPE_SEQUENCES[0x08]   = '\\b';
ESCAPE_SEQUENCES[0x09]   = '\\t';
ESCAPE_SEQUENCES[0x0A]   = '\\n';
ESCAPE_SEQUENCES[0x0B]   = '\\v';
ESCAPE_SEQUENCES[0x0C]   = '\\f';
ESCAPE_SEQUENCES[0x0D]   = '\\r';
ESCAPE_SEQUENCES[0x1B]   = '\\e';
ESCAPE_SEQUENCES[0x22]   = '\\"';
ESCAPE_SEQUENCES[0x5C]   = '\\\\';
ESCAPE_SEQUENCES[0x85]   = '\\N';
ESCAPE_SEQUENCES[0xA0]   = '\\_';
ESCAPE_SEQUENCES[0x2028] = '\\L';
ESCAPE_SEQUENCES[0x2029] = '\\P';

var DEPRECATED_BOOLEANS_SYNTAX = [
  'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
  'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
];

function compileStyleMap(schema, map) {
  var result, keys, index, length, tag, style, type;

  if (map === null) return {};

  result = {};
  keys = Object.keys(map);

  for (index = 0, length = keys.length; index < length; index += 1) {
    tag = keys[index];
    style = String(map[tag]);

    if (tag.slice(0, 2) === '!!') {
      tag = 'tag:yaml.org,2002:' + tag.slice(2);
    }
    type = schema.compiledTypeMap['fallback'][tag];

    if (type && _hasOwnProperty.call(type.styleAliases, style)) {
      style = type.styleAliases[style];
    }

    result[tag] = style;
  }

  return result;
}

function encodeHex(character) {
  var string, handle, length;

  string = character.toString(16).toUpperCase();

  if (character <= 0xFF) {
    handle = 'x';
    length = 2;
  } else if (character <= 0xFFFF) {
    handle = 'u';
    length = 4;
  } else if (character <= 0xFFFFFFFF) {
    handle = 'U';
    length = 8;
  } else {
    throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');
  }

  return '\\' + handle + common.repeat('0', length - string.length) + string;
}

function State(options) {
  this.schema        = options['schema'] || DEFAULT_FULL_SCHEMA;
  this.indent        = Math.max(1, (options['indent'] || 2));
  this.noArrayIndent = options['noArrayIndent'] || false;
  this.skipInvalid   = options['skipInvalid'] || false;
  this.flowLevel     = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
  this.styleMap      = compileStyleMap(this.schema, options['styles'] || null);
  this.sortKeys      = options['sortKeys'] || false;
  this.lineWidth     = options['lineWidth'] || 80;
  this.noRefs        = options['noRefs'] || false;
  this.noCompatMode  = options['noCompatMode'] || false;
  this.condenseFlow  = options['condenseFlow'] || false;

  this.implicitTypes = this.schema.compiledImplicit;
  this.explicitTypes = this.schema.compiledExplicit;

  this.tag = null;
  this.result = '';

  this.duplicates = [];
  this.usedDuplicates = null;
}

// Indents every line in a string. Empty lines (\n only) are not indented.
function indentString(string, spaces) {
  var ind = common.repeat(' ', spaces),
      position = 0,
      next = -1,
      result = '',
      line,
      length = string.length;

  while (position < length) {
    next = string.indexOf('\n', position);
    if (next === -1) {
      line = string.slice(position);
      position = length;
    } else {
      line = string.slice(position, next + 1);
      position = next + 1;
    }

    if (line.length && line !== '\n') result += ind;

    result += line;
  }

  return result;
}

function generateNextLine(state, level) {
  return '\n' + common.repeat(' ', state.indent * level);
}

function testImplicitResolving(state, str) {
  var index, length, type;

  for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
    type = state.implicitTypes[index];

    if (type.resolve(str)) {
      return true;
    }
  }

  return false;
}

// [33] s-white ::= s-space | s-tab
function isWhitespace(c) {
  return c === CHAR_SPACE || c === CHAR_TAB;
}

// Returns true if the character can be printed without escaping.
// From YAML 1.2: "any allowed characters known to be non-printable
// should also be escaped. [However,] This isn’t mandatory"
// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
function isPrintable(c) {
  return  (0x00020 <= c && c <= 0x00007E)
      || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)
      || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */)
      ||  (0x10000 <= c && c <= 0x10FFFF);
}

// [34] ns-char ::= nb-char - s-white
// [27] nb-char ::= c-printable - b-char - c-byte-order-mark
// [26] b-char  ::= b-line-feed | b-carriage-return
// [24] b-line-feed       ::=     #xA    /* LF */
// [25] b-carriage-return ::=     #xD    /* CR */
// [3]  c-byte-order-mark ::=     #xFEFF
function isNsChar(c) {
  return isPrintable(c) && !isWhitespace(c)
    // byte-order-mark
    && c !== 0xFEFF
    // b-char
    && c !== CHAR_CARRIAGE_RETURN
    && c !== CHAR_LINE_FEED;
}

// Simplified test for values allowed after the first character in plain style.
function isPlainSafe(c, prev) {
  // Uses a subset of nb-char - c-flow-indicator - ":" - "#"
  // where nb-char ::= c-printable - b-char - c-byte-order-mark.
  return isPrintable(c) && c !== 0xFEFF
    // - c-flow-indicator
    && c !== CHAR_COMMA
    && c !== CHAR_LEFT_SQUARE_BRACKET
    && c !== CHAR_RIGHT_SQUARE_BRACKET
    && c !== CHAR_LEFT_CURLY_BRACKET
    && c !== CHAR_RIGHT_CURLY_BRACKET
    // - ":" - "#"
    // /* An ns-char preceding */ "#"
    && c !== CHAR_COLON
    && ((c !== CHAR_SHARP) || (prev && isNsChar(prev)));
}

// Simplified test for values allowed as the first character in plain style.
function isPlainSafeFirst(c) {
  // Uses a subset of ns-char - c-indicator
  // where ns-char = nb-char - s-white.
  return isPrintable(c) && c !== 0xFEFF
    && !isWhitespace(c) // - s-white
    // - (c-indicator ::=
    // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
    && c !== CHAR_MINUS
    && c !== CHAR_QUESTION
    && c !== CHAR_COLON
    && c !== CHAR_COMMA
    && c !== CHAR_LEFT_SQUARE_BRACKET
    && c !== CHAR_RIGHT_SQUARE_BRACKET
    && c !== CHAR_LEFT_CURLY_BRACKET
    && c !== CHAR_RIGHT_CURLY_BRACKET
    // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"”
    && c !== CHAR_SHARP
    && c !== CHAR_AMPERSAND
    && c !== CHAR_ASTERISK
    && c !== CHAR_EXCLAMATION
    && c !== CHAR_VERTICAL_LINE
    && c !== CHAR_EQUALS
    && c !== CHAR_GREATER_THAN
    && c !== CHAR_SINGLE_QUOTE
    && c !== CHAR_DOUBLE_QUOTE
    // | “%” | “@” | “`”)
    && c !== CHAR_PERCENT
    && c !== CHAR_COMMERCIAL_AT
    && c !== CHAR_GRAVE_ACCENT;
}

// Determines whether block indentation indicator is required.
function needIndentIndicator(string) {
  var leadingSpaceRe = /^\n* /;
  return leadingSpaceRe.test(string);
}

var STYLE_PLAIN   = 1,
    STYLE_SINGLE  = 2,
    STYLE_LITERAL = 3,
    STYLE_FOLDED  = 4,
    STYLE_DOUBLE  = 5;

// Determines which scalar styles are possible and returns the preferred style.
// lineWidth = -1 => no limit.
// Pre-conditions: str.length > 0.
// Post-conditions:
//    STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
//    STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
//    STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
  var i;
  var char, prev_char;
  var hasLineBreak = false;
  var hasFoldableLine = false; // only checked if shouldTrackWidth
  var shouldTrackWidth = lineWidth !== -1;
  var previousLineBreak = -1; // count the first line correctly
  var plain = isPlainSafeFirst(string.charCodeAt(0))
          && !isWhitespace(string.charCodeAt(string.length - 1));

  if (singleLineOnly) {
    // Case: no block styles.
    // Check for disallowed characters to rule out plain and single.
    for (i = 0; i < string.length; i++) {
      char = string.charCodeAt(i);
      if (!isPrintable(char)) {
        return STYLE_DOUBLE;
      }
      prev_char = i > 0 ? string.charCodeAt(i - 1) : null;
      plain = plain && isPlainSafe(char, prev_char);
    }
  } else {
    // Case: block styles permitted.
    for (i = 0; i < string.length; i++) {
      char = string.charCodeAt(i);
      if (char === CHAR_LINE_FEED) {
        hasLineBreak = true;
        // Check if any line can be folded.
        if (shouldTrackWidth) {
          hasFoldableLine = hasFoldableLine ||
            // Foldable line = too long, and not more-indented.
            (i - previousLineBreak - 1 > lineWidth &&
             string[previousLineBreak + 1] !== ' ');
          previousLineBreak = i;
        }
      } else if (!isPrintable(char)) {
        return STYLE_DOUBLE;
      }
      prev_char = i > 0 ? string.charCodeAt(i - 1) : null;
      plain = plain && isPlainSafe(char, prev_char);
    }
    // in case the end is missing a \n
    hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&
      (i - previousLineBreak - 1 > lineWidth &&
       string[previousLineBreak + 1] !== ' '));
  }
  // Although every style can represent \n without escaping, prefer block styles
  // for multiline, since they're more readable and they don't add empty lines.
  // Also prefer folding a super-long line.
  if (!hasLineBreak && !hasFoldableLine) {
    // Strings interpretable as another type have to be quoted;
    // e.g. the string 'true' vs. the boolean true.
    return plain && !testAmbiguousType(string)
      ? STYLE_PLAIN : STYLE_SINGLE;
  }
  // Edge case: block indentation indicator can only have one digit.
  if (indentPerLevel > 9 && needIndentIndicator(string)) {
    return STYLE_DOUBLE;
  }
  // At this point we know block styles are valid.
  // Prefer literal style unless we want to fold.
  return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
}

// Note: line breaking/folding is implemented for only the folded style.
// NB. We drop the last trailing newline (if any) of a returned block scalar
//  since the dumper adds its own newline. This always works:
//    • No ending newline => unaffected; already using strip "-" chomping.
//    • Ending newline    => removed then restored.
//  Importantly, this keeps the "+" chomp indicator from gaining an extra line.
function writeScalar(state, string, level, iskey) {
  state.dump = (function () {
    if (string.length === 0) {
      return "''";
    }
    if (!state.noCompatMode &&
        DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {
      return "'" + string + "'";
    }

    var indent = state.indent * Math.max(1, level); // no 0-indent scalars
    // As indentation gets deeper, let the width decrease monotonically
    // to the lower bound min(state.lineWidth, 40).
    // Note that this implies
    //  state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
    //  state.lineWidth > 40 + state.indent: width decreases until the lower bound.
    // This behaves better than a constant minimum width which disallows narrower options,
    // or an indent threshold which causes the width to suddenly increase.
    var lineWidth = state.lineWidth === -1
      ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);

    // Without knowing if keys are implicit/explicit, assume implicit for safety.
    var singleLineOnly = iskey
      // No block styles in flow mode.
      || (state.flowLevel > -1 && level >= state.flowLevel);
    function testAmbiguity(string) {
      return testImplicitResolving(state, string);
    }

    switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {
      case STYLE_PLAIN:
        return string;
      case STYLE_SINGLE:
        return "'" + string.replace(/'/g, "''") + "'";
      case STYLE_LITERAL:
        return '|' + blockHeader(string, state.indent)
          + dropEndingNewline(indentString(string, indent));
      case STYLE_FOLDED:
        return '>' + blockHeader(string, state.indent)
          + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
      case STYLE_DOUBLE:
        return '"' + escapeString(string, lineWidth) + '"';
      default:
        throw new YAMLException('impossible error: invalid scalar style');
    }
  }());
}

// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
function blockHeader(string, indentPerLevel) {
  var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';

  // note the special case: the string '\n' counts as a "trailing" empty line.
  var clip =          string[string.length - 1] === '\n';
  var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
  var chomp = keep ? '+' : (clip ? '' : '-');

  return indentIndicator + chomp + '\n';
}

// (See the note for writeScalar.)
function dropEndingNewline(string) {
  return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
}

// Note: a long line without a suitable break point will exceed the width limit.
// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
function foldString(string, width) {
  // In folded style, $k$ consecutive newlines output as $k+1$ newlines—
  // unless they're before or after a more-indented line, or at the very
  // beginning or end, in which case $k$ maps to $k$.
  // Therefore, parse each chunk as newline(s) followed by a content line.
  var lineRe = /(\n+)([^\n]*)/g;

  // first line (possibly an empty line)
  var result = (function () {
    var nextLF = string.indexOf('\n');
    nextLF = nextLF !== -1 ? nextLF : string.length;
    lineRe.lastIndex = nextLF;
    return foldLine(string.slice(0, nextLF), width);
  }());
  // If we haven't reached the first content line yet, don't add an extra \n.
  var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
  var moreIndented;

  // rest of the lines
  var match;
  while ((match = lineRe.exec(string))) {
    var prefix = match[1], line = match[2];
    moreIndented = (line[0] === ' ');
    result += prefix
      + (!prevMoreIndented && !moreIndented && line !== ''
        ? '\n' : '')
      + foldLine(line, width);
    prevMoreIndented = moreIndented;
  }

  return result;
}

// Greedy line breaking.
// Picks the longest line under the limit each time,
// otherwise settles for the shortest line over the limit.
// NB. More-indented lines *cannot* be folded, as that would add an extra \n.
function foldLine(line, width) {
  if (line === '' || line[0] === ' ') return line;

  // Since a more-indented line adds a \n, breaks can't be followed by a space.
  var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
  var match;
  // start is an inclusive index. end, curr, and next are exclusive.
  var start = 0, end, curr = 0, next = 0;
  var result = '';

  // Invariants: 0 <= start <= length-1.
  //   0 <= curr <= next <= max(0, length-2). curr - start <= width.
  // Inside the loop:
  //   A match implies length >= 2, so curr and next are <= length-2.
  while ((match = breakRe.exec(line))) {
    next = match.index;
    // maintain invariant: curr - start <= width
    if (next - start > width) {
      end = (curr > start) ? curr : next; // derive end <= length-2
      result += '\n' + line.slice(start, end);
      // skip the space that was output as \n
      start = end + 1;                    // derive start <= length-1
    }
    curr = next;
  }

  // By the invariants, start <= length-1, so there is something left over.
  // It is either the whole string or a part starting from non-whitespace.
  result += '\n';
  // Insert a break if the remainder is too long and there is a break available.
  if (line.length - start > width && curr > start) {
    result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
  } else {
    result += line.slice(start);
  }

  return result.slice(1); // drop extra \n joiner
}

// Escapes a double-quoted string.
function escapeString(string) {
  var result = '';
  var char, nextChar;
  var escapeSeq;

  for (var i = 0; i < string.length; i++) {
    char = string.charCodeAt(i);
    // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates").
    if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) {
      nextChar = string.charCodeAt(i + 1);
      if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) {
        // Combine the surrogate pair and store it escaped.
        result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000);
        // Advance index one extra since we already used that char here.
        i++; continue;
      }
    }
    escapeSeq = ESCAPE_SEQUENCES[char];
    result += !escapeSeq && isPrintable(char)
      ? string[i]
      : escapeSeq || encodeHex(char);
  }

  return result;
}

function writeFlowSequence(state, level, object) {
  var _result = '',
      _tag    = state.tag,
      index,
      length;

  for (index = 0, length = object.length; index < length; index += 1) {
    // Write only valid elements.
    if (writeNode(state, level, object[index], false, false)) {
      if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : '');
      _result += state.dump;
    }
  }

  state.tag = _tag;
  state.dump = '[' + _result + ']';
}

function writeBlockSequence(state, level, object, compact) {
  var _result = '',
      _tag    = state.tag,
      index,
      length;

  for (index = 0, length = object.length; index < length; index += 1) {
    // Write only valid elements.
    if (writeNode(state, level + 1, object[index], true, true)) {
      if (!compact || index !== 0) {
        _result += generateNextLine(state, level);
      }

      if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
        _result += '-';
      } else {
        _result += '- ';
      }

      _result += state.dump;
    }
  }

  state.tag = _tag;
  state.dump = _result || '[]'; // Empty sequence if no valid values.
}

function writeFlowMapping(state, level, object) {
  var _result       = '',
      _tag          = state.tag,
      objectKeyList = Object.keys(object),
      index,
      length,
      objectKey,
      objectValue,
      pairBuffer;

  for (index = 0, length = objectKeyList.length; index < length; index += 1) {

    pairBuffer = '';
    if (index !== 0) pairBuffer += ', ';

    if (state.condenseFlow) pairBuffer += '"';

    objectKey = objectKeyList[index];
    objectValue = object[objectKey];

    if (!writeNode(state, level, objectKey, false, false)) {
      continue; // Skip this pair because of invalid key;
    }

    if (state.dump.length > 1024) pairBuffer += '? ';

    pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');

    if (!writeNode(state, level, objectValue, false, false)) {
      continue; // Skip this pair because of invalid value.
    }

    pairBuffer += state.dump;

    // Both key and value are valid.
    _result += pairBuffer;
  }

  state.tag = _tag;
  state.dump = '{' + _result + '}';
}

function writeBlockMapping(state, level, object, compact) {
  var _result       = '',
      _tag          = state.tag,
      objectKeyList = Object.keys(object),
      index,
      length,
      objectKey,
      objectValue,
      explicitPair,
      pairBuffer;

  // Allow sorting keys so that the output file is deterministic
  if (state.sortKeys === true) {
    // Default sorting
    objectKeyList.sort();
  } else if (typeof state.sortKeys === 'function') {
    // Custom sort function
    objectKeyList.sort(state.sortKeys);
  } else if (state.sortKeys) {
    // Something is wrong
    throw new YAMLException('sortKeys must be a boolean or a function');
  }

  for (index = 0, length = objectKeyList.length; index < length; index += 1) {
    pairBuffer = '';

    if (!compact || index !== 0) {
      pairBuffer += generateNextLine(state, level);
    }

    objectKey = objectKeyList[index];
    objectValue = object[objectKey];

    if (!writeNode(state, level + 1, objectKey, true, true, true)) {
      continue; // Skip this pair because of invalid key.
    }

    explicitPair = (state.tag !== null && state.tag !== '?') ||
                   (state.dump && state.dump.length > 1024);

    if (explicitPair) {
      if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
        pairBuffer += '?';
      } else {
        pairBuffer += '? ';
      }
    }

    pairBuffer += state.dump;

    if (explicitPair) {
      pairBuffer += generateNextLine(state, level);
    }

    if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
      continue; // Skip this pair because of invalid value.
    }

    if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
      pairBuffer += ':';
    } else {
      pairBuffer += ': ';
    }

    pairBuffer += state.dump;

    // Both key and value are valid.
    _result += pairBuffer;
  }

  state.tag = _tag;
  state.dump = _result || '{}'; // Empty mapping if no valid pairs.
}

function detectType(state, object, explicit) {
  var _result, typeList, index, length, type, style;

  typeList = explicit ? state.explicitTypes : state.implicitTypes;

  for (index = 0, length = typeList.length; index < length; index += 1) {
    type = typeList[index];

    if ((type.instanceOf  || type.predicate) &&
        (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
        (!type.predicate  || type.predicate(object))) {

      state.tag = explicit ? type.tag : '?';

      if (type.represent) {
        style = state.styleMap[type.tag] || type.defaultStyle;

        if (_toString.call(type.represent) === '[object Function]') {
          _result = type.represent(object, style);
        } else if (_hasOwnProperty.call(type.represent, style)) {
          _result = type.represent[style](object, style);
        } else {
          throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
        }

        state.dump = _result;
      }

      return true;
    }
  }

  return false;
}

// Serializes `object` and writes it to global `result`.
// Returns true on success, or false on invalid object.
//
function writeNode(state, level, object, block, compact, iskey) {
  state.tag = null;
  state.dump = object;

  if (!detectType(state, object, false)) {
    detectType(state, object, true);
  }

  var type = _toString.call(state.dump);

  if (block) {
    block = (state.flowLevel < 0 || state.flowLevel > level);
  }

  var objectOrArray = type === '[object Object]' || type === '[object Array]',
      duplicateIndex,
      duplicate;

  if (objectOrArray) {
    duplicateIndex = state.duplicates.indexOf(object);
    duplicate = duplicateIndex !== -1;
  }

  if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
    compact = false;
  }

  if (duplicate && state.usedDuplicates[duplicateIndex]) {
    state.dump = '*ref_' + duplicateIndex;
  } else {
    if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
      state.usedDuplicates[duplicateIndex] = true;
    }
    if (type === '[object Object]') {
      if (block && (Object.keys(state.dump).length !== 0)) {
        writeBlockMapping(state, level, state.dump, compact);
        if (duplicate) {
          state.dump = '&ref_' + duplicateIndex + state.dump;
        }
      } else {
        writeFlowMapping(state, level, state.dump);
        if (duplicate) {
          state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
        }
      }
    } else if (type === '[object Array]') {
      var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level;
      if (block && (state.dump.length !== 0)) {
        writeBlockSequence(state, arrayLevel, state.dump, compact);
        if (duplicate) {
          state.dump = '&ref_' + duplicateIndex + state.dump;
        }
      } else {
        writeFlowSequence(state, arrayLevel, state.dump);
        if (duplicate) {
          state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
        }
      }
    } else if (type === '[object String]') {
      if (state.tag !== '?') {
        writeScalar(state, state.dump, level, iskey);
      }
    } else {
      if (state.skipInvalid) return false;
      throw new YAMLException('unacceptable kind of an object to dump ' + type);
    }

    if (state.tag !== null && state.tag !== '?') {
      state.dump = '!<' + state.tag + '> ' + state.dump;
    }
  }

  return true;
}

function getDuplicateReferences(object, state) {
  var objects = [],
      duplicatesIndexes = [],
      index,
      length;

  inspectNode(object, objects, duplicatesIndexes);

  for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
    state.duplicates.push(objects[duplicatesIndexes[index]]);
  }
  state.usedDuplicates = new Array(length);
}

function inspectNode(object, objects, duplicatesIndexes) {
  var objectKeyList,
      index,
      length;

  if (object !== null && typeof object === 'object') {
    index = objects.indexOf(object);
    if (index !== -1) {
      if (duplicatesIndexes.indexOf(index) === -1) {
        duplicatesIndexes.push(index);
      }
    } else {
      objects.push(object);

      if (Array.isArray(object)) {
        for (index = 0, length = object.length; index < length; index += 1) {
          inspectNode(object[index], objects, duplicatesIndexes);
        }
      } else {
        objectKeyList = Object.keys(object);

        for (index = 0, length = objectKeyList.length; index < length; index += 1) {
          inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
        }
      }
    }
  }
}

function dump(input, options) {
  options = options || {};

  var state = new State(options);

  if (!state.noRefs) getDuplicateReferences(input, state);

  if (writeNode(state, 0, input, true, true)) return state.dump + '\n';

  return '';
}

function safeDump(input, options) {
  return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
}

module.exports.dump     = dump;
module.exports.safeDump = safeDump;


/***/ }),

/***/ 9643:
/***/ ((module) => {

"use strict";
// YAML error class. http://stackoverflow.com/questions/8458984
//


function YAMLException(reason, mark) {
  // Super constructor
  Error.call(this);

  this.name = 'YAMLException';
  this.reason = reason;
  this.mark = mark;
  this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : '');

  // Include stack trace in error object
  if (Error.captureStackTrace) {
    // Chrome and NodeJS
    Error.captureStackTrace(this, this.constructor);
  } else {
    // FF, IE 10+ and Safari 6+. Fallback for others
    this.stack = (new Error()).stack || '';
  }
}


// Inherit from Error
YAMLException.prototype = Object.create(Error.prototype);
YAMLException.prototype.constructor = YAMLException;


YAMLException.prototype.toString = function toString(compact) {
  var result = this.name + ': ';

  result += this.reason || '(unknown reason)';

  if (!compact && this.mark) {
    result += ' ' + this.mark.toString();
  }

  return result;
};


module.exports = YAMLException;


/***/ }),

/***/ 36279:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


/*eslint-disable max-len,no-use-before-define*/

var common              = __webpack_require__(19333);
var YAMLException       = __webpack_require__(9643);
var Mark                = __webpack_require__(21617);
var DEFAULT_SAFE_SCHEMA = __webpack_require__(41893);
var DEFAULT_FULL_SCHEMA = __webpack_require__(41413);


var _hasOwnProperty = Object.prototype.hasOwnProperty;


var CONTEXT_FLOW_IN   = 1;
var CONTEXT_FLOW_OUT  = 2;
var CONTEXT_BLOCK_IN  = 3;
var CONTEXT_BLOCK_OUT = 4;


var CHOMPING_CLIP  = 1;
var CHOMPING_STRIP = 2;
var CHOMPING_KEEP  = 3;


var PATTERN_NON_PRINTABLE         = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
var PATTERN_FLOW_INDICATORS       = /[,\[\]\{\}]/;
var PATTERN_TAG_HANDLE            = /^(?:!|!!|![a-z\-]+!)$/i;
var PATTERN_TAG_URI               = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;


function _class(obj) { return Object.prototype.toString.call(obj); }

function is_EOL(c) {
  return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);
}

function is_WHITE_SPACE(c) {
  return (c === 0x09/* Tab */) || (c === 0x20/* Space */);
}

function is_WS_OR_EOL(c) {
  return (c === 0x09/* Tab */) ||
         (c === 0x20/* Space */) ||
         (c === 0x0A/* LF */) ||
         (c === 0x0D/* CR */);
}

function is_FLOW_INDICATOR(c) {
  return c === 0x2C/* , */ ||
         c === 0x5B/* [ */ ||
         c === 0x5D/* ] */ ||
         c === 0x7B/* { */ ||
         c === 0x7D/* } */;
}

function fromHexCode(c) {
  var lc;

  if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
    return c - 0x30;
  }

  /*eslint-disable no-bitwise*/
  lc = c | 0x20;

  if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {
    return lc - 0x61 + 10;
  }

  return -1;
}

function escapedHexLen(c) {
  if (c === 0x78/* x */) { return 2; }
  if (c === 0x75/* u */) { return 4; }
  if (c === 0x55/* U */) { return 8; }
  return 0;
}

function fromDecimalCode(c) {
  if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
    return c - 0x30;
  }

  return -1;
}

function simpleEscapeSequence(c) {
  /* eslint-disable indent */
  return (c === 0x30/* 0 */) ? '\x00' :
        (c === 0x61/* a */) ? '\x07' :
        (c === 0x62/* b */) ? '\x08' :
        (c === 0x74/* t */) ? '\x09' :
        (c === 0x09/* Tab */) ? '\x09' :
        (c === 0x6E/* n */) ? '\x0A' :
        (c === 0x76/* v */) ? '\x0B' :
        (c === 0x66/* f */) ? '\x0C' :
        (c === 0x72/* r */) ? '\x0D' :
        (c === 0x65/* e */) ? '\x1B' :
        (c === 0x20/* Space */) ? ' ' :
        (c === 0x22/* " */) ? '\x22' :
        (c === 0x2F/* / */) ? '/' :
        (c === 0x5C/* \ */) ? '\x5C' :
        (c === 0x4E/* N */) ? '\x85' :
        (c === 0x5F/* _ */) ? '\xA0' :
        (c === 0x4C/* L */) ? '\u2028' :
        (c === 0x50/* P */) ? '\u2029' : '';
}

function charFromCodepoint(c) {
  if (c <= 0xFFFF) {
    return String.fromCharCode(c);
  }
  // Encode UTF-16 surrogate pair
  // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF
  return String.fromCharCode(
    ((c - 0x010000) >> 10) + 0xD800,
    ((c - 0x010000) & 0x03FF) + 0xDC00
  );
}

var simpleEscapeCheck = new Array(256); // integer, for fast access
var simpleEscapeMap = new Array(256);
for (var i = 0; i < 256; i++) {
  simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
  simpleEscapeMap[i] = simpleEscapeSequence(i);
}


function State(input, options) {
  this.input = input;

  this.filename  = options['filename']  || null;
  this.schema    = options['schema']    || DEFAULT_FULL_SCHEMA;
  this.onWarning = options['onWarning'] || null;
  this.legacy    = options['legacy']    || false;
  this.json      = options['json']      || false;
  this.listener  = options['listener']  || null;

  this.implicitTypes = this.schema.compiledImplicit;
  this.typeMap       = this.schema.compiledTypeMap;

  this.length     = input.length;
  this.position   = 0;
  this.line       = 0;
  this.lineStart  = 0;
  this.lineIndent = 0;

  this.documents = [];

  /*
  this.version;
  this.checkLineBreaks;
  this.tagMap;
  this.anchorMap;
  this.tag;
  this.anchor;
  this.kind;
  this.result;*/

}


function generateError(state, message) {
  return new YAMLException(
    message,
    new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart)));
}

function throwError(state, message) {
  throw generateError(state, message);
}

function throwWarning(state, message) {
  if (state.onWarning) {
    state.onWarning.call(null, generateError(state, message));
  }
}


var directiveHandlers = {

  YAML: function handleYamlDirective(state, name, args) {

    var match, major, minor;

    if (state.version !== null) {
      throwError(state, 'duplication of %YAML directive');
    }

    if (args.length !== 1) {
      throwError(state, 'YAML directive accepts exactly one argument');
    }

    match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);

    if (match === null) {
      throwError(state, 'ill-formed argument of the YAML directive');
    }

    major = parseInt(match[1], 10);
    minor = parseInt(match[2], 10);

    if (major !== 1) {
      throwError(state, 'unacceptable YAML version of the document');
    }

    state.version = args[0];
    state.checkLineBreaks = (minor < 2);

    if (minor !== 1 && minor !== 2) {
      throwWarning(state, 'unsupported YAML version of the document');
    }
  },

  TAG: function handleTagDirective(state, name, args) {

    var handle, prefix;

    if (args.length !== 2) {
      throwError(state, 'TAG directive accepts exactly two arguments');
    }

    handle = args[0];
    prefix = args[1];

    if (!PATTERN_TAG_HANDLE.test(handle)) {
      throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');
    }

    if (_hasOwnProperty.call(state.tagMap, handle)) {
      throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
    }

    if (!PATTERN_TAG_URI.test(prefix)) {
      throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');
    }

    state.tagMap[handle] = prefix;
  }
};


function captureSegment(state, start, end, checkJson) {
  var _position, _length, _character, _result;

  if (start < end) {
    _result = state.input.slice(start, end);

    if (checkJson) {
      for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
        _character = _result.charCodeAt(_position);
        if (!(_character === 0x09 ||
              (0x20 <= _character && _character <= 0x10FFFF))) {
          throwError(state, 'expected valid JSON character');
        }
      }
    } else if (PATTERN_NON_PRINTABLE.test(_result)) {
      throwError(state, 'the stream contains non-printable characters');
    }

    state.result += _result;
  }
}

function mergeMappings(state, destination, source, overridableKeys) {
  var sourceKeys, key, index, quantity;

  if (!common.isObject(source)) {
    throwError(state, 'cannot merge mappings; the provided source object is unacceptable');
  }

  sourceKeys = Object.keys(source);

  for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
    key = sourceKeys[index];

    if (!_hasOwnProperty.call(destination, key)) {
      destination[key] = source[key];
      overridableKeys[key] = true;
    }
  }
}

function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) {
  var index, quantity;

  // The output is a plain object here, so keys can only be strings.
  // We need to convert keyNode to a string, but doing so can hang the process
  // (deeply nested arrays that explode exponentially using aliases).
  if (Array.isArray(keyNode)) {
    keyNode = Array.prototype.slice.call(keyNode);

    for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {
      if (Array.isArray(keyNode[index])) {
        throwError(state, 'nested arrays are not supported inside keys');
      }

      if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {
        keyNode[index] = '[object Object]';
      }
    }
  }

  // Avoid code execution in load() via toString property
  // (still use its own toString for arrays, timestamps,
  // and whatever user schema extensions happen to have @@toStringTag)
  if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {
    keyNode = '[object Object]';
  }


  keyNode = String(keyNode);

  if (_result === null) {
    _result = {};
  }

  if (keyTag === 'tag:yaml.org,2002:merge') {
    if (Array.isArray(valueNode)) {
      for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
        mergeMappings(state, _result, valueNode[index], overridableKeys);
      }
    } else {
      mergeMappings(state, _result, valueNode, overridableKeys);
    }
  } else {
    if (!state.json &&
        !_hasOwnProperty.call(overridableKeys, keyNode) &&
        _hasOwnProperty.call(_result, keyNode)) {
      state.line = startLine || state.line;
      state.position = startPos || state.position;
      throwError(state, 'duplicated mapping key');
    }
    _result[keyNode] = valueNode;
    delete overridableKeys[keyNode];
  }

  return _result;
}

function readLineBreak(state) {
  var ch;

  ch = state.input.charCodeAt(state.position);

  if (ch === 0x0A/* LF */) {
    state.position++;
  } else if (ch === 0x0D/* CR */) {
    state.position++;
    if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {
      state.position++;
    }
  } else {
    throwError(state, 'a line break is expected');
  }

  state.line += 1;
  state.lineStart = state.position;
}

function skipSeparationSpace(state, allowComments, checkIndent) {
  var lineBreaks = 0,
      ch = state.input.charCodeAt(state.position);

  while (ch !== 0) {
    while (is_WHITE_SPACE(ch)) {
      ch = state.input.charCodeAt(++state.position);
    }

    if (allowComments && ch === 0x23/* # */) {
      do {
        ch = state.input.charCodeAt(++state.position);
      } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);
    }

    if (is_EOL(ch)) {
      readLineBreak(state);

      ch = state.input.charCodeAt(state.position);
      lineBreaks++;
      state.lineIndent = 0;

      while (ch === 0x20/* Space */) {
        state.lineIndent++;
        ch = state.input.charCodeAt(++state.position);
      }
    } else {
      break;
    }
  }

  if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
    throwWarning(state, 'deficient indentation');
  }

  return lineBreaks;
}

function testDocumentSeparator(state) {
  var _position = state.position,
      ch;

  ch = state.input.charCodeAt(_position);

  // Condition state.position === state.lineStart is tested
  // in parent on each call, for efficiency. No needs to test here again.
  if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&
      ch === state.input.charCodeAt(_position + 1) &&
      ch === state.input.charCodeAt(_position + 2)) {

    _position += 3;

    ch = state.input.charCodeAt(_position);

    if (ch === 0 || is_WS_OR_EOL(ch)) {
      return true;
    }
  }

  return false;
}

function writeFoldedLines(state, count) {
  if (count === 1) {
    state.result += ' ';
  } else if (count > 1) {
    state.result += common.repeat('\n', count - 1);
  }
}


function readPlainScalar(state, nodeIndent, withinFlowCollection) {
  var preceding,
      following,
      captureStart,
      captureEnd,
      hasPendingContent,
      _line,
      _lineStart,
      _lineIndent,
      _kind = state.kind,
      _result = state.result,
      ch;

  ch = state.input.charCodeAt(state.position);

  if (is_WS_OR_EOL(ch)      ||
      is_FLOW_INDICATOR(ch) ||
      ch === 0x23/* # */    ||
      ch === 0x26/* & */    ||
      ch === 0x2A/* * */    ||
      ch === 0x21/* ! */    ||
      ch === 0x7C/* | */    ||
      ch === 0x3E/* > */    ||
      ch === 0x27/* ' */    ||
      ch === 0x22/* " */    ||
      ch === 0x25/* % */    ||
      ch === 0x40/* @ */    ||
      ch === 0x60/* ` */) {
    return false;
  }

  if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {
    following = state.input.charCodeAt(state.position + 1);

    if (is_WS_OR_EOL(following) ||
        withinFlowCollection && is_FLOW_INDICATOR(following)) {
      return false;
    }
  }

  state.kind = 'scalar';
  state.result = '';
  captureStart = captureEnd = state.position;
  hasPendingContent = false;

  while (ch !== 0) {
    if (ch === 0x3A/* : */) {
      following = state.input.charCodeAt(state.position + 1);

      if (is_WS_OR_EOL(following) ||
          withinFlowCollection && is_FLOW_INDICATOR(following)) {
        break;
      }

    } else if (ch === 0x23/* # */) {
      preceding = state.input.charCodeAt(state.position - 1);

      if (is_WS_OR_EOL(preceding)) {
        break;
      }

    } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||
               withinFlowCollection && is_FLOW_INDICATOR(ch)) {
      break;

    } else if (is_EOL(ch)) {
      _line = state.line;
      _lineStart = state.lineStart;
      _lineIndent = state.lineIndent;
      skipSeparationSpace(state, false, -1);

      if (state.lineIndent >= nodeIndent) {
        hasPendingContent = true;
        ch = state.input.charCodeAt(state.position);
        continue;
      } else {
        state.position = captureEnd;
        state.line = _line;
        state.lineStart = _lineStart;
        state.lineIndent = _lineIndent;
        break;
      }
    }

    if (hasPendingContent) {
      captureSegment(state, captureStart, captureEnd, false);
      writeFoldedLines(state, state.line - _line);
      captureStart = captureEnd = state.position;
      hasPendingContent = false;
    }

    if (!is_WHITE_SPACE(ch)) {
      captureEnd = state.position + 1;
    }

    ch = state.input.charCodeAt(++state.position);
  }

  captureSegment(state, captureStart, captureEnd, false);

  if (state.result) {
    return true;
  }

  state.kind = _kind;
  state.result = _result;
  return false;
}

function readSingleQuotedScalar(state, nodeIndent) {
  var ch,
      captureStart, captureEnd;

  ch = state.input.charCodeAt(state.position);

  if (ch !== 0x27/* ' */) {
    return false;
  }

  state.kind = 'scalar';
  state.result = '';
  state.position++;
  captureStart = captureEnd = state.position;

  while ((ch = state.input.charCodeAt(state.position)) !== 0) {
    if (ch === 0x27/* ' */) {
      captureSegment(state, captureStart, state.position, true);
      ch = state.input.charCodeAt(++state.position);

      if (ch === 0x27/* ' */) {
        captureStart = state.position;
        state.position++;
        captureEnd = state.position;
      } else {
        return true;
      }

    } else if (is_EOL(ch)) {
      captureSegment(state, captureStart, captureEnd, true);
      writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
      captureStart = captureEnd = state.position;

    } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
      throwError(state, 'unexpected end of the document within a single quoted scalar');

    } else {
      state.position++;
      captureEnd = state.position;
    }
  }

  throwError(state, 'unexpected end of the stream within a single quoted scalar');
}

function readDoubleQuotedScalar(state, nodeIndent) {
  var captureStart,
      captureEnd,
      hexLength,
      hexResult,
      tmp,
      ch;

  ch = state.input.charCodeAt(state.position);

  if (ch !== 0x22/* " */) {
    return false;
  }

  state.kind = 'scalar';
  state.result = '';
  state.position++;
  captureStart = captureEnd = state.position;

  while ((ch = state.input.charCodeAt(state.position)) !== 0) {
    if (ch === 0x22/* " */) {
      captureSegment(state, captureStart, state.position, true);
      state.position++;
      return true;

    } else if (ch === 0x5C/* \ */) {
      captureSegment(state, captureStart, state.position, true);
      ch = state.input.charCodeAt(++state.position);

      if (is_EOL(ch)) {
        skipSeparationSpace(state, false, nodeIndent);

        // TODO: rework to inline fn with no type cast?
      } else if (ch < 256 && simpleEscapeCheck[ch]) {
        state.result += simpleEscapeMap[ch];
        state.position++;

      } else if ((tmp = escapedHexLen(ch)) > 0) {
        hexLength = tmp;
        hexResult = 0;

        for (; hexLength > 0; hexLength--) {
          ch = state.input.charCodeAt(++state.position);

          if ((tmp = fromHexCode(ch)) >= 0) {
            hexResult = (hexResult << 4) + tmp;

          } else {
            throwError(state, 'expected hexadecimal character');
          }
        }

        state.result += charFromCodepoint(hexResult);

        state.position++;

      } else {
        throwError(state, 'unknown escape sequence');
      }

      captureStart = captureEnd = state.position;

    } else if (is_EOL(ch)) {
      captureSegment(state, captureStart, captureEnd, true);
      writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
      captureStart = captureEnd = state.position;

    } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
      throwError(state, 'unexpected end of the document within a double quoted scalar');

    } else {
      state.position++;
      captureEnd = state.position;
    }
  }

  throwError(state, 'unexpected end of the stream within a double quoted scalar');
}

function readFlowCollection(state, nodeIndent) {
  var readNext = true,
      _line,
      _tag     = state.tag,
      _result,
      _anchor  = state.anchor,
      following,
      terminator,
      isPair,
      isExplicitPair,
      isMapping,
      overridableKeys = {},
      keyNode,
      keyTag,
      valueNode,
      ch;

  ch = state.input.charCodeAt(state.position);

  if (ch === 0x5B/* [ */) {
    terminator = 0x5D;/* ] */
    isMapping = false;
    _result = [];
  } else if (ch === 0x7B/* { */) {
    terminator = 0x7D;/* } */
    isMapping = true;
    _result = {};
  } else {
    return false;
  }

  if (state.anchor !== null) {
    state.anchorMap[state.anchor] = _result;
  }

  ch = state.input.charCodeAt(++state.position);

  while (ch !== 0) {
    skipSeparationSpace(state, true, nodeIndent);

    ch = state.input.charCodeAt(state.position);

    if (ch === terminator) {
      state.position++;
      state.tag = _tag;
      state.anchor = _anchor;
      state.kind = isMapping ? 'mapping' : 'sequence';
      state.result = _result;
      return true;
    } else if (!readNext) {
      throwError(state, 'missed comma between flow collection entries');
    }

    keyTag = keyNode = valueNode = null;
    isPair = isExplicitPair = false;

    if (ch === 0x3F/* ? */) {
      following = state.input.charCodeAt(state.position + 1);

      if (is_WS_OR_EOL(following)) {
        isPair = isExplicitPair = true;
        state.position++;
        skipSeparationSpace(state, true, nodeIndent);
      }
    }

    _line = state.line;
    composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
    keyTag = state.tag;
    keyNode = state.result;
    skipSeparationSpace(state, true, nodeIndent);

    ch = state.input.charCodeAt(state.position);

    if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {
      isPair = true;
      ch = state.input.charCodeAt(++state.position);
      skipSeparationSpace(state, true, nodeIndent);
      composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
      valueNode = state.result;
    }

    if (isMapping) {
      storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode);
    } else if (isPair) {
      _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode));
    } else {
      _result.push(keyNode);
    }

    skipSeparationSpace(state, true, nodeIndent);

    ch = state.input.charCodeAt(state.position);

    if (ch === 0x2C/* , */) {
      readNext = true;
      ch = state.input.charCodeAt(++state.position);
    } else {
      readNext = false;
    }
  }

  throwError(state, 'unexpected end of the stream within a flow collection');
}

function readBlockScalar(state, nodeIndent) {
  var captureStart,
      folding,
      chomping       = CHOMPING_CLIP,
      didReadContent = false,
      detectedIndent = false,
      textIndent     = nodeIndent,
      emptyLines     = 0,
      atMoreIndented = false,
      tmp,
      ch;

  ch = state.input.charCodeAt(state.position);

  if (ch === 0x7C/* | */) {
    folding = false;
  } else if (ch === 0x3E/* > */) {
    folding = true;
  } else {
    return false;
  }

  state.kind = 'scalar';
  state.result = '';

  while (ch !== 0) {
    ch = state.input.charCodeAt(++state.position);

    if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {
      if (CHOMPING_CLIP === chomping) {
        chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;
      } else {
        throwError(state, 'repeat of a chomping mode identifier');
      }

    } else if ((tmp = fromDecimalCode(ch)) >= 0) {
      if (tmp === 0) {
        throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');
      } else if (!detectedIndent) {
        textIndent = nodeIndent + tmp - 1;
        detectedIndent = true;
      } else {
        throwError(state, 'repeat of an indentation width identifier');
      }

    } else {
      break;
    }
  }

  if (is_WHITE_SPACE(ch)) {
    do { ch = state.input.charCodeAt(++state.position); }
    while (is_WHITE_SPACE(ch));

    if (ch === 0x23/* # */) {
      do { ch = state.input.charCodeAt(++state.position); }
      while (!is_EOL(ch) && (ch !== 0));
    }
  }

  while (ch !== 0) {
    readLineBreak(state);
    state.lineIndent = 0;

    ch = state.input.charCodeAt(state.position);

    while ((!detectedIndent || state.lineIndent < textIndent) &&
           (ch === 0x20/* Space */)) {
      state.lineIndent++;
      ch = state.input.charCodeAt(++state.position);
    }

    if (!detectedIndent && state.lineIndent > textIndent) {
      textIndent = state.lineIndent;
    }

    if (is_EOL(ch)) {
      emptyLines++;
      continue;
    }

    // End of the scalar.
    if (state.lineIndent < textIndent) {

      // Perform the chomping.
      if (chomping === CHOMPING_KEEP) {
        state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
      } else if (chomping === CHOMPING_CLIP) {
        if (didReadContent) { // i.e. only if the scalar is not empty.
          state.result += '\n';
        }
      }

      // Break this `while` cycle and go to the funciton's epilogue.
      break;
    }

    // Folded style: use fancy rules to handle line breaks.
    if (folding) {

      // Lines starting with white space characters (more-indented lines) are not folded.
      if (is_WHITE_SPACE(ch)) {
        atMoreIndented = true;
        // except for the first content line (cf. Example 8.1)
        state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);

      // End of more-indented block.
      } else if (atMoreIndented) {
        atMoreIndented = false;
        state.result += common.repeat('\n', emptyLines + 1);

      // Just one line break - perceive as the same line.
      } else if (emptyLines === 0) {
        if (didReadContent) { // i.e. only if we have already read some scalar content.
          state.result += ' ';
        }

      // Several line breaks - perceive as different lines.
      } else {
        state.result += common.repeat('\n', emptyLines);
      }

    // Literal style: just add exact number of line breaks between content lines.
    } else {
      // Keep all line breaks except the header line break.
      state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
    }

    didReadContent = true;
    detectedIndent = true;
    emptyLines = 0;
    captureStart = state.position;

    while (!is_EOL(ch) && (ch !== 0)) {
      ch = state.input.charCodeAt(++state.position);
    }

    captureSegment(state, captureStart, state.position, false);
  }

  return true;
}

function readBlockSequence(state, nodeIndent) {
  var _line,
      _tag      = state.tag,
      _anchor   = state.anchor,
      _result   = [],
      following,
      detected  = false,
      ch;

  if (state.anchor !== null) {
    state.anchorMap[state.anchor] = _result;
  }

  ch = state.input.charCodeAt(state.position);

  while (ch !== 0) {

    if (ch !== 0x2D/* - */) {
      break;
    }

    following = state.input.charCodeAt(state.position + 1);

    if (!is_WS_OR_EOL(following)) {
      break;
    }

    detected = true;
    state.position++;

    if (skipSeparationSpace(state, true, -1)) {
      if (state.lineIndent <= nodeIndent) {
        _result.push(null);
        ch = state.input.charCodeAt(state.position);
        continue;
      }
    }

    _line = state.line;
    composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
    _result.push(state.result);
    skipSeparationSpace(state, true, -1);

    ch = state.input.charCodeAt(state.position);

    if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
      throwError(state, 'bad indentation of a sequence entry');
    } else if (state.lineIndent < nodeIndent) {
      break;
    }
  }

  if (detected) {
    state.tag = _tag;
    state.anchor = _anchor;
    state.kind = 'sequence';
    state.result = _result;
    return true;
  }
  return false;
}

function readBlockMapping(state, nodeIndent, flowIndent) {
  var following,
      allowCompact,
      _line,
      _pos,
      _tag          = state.tag,
      _anchor       = state.anchor,
      _result       = {},
      overridableKeys = {},
      keyTag        = null,
      keyNode       = null,
      valueNode     = null,
      atExplicitKey = false,
      detected      = false,
      ch;

  if (state.anchor !== null) {
    state.anchorMap[state.anchor] = _result;
  }

  ch = state.input.charCodeAt(state.position);

  while (ch !== 0) {
    following = state.input.charCodeAt(state.position + 1);
    _line = state.line; // Save the current line.
    _pos = state.position;

    //
    // Explicit notation case. There are two separate blocks:
    // first for the key (denoted by "?") and second for the value (denoted by ":")
    //
    if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {

      if (ch === 0x3F/* ? */) {
        if (atExplicitKey) {
          storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
          keyTag = keyNode = valueNode = null;
        }

        detected = true;
        atExplicitKey = true;
        allowCompact = true;

      } else if (atExplicitKey) {
        // i.e. 0x3A/* : */ === character after the explicit key.
        atExplicitKey = false;
        allowCompact = true;

      } else {
        throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');
      }

      state.position += 1;
      ch = following;

    //
    // Implicit notation case. Flow-style node as the key first, then ":", and the value.
    //
    } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {

      if (state.line === _line) {
        ch = state.input.charCodeAt(state.position);

        while (is_WHITE_SPACE(ch)) {
          ch = state.input.charCodeAt(++state.position);
        }

        if (ch === 0x3A/* : */) {
          ch = state.input.charCodeAt(++state.position);

          if (!is_WS_OR_EOL(ch)) {
            throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');
          }

          if (atExplicitKey) {
            storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
            keyTag = keyNode = valueNode = null;
          }

          detected = true;
          atExplicitKey = false;
          allowCompact = false;
          keyTag = state.tag;
          keyNode = state.result;

        } else if (detected) {
          throwError(state, 'can not read an implicit mapping pair; a colon is missed');

        } else {
          state.tag = _tag;
          state.anchor = _anchor;
          return true; // Keep the result of `composeNode`.
        }

      } else if (detected) {
        throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');

      } else {
        state.tag = _tag;
        state.anchor = _anchor;
        return true; // Keep the result of `composeNode`.
      }

    } else {
      break; // Reading is done. Go to the epilogue.
    }

    //
    // Common reading code for both explicit and implicit notations.
    //
    if (state.line === _line || state.lineIndent > nodeIndent) {
      if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
        if (atExplicitKey) {
          keyNode = state.result;
        } else {
          valueNode = state.result;
        }
      }

      if (!atExplicitKey) {
        storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos);
        keyTag = keyNode = valueNode = null;
      }

      skipSeparationSpace(state, true, -1);
      ch = state.input.charCodeAt(state.position);
    }

    if (state.lineIndent > nodeIndent && (ch !== 0)) {
      throwError(state, 'bad indentation of a mapping entry');
    } else if (state.lineIndent < nodeIndent) {
      break;
    }
  }

  //
  // Epilogue.
  //

  // Special case: last mapping's node contains only the key in explicit notation.
  if (atExplicitKey) {
    storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
  }

  // Expose the resulting mapping.
  if (detected) {
    state.tag = _tag;
    state.anchor = _anchor;
    state.kind = 'mapping';
    state.result = _result;
  }

  return detected;
}

function readTagProperty(state) {
  var _position,
      isVerbatim = false,
      isNamed    = false,
      tagHandle,
      tagName,
      ch;

  ch = state.input.charCodeAt(state.position);

  if (ch !== 0x21/* ! */) return false;

  if (state.tag !== null) {
    throwError(state, 'duplication of a tag property');
  }

  ch = state.input.charCodeAt(++state.position);

  if (ch === 0x3C/* < */) {
    isVerbatim = true;
    ch = state.input.charCodeAt(++state.position);

  } else if (ch === 0x21/* ! */) {
    isNamed = true;
    tagHandle = '!!';
    ch = state.input.charCodeAt(++state.position);

  } else {
    tagHandle = '!';
  }

  _position = state.position;

  if (isVerbatim) {
    do { ch = state.input.charCodeAt(++state.position); }
    while (ch !== 0 && ch !== 0x3E/* > */);

    if (state.position < state.length) {
      tagName = state.input.slice(_position, state.position);
      ch = state.input.charCodeAt(++state.position);
    } else {
      throwError(state, 'unexpected end of the stream within a verbatim tag');
    }
  } else {
    while (ch !== 0 && !is_WS_OR_EOL(ch)) {

      if (ch === 0x21/* ! */) {
        if (!isNamed) {
          tagHandle = state.input.slice(_position - 1, state.position + 1);

          if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
            throwError(state, 'named tag handle cannot contain such characters');
          }

          isNamed = true;
          _position = state.position + 1;
        } else {
          throwError(state, 'tag suffix cannot contain exclamation marks');
        }
      }

      ch = state.input.charCodeAt(++state.position);
    }

    tagName = state.input.slice(_position, state.position);

    if (PATTERN_FLOW_INDICATORS.test(tagName)) {
      throwError(state, 'tag suffix cannot contain flow indicator characters');
    }
  }

  if (tagName && !PATTERN_TAG_URI.test(tagName)) {
    throwError(state, 'tag name cannot contain such characters: ' + tagName);
  }

  if (isVerbatim) {
    state.tag = tagName;

  } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) {
    state.tag = state.tagMap[tagHandle] + tagName;

  } else if (tagHandle === '!') {
    state.tag = '!' + tagName;

  } else if (tagHandle === '!!') {
    state.tag = 'tag:yaml.org,2002:' + tagName;

  } else {
    throwError(state, 'undeclared tag handle "' + tagHandle + '"');
  }

  return true;
}

function readAnchorProperty(state) {
  var _position,
      ch;

  ch = state.input.charCodeAt(state.position);

  if (ch !== 0x26/* & */) return false;

  if (state.anchor !== null) {
    throwError(state, 'duplication of an anchor property');
  }

  ch = state.input.charCodeAt(++state.position);
  _position = state.position;

  while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
    ch = state.input.charCodeAt(++state.position);
  }

  if (state.position === _position) {
    throwError(state, 'name of an anchor node must contain at least one character');
  }

  state.anchor = state.input.slice(_position, state.position);
  return true;
}

function readAlias(state) {
  var _position, alias,
      ch;

  ch = state.input.charCodeAt(state.position);

  if (ch !== 0x2A/* * */) return false;

  ch = state.input.charCodeAt(++state.position);
  _position = state.position;

  while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
    ch = state.input.charCodeAt(++state.position);
  }

  if (state.position === _position) {
    throwError(state, 'name of an alias node must contain at least one character');
  }

  alias = state.input.slice(_position, state.position);

  if (!_hasOwnProperty.call(state.anchorMap, alias)) {
    throwError(state, 'unidentified alias "' + alias + '"');
  }

  state.result = state.anchorMap[alias];
  skipSeparationSpace(state, true, -1);
  return true;
}

function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
  var allowBlockStyles,
      allowBlockScalars,
      allowBlockCollections,
      indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent
      atNewLine  = false,
      hasContent = false,
      typeIndex,
      typeQuantity,
      type,
      flowIndent,
      blockIndent;

  if (state.listener !== null) {
    state.listener('open', state);
  }

  state.tag    = null;
  state.anchor = null;
  state.kind   = null;
  state.result = null;

  allowBlockStyles = allowBlockScalars = allowBlockCollections =
    CONTEXT_BLOCK_OUT === nodeContext ||
    CONTEXT_BLOCK_IN  === nodeContext;

  if (allowToSeek) {
    if (skipSeparationSpace(state, true, -1)) {
      atNewLine = true;

      if (state.lineIndent > parentIndent) {
        indentStatus = 1;
      } else if (state.lineIndent === parentIndent) {
        indentStatus = 0;
      } else if (state.lineIndent < parentIndent) {
        indentStatus = -1;
      }
    }
  }

  if (indentStatus === 1) {
    while (readTagProperty(state) || readAnchorProperty(state)) {
      if (skipSeparationSpace(state, true, -1)) {
        atNewLine = true;
        allowBlockCollections = allowBlockStyles;

        if (state.lineIndent > parentIndent) {
          indentStatus = 1;
        } else if (state.lineIndent === parentIndent) {
          indentStatus = 0;
        } else if (state.lineIndent < parentIndent) {
          indentStatus = -1;
        }
      } else {
        allowBlockCollections = false;
      }
    }
  }

  if (allowBlockCollections) {
    allowBlockCollections = atNewLine || allowCompact;
  }

  if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
    if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
      flowIndent = parentIndent;
    } else {
      flowIndent = parentIndent + 1;
    }

    blockIndent = state.position - state.lineStart;

    if (indentStatus === 1) {
      if (allowBlockCollections &&
          (readBlockSequence(state, blockIndent) ||
           readBlockMapping(state, blockIndent, flowIndent)) ||
          readFlowCollection(state, flowIndent)) {
        hasContent = true;
      } else {
        if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||
            readSingleQuotedScalar(state, flowIndent) ||
            readDoubleQuotedScalar(state, flowIndent)) {
          hasContent = true;

        } else if (readAlias(state)) {
          hasContent = true;

          if (state.tag !== null || state.anchor !== null) {
            throwError(state, 'alias node should not have any properties');
          }

        } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
          hasContent = true;

          if (state.tag === null) {
            state.tag = '?';
          }
        }

        if (state.anchor !== null) {
          state.anchorMap[state.anchor] = state.result;
        }
      }
    } else if (indentStatus === 0) {
      // Special case: block sequences are allowed to have same indentation level as the parent.
      // http://www.yaml.org/spec/1.2/spec.html#id2799784
      hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
    }
  }

  if (state.tag !== null && state.tag !== '!') {
    if (state.tag === '?') {
      // Implicit resolving is not allowed for non-scalar types, and '?'
      // non-specific tag is only automatically assigned to plain scalars.
      //
      // We only need to check kind conformity in case user explicitly assigns '?'
      // tag, for example like this: "!<?> [0]"
      //
      if (state.result !== null && state.kind !== 'scalar') {
        throwError(state, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state.kind + '"');
      }

      for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
        type = state.implicitTypes[typeIndex];

        if (type.resolve(state.result)) { // `state.result` updated in resolver if matched
          state.result = type.construct(state.result);
          state.tag = type.tag;
          if (state.anchor !== null) {
            state.anchorMap[state.anchor] = state.result;
          }
          break;
        }
      }
    } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) {
      type = state.typeMap[state.kind || 'fallback'][state.tag];

      if (state.result !== null && type.kind !== state.kind) {
        throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');
      }

      if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched
        throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');
      } else {
        state.result = type.construct(state.result);
        if (state.anchor !== null) {
          state.anchorMap[state.anchor] = state.result;
        }
      }
    } else {
      throwError(state, 'unknown tag !<' + state.tag + '>');
    }
  }

  if (state.listener !== null) {
    state.listener('close', state);
  }
  return state.tag !== null ||  state.anchor !== null || hasContent;
}

function readDocument(state) {
  var documentStart = state.position,
      _position,
      directiveName,
      directiveArgs,
      hasDirectives = false,
      ch;

  state.version = null;
  state.checkLineBreaks = state.legacy;
  state.tagMap = {};
  state.anchorMap = {};

  while ((ch = state.input.charCodeAt(state.position)) !== 0) {
    skipSeparationSpace(state, true, -1);

    ch = state.input.charCodeAt(state.position);

    if (state.lineIndent > 0 || ch !== 0x25/* % */) {
      break;
    }

    hasDirectives = true;
    ch = state.input.charCodeAt(++state.position);
    _position = state.position;

    while (ch !== 0 && !is_WS_OR_EOL(ch)) {
      ch = state.input.charCodeAt(++state.position);
    }

    directiveName = state.input.slice(_position, state.position);
    directiveArgs = [];

    if (directiveName.length < 1) {
      throwError(state, 'directive name must not be less than one character in length');
    }

    while (ch !== 0) {
      while (is_WHITE_SPACE(ch)) {
        ch = state.input.charCodeAt(++state.position);
      }

      if (ch === 0x23/* # */) {
        do { ch = state.input.charCodeAt(++state.position); }
        while (ch !== 0 && !is_EOL(ch));
        break;
      }

      if (is_EOL(ch)) break;

      _position = state.position;

      while (ch !== 0 && !is_WS_OR_EOL(ch)) {
        ch = state.input.charCodeAt(++state.position);
      }

      directiveArgs.push(state.input.slice(_position, state.position));
    }

    if (ch !== 0) readLineBreak(state);

    if (_hasOwnProperty.call(directiveHandlers, directiveName)) {
      directiveHandlers[directiveName](state, directiveName, directiveArgs);
    } else {
      throwWarning(state, 'unknown document directive "' + directiveName + '"');
    }
  }

  skipSeparationSpace(state, true, -1);

  if (state.lineIndent === 0 &&
      state.input.charCodeAt(state.position)     === 0x2D/* - */ &&
      state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&
      state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {
    state.position += 3;
    skipSeparationSpace(state, true, -1);

  } else if (hasDirectives) {
    throwError(state, 'directives end mark is expected');
  }

  composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
  skipSeparationSpace(state, true, -1);

  if (state.checkLineBreaks &&
      PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
    throwWarning(state, 'non-ASCII line breaks are interpreted as content');
  }

  state.documents.push(state.result);

  if (state.position === state.lineStart && testDocumentSeparator(state)) {

    if (state.input.charCodeAt(state.position) === 0x2E/* . */) {
      state.position += 3;
      skipSeparationSpace(state, true, -1);
    }
    return;
  }

  if (state.position < (state.length - 1)) {
    throwError(state, 'end of the stream or a document separator is expected');
  } else {
    return;
  }
}


function loadDocuments(input, options) {
  input = String(input);
  options = options || {};

  if (input.length !== 0) {

    // Add tailing `\n` if not exists
    if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&
        input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {
      input += '\n';
    }

    // Strip BOM
    if (input.charCodeAt(0) === 0xFEFF) {
      input = input.slice(1);
    }
  }

  var state = new State(input, options);

  var nullpos = input.indexOf('\0');

  if (nullpos !== -1) {
    state.position = nullpos;
    throwError(state, 'null byte is not allowed in input');
  }

  // Use 0 as string terminator. That significantly simplifies bounds check.
  state.input += '\0';

  while (state.input.charCodeAt(state.position) === 0x20/* Space */) {
    state.lineIndent += 1;
    state.position += 1;
  }

  while (state.position < (state.length - 1)) {
    readDocument(state);
  }

  return state.documents;
}


function loadAll(input, iterator, options) {
  if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {
    options = iterator;
    iterator = null;
  }

  var documents = loadDocuments(input, options);

  if (typeof iterator !== 'function') {
    return documents;
  }

  for (var index = 0, length = documents.length; index < length; index += 1) {
    iterator(documents[index]);
  }
}


function load(input, options) {
  var documents = loadDocuments(input, options);

  if (documents.length === 0) {
    /*eslint-disable no-undefined*/
    return undefined;
  } else if (documents.length === 1) {
    return documents[0];
  }
  throw new YAMLException('expected a single document in the stream, but found more');
}


function safeLoadAll(input, iterator, options) {
  if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') {
    options = iterator;
    iterator = null;
  }

  return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
}


function safeLoad(input, options) {
  return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
}


module.exports.loadAll     = loadAll;
module.exports.load        = load;
module.exports.safeLoadAll = safeLoadAll;
module.exports.safeLoad    = safeLoad;


/***/ }),

/***/ 21617:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";



var common = __webpack_require__(19333);


function Mark(name, buffer, position, line, column) {
  this.name     = name;
  this.buffer   = buffer;
  this.position = position;
  this.line     = line;
  this.column   = column;
}


Mark.prototype.getSnippet = function getSnippet(indent, maxLength) {
  var head, start, tail, end, snippet;

  if (!this.buffer) return null;

  indent = indent || 4;
  maxLength = maxLength || 75;

  head = '';
  start = this.position;

  while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) {
    start -= 1;
    if (this.position - start > (maxLength / 2 - 1)) {
      head = ' ... ';
      start += 5;
      break;
    }
  }

  tail = '';
  end = this.position;

  while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) {
    end += 1;
    if (end - this.position > (maxLength / 2 - 1)) {
      tail = ' ... ';
      end -= 5;
      break;
    }
  }

  snippet = this.buffer.slice(start, end);

  return common.repeat(' ', indent) + head + snippet + tail + '\n' +
         common.repeat(' ', indent + this.position - start + head.length) + '^';
};


Mark.prototype.toString = function toString(compact) {
  var snippet, where = '';

  if (this.name) {
    where += 'in "' + this.name + '" ';
  }

  where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1);

  if (!compact) {
    snippet = this.getSnippet();

    if (snippet) {
      where += ':\n' + snippet;
    }
  }

  return where;
};


module.exports = Mark;


/***/ }),

/***/ 92915:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


/*eslint-disable max-len*/

var common        = __webpack_require__(19333);
var YAMLException = __webpack_require__(9643);
var Type          = __webpack_require__(26136);


function compileList(schema, name, result) {
  var exclude = [];

  schema.include.forEach(function (includedSchema) {
    result = compileList(includedSchema, name, result);
  });

  schema[name].forEach(function (currentType) {
    result.forEach(function (previousType, previousIndex) {
      if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {
        exclude.push(previousIndex);
      }
    });

    result.push(currentType);
  });

  return result.filter(function (type, index) {
    return exclude.indexOf(index) === -1;
  });
}


function compileMap(/* lists... */) {
  var result = {
        scalar: {},
        sequence: {},
        mapping: {},
        fallback: {}
      }, index, length;

  function collectType(type) {
    result[type.kind][type.tag] = result['fallback'][type.tag] = type;
  }

  for (index = 0, length = arguments.length; index < length; index += 1) {
    arguments[index].forEach(collectType);
  }
  return result;
}


function Schema(definition) {
  this.include  = definition.include  || [];
  this.implicit = definition.implicit || [];
  this.explicit = definition.explicit || [];

  this.implicit.forEach(function (type) {
    if (type.loadKind && type.loadKind !== 'scalar') {
      throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
    }
  });

  this.compiledImplicit = compileList(this, 'implicit', []);
  this.compiledExplicit = compileList(this, 'explicit', []);
  this.compiledTypeMap  = compileMap(this.compiledImplicit, this.compiledExplicit);
}


Schema.DEFAULT = null;


Schema.create = function createSchema() {
  var schemas, types;

  switch (arguments.length) {
    case 1:
      schemas = Schema.DEFAULT;
      types = arguments[0];
      break;

    case 2:
      schemas = arguments[0];
      types = arguments[1];
      break;

    default:
      throw new YAMLException('Wrong number of arguments for Schema.create function');
  }

  schemas = common.toArray(schemas);
  types = common.toArray(types);

  if (!schemas.every(function (schema) { return schema instanceof Schema; })) {
    throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.');
  }

  if (!types.every(function (type) { return type instanceof Type; })) {
    throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.');
  }

  return new Schema({
    include: schemas,
    explicit: types
  });
};


module.exports = Schema;


/***/ }),

/***/ 76421:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
// Standard YAML's Core schema.
// http://www.yaml.org/spec/1.2/spec.html#id2804923
//
// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.
// So, Core schema has no distinctions from JSON schema is JS-YAML.





var Schema = __webpack_require__(92915);


module.exports = new Schema({
  include: [
    __webpack_require__(33460)
  ]
});


/***/ }),

/***/ 41413:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
// JS-YAML's default schema for `load` function.
// It is not described in the YAML specification.
//
// This schema is based on JS-YAML's default safe schema and includes
// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function.
//
// Also this schema is used as default base schema at `Schema.create` function.





var Schema = __webpack_require__(92915);


module.exports = Schema.DEFAULT = new Schema({
  include: [
    __webpack_require__(41893)
  ],
  explicit: [
    __webpack_require__(34415),
    __webpack_require__(52578),
    __webpack_require__(33611)
  ]
});


/***/ }),

/***/ 41893:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
// JS-YAML's default schema for `safeLoad` function.
// It is not described in the YAML specification.
//
// This schema is based on standard YAML's Core schema and includes most of
// extra types described at YAML tag repository. (http://yaml.org/type/)





var Schema = __webpack_require__(92915);


module.exports = new Schema({
  include: [
    __webpack_require__(76421)
  ],
  implicit: [
    __webpack_require__(45803),
    __webpack_require__(61327)
  ],
  explicit: [
    __webpack_require__(10898),
    __webpack_require__(89582),
    __webpack_require__(47650),
    __webpack_require__(73707)
  ]
});


/***/ }),

/***/ 29899:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
// Standard YAML's Failsafe schema.
// http://www.yaml.org/spec/1.2/spec.html#id2802346





var Schema = __webpack_require__(92915);


module.exports = new Schema({
  explicit: [
    __webpack_require__(84824),
    __webpack_require__(41816),
    __webpack_require__(95757)
  ]
});


/***/ }),

/***/ 33460:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
// Standard YAML's JSON schema.
// http://www.yaml.org/spec/1.2/spec.html#id2803231
//
// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.
// So, this schema is not such strict as defined in the YAML specification.
// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc.





var Schema = __webpack_require__(92915);


module.exports = new Schema({
  include: [
    __webpack_require__(29899)
  ],
  implicit: [
    __webpack_require__(31930),
    __webpack_require__(54043),
    __webpack_require__(61142),
    __webpack_require__(81289)
  ]
});


/***/ }),

/***/ 26136:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var YAMLException = __webpack_require__(9643);

var TYPE_CONSTRUCTOR_OPTIONS = [
  'kind',
  'resolve',
  'construct',
  'instanceOf',
  'predicate',
  'represent',
  'defaultStyle',
  'styleAliases'
];

var YAML_NODE_KINDS = [
  'scalar',
  'sequence',
  'mapping'
];

function compileStyleAliases(map) {
  var result = {};

  if (map !== null) {
    Object.keys(map).forEach(function (style) {
      map[style].forEach(function (alias) {
        result[String(alias)] = style;
      });
    });
  }

  return result;
}

function Type(tag, options) {
  options = options || {};

  Object.keys(options).forEach(function (name) {
    if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
      throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
    }
  });

  // TODO: Add tag format check.
  this.tag          = tag;
  this.kind         = options['kind']         || null;
  this.resolve      = options['resolve']      || function () { return true; };
  this.construct    = options['construct']    || function (data) { return data; };
  this.instanceOf   = options['instanceOf']   || null;
  this.predicate    = options['predicate']    || null;
  this.represent    = options['represent']    || null;
  this.defaultStyle = options['defaultStyle'] || null;
  this.styleAliases = compileStyleAliases(options['styleAliases'] || null);

  if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
    throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
  }
}

module.exports = Type;


/***/ }),

/***/ 10898:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


/*eslint-disable no-bitwise*/

var NodeBuffer;

try {
  // A trick for browserified version, to not include `Buffer` shim
  var _require = undefined;
  NodeBuffer = (__webpack_require__(78378).Buffer);
} catch (__) {}

var Type       = __webpack_require__(26136);


// [ 64, 65, 66 ] -> [ padding, CR, LF ]
var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';


function resolveYamlBinary(data) {
  if (data === null) return false;

  var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;

  // Convert one by one.
  for (idx = 0; idx < max; idx++) {
    code = map.indexOf(data.charAt(idx));

    // Skip CR/LF
    if (code > 64) continue;

    // Fail on illegal characters
    if (code < 0) return false;

    bitlen += 6;
  }

  // If there are any bits left, source was corrupted
  return (bitlen % 8) === 0;
}

function constructYamlBinary(data) {
  var idx, tailbits,
      input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
      max = input.length,
      map = BASE64_MAP,
      bits = 0,
      result = [];

  // Collect by 6*4 bits (3 bytes)

  for (idx = 0; idx < max; idx++) {
    if ((idx % 4 === 0) && idx) {
      result.push((bits >> 16) & 0xFF);
      result.push((bits >> 8) & 0xFF);
      result.push(bits & 0xFF);
    }

    bits = (bits << 6) | map.indexOf(input.charAt(idx));
  }

  // Dump tail

  tailbits = (max % 4) * 6;

  if (tailbits === 0) {
    result.push((bits >> 16) & 0xFF);
    result.push((bits >> 8) & 0xFF);
    result.push(bits & 0xFF);
  } else if (tailbits === 18) {
    result.push((bits >> 10) & 0xFF);
    result.push((bits >> 2) & 0xFF);
  } else if (tailbits === 12) {
    result.push((bits >> 4) & 0xFF);
  }

  // Wrap into Buffer for NodeJS and leave Array for browser
  if (NodeBuffer) {
    // Support node 6.+ Buffer API when available
    return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result);
  }

  return result;
}

function representYamlBinary(object /*, style*/) {
  var result = '', bits = 0, idx, tail,
      max = object.length,
      map = BASE64_MAP;

  // Convert every three bytes to 4 ASCII characters.

  for (idx = 0; idx < max; idx++) {
    if ((idx % 3 === 0) && idx) {
      result += map[(bits >> 18) & 0x3F];
      result += map[(bits >> 12) & 0x3F];
      result += map[(bits >> 6) & 0x3F];
      result += map[bits & 0x3F];
    }

    bits = (bits << 8) + object[idx];
  }

  // Dump tail

  tail = max % 3;

  if (tail === 0) {
    result += map[(bits >> 18) & 0x3F];
    result += map[(bits >> 12) & 0x3F];
    result += map[(bits >> 6) & 0x3F];
    result += map[bits & 0x3F];
  } else if (tail === 2) {
    result += map[(bits >> 10) & 0x3F];
    result += map[(bits >> 4) & 0x3F];
    result += map[(bits << 2) & 0x3F];
    result += map[64];
  } else if (tail === 1) {
    result += map[(bits >> 2) & 0x3F];
    result += map[(bits << 4) & 0x3F];
    result += map[64];
    result += map[64];
  }

  return result;
}

function isBinary(object) {
  return NodeBuffer && NodeBuffer.isBuffer(object);
}

module.exports = new Type('tag:yaml.org,2002:binary', {
  kind: 'scalar',
  resolve: resolveYamlBinary,
  construct: constructYamlBinary,
  predicate: isBinary,
  represent: representYamlBinary
});


/***/ }),

/***/ 54043:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var Type = __webpack_require__(26136);

function resolveYamlBoolean(data) {
  if (data === null) return false;

  var max = data.length;

  return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||
         (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));
}

function constructYamlBoolean(data) {
  return data === 'true' ||
         data === 'True' ||
         data === 'TRUE';
}

function isBoolean(object) {
  return Object.prototype.toString.call(object) === '[object Boolean]';
}

module.exports = new Type('tag:yaml.org,2002:bool', {
  kind: 'scalar',
  resolve: resolveYamlBoolean,
  construct: constructYamlBoolean,
  predicate: isBoolean,
  represent: {
    lowercase: function (object) { return object ? 'true' : 'false'; },
    uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },
    camelcase: function (object) { return object ? 'True' : 'False'; }
  },
  defaultStyle: 'lowercase'
});


/***/ }),

/***/ 81289:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var common = __webpack_require__(19333);
var Type   = __webpack_require__(26136);

var YAML_FLOAT_PATTERN = new RegExp(
  // 2.5e4, 2.5 and integers
  '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +
  // .2e4, .2
  // special case, seems not from spec
  '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +
  // 20:59
  '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' +
  // .inf
  '|[-+]?\\.(?:inf|Inf|INF)' +
  // .nan
  '|\\.(?:nan|NaN|NAN))$');

function resolveYamlFloat(data) {
  if (data === null) return false;

  if (!YAML_FLOAT_PATTERN.test(data) ||
      // Quick hack to not allow integers end with `_`
      // Probably should update regexp & check speed
      data[data.length - 1] === '_') {
    return false;
  }

  return true;
}

function constructYamlFloat(data) {
  var value, sign, base, digits;

  value  = data.replace(/_/g, '').toLowerCase();
  sign   = value[0] === '-' ? -1 : 1;
  digits = [];

  if ('+-'.indexOf(value[0]) >= 0) {
    value = value.slice(1);
  }

  if (value === '.inf') {
    return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;

  } else if (value === '.nan') {
    return NaN;

  } else if (value.indexOf(':') >= 0) {
    value.split(':').forEach(function (v) {
      digits.unshift(parseFloat(v, 10));
    });

    value = 0.0;
    base = 1;

    digits.forEach(function (d) {
      value += d * base;
      base *= 60;
    });

    return sign * value;

  }
  return sign * parseFloat(value, 10);
}


var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;

function representYamlFloat(object, style) {
  var res;

  if (isNaN(object)) {
    switch (style) {
      case 'lowercase': return '.nan';
      case 'uppercase': return '.NAN';
      case 'camelcase': return '.NaN';
    }
  } else if (Number.POSITIVE_INFINITY === object) {
    switch (style) {
      case 'lowercase': return '.inf';
      case 'uppercase': return '.INF';
      case 'camelcase': return '.Inf';
    }
  } else if (Number.NEGATIVE_INFINITY === object) {
    switch (style) {
      case 'lowercase': return '-.inf';
      case 'uppercase': return '-.INF';
      case 'camelcase': return '-.Inf';
    }
  } else if (common.isNegativeZero(object)) {
    return '-0.0';
  }

  res = object.toString(10);

  // JS stringifier can build scientific format without dots: 5e-100,
  // while YAML requres dot: 5.e-100. Fix it with simple hack

  return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;
}

function isFloat(object) {
  return (Object.prototype.toString.call(object) === '[object Number]') &&
         (object % 1 !== 0 || common.isNegativeZero(object));
}

module.exports = new Type('tag:yaml.org,2002:float', {
  kind: 'scalar',
  resolve: resolveYamlFloat,
  construct: constructYamlFloat,
  predicate: isFloat,
  represent: representYamlFloat,
  defaultStyle: 'lowercase'
});


/***/ }),

/***/ 61142:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var common = __webpack_require__(19333);
var Type   = __webpack_require__(26136);

function isHexCode(c) {
  return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||
         ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||
         ((0x61/* a */ <= c) && (c <= 0x66/* f */));
}

function isOctCode(c) {
  return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));
}

function isDecCode(c) {
  return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));
}

function resolveYamlInteger(data) {
  if (data === null) return false;

  var max = data.length,
      index = 0,
      hasDigits = false,
      ch;

  if (!max) return false;

  ch = data[index];

  // sign
  if (ch === '-' || ch === '+') {
    ch = data[++index];
  }

  if (ch === '0') {
    // 0
    if (index + 1 === max) return true;
    ch = data[++index];

    // base 2, base 8, base 16

    if (ch === 'b') {
      // base 2
      index++;

      for (; index < max; index++) {
        ch = data[index];
        if (ch === '_') continue;
        if (ch !== '0' && ch !== '1') return false;
        hasDigits = true;
      }
      return hasDigits && ch !== '_';
    }


    if (ch === 'x') {
      // base 16
      index++;

      for (; index < max; index++) {
        ch = data[index];
        if (ch === '_') continue;
        if (!isHexCode(data.charCodeAt(index))) return false;
        hasDigits = true;
      }
      return hasDigits && ch !== '_';
    }

    // base 8
    for (; index < max; index++) {
      ch = data[index];
      if (ch === '_') continue;
      if (!isOctCode(data.charCodeAt(index))) return false;
      hasDigits = true;
    }
    return hasDigits && ch !== '_';
  }

  // base 10 (except 0) or base 60

  // value should not start with `_`;
  if (ch === '_') return false;

  for (; index < max; index++) {
    ch = data[index];
    if (ch === '_') continue;
    if (ch === ':') break;
    if (!isDecCode(data.charCodeAt(index))) {
      return false;
    }
    hasDigits = true;
  }

  // Should have digits and should not end with `_`
  if (!hasDigits || ch === '_') return false;

  // if !base60 - done;
  if (ch !== ':') return true;

  // base60 almost not used, no needs to optimize
  return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
}

function constructYamlInteger(data) {
  var value = data, sign = 1, ch, base, digits = [];

  if (value.indexOf('_') !== -1) {
    value = value.replace(/_/g, '');
  }

  ch = value[0];

  if (ch === '-' || ch === '+') {
    if (ch === '-') sign = -1;
    value = value.slice(1);
    ch = value[0];
  }

  if (value === '0') return 0;

  if (ch === '0') {
    if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
    if (value[1] === 'x') return sign * parseInt(value, 16);
    return sign * parseInt(value, 8);
  }

  if (value.indexOf(':') !== -1) {
    value.split(':').forEach(function (v) {
      digits.unshift(parseInt(v, 10));
    });

    value = 0;
    base = 1;

    digits.forEach(function (d) {
      value += (d * base);
      base *= 60;
    });

    return sign * value;

  }

  return sign * parseInt(value, 10);
}

function isInteger(object) {
  return (Object.prototype.toString.call(object)) === '[object Number]' &&
         (object % 1 === 0 && !common.isNegativeZero(object));
}

module.exports = new Type('tag:yaml.org,2002:int', {
  kind: 'scalar',
  resolve: resolveYamlInteger,
  construct: constructYamlInteger,
  predicate: isInteger,
  represent: {
    binary:      function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },
    octal:       function (obj) { return obj >= 0 ? '0'  + obj.toString(8) : '-0'  + obj.toString(8).slice(1); },
    decimal:     function (obj) { return obj.toString(10); },
    /* eslint-disable max-len */
    hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() :  '-0x' + obj.toString(16).toUpperCase().slice(1); }
  },
  defaultStyle: 'decimal',
  styleAliases: {
    binary:      [ 2,  'bin' ],
    octal:       [ 8,  'oct' ],
    decimal:     [ 10, 'dec' ],
    hexadecimal: [ 16, 'hex' ]
  }
});


/***/ }),

/***/ 33611:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var esprima;

// Browserified version does not have esprima
//
// 1. For node.js just require module as deps
// 2. For browser try to require mudule via external AMD system.
//    If not found - try to fallback to window.esprima. If not
//    found too - then fail to parse.
//
try {
  // workaround to exclude package from browserify list.
  var _require = undefined;
  esprima = __webpack_require__(50608);
} catch (_) {
  /* eslint-disable no-redeclare */
  /* global window */
  if (typeof window !== 'undefined') esprima = window.esprima;
}

var Type = __webpack_require__(26136);

function resolveJavascriptFunction(data) {
  if (data === null) return false;

  try {
    var source = '(' + data + ')',
        ast    = esprima.parse(source, { range: true });

    if (ast.type                    !== 'Program'             ||
        ast.body.length             !== 1                     ||
        ast.body[0].type            !== 'ExpressionStatement' ||
        (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&
          ast.body[0].expression.type !== 'FunctionExpression')) {
      return false;
    }

    return true;
  } catch (err) {
    return false;
  }
}

function constructJavascriptFunction(data) {
  /*jslint evil:true*/

  var source = '(' + data + ')',
      ast    = esprima.parse(source, { range: true }),
      params = [],
      body;

  if (ast.type                    !== 'Program'             ||
      ast.body.length             !== 1                     ||
      ast.body[0].type            !== 'ExpressionStatement' ||
      (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&
        ast.body[0].expression.type !== 'FunctionExpression')) {
    throw new Error('Failed to resolve function');
  }

  ast.body[0].expression.params.forEach(function (param) {
    params.push(param.name);
  });

  body = ast.body[0].expression.body.range;

  // Esprima's ranges include the first '{' and the last '}' characters on
  // function expressions. So cut them out.
  if (ast.body[0].expression.body.type === 'BlockStatement') {
    /*eslint-disable no-new-func*/
    return new Function(params, source.slice(body[0] + 1, body[1] - 1));
  }
  // ES6 arrow functions can omit the BlockStatement. In that case, just return
  // the body.
  /*eslint-disable no-new-func*/
  return new Function(params, 'return ' + source.slice(body[0], body[1]));
}

function representJavascriptFunction(object /*, style*/) {
  return object.toString();
}

function isFunction(object) {
  return Object.prototype.toString.call(object) === '[object Function]';
}

module.exports = new Type('tag:yaml.org,2002:js/function', {
  kind: 'scalar',
  resolve: resolveJavascriptFunction,
  construct: constructJavascriptFunction,
  predicate: isFunction,
  represent: representJavascriptFunction
});


/***/ }),

/***/ 52578:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var Type = __webpack_require__(26136);

function resolveJavascriptRegExp(data) {
  if (data === null) return false;
  if (data.length === 0) return false;

  var regexp = data,
      tail   = /\/([gim]*)$/.exec(data),
      modifiers = '';

  // if regexp starts with '/' it can have modifiers and must be properly closed
  // `/foo/gim` - modifiers tail can be maximum 3 chars
  if (regexp[0] === '/') {
    if (tail) modifiers = tail[1];

    if (modifiers.length > 3) return false;
    // if expression starts with /, is should be properly terminated
    if (regexp[regexp.length - modifiers.length - 1] !== '/') return false;
  }

  return true;
}

function constructJavascriptRegExp(data) {
  var regexp = data,
      tail   = /\/([gim]*)$/.exec(data),
      modifiers = '';

  // `/foo/gim` - tail can be maximum 4 chars
  if (regexp[0] === '/') {
    if (tail) modifiers = tail[1];
    regexp = regexp.slice(1, regexp.length - modifiers.length - 1);
  }

  return new RegExp(regexp, modifiers);
}

function representJavascriptRegExp(object /*, style*/) {
  var result = '/' + object.source + '/';

  if (object.global) result += 'g';
  if (object.multiline) result += 'm';
  if (object.ignoreCase) result += 'i';

  return result;
}

function isRegExp(object) {
  return Object.prototype.toString.call(object) === '[object RegExp]';
}

module.exports = new Type('tag:yaml.org,2002:js/regexp', {
  kind: 'scalar',
  resolve: resolveJavascriptRegExp,
  construct: constructJavascriptRegExp,
  predicate: isRegExp,
  represent: representJavascriptRegExp
});


/***/ }),

/***/ 34415:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var Type = __webpack_require__(26136);

function resolveJavascriptUndefined() {
  return true;
}

function constructJavascriptUndefined() {
  /*eslint-disable no-undefined*/
  return undefined;
}

function representJavascriptUndefined() {
  return '';
}

function isUndefined(object) {
  return typeof object === 'undefined';
}

module.exports = new Type('tag:yaml.org,2002:js/undefined', {
  kind: 'scalar',
  resolve: resolveJavascriptUndefined,
  construct: constructJavascriptUndefined,
  predicate: isUndefined,
  represent: representJavascriptUndefined
});


/***/ }),

/***/ 95757:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var Type = __webpack_require__(26136);

module.exports = new Type('tag:yaml.org,2002:map', {
  kind: 'mapping',
  construct: function (data) { return data !== null ? data : {}; }
});


/***/ }),

/***/ 61327:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var Type = __webpack_require__(26136);

function resolveYamlMerge(data) {
  return data === '<<' || data === null;
}

module.exports = new Type('tag:yaml.org,2002:merge', {
  kind: 'scalar',
  resolve: resolveYamlMerge
});


/***/ }),

/***/ 31930:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var Type = __webpack_require__(26136);

function resolveYamlNull(data) {
  if (data === null) return true;

  var max = data.length;

  return (max === 1 && data === '~') ||
         (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));
}

function constructYamlNull() {
  return null;
}

function isNull(object) {
  return object === null;
}

module.exports = new Type('tag:yaml.org,2002:null', {
  kind: 'scalar',
  resolve: resolveYamlNull,
  construct: constructYamlNull,
  predicate: isNull,
  represent: {
    canonical: function () { return '~';    },
    lowercase: function () { return 'null'; },
    uppercase: function () { return 'NULL'; },
    camelcase: function () { return 'Null'; }
  },
  defaultStyle: 'lowercase'
});


/***/ }),

/***/ 89582:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var Type = __webpack_require__(26136);

var _hasOwnProperty = Object.prototype.hasOwnProperty;
var _toString       = Object.prototype.toString;

function resolveYamlOmap(data) {
  if (data === null) return true;

  var objectKeys = [], index, length, pair, pairKey, pairHasKey,
      object = data;

  for (index = 0, length = object.length; index < length; index += 1) {
    pair = object[index];
    pairHasKey = false;

    if (_toString.call(pair) !== '[object Object]') return false;

    for (pairKey in pair) {
      if (_hasOwnProperty.call(pair, pairKey)) {
        if (!pairHasKey) pairHasKey = true;
        else return false;
      }
    }

    if (!pairHasKey) return false;

    if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
    else return false;
  }

  return true;
}

function constructYamlOmap(data) {
  return data !== null ? data : [];
}

module.exports = new Type('tag:yaml.org,2002:omap', {
  kind: 'sequence',
  resolve: resolveYamlOmap,
  construct: constructYamlOmap
});


/***/ }),

/***/ 47650:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var Type = __webpack_require__(26136);

var _toString = Object.prototype.toString;

function resolveYamlPairs(data) {
  if (data === null) return true;

  var index, length, pair, keys, result,
      object = data;

  result = new Array(object.length);

  for (index = 0, length = object.length; index < length; index += 1) {
    pair = object[index];

    if (_toString.call(pair) !== '[object Object]') return false;

    keys = Object.keys(pair);

    if (keys.length !== 1) return false;

    result[index] = [ keys[0], pair[keys[0]] ];
  }

  return true;
}

function constructYamlPairs(data) {
  if (data === null) return [];

  var index, length, pair, keys, result,
      object = data;

  result = new Array(object.length);

  for (index = 0, length = object.length; index < length; index += 1) {
    pair = object[index];

    keys = Object.keys(pair);

    result[index] = [ keys[0], pair[keys[0]] ];
  }

  return result;
}

module.exports = new Type('tag:yaml.org,2002:pairs', {
  kind: 'sequence',
  resolve: resolveYamlPairs,
  construct: constructYamlPairs
});


/***/ }),

/***/ 41816:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var Type = __webpack_require__(26136);

module.exports = new Type('tag:yaml.org,2002:seq', {
  kind: 'sequence',
  construct: function (data) { return data !== null ? data : []; }
});


/***/ }),

/***/ 73707:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var Type = __webpack_require__(26136);

var _hasOwnProperty = Object.prototype.hasOwnProperty;

function resolveYamlSet(data) {
  if (data === null) return true;

  var key, object = data;

  for (key in object) {
    if (_hasOwnProperty.call(object, key)) {
      if (object[key] !== null) return false;
    }
  }

  return true;
}

function constructYamlSet(data) {
  return data !== null ? data : {};
}

module.exports = new Type('tag:yaml.org,2002:set', {
  kind: 'mapping',
  resolve: resolveYamlSet,
  construct: constructYamlSet
});


/***/ }),

/***/ 84824:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var Type = __webpack_require__(26136);

module.exports = new Type('tag:yaml.org,2002:str', {
  kind: 'scalar',
  construct: function (data) { return data !== null ? data : ''; }
});


/***/ }),

/***/ 45803:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var Type = __webpack_require__(26136);

var YAML_DATE_REGEXP = new RegExp(
  '^([0-9][0-9][0-9][0-9])'          + // [1] year
  '-([0-9][0-9])'                    + // [2] month
  '-([0-9][0-9])$');                   // [3] day

var YAML_TIMESTAMP_REGEXP = new RegExp(
  '^([0-9][0-9][0-9][0-9])'          + // [1] year
  '-([0-9][0-9]?)'                   + // [2] month
  '-([0-9][0-9]?)'                   + // [3] day
  '(?:[Tt]|[ \\t]+)'                 + // ...
  '([0-9][0-9]?)'                    + // [4] hour
  ':([0-9][0-9])'                    + // [5] minute
  ':([0-9][0-9])'                    + // [6] second
  '(?:\\.([0-9]*))?'                 + // [7] fraction
  '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
  '(?::([0-9][0-9]))?))?$');           // [11] tz_minute

function resolveYamlTimestamp(data) {
  if (data === null) return false;
  if (YAML_DATE_REGEXP.exec(data) !== null) return true;
  if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
  return false;
}

function constructYamlTimestamp(data) {
  var match, year, month, day, hour, minute, second, fraction = 0,
      delta = null, tz_hour, tz_minute, date;

  match = YAML_DATE_REGEXP.exec(data);
  if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);

  if (match === null) throw new Error('Date resolve error');

  // match: [1] year [2] month [3] day

  year = +(match[1]);
  month = +(match[2]) - 1; // JS month starts with 0
  day = +(match[3]);

  if (!match[4]) { // no hour
    return new Date(Date.UTC(year, month, day));
  }

  // match: [4] hour [5] minute [6] second [7] fraction

  hour = +(match[4]);
  minute = +(match[5]);
  second = +(match[6]);

  if (match[7]) {
    fraction = match[7].slice(0, 3);
    while (fraction.length < 3) { // milli-seconds
      fraction += '0';
    }
    fraction = +fraction;
  }

  // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute

  if (match[9]) {
    tz_hour = +(match[10]);
    tz_minute = +(match[11] || 0);
    delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
    if (match[9] === '-') delta = -delta;
  }

  date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));

  if (delta) date.setTime(date.getTime() - delta);

  return date;
}

function representYamlTimestamp(object /*, style*/) {
  return object.toISOString();
}

module.exports = new Type('tag:yaml.org,2002:timestamp', {
  kind: 'scalar',
  resolve: resolveYamlTimestamp,
  construct: constructYamlTimestamp,
  instanceOf: Date,
  represent: representYamlTimestamp
});


/***/ }),

/***/ 91801:
/***/ (function(module) {

(function (global, factory) {
	 true ? module.exports = factory() :
	0;
}(this, (function () { 'use strict';

	function createCommonjsModule(fn, module) {
		return module = { exports: {} }, fn(module, module.exports), module.exports;
	}

	var _global = createCommonjsModule(function (module) {
	// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
	var global = module.exports = typeof window != 'undefined' && window.Math == Math
	  ? window : typeof self != 'undefined' && self.Math == Math ? self
	  // eslint-disable-next-line no-new-func
	  : Function('return this')();
	if (typeof __g == 'number') { __g = global; } // eslint-disable-line no-undef
	});

	var _core = createCommonjsModule(function (module) {
	var core = module.exports = { version: '2.6.5' };
	if (typeof __e == 'number') { __e = core; } // eslint-disable-line no-undef
	});
	var _core_1 = _core.version;

	var _isObject = function (it) {
	  return typeof it === 'object' ? it !== null : typeof it === 'function';
	};

	var _anObject = function (it) {
	  if (!_isObject(it)) { throw TypeError(it + ' is not an object!'); }
	  return it;
	};

	var _fails = function (exec) {
	  try {
	    return !!exec();
	  } catch (e) {
	    return true;
	  }
	};

	// Thank's IE8 for his funny defineProperty
	var _descriptors = !_fails(function () {
	  return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
	});

	var document = _global.document;
	// typeof document.createElement is 'object' in old IE
	var is = _isObject(document) && _isObject(document.createElement);
	var _domCreate = function (it) {
	  return is ? document.createElement(it) : {};
	};

	var _ie8DomDefine = !_descriptors && !_fails(function () {
	  return Object.defineProperty(_domCreate('div'), 'a', { get: function () { return 7; } }).a != 7;
	});

	// 7.1.1 ToPrimitive(input [, PreferredType])

	// instead of the ES6 spec version, we didn't implement @@toPrimitive case
	// and the second argument - flag - preferred type is a string
	var _toPrimitive = function (it, S) {
	  if (!_isObject(it)) { return it; }
	  var fn, val;
	  if (S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) { return val; }
	  if (typeof (fn = it.valueOf) == 'function' && !_isObject(val = fn.call(it))) { return val; }
	  if (!S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) { return val; }
	  throw TypeError("Can't convert object to primitive value");
	};

	var dP = Object.defineProperty;

	var f = _descriptors ? Object.defineProperty : function defineProperty(O, P, Attributes) {
	  _anObject(O);
	  P = _toPrimitive(P, true);
	  _anObject(Attributes);
	  if (_ie8DomDefine) { try {
	    return dP(O, P, Attributes);
	  } catch (e) { /* empty */ } }
	  if ('get' in Attributes || 'set' in Attributes) { throw TypeError('Accessors not supported!'); }
	  if ('value' in Attributes) { O[P] = Attributes.value; }
	  return O;
	};

	var _objectDp = {
		f: f
	};

	var _propertyDesc = function (bitmap, value) {
	  return {
	    enumerable: !(bitmap & 1),
	    configurable: !(bitmap & 2),
	    writable: !(bitmap & 4),
	    value: value
	  };
	};

	var _hide = _descriptors ? function (object, key, value) {
	  return _objectDp.f(object, key, _propertyDesc(1, value));
	} : function (object, key, value) {
	  object[key] = value;
	  return object;
	};

	var hasOwnProperty = {}.hasOwnProperty;
	var _has = function (it, key) {
	  return hasOwnProperty.call(it, key);
	};

	var id = 0;
	var px = Math.random();
	var _uid = function (key) {
	  return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
	};

	var _library = false;

	var _shared = createCommonjsModule(function (module) {
	var SHARED = '__core-js_shared__';
	var store = _global[SHARED] || (_global[SHARED] = {});

	(module.exports = function (key, value) {
	  return store[key] || (store[key] = value !== undefined ? value : {});
	})('versions', []).push({
	  version: _core.version,
	  mode: _library ? 'pure' : 'global',
	  copyright: '© 2019 Denis Pushkarev (zloirock.ru)'
	});
	});

	var _functionToString = _shared('native-function-to-string', Function.toString);

	var _redefine = createCommonjsModule(function (module) {
	var SRC = _uid('src');

	var TO_STRING = 'toString';
	var TPL = ('' + _functionToString).split(TO_STRING);

	_core.inspectSource = function (it) {
	  return _functionToString.call(it);
	};

	(module.exports = function (O, key, val, safe) {
	  var isFunction = typeof val == 'function';
	  if (isFunction) { _has(val, 'name') || _hide(val, 'name', key); }
	  if (O[key] === val) { return; }
	  if (isFunction) { _has(val, SRC) || _hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); }
	  if (O === _global) {
	    O[key] = val;
	  } else if (!safe) {
	    delete O[key];
	    _hide(O, key, val);
	  } else if (O[key]) {
	    O[key] = val;
	  } else {
	    _hide(O, key, val);
	  }
	// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
	})(Function.prototype, TO_STRING, function toString() {
	  return typeof this == 'function' && this[SRC] || _functionToString.call(this);
	});
	});

	var _aFunction = function (it) {
	  if (typeof it != 'function') { throw TypeError(it + ' is not a function!'); }
	  return it;
	};

	// optional / simple context binding

	var _ctx = function (fn, that, length) {
	  _aFunction(fn);
	  if (that === undefined) { return fn; }
	  switch (length) {
	    case 1: return function (a) {
	      return fn.call(that, a);
	    };
	    case 2: return function (a, b) {
	      return fn.call(that, a, b);
	    };
	    case 3: return function (a, b, c) {
	      return fn.call(that, a, b, c);
	    };
	  }
	  return function (/* ...args */) {
	    return fn.apply(that, arguments);
	  };
	};

	var PROTOTYPE = 'prototype';

	var $export = function (type, name, source) {
	  var IS_FORCED = type & $export.F;
	  var IS_GLOBAL = type & $export.G;
	  var IS_STATIC = type & $export.S;
	  var IS_PROTO = type & $export.P;
	  var IS_BIND = type & $export.B;
	  var target = IS_GLOBAL ? _global : IS_STATIC ? _global[name] || (_global[name] = {}) : (_global[name] || {})[PROTOTYPE];
	  var exports = IS_GLOBAL ? _core : _core[name] || (_core[name] = {});
	  var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {});
	  var key, own, out, exp;
	  if (IS_GLOBAL) { source = name; }
	  for (key in source) {
	    // contains in native
	    own = !IS_FORCED && target && target[key] !== undefined;
	    // export native or passed
	    out = (own ? target : source)[key];
	    // bind timers to global for call from export context
	    exp = IS_BIND && own ? _ctx(out, _global) : IS_PROTO && typeof out == 'function' ? _ctx(Function.call, out) : out;
	    // extend global
	    if (target) { _redefine(target, key, out, type & $export.U); }
	    // export
	    if (exports[key] != out) { _hide(exports, key, exp); }
	    if (IS_PROTO && expProto[key] != out) { expProto[key] = out; }
	  }
	};
	_global.core = _core;
	// type bitmap
	$export.F = 1;   // forced
	$export.G = 2;   // global
	$export.S = 4;   // static
	$export.P = 8;   // proto
	$export.B = 16;  // bind
	$export.W = 32;  // wrap
	$export.U = 64;  // safe
	$export.R = 128; // real proto method for `library`
	var _export = $export;

	// 7.1.4 ToInteger
	var ceil = Math.ceil;
	var floor = Math.floor;
	var _toInteger = function (it) {
	  return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
	};

	// 7.2.1 RequireObjectCoercible(argument)
	var _defined = function (it) {
	  if (it == undefined) { throw TypeError("Can't call method on  " + it); }
	  return it;
	};

	// true  -> String#at
	// false -> String#codePointAt
	var _stringAt = function (TO_STRING) {
	  return function (that, pos) {
	    var s = String(_defined(that));
	    var i = _toInteger(pos);
	    var l = s.length;
	    var a, b;
	    if (i < 0 || i >= l) { return TO_STRING ? '' : undefined; }
	    a = s.charCodeAt(i);
	    return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
	      ? TO_STRING ? s.charAt(i) : a
	      : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
	  };
	};

	var $at = _stringAt(false);
	_export(_export.P, 'String', {
	  // 21.1.3.3 String.prototype.codePointAt(pos)
	  codePointAt: function codePointAt(pos) {
	    return $at(this, pos);
	  }
	});

	var codePointAt = _core.String.codePointAt;

	var max = Math.max;
	var min = Math.min;
	var _toAbsoluteIndex = function (index, length) {
	  index = _toInteger(index);
	  return index < 0 ? max(index + length, 0) : min(index, length);
	};

	var fromCharCode = String.fromCharCode;
	var $fromCodePoint = String.fromCodePoint;

	// length should be 1, old FF problem
	_export(_export.S + _export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {
	  // 21.1.2.2 String.fromCodePoint(...codePoints)
	  fromCodePoint: function fromCodePoint(x) {
	    var arguments$1 = arguments;
	 // eslint-disable-line no-unused-vars
	    var res = [];
	    var aLen = arguments.length;
	    var i = 0;
	    var code;
	    while (aLen > i) {
	      code = +arguments$1[i++];
	      if (_toAbsoluteIndex(code, 0x10ffff) !== code) { throw RangeError(code + ' is not a valid code point'); }
	      res.push(code < 0x10000
	        ? fromCharCode(code)
	        : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)
	      );
	    } return res.join('');
	  }
	});

	var fromCodePoint = _core.String.fromCodePoint;

	// This is a generated file. Do not edit.
	var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/;
	var ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;
	var ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/;

	var unicode = {
		Space_Separator: Space_Separator,
		ID_Start: ID_Start,
		ID_Continue: ID_Continue
	};

	var util = {
	    isSpaceSeparator: function isSpaceSeparator (c) {
	        return typeof c === 'string' && unicode.Space_Separator.test(c)
	    },

	    isIdStartChar: function isIdStartChar (c) {
	        return typeof c === 'string' && (
	            (c >= 'a' && c <= 'z') ||
	        (c >= 'A' && c <= 'Z') ||
	        (c === '$') || (c === '_') ||
	        unicode.ID_Start.test(c)
	        )
	    },

	    isIdContinueChar: function isIdContinueChar (c) {
	        return typeof c === 'string' && (
	            (c >= 'a' && c <= 'z') ||
	        (c >= 'A' && c <= 'Z') ||
	        (c >= '0' && c <= '9') ||
	        (c === '$') || (c === '_') ||
	        (c === '\u200C') || (c === '\u200D') ||
	        unicode.ID_Continue.test(c)
	        )
	    },

	    isDigit: function isDigit (c) {
	        return typeof c === 'string' && /[0-9]/.test(c)
	    },

	    isHexDigit: function isHexDigit (c) {
	        return typeof c === 'string' && /[0-9A-Fa-f]/.test(c)
	    },
	};

	var source;
	var parseState;
	var stack;
	var pos;
	var line;
	var column;
	var token;
	var key;
	var root;

	var parse = function parse (text, reviver) {
	    source = String(text);
	    parseState = 'start';
	    stack = [];
	    pos = 0;
	    line = 1;
	    column = 0;
	    token = undefined;
	    key = undefined;
	    root = undefined;

	    do {
	        token = lex();

	        // This code is unreachable.
	        // if (!parseStates[parseState]) {
	        //     throw invalidParseState()
	        // }

	        parseStates[parseState]();
	    } while (token.type !== 'eof')

	    if (typeof reviver === 'function') {
	        return internalize({'': root}, '', reviver)
	    }

	    return root
	};

	function internalize (holder, name, reviver) {
	    var value = holder[name];
	    if (value != null && typeof value === 'object') {
	        if (Array.isArray(value)) {
	            for (var i = 0; i < value.length; i++) {
	                var key = String(i);
	                var replacement = internalize(value, key, reviver);
	                if (replacement === undefined) {
	                    delete value[key];
	                } else {
	                    Object.defineProperty(value, key, {
	                        value: replacement,
	                        writable: true,
	                        enumerable: true,
	                        configurable: true,
	                    });
	                }
	            }
	        } else {
	            for (var key$1 in value) {
	                var replacement$1 = internalize(value, key$1, reviver);
	                if (replacement$1 === undefined) {
	                    delete value[key$1];
	                } else {
	                    Object.defineProperty(value, key$1, {
	                        value: replacement$1,
	                        writable: true,
	                        enumerable: true,
	                        configurable: true,
	                    });
	                }
	            }
	        }
	    }

	    return reviver.call(holder, name, value)
	}

	var lexState;
	var buffer;
	var doubleQuote;
	var sign;
	var c;

	function lex () {
	    lexState = 'default';
	    buffer = '';
	    doubleQuote = false;
	    sign = 1;

	    for (;;) {
	        c = peek();

	        // This code is unreachable.
	        // if (!lexStates[lexState]) {
	        //     throw invalidLexState(lexState)
	        // }

	        var token = lexStates[lexState]();
	        if (token) {
	            return token
	        }
	    }
	}

	function peek () {
	    if (source[pos]) {
	        return String.fromCodePoint(source.codePointAt(pos))
	    }
	}

	function read () {
	    var c = peek();

	    if (c === '\n') {
	        line++;
	        column = 0;
	    } else if (c) {
	        column += c.length;
	    } else {
	        column++;
	    }

	    if (c) {
	        pos += c.length;
	    }

	    return c
	}

	var lexStates = {
	    default: function default$1 () {
	        switch (c) {
	        case '\t':
	        case '\v':
	        case '\f':
	        case ' ':
	        case '\u00A0':
	        case '\uFEFF':
	        case '\n':
	        case '\r':
	        case '\u2028':
	        case '\u2029':
	            read();
	            return

	        case '/':
	            read();
	            lexState = 'comment';
	            return

	        case undefined:
	            read();
	            return newToken('eof')
	        }

	        if (util.isSpaceSeparator(c)) {
	            read();
	            return
	        }

	        // This code is unreachable.
	        // if (!lexStates[parseState]) {
	        //     throw invalidLexState(parseState)
	        // }

	        return lexStates[parseState]()
	    },

	    comment: function comment () {
	        switch (c) {
	        case '*':
	            read();
	            lexState = 'multiLineComment';
	            return

	        case '/':
	            read();
	            lexState = 'singleLineComment';
	            return
	        }

	        throw invalidChar(read())
	    },

	    multiLineComment: function multiLineComment () {
	        switch (c) {
	        case '*':
	            read();
	            lexState = 'multiLineCommentAsterisk';
	            return

	        case undefined:
	            throw invalidChar(read())
	        }

	        read();
	    },

	    multiLineCommentAsterisk: function multiLineCommentAsterisk () {
	        switch (c) {
	        case '*':
	            read();
	            return

	        case '/':
	            read();
	            lexState = 'default';
	            return

	        case undefined:
	            throw invalidChar(read())
	        }

	        read();
	        lexState = 'multiLineComment';
	    },

	    singleLineComment: function singleLineComment () {
	        switch (c) {
	        case '\n':
	        case '\r':
	        case '\u2028':
	        case '\u2029':
	            read();
	            lexState = 'default';
	            return

	        case undefined:
	            read();
	            return newToken('eof')
	        }

	        read();
	    },

	    value: function value () {
	        switch (c) {
	        case '{':
	        case '[':
	            return newToken('punctuator', read())

	        case 'n':
	            read();
	            literal('ull');
	            return newToken('null', null)

	        case 't':
	            read();
	            literal('rue');
	            return newToken('boolean', true)

	        case 'f':
	            read();
	            literal('alse');
	            return newToken('boolean', false)

	        case '-':
	        case '+':
	            if (read() === '-') {
	                sign = -1;
	            }

	            lexState = 'sign';
	            return

	        case '.':
	            buffer = read();
	            lexState = 'decimalPointLeading';
	            return

	        case '0':
	            buffer = read();
	            lexState = 'zero';
	            return

	        case '1':
	        case '2':
	        case '3':
	        case '4':
	        case '5':
	        case '6':
	        case '7':
	        case '8':
	        case '9':
	            buffer = read();
	            lexState = 'decimalInteger';
	            return

	        case 'I':
	            read();
	            literal('nfinity');
	            return newToken('numeric', Infinity)

	        case 'N':
	            read();
	            literal('aN');
	            return newToken('numeric', NaN)

	        case '"':
	        case "'":
	            doubleQuote = (read() === '"');
	            buffer = '';
	            lexState = 'string';
	            return
	        }

	        throw invalidChar(read())
	    },

	    identifierNameStartEscape: function identifierNameStartEscape () {
	        if (c !== 'u') {
	            throw invalidChar(read())
	        }

	        read();
	        var u = unicodeEscape();
	        switch (u) {
	        case '$':
	        case '_':
	            break

	        default:
	            if (!util.isIdStartChar(u)) {
	                throw invalidIdentifier()
	            }

	            break
	        }

	        buffer += u;
	        lexState = 'identifierName';
	    },

	    identifierName: function identifierName () {
	        switch (c) {
	        case '$':
	        case '_':
	        case '\u200C':
	        case '\u200D':
	            buffer += read();
	            return

	        case '\\':
	            read();
	            lexState = 'identifierNameEscape';
	            return
	        }

	        if (util.isIdContinueChar(c)) {
	            buffer += read();
	            return
	        }

	        return newToken('identifier', buffer)
	    },

	    identifierNameEscape: function identifierNameEscape () {
	        if (c !== 'u') {
	            throw invalidChar(read())
	        }

	        read();
	        var u = unicodeEscape();
	        switch (u) {
	        case '$':
	        case '_':
	        case '\u200C':
	        case '\u200D':
	            break

	        default:
	            if (!util.isIdContinueChar(u)) {
	                throw invalidIdentifier()
	            }

	            break
	        }

	        buffer += u;
	        lexState = 'identifierName';
	    },

	    sign: function sign$1 () {
	        switch (c) {
	        case '.':
	            buffer = read();
	            lexState = 'decimalPointLeading';
	            return

	        case '0':
	            buffer = read();
	            lexState = 'zero';
	            return

	        case '1':
	        case '2':
	        case '3':
	        case '4':
	        case '5':
	        case '6':
	        case '7':
	        case '8':
	        case '9':
	            buffer = read();
	            lexState = 'decimalInteger';
	            return

	        case 'I':
	            read();
	            literal('nfinity');
	            return newToken('numeric', sign * Infinity)

	        case 'N':
	            read();
	            literal('aN');
	            return newToken('numeric', NaN)
	        }

	        throw invalidChar(read())
	    },

	    zero: function zero () {
	        switch (c) {
	        case '.':
	            buffer += read();
	            lexState = 'decimalPoint';
	            return

	        case 'e':
	        case 'E':
	            buffer += read();
	            lexState = 'decimalExponent';
	            return

	        case 'x':
	        case 'X':
	            buffer += read();
	            lexState = 'hexadecimal';
	            return
	        }

	        return newToken('numeric', sign * 0)
	    },

	    decimalInteger: function decimalInteger () {
	        switch (c) {
	        case '.':
	            buffer += read();
	            lexState = 'decimalPoint';
	            return

	        case 'e':
	        case 'E':
	            buffer += read();
	            lexState = 'decimalExponent';
	            return
	        }

	        if (util.isDigit(c)) {
	            buffer += read();
	            return
	        }

	        return newToken('numeric', sign * Number(buffer))
	    },

	    decimalPointLeading: function decimalPointLeading () {
	        if (util.isDigit(c)) {
	            buffer += read();
	            lexState = 'decimalFraction';
	            return
	        }

	        throw invalidChar(read())
	    },

	    decimalPoint: function decimalPoint () {
	        switch (c) {
	        case 'e':
	        case 'E':
	            buffer += read();
	            lexState = 'decimalExponent';
	            return
	        }

	        if (util.isDigit(c)) {
	            buffer += read();
	            lexState = 'decimalFraction';
	            return
	        }

	        return newToken('numeric', sign * Number(buffer))
	    },

	    decimalFraction: function decimalFraction () {
	        switch (c) {
	        case 'e':
	        case 'E':
	            buffer += read();
	            lexState = 'decimalExponent';
	            return
	        }

	        if (util.isDigit(c)) {
	            buffer += read();
	            return
	        }

	        return newToken('numeric', sign * Number(buffer))
	    },

	    decimalExponent: function decimalExponent () {
	        switch (c) {
	        case '+':
	        case '-':
	            buffer += read();
	            lexState = 'decimalExponentSign';
	            return
	        }

	        if (util.isDigit(c)) {
	            buffer += read();
	            lexState = 'decimalExponentInteger';
	            return
	        }

	        throw invalidChar(read())
	    },

	    decimalExponentSign: function decimalExponentSign () {
	        if (util.isDigit(c)) {
	            buffer += read();
	            lexState = 'decimalExponentInteger';
	            return
	        }

	        throw invalidChar(read())
	    },

	    decimalExponentInteger: function decimalExponentInteger () {
	        if (util.isDigit(c)) {
	            buffer += read();
	            return
	        }

	        return newToken('numeric', sign * Number(buffer))
	    },

	    hexadecimal: function hexadecimal () {
	        if (util.isHexDigit(c)) {
	            buffer += read();
	            lexState = 'hexadecimalInteger';
	            return
	        }

	        throw invalidChar(read())
	    },

	    hexadecimalInteger: function hexadecimalInteger () {
	        if (util.isHexDigit(c)) {
	            buffer += read();
	            return
	        }

	        return newToken('numeric', sign * Number(buffer))
	    },

	    string: function string () {
	        switch (c) {
	        case '\\':
	            read();
	            buffer += escape();
	            return

	        case '"':
	            if (doubleQuote) {
	                read();
	                return newToken('string', buffer)
	            }

	            buffer += read();
	            return

	        case "'":
	            if (!doubleQuote) {
	                read();
	                return newToken('string', buffer)
	            }

	            buffer += read();
	            return

	        case '\n':
	        case '\r':
	            throw invalidChar(read())

	        case '\u2028':
	        case '\u2029':
	            separatorChar(c);
	            break

	        case undefined:
	            throw invalidChar(read())
	        }

	        buffer += read();
	    },

	    start: function start () {
	        switch (c) {
	        case '{':
	        case '[':
	            return newToken('punctuator', read())

	        // This code is unreachable since the default lexState handles eof.
	        // case undefined:
	        //     return newToken('eof')
	        }

	        lexState = 'value';
	    },

	    beforePropertyName: function beforePropertyName () {
	        switch (c) {
	        case '$':
	        case '_':
	            buffer = read();
	            lexState = 'identifierName';
	            return

	        case '\\':
	            read();
	            lexState = 'identifierNameStartEscape';
	            return

	        case '}':
	            return newToken('punctuator', read())

	        case '"':
	        case "'":
	            doubleQuote = (read() === '"');
	            lexState = 'string';
	            return
	        }

	        if (util.isIdStartChar(c)) {
	            buffer += read();
	            lexState = 'identifierName';
	            return
	        }

	        throw invalidChar(read())
	    },

	    afterPropertyName: function afterPropertyName () {
	        if (c === ':') {
	            return newToken('punctuator', read())
	        }

	        throw invalidChar(read())
	    },

	    beforePropertyValue: function beforePropertyValue () {
	        lexState = 'value';
	    },

	    afterPropertyValue: function afterPropertyValue () {
	        switch (c) {
	        case ',':
	        case '}':
	            return newToken('punctuator', read())
	        }

	        throw invalidChar(read())
	    },

	    beforeArrayValue: function beforeArrayValue () {
	        if (c === ']') {
	            return newToken('punctuator', read())
	        }

	        lexState = 'value';
	    },

	    afterArrayValue: function afterArrayValue () {
	        switch (c) {
	        case ',':
	        case ']':
	            return newToken('punctuator', read())
	        }

	        throw invalidChar(read())
	    },

	    end: function end () {
	        // This code is unreachable since it's handled by the default lexState.
	        // if (c === undefined) {
	        //     read()
	        //     return newToken('eof')
	        // }

	        throw invalidChar(read())
	    },
	};

	function newToken (type, value) {
	    return {
	        type: type,
	        value: value,
	        line: line,
	        column: column,
	    }
	}

	function literal (s) {
	    for (var i = 0, list = s; i < list.length; i += 1) {
	        var c = list[i];

	        var p = peek();

	        if (p !== c) {
	            throw invalidChar(read())
	        }

	        read();
	    }
	}

	function escape () {
	    var c = peek();
	    switch (c) {
	    case 'b':
	        read();
	        return '\b'

	    case 'f':
	        read();
	        return '\f'

	    case 'n':
	        read();
	        return '\n'

	    case 'r':
	        read();
	        return '\r'

	    case 't':
	        read();
	        return '\t'

	    case 'v':
	        read();
	        return '\v'

	    case '0':
	        read();
	        if (util.isDigit(peek())) {
	            throw invalidChar(read())
	        }

	        return '\0'

	    case 'x':
	        read();
	        return hexEscape()

	    case 'u':
	        read();
	        return unicodeEscape()

	    case '\n':
	    case '\u2028':
	    case '\u2029':
	        read();
	        return ''

	    case '\r':
	        read();
	        if (peek() === '\n') {
	            read();
	        }

	        return ''

	    case '1':
	    case '2':
	    case '3':
	    case '4':
	    case '5':
	    case '6':
	    case '7':
	    case '8':
	    case '9':
	        throw invalidChar(read())

	    case undefined:
	        throw invalidChar(read())
	    }

	    return read()
	}

	function hexEscape () {
	    var buffer = '';
	    var c = peek();

	    if (!util.isHexDigit(c)) {
	        throw invalidChar(read())
	    }

	    buffer += read();

	    c = peek();
	    if (!util.isHexDigit(c)) {
	        throw invalidChar(read())
	    }

	    buffer += read();

	    return String.fromCodePoint(parseInt(buffer, 16))
	}

	function unicodeEscape () {
	    var buffer = '';
	    var count = 4;

	    while (count-- > 0) {
	        var c = peek();
	        if (!util.isHexDigit(c)) {
	            throw invalidChar(read())
	        }

	        buffer += read();
	    }

	    return String.fromCodePoint(parseInt(buffer, 16))
	}

	var parseStates = {
	    start: function start () {
	        if (token.type === 'eof') {
	            throw invalidEOF()
	        }

	        push();
	    },

	    beforePropertyName: function beforePropertyName () {
	        switch (token.type) {
	        case 'identifier':
	        case 'string':
	            key = token.value;
	            parseState = 'afterPropertyName';
	            return

	        case 'punctuator':
	            // This code is unreachable since it's handled by the lexState.
	            // if (token.value !== '}') {
	            //     throw invalidToken()
	            // }

	            pop();
	            return

	        case 'eof':
	            throw invalidEOF()
	        }

	        // This code is unreachable since it's handled by the lexState.
	        // throw invalidToken()
	    },

	    afterPropertyName: function afterPropertyName () {
	        // This code is unreachable since it's handled by the lexState.
	        // if (token.type !== 'punctuator' || token.value !== ':') {
	        //     throw invalidToken()
	        // }

	        if (token.type === 'eof') {
	            throw invalidEOF()
	        }

	        parseState = 'beforePropertyValue';
	    },

	    beforePropertyValue: function beforePropertyValue () {
	        if (token.type === 'eof') {
	            throw invalidEOF()
	        }

	        push();
	    },

	    beforeArrayValue: function beforeArrayValue () {
	        if (token.type === 'eof') {
	            throw invalidEOF()
	        }

	        if (token.type === 'punctuator' && token.value === ']') {
	            pop();
	            return
	        }

	        push();
	    },

	    afterPropertyValue: function afterPropertyValue () {
	        // This code is unreachable since it's handled by the lexState.
	        // if (token.type !== 'punctuator') {
	        //     throw invalidToken()
	        // }

	        if (token.type === 'eof') {
	            throw invalidEOF()
	        }

	        switch (token.value) {
	        case ',':
	            parseState = 'beforePropertyName';
	            return

	        case '}':
	            pop();
	        }

	        // This code is unreachable since it's handled by the lexState.
	        // throw invalidToken()
	    },

	    afterArrayValue: function afterArrayValue () {
	        // This code is unreachable since it's handled by the lexState.
	        // if (token.type !== 'punctuator') {
	        //     throw invalidToken()
	        // }

	        if (token.type === 'eof') {
	            throw invalidEOF()
	        }

	        switch (token.value) {
	        case ',':
	            parseState = 'beforeArrayValue';
	            return

	        case ']':
	            pop();
	        }

	        // This code is unreachable since it's handled by the lexState.
	        // throw invalidToken()
	    },

	    end: function end () {
	        // This code is unreachable since it's handled by the lexState.
	        // if (token.type !== 'eof') {
	        //     throw invalidToken()
	        // }
	    },
	};

	function push () {
	    var value;

	    switch (token.type) {
	    case 'punctuator':
	        switch (token.value) {
	        case '{':
	            value = {};
	            break

	        case '[':
	            value = [];
	            break
	        }

	        break

	    case 'null':
	    case 'boolean':
	    case 'numeric':
	    case 'string':
	        value = token.value;
	        break

	    // This code is unreachable.
	    // default:
	    //     throw invalidToken()
	    }

	    if (root === undefined) {
	        root = value;
	    } else {
	        var parent = stack[stack.length - 1];
	        if (Array.isArray(parent)) {
	            parent.push(value);
	        } else {
	            Object.defineProperty(parent, key, {
	                value: value,
	                writable: true,
	                enumerable: true,
	                configurable: true,
	            });
	        }
	    }

	    if (value !== null && typeof value === 'object') {
	        stack.push(value);

	        if (Array.isArray(value)) {
	            parseState = 'beforeArrayValue';
	        } else {
	            parseState = 'beforePropertyName';
	        }
	    } else {
	        var current = stack[stack.length - 1];
	        if (current == null) {
	            parseState = 'end';
	        } else if (Array.isArray(current)) {
	            parseState = 'afterArrayValue';
	        } else {
	            parseState = 'afterPropertyValue';
	        }
	    }
	}

	function pop () {
	    stack.pop();

	    var current = stack[stack.length - 1];
	    if (current == null) {
	        parseState = 'end';
	    } else if (Array.isArray(current)) {
	        parseState = 'afterArrayValue';
	    } else {
	        parseState = 'afterPropertyValue';
	    }
	}

	// This code is unreachable.
	// function invalidParseState () {
	//     return new Error(`JSON5: invalid parse state '${parseState}'`)
	// }

	// This code is unreachable.
	// function invalidLexState (state) {
	//     return new Error(`JSON5: invalid lex state '${state}'`)
	// }

	function invalidChar (c) {
	    if (c === undefined) {
	        return syntaxError(("JSON5: invalid end of input at " + line + ":" + column))
	    }

	    return syntaxError(("JSON5: invalid character '" + (formatChar(c)) + "' at " + line + ":" + column))
	}

	function invalidEOF () {
	    return syntaxError(("JSON5: invalid end of input at " + line + ":" + column))
	}

	// This code is unreachable.
	// function invalidToken () {
	//     if (token.type === 'eof') {
	//         return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
	//     }

	//     const c = String.fromCodePoint(token.value.codePointAt(0))
	//     return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)
	// }

	function invalidIdentifier () {
	    column -= 5;
	    return syntaxError(("JSON5: invalid identifier character at " + line + ":" + column))
	}

	function separatorChar (c) {
	    console.warn(("JSON5: '" + (formatChar(c)) + "' in strings is not valid ECMAScript; consider escaping"));
	}

	function formatChar (c) {
	    var replacements = {
	        "'": "\\'",
	        '"': '\\"',
	        '\\': '\\\\',
	        '\b': '\\b',
	        '\f': '\\f',
	        '\n': '\\n',
	        '\r': '\\r',
	        '\t': '\\t',
	        '\v': '\\v',
	        '\0': '\\0',
	        '\u2028': '\\u2028',
	        '\u2029': '\\u2029',
	    };

	    if (replacements[c]) {
	        return replacements[c]
	    }

	    if (c < ' ') {
	        var hexString = c.charCodeAt(0).toString(16);
	        return '\\x' + ('00' + hexString).substring(hexString.length)
	    }

	    return c
	}

	function syntaxError (message) {
	    var err = new SyntaxError(message);
	    err.lineNumber = line;
	    err.columnNumber = column;
	    return err
	}

	var stringify = function stringify (value, replacer, space) {
	    var stack = [];
	    var indent = '';
	    var propertyList;
	    var replacerFunc;
	    var gap = '';
	    var quote;

	    if (
	        replacer != null &&
	        typeof replacer === 'object' &&
	        !Array.isArray(replacer)
	    ) {
	        space = replacer.space;
	        quote = replacer.quote;
	        replacer = replacer.replacer;
	    }

	    if (typeof replacer === 'function') {
	        replacerFunc = replacer;
	    } else if (Array.isArray(replacer)) {
	        propertyList = [];
	        for (var i = 0, list = replacer; i < list.length; i += 1) {
	            var v = list[i];

	            var item = (void 0);

	            if (typeof v === 'string') {
	                item = v;
	            } else if (
	                typeof v === 'number' ||
	                v instanceof String ||
	                v instanceof Number
	            ) {
	                item = String(v);
	            }

	            if (item !== undefined && propertyList.indexOf(item) < 0) {
	                propertyList.push(item);
	            }
	        }
	    }

	    if (space instanceof Number) {
	        space = Number(space);
	    } else if (space instanceof String) {
	        space = String(space);
	    }

	    if (typeof space === 'number') {
	        if (space > 0) {
	            space = Math.min(10, Math.floor(space));
	            gap = '          '.substr(0, space);
	        }
	    } else if (typeof space === 'string') {
	        gap = space.substr(0, 10);
	    }

	    return serializeProperty('', {'': value})

	    function serializeProperty (key, holder) {
	        var value = holder[key];
	        if (value != null) {
	            if (typeof value.toJSON5 === 'function') {
	                value = value.toJSON5(key);
	            } else if (typeof value.toJSON === 'function') {
	                value = value.toJSON(key);
	            }
	        }

	        if (replacerFunc) {
	            value = replacerFunc.call(holder, key, value);
	        }

	        if (value instanceof Number) {
	            value = Number(value);
	        } else if (value instanceof String) {
	            value = String(value);
	        } else if (value instanceof Boolean) {
	            value = value.valueOf();
	        }

	        switch (value) {
	        case null: return 'null'
	        case true: return 'true'
	        case false: return 'false'
	        }

	        if (typeof value === 'string') {
	            return quoteString(value, false)
	        }

	        if (typeof value === 'number') {
	            return String(value)
	        }

	        if (typeof value === 'object') {
	            return Array.isArray(value) ? serializeArray(value) : serializeObject(value)
	        }

	        return undefined
	    }

	    function quoteString (value) {
	        var quotes = {
	            "'": 0.1,
	            '"': 0.2,
	        };

	        var replacements = {
	            "'": "\\'",
	            '"': '\\"',
	            '\\': '\\\\',
	            '\b': '\\b',
	            '\f': '\\f',
	            '\n': '\\n',
	            '\r': '\\r',
	            '\t': '\\t',
	            '\v': '\\v',
	            '\0': '\\0',
	            '\u2028': '\\u2028',
	            '\u2029': '\\u2029',
	        };

	        var product = '';

	        for (var i = 0; i < value.length; i++) {
	            var c = value[i];
	            switch (c) {
	            case "'":
	            case '"':
	                quotes[c]++;
	                product += c;
	                continue

	            case '\0':
	                if (util.isDigit(value[i + 1])) {
	                    product += '\\x00';
	                    continue
	                }
	            }

	            if (replacements[c]) {
	                product += replacements[c];
	                continue
	            }

	            if (c < ' ') {
	                var hexString = c.charCodeAt(0).toString(16);
	                product += '\\x' + ('00' + hexString).substring(hexString.length);
	                continue
	            }

	            product += c;
	        }

	        var quoteChar = quote || Object.keys(quotes).reduce(function (a, b) { return (quotes[a] < quotes[b]) ? a : b; });

	        product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]);

	        return quoteChar + product + quoteChar
	    }

	    function serializeObject (value) {
	        if (stack.indexOf(value) >= 0) {
	            throw TypeError('Converting circular structure to JSON5')
	        }

	        stack.push(value);

	        var stepback = indent;
	        indent = indent + gap;

	        var keys = propertyList || Object.keys(value);
	        var partial = [];
	        for (var i = 0, list = keys; i < list.length; i += 1) {
	            var key = list[i];

	            var propertyString = serializeProperty(key, value);
	            if (propertyString !== undefined) {
	                var member = serializeKey(key) + ':';
	                if (gap !== '') {
	                    member += ' ';
	                }
	                member += propertyString;
	                partial.push(member);
	            }
	        }

	        var final;
	        if (partial.length === 0) {
	            final = '{}';
	        } else {
	            var properties;
	            if (gap === '') {
	                properties = partial.join(',');
	                final = '{' + properties + '}';
	            } else {
	                var separator = ',\n' + indent;
	                properties = partial.join(separator);
	                final = '{\n' + indent + properties + ',\n' + stepback + '}';
	            }
	        }

	        stack.pop();
	        indent = stepback;
	        return final
	    }

	    function serializeKey (key) {
	        if (key.length === 0) {
	            return quoteString(key, true)
	        }

	        var firstChar = String.fromCodePoint(key.codePointAt(0));
	        if (!util.isIdStartChar(firstChar)) {
	            return quoteString(key, true)
	        }

	        for (var i = firstChar.length; i < key.length; i++) {
	            if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) {
	                return quoteString(key, true)
	            }
	        }

	        return key
	    }

	    function serializeArray (value) {
	        if (stack.indexOf(value) >= 0) {
	            throw TypeError('Converting circular structure to JSON5')
	        }

	        stack.push(value);

	        var stepback = indent;
	        indent = indent + gap;

	        var partial = [];
	        for (var i = 0; i < value.length; i++) {
	            var propertyString = serializeProperty(String(i), value);
	            partial.push((propertyString !== undefined) ? propertyString : 'null');
	        }

	        var final;
	        if (partial.length === 0) {
	            final = '[]';
	        } else {
	            if (gap === '') {
	                var properties = partial.join(',');
	                final = '[' + properties + ']';
	            } else {
	                var separator = ',\n' + indent;
	                var properties$1 = partial.join(separator);
	                final = '[\n' + indent + properties$1 + ',\n' + stepback + ']';
	            }
	        }

	        stack.pop();
	        indent = stepback;
	        return final
	    }
	};

	var JSON5 = {
	    parse: parse,
	    stringify: stringify,
	};

	var lib = JSON5;

	var es5 = lib;

	return es5;

})));


/***/ }),

/***/ 17884:
/***/ ((module) => {

var toString = Object.prototype.toString;

module.exports = function kindOf(val) {
  if (val === void 0) return 'undefined';
  if (val === null) return 'null';

  var type = typeof val;
  if (type === 'boolean') return 'boolean';
  if (type === 'string') return 'string';
  if (type === 'number') return 'number';
  if (type === 'symbol') return 'symbol';
  if (type === 'function') {
    return isGeneratorFn(val) ? 'generatorfunction' : 'function';
  }

  if (isArray(val)) return 'array';
  if (isBuffer(val)) return 'buffer';
  if (isArguments(val)) return 'arguments';
  if (isDate(val)) return 'date';
  if (isError(val)) return 'error';
  if (isRegexp(val)) return 'regexp';

  switch (ctorName(val)) {
    case 'Symbol': return 'symbol';
    case 'Promise': return 'promise';

    // Set, Map, WeakSet, WeakMap
    case 'WeakMap': return 'weakmap';
    case 'WeakSet': return 'weakset';
    case 'Map': return 'map';
    case 'Set': return 'set';

    // 8-bit typed arrays
    case 'Int8Array': return 'int8array';
    case 'Uint8Array': return 'uint8array';
    case 'Uint8ClampedArray': return 'uint8clampedarray';

    // 16-bit typed arrays
    case 'Int16Array': return 'int16array';
    case 'Uint16Array': return 'uint16array';

    // 32-bit typed arrays
    case 'Int32Array': return 'int32array';
    case 'Uint32Array': return 'uint32array';
    case 'Float32Array': return 'float32array';
    case 'Float64Array': return 'float64array';
  }

  if (isGeneratorObj(val)) {
    return 'generator';
  }

  // Non-plain objects
  type = toString.call(val);
  switch (type) {
    case '[object Object]': return 'object';
    // iterators
    case '[object Map Iterator]': return 'mapiterator';
    case '[object Set Iterator]': return 'setiterator';
    case '[object String Iterator]': return 'stringiterator';
    case '[object Array Iterator]': return 'arrayiterator';
  }

  // other
  return type.slice(8, -1).toLowerCase().replace(/\s/g, '');
};

function ctorName(val) {
  return typeof val.constructor === 'function' ? val.constructor.name : null;
}

function isArray(val) {
  if (Array.isArray) return Array.isArray(val);
  return val instanceof Array;
}

function isError(val) {
  return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number');
}

function isDate(val) {
  if (val instanceof Date) return true;
  return typeof val.toDateString === 'function'
    && typeof val.getDate === 'function'
    && typeof val.setDate === 'function';
}

function isRegexp(val) {
  if (val instanceof RegExp) return true;
  return typeof val.flags === 'string'
    && typeof val.ignoreCase === 'boolean'
    && typeof val.multiline === 'boolean'
    && typeof val.global === 'boolean';
}

function isGeneratorFn(name, val) {
  return ctorName(name) === 'GeneratorFunction';
}

function isGeneratorObj(val) {
  return typeof val.throw === 'function'
    && typeof val.return === 'function'
    && typeof val.next === 'function';
}

function isArguments(val) {
  try {
    if (typeof val.length === 'number' && typeof val.callee === 'function') {
      return true;
    }
  } catch (err) {
    if (err.message.indexOf('callee') !== -1) {
      return true;
    }
  }
  return false;
}

/**
 * If you need to support Safari 5-7 (8-10 yr-old browser),
 * take a look at https://github.com/feross/is-buffer
 */

function isBuffer(val) {
  if (val.constructor && typeof val.constructor.isBuffer === 'function') {
    return val.constructor.isBuffer(val);
  }
  return false;
}


/***/ }),

/***/ 29160:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var inherits = __webpack_require__(72116)
var HashBase = __webpack_require__(63871)
var Buffer = (__webpack_require__(60571).Buffer)

var ARRAY16 = new Array(16)

function MD5 () {
  HashBase.call(this, 64)

  // state
  this._a = 0x67452301
  this._b = 0xefcdab89
  this._c = 0x98badcfe
  this._d = 0x10325476
}

inherits(MD5, HashBase)

MD5.prototype._update = function () {
  var M = ARRAY16
  for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4)

  var a = this._a
  var b = this._b
  var c = this._c
  var d = this._d

  a = fnF(a, b, c, d, M[0], 0xd76aa478, 7)
  d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12)
  c = fnF(c, d, a, b, M[2], 0x242070db, 17)
  b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22)
  a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7)
  d = fnF(d, a, b, c, M[5], 0x4787c62a, 12)
  c = fnF(c, d, a, b, M[6], 0xa8304613, 17)
  b = fnF(b, c, d, a, M[7], 0xfd469501, 22)
  a = fnF(a, b, c, d, M[8], 0x698098d8, 7)
  d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12)
  c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17)
  b = fnF(b, c, d, a, M[11], 0x895cd7be, 22)
  a = fnF(a, b, c, d, M[12], 0x6b901122, 7)
  d = fnF(d, a, b, c, M[13], 0xfd987193, 12)
  c = fnF(c, d, a, b, M[14], 0xa679438e, 17)
  b = fnF(b, c, d, a, M[15], 0x49b40821, 22)

  a = fnG(a, b, c, d, M[1], 0xf61e2562, 5)
  d = fnG(d, a, b, c, M[6], 0xc040b340, 9)
  c = fnG(c, d, a, b, M[11], 0x265e5a51, 14)
  b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20)
  a = fnG(a, b, c, d, M[5], 0xd62f105d, 5)
  d = fnG(d, a, b, c, M[10], 0x02441453, 9)
  c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14)
  b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20)
  a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5)
  d = fnG(d, a, b, c, M[14], 0xc33707d6, 9)
  c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14)
  b = fnG(b, c, d, a, M[8], 0x455a14ed, 20)
  a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5)
  d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9)
  c = fnG(c, d, a, b, M[7], 0x676f02d9, 14)
  b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20)

  a = fnH(a, b, c, d, M[5], 0xfffa3942, 4)
  d = fnH(d, a, b, c, M[8], 0x8771f681, 11)
  c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16)
  b = fnH(b, c, d, a, M[14], 0xfde5380c, 23)
  a = fnH(a, b, c, d, M[1], 0xa4beea44, 4)
  d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11)
  c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16)
  b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23)
  a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4)
  d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11)
  c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16)
  b = fnH(b, c, d, a, M[6], 0x04881d05, 23)
  a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4)
  d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11)
  c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16)
  b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23)

  a = fnI(a, b, c, d, M[0], 0xf4292244, 6)
  d = fnI(d, a, b, c, M[7], 0x432aff97, 10)
  c = fnI(c, d, a, b, M[14], 0xab9423a7, 15)
  b = fnI(b, c, d, a, M[5], 0xfc93a039, 21)
  a = fnI(a, b, c, d, M[12], 0x655b59c3, 6)
  d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10)
  c = fnI(c, d, a, b, M[10], 0xffeff47d, 15)
  b = fnI(b, c, d, a, M[1], 0x85845dd1, 21)
  a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6)
  d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10)
  c = fnI(c, d, a, b, M[6], 0xa3014314, 15)
  b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21)
  a = fnI(a, b, c, d, M[4], 0xf7537e82, 6)
  d = fnI(d, a, b, c, M[11], 0xbd3af235, 10)
  c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15)
  b = fnI(b, c, d, a, M[9], 0xeb86d391, 21)

  this._a = (this._a + a) | 0
  this._b = (this._b + b) | 0
  this._c = (this._c + c) | 0
  this._d = (this._d + d) | 0
}

MD5.prototype._digest = function () {
  // create padding and handle blocks
  this._block[this._blockOffset++] = 0x80
  if (this._blockOffset > 56) {
    this._block.fill(0, this._blockOffset, 64)
    this._update()
    this._blockOffset = 0
  }

  this._block.fill(0, this._blockOffset, 56)
  this._block.writeUInt32LE(this._length[0], 56)
  this._block.writeUInt32LE(this._length[1], 60)
  this._update()

  // produce result
  var buffer = Buffer.allocUnsafe(16)
  buffer.writeInt32LE(this._a, 0)
  buffer.writeInt32LE(this._b, 4)
  buffer.writeInt32LE(this._c, 8)
  buffer.writeInt32LE(this._d, 12)
  return buffer
}

function rotl (x, n) {
  return (x << n) | (x >>> (32 - n))
}

function fnF (a, b, c, d, m, k, s) {
  return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0
}

function fnG (a, b, c, d, m, k, s) {
  return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0
}

function fnH (a, b, c, d, m, k, s) {
  return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0
}

function fnI (a, b, c, d, m, k, s) {
  return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0
}

module.exports = MD5


/***/ }),

/***/ 7427:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var bn = __webpack_require__(89991);
var brorand = __webpack_require__(35973);

function MillerRabin(rand) {
  this.rand = rand || new brorand.Rand();
}
module.exports = MillerRabin;

MillerRabin.create = function create(rand) {
  return new MillerRabin(rand);
};

MillerRabin.prototype._randbelow = function _randbelow(n) {
  var len = n.bitLength();
  var min_bytes = Math.ceil(len / 8);

  // Generage random bytes until a number less than n is found.
  // This ensures that 0..n-1 have an equal probability of being selected.
  do
    var a = new bn(this.rand.generate(min_bytes));
  while (a.cmp(n) >= 0);

  return a;
};

MillerRabin.prototype._randrange = function _randrange(start, stop) {
  // Generate a random number greater than or equal to start and less than stop.
  var size = stop.sub(start);
  return start.add(this._randbelow(size));
};

MillerRabin.prototype.test = function test(n, k, cb) {
  var len = n.bitLength();
  var red = bn.mont(n);
  var rone = new bn(1).toRed(red);

  if (!k)
    k = Math.max(1, (len / 48) | 0);

  // Find d and s, (n - 1) = (2 ^ s) * d;
  var n1 = n.subn(1);
  for (var s = 0; !n1.testn(s); s++) {}
  var d = n.shrn(s);

  var rn1 = n1.toRed(red);

  var prime = true;
  for (; k > 0; k--) {
    var a = this._randrange(new bn(2), n1);
    if (cb)
      cb(a);

    var x = a.toRed(red).redPow(d);
    if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
      continue;

    for (var i = 1; i < s; i++) {
      x = x.redSqr();

      if (x.cmp(rone) === 0)
        return false;
      if (x.cmp(rn1) === 0)
        break;
    }

    if (i === s)
      return false;
  }

  return prime;
};

MillerRabin.prototype.getDivisor = function getDivisor(n, k) {
  var len = n.bitLength();
  var red = bn.mont(n);
  var rone = new bn(1).toRed(red);

  if (!k)
    k = Math.max(1, (len / 48) | 0);

  // Find d and s, (n - 1) = (2 ^ s) * d;
  var n1 = n.subn(1);
  for (var s = 0; !n1.testn(s); s++) {}
  var d = n.shrn(s);

  var rn1 = n1.toRed(red);

  for (; k > 0; k--) {
    var a = this._randrange(new bn(2), n1);

    var g = n.gcd(a);
    if (g.cmpn(1) !== 0)
      return g;

    var x = a.toRed(red).redPow(d);
    if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
      continue;

    for (var i = 1; i < s; i++) {
      x = x.redSqr();

      if (x.cmp(rone) === 0)
        return x.fromRed().subn(1).gcd(n);
      if (x.cmp(rn1) === 0)
        break;
    }

    if (i === s) {
      x = x.redSqr();
      return x.fromRed().subn(1).gcd(n);
    }
  }

  return false;
};


/***/ }),

/***/ 2481:
/***/ ((module) => {

module.exports = assert;

function assert(val, msg) {
  if (!val)
    throw new Error(msg || 'Assertion failed');
}

assert.equal = function assertEqual(l, r, msg) {
  if (l != r)
    throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
};


/***/ }),

/***/ 44086:
/***/ ((__unused_webpack_module, exports) => {

"use strict";


var utils = exports;

function toArray(msg, enc) {
  if (Array.isArray(msg))
    return msg.slice();
  if (!msg)
    return [];
  var res = [];
  if (typeof msg !== 'string') {
    for (var i = 0; i < msg.length; i++)
      res[i] = msg[i] | 0;
    return res;
  }
  if (enc === 'hex') {
    msg = msg.replace(/[^a-z0-9]+/ig, '');
    if (msg.length % 2 !== 0)
      msg = '0' + msg;
    for (var i = 0; i < msg.length; i += 2)
      res.push(parseInt(msg[i] + msg[i + 1], 16));
  } else {
    for (var i = 0; i < msg.length; i++) {
      var c = msg.charCodeAt(i);
      var hi = c >> 8;
      var lo = c & 0xff;
      if (hi)
        res.push(hi, lo);
      else
        res.push(lo);
    }
  }
  return res;
}
utils.toArray = toArray;

function zero2(word) {
  if (word.length === 1)
    return '0' + word;
  else
    return word;
}
utils.zero2 = zero2;

function toHex(msg) {
  var res = '';
  for (var i = 0; i < msg.length; i++)
    res += zero2(msg[i].toString(16));
  return res;
}
utils.toHex = toHex;

utils.encode = function encode(arr, enc) {
  if (enc === 'hex')
    return toHex(arr);
  else
    return arr;
};


/***/ }),

/***/ 33807:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";
// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js
// Fedor, you are amazing.



var asn1 = __webpack_require__(39000);

exports.certificate = __webpack_require__(24159);

var RSAPrivateKey = asn1.define('RSAPrivateKey', function () {
	this.seq().obj(
		this.key('version')['int'](),
		this.key('modulus')['int'](),
		this.key('publicExponent')['int'](),
		this.key('privateExponent')['int'](),
		this.key('prime1')['int'](),
		this.key('prime2')['int'](),
		this.key('exponent1')['int'](),
		this.key('exponent2')['int'](),
		this.key('coefficient')['int']()
	);
});
exports.RSAPrivateKey = RSAPrivateKey;

var RSAPublicKey = asn1.define('RSAPublicKey', function () {
	this.seq().obj(
		this.key('modulus')['int'](),
		this.key('publicExponent')['int']()
	);
});
exports.RSAPublicKey = RSAPublicKey;

var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () {
	this.seq().obj(
		this.key('algorithm').objid(),
		this.key('none').null_().optional(),
		this.key('curve').objid().optional(),
		this.key('params').seq().obj(
			this.key('p')['int'](),
			this.key('q')['int'](),
			this.key('g')['int']()
		).optional()
	);
});

var PublicKey = asn1.define('SubjectPublicKeyInfo', function () {
	this.seq().obj(
		this.key('algorithm').use(AlgorithmIdentifier),
		this.key('subjectPublicKey').bitstr()
	);
});
exports.PublicKey = PublicKey;

var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () {
	this.seq().obj(
		this.key('version')['int'](),
		this.key('algorithm').use(AlgorithmIdentifier),
		this.key('subjectPrivateKey').octstr()
	);
});
exports.PrivateKey = PrivateKeyInfo;
var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () {
	this.seq().obj(
		this.key('algorithm').seq().obj(
			this.key('id').objid(),
			this.key('decrypt').seq().obj(
				this.key('kde').seq().obj(
					this.key('id').objid(),
					this.key('kdeparams').seq().obj(
						this.key('salt').octstr(),
						this.key('iters')['int']()
					)
				),
				this.key('cipher').seq().obj(
					this.key('algo').objid(),
					this.key('iv').octstr()
				)
			)
		),
		this.key('subjectPrivateKey').octstr()
	);
});

exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo;

var DSAPrivateKey = asn1.define('DSAPrivateKey', function () {
	this.seq().obj(
		this.key('version')['int'](),
		this.key('p')['int'](),
		this.key('q')['int'](),
		this.key('g')['int'](),
		this.key('pub_key')['int'](),
		this.key('priv_key')['int']()
	);
});
exports.DSAPrivateKey = DSAPrivateKey;

exports.DSAparam = asn1.define('DSAparam', function () {
	this['int']();
});

var ECParameters = asn1.define('ECParameters', function () {
	this.choice({
		namedCurve: this.objid()
	});
});

var ECPrivateKey = asn1.define('ECPrivateKey', function () {
	this.seq().obj(
		this.key('version')['int'](),
		this.key('privateKey').octstr(),
		this.key('parameters').optional().explicit(0).use(ECParameters),
		this.key('publicKey').optional().explicit(1).bitstr()
	);
});
exports.ECPrivateKey = ECPrivateKey;

exports.signature = asn1.define('signature', function () {
	this.seq().obj(
		this.key('r')['int'](),
		this.key('s')['int']()
	);
});


/***/ }),

/***/ 24159:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
// from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js
// thanks to @Rantanen



var asn = __webpack_require__(39000);

var Time = asn.define('Time', function () {
	this.choice({
		utcTime: this.utctime(),
		generalTime: this.gentime()
	});
});

var AttributeTypeValue = asn.define('AttributeTypeValue', function () {
	this.seq().obj(
		this.key('type').objid(),
		this.key('value').any()
	);
});

var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () {
	this.seq().obj(
		this.key('algorithm').objid(),
		this.key('parameters').optional(),
		this.key('curve').objid().optional()
	);
});

var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () {
	this.seq().obj(
		this.key('algorithm').use(AlgorithmIdentifier),
		this.key('subjectPublicKey').bitstr()
	);
});

var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () {
	this.setof(AttributeTypeValue);
});

var RDNSequence = asn.define('RDNSequence', function () {
	this.seqof(RelativeDistinguishedName);
});

var Name = asn.define('Name', function () {
	this.choice({
		rdnSequence: this.use(RDNSequence)
	});
});

var Validity = asn.define('Validity', function () {
	this.seq().obj(
		this.key('notBefore').use(Time),
		this.key('notAfter').use(Time)
	);
});

var Extension = asn.define('Extension', function () {
	this.seq().obj(
		this.key('extnID').objid(),
		this.key('critical').bool().def(false),
		this.key('extnValue').octstr()
	);
});

var TBSCertificate = asn.define('TBSCertificate', function () {
	this.seq().obj(
		this.key('version').explicit(0)['int']().optional(),
		this.key('serialNumber')['int'](),
		this.key('signature').use(AlgorithmIdentifier),
		this.key('issuer').use(Name),
		this.key('validity').use(Validity),
		this.key('subject').use(Name),
		this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo),
		this.key('issuerUniqueID').implicit(1).bitstr().optional(),
		this.key('subjectUniqueID').implicit(2).bitstr().optional(),
		this.key('extensions').explicit(3).seqof(Extension).optional()
	);
});

var X509Certificate = asn.define('X509Certificate', function () {
	this.seq().obj(
		this.key('tbsCertificate').use(TBSCertificate),
		this.key('signatureAlgorithm').use(AlgorithmIdentifier),
		this.key('signatureValue').bitstr()
	);
});

module.exports = X509Certificate;


/***/ }),

/***/ 63671:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


// adapted from https://github.com/apatil/pemstrip
var findProc = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m;
var startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m;
var fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m;
var evp = __webpack_require__(32615);
var ciphers = __webpack_require__(17044);
var Buffer = (__webpack_require__(60571).Buffer);
module.exports = function (okey, password) {
	var key = okey.toString();
	var match = key.match(findProc);
	var decrypted;
	if (!match) {
		var match2 = key.match(fullRegex);
		decrypted = Buffer.from(match2[2].replace(/[\r\n]/g, ''), 'base64');
	} else {
		var suite = 'aes' + match[1];
		var iv = Buffer.from(match[2], 'hex');
		var cipherText = Buffer.from(match[3].replace(/[\r\n]/g, ''), 'base64');
		var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key;
		var out = [];
		var cipher = ciphers.createDecipheriv(suite, cipherKey, iv);
		out.push(cipher.update(cipherText));
		out.push(cipher['final']());
		decrypted = Buffer.concat(out);
	}
	var tag = key.match(startRegex)[1];
	return {
		tag: tag,
		data: decrypted
	};
};


/***/ }),

/***/ 20672:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var asn1 = __webpack_require__(33807);
var aesid = __webpack_require__(77029);
var fixProc = __webpack_require__(63671);
var ciphers = __webpack_require__(17044);
var compat = __webpack_require__(8033);
var Buffer = (__webpack_require__(60571).Buffer);

function decrypt(data, password) {
	var salt = data.algorithm.decrypt.kde.kdeparams.salt;
	var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10);
	var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')];
	var iv = data.algorithm.decrypt.cipher.iv;
	var cipherText = data.subjectPrivateKey;
	var keylen = parseInt(algo.split('-')[1], 10) / 8;
	var key = compat.pbkdf2Sync(password, salt, iters, keylen, 'sha1');
	var cipher = ciphers.createDecipheriv(algo, key, iv);
	var out = [];
	out.push(cipher.update(cipherText));
	out.push(cipher['final']());
	return Buffer.concat(out);
}

function parseKeys(buffer) {
	var password;
	if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) {
		password = buffer.passphrase;
		buffer = buffer.key;
	}
	if (typeof buffer === 'string') {
		buffer = Buffer.from(buffer);
	}

	var stripped = fixProc(buffer, password);

	var type = stripped.tag;
	var data = stripped.data;
	var subtype, ndata;
	switch (type) {
		case 'CERTIFICATE':
			ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo;
			// falls through
		case 'PUBLIC KEY':
			if (!ndata) {
				ndata = asn1.PublicKey.decode(data, 'der');
			}
			subtype = ndata.algorithm.algorithm.join('.');
			switch (subtype) {
				case '1.2.840.113549.1.1.1':
					return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der');
				case '1.2.840.10045.2.1':
					ndata.subjectPrivateKey = ndata.subjectPublicKey;
					return {
						type: 'ec',
						data: ndata
					};
				case '1.2.840.10040.4.1':
					ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der');
					return {
						type: 'dsa',
						data: ndata.algorithm.params
					};
				default: throw new Error('unknown key id ' + subtype);
			}
			// throw new Error('unknown key type ' + type)
		case 'ENCRYPTED PRIVATE KEY':
			data = asn1.EncryptedPrivateKey.decode(data, 'der');
			data = decrypt(data, password);
			// falls through
		case 'PRIVATE KEY':
			ndata = asn1.PrivateKey.decode(data, 'der');
			subtype = ndata.algorithm.algorithm.join('.');
			switch (subtype) {
				case '1.2.840.113549.1.1.1':
					return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der');
				case '1.2.840.10045.2.1':
					return {
						curve: ndata.algorithm.curve,
						privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey
					};
				case '1.2.840.10040.4.1':
					ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der');
					return {
						type: 'dsa',
						params: ndata.algorithm.params
					};
				default: throw new Error('unknown key id ' + subtype);
			}
			// throw new Error('unknown key type ' + type)
		case 'RSA PUBLIC KEY':
			return asn1.RSAPublicKey.decode(data, 'der');
		case 'RSA PRIVATE KEY':
			return asn1.RSAPrivateKey.decode(data, 'der');
		case 'DSA PRIVATE KEY':
			return {
				type: 'dsa',
				params: asn1.DSAPrivateKey.decode(data, 'der')
			};
		case 'EC PRIVATE KEY':
			data = asn1.ECPrivateKey.decode(data, 'der');
			return {
				curve: data.parameters.value,
				privateKey: data.privateKey
			};
		default: throw new Error('unknown key type ' + type);
	}
}
parseKeys.signature = asn1.signature;

module.exports = parseKeys;


/***/ }),

/***/ 8033:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

exports.pbkdf2 = __webpack_require__(63545)
exports.pbkdf2Sync = __webpack_require__(89547)


/***/ }),

/***/ 63545:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var Buffer = (__webpack_require__(60571).Buffer)

var checkParameters = __webpack_require__(62787)
var defaultEncoding = __webpack_require__(22420)
var sync = __webpack_require__(89547)
var toBuffer = __webpack_require__(5839)

var ZERO_BUF
var subtle = __webpack_require__.g.crypto && __webpack_require__.g.crypto.subtle
var toBrowser = {
  sha: 'SHA-1',
  'sha-1': 'SHA-1',
  sha1: 'SHA-1',
  sha256: 'SHA-256',
  'sha-256': 'SHA-256',
  sha384: 'SHA-384',
  'sha-384': 'SHA-384',
  'sha-512': 'SHA-512',
  sha512: 'SHA-512'
}
var checks = []
function checkNative (algo) {
  if (__webpack_require__.g.process && !__webpack_require__.g.process.browser) {
    return Promise.resolve(false)
  }
  if (!subtle || !subtle.importKey || !subtle.deriveBits) {
    return Promise.resolve(false)
  }
  if (checks[algo] !== undefined) {
    return checks[algo]
  }
  ZERO_BUF = ZERO_BUF || Buffer.alloc(8)
  var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo)
    .then(function () {
      return true
    }).catch(function () {
      return false
    })
  checks[algo] = prom
  return prom
}
var nextTick
function getNextTick () {
  if (nextTick) {
    return nextTick
  }
  if (__webpack_require__.g.process && __webpack_require__.g.process.nextTick) {
    nextTick = __webpack_require__.g.process.nextTick
  } else if (__webpack_require__.g.queueMicrotask) {
    nextTick = __webpack_require__.g.queueMicrotask
  } else if (__webpack_require__.g.setImmediate) {
    nextTick = __webpack_require__.g.setImmediate
  } else {
    nextTick = __webpack_require__.g.setTimeout
  }
  return nextTick
}
function browserPbkdf2 (password, salt, iterations, length, algo) {
  return subtle.importKey(
    'raw', password, { name: 'PBKDF2' }, false, ['deriveBits']
  ).then(function (key) {
    return subtle.deriveBits({
      name: 'PBKDF2',
      salt: salt,
      iterations: iterations,
      hash: {
        name: algo
      }
    }, key, length << 3)
  }).then(function (res) {
    return Buffer.from(res)
  })
}

function resolvePromise (promise, callback) {
  promise.then(function (out) {
    getNextTick()(function () {
      callback(null, out)
    })
  }, function (e) {
    getNextTick()(function () {
      callback(e)
    })
  })
}
module.exports = function (password, salt, iterations, keylen, digest, callback) {
  if (typeof digest === 'function') {
    callback = digest
    digest = undefined
  }

  digest = digest || 'sha1'
  var algo = toBrowser[digest.toLowerCase()]

  if (!algo || typeof __webpack_require__.g.Promise !== 'function') {
    getNextTick()(function () {
      var out
      try {
        out = sync(password, salt, iterations, keylen, digest)
      } catch (e) {
        return callback(e)
      }
      callback(null, out)
    })
    return
  }

  checkParameters(iterations, keylen)
  password = toBuffer(password, defaultEncoding, 'Password')
  salt = toBuffer(salt, defaultEncoding, 'Salt')
  if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2')

  resolvePromise(checkNative(algo).then(function (resp) {
    if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo)

    return sync(password, salt, iterations, keylen, digest)
  }), callback)
}


/***/ }),

/***/ 22420:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var defaultEncoding
/* istanbul ignore next */
if (__webpack_require__.g.process && __webpack_require__.g.process.browser) {
  defaultEncoding = 'utf-8'
} else if (__webpack_require__.g.process && __webpack_require__.g.process.version) {
  var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10)

  defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary'
} else {
  defaultEncoding = 'utf-8'
}
module.exports = defaultEncoding


/***/ }),

/***/ 62787:
/***/ ((module) => {

var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs

module.exports = function (iterations, keylen) {
  if (typeof iterations !== 'number') {
    throw new TypeError('Iterations not a number')
  }

  if (iterations < 0) {
    throw new TypeError('Bad iterations')
  }

  if (typeof keylen !== 'number') {
    throw new TypeError('Key length not a number')
  }

  if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */
    throw new TypeError('Bad key length')
  }
}


/***/ }),

/***/ 89547:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var md5 = __webpack_require__(51168)
var RIPEMD160 = __webpack_require__(84861)
var sha = __webpack_require__(79997)
var Buffer = (__webpack_require__(60571).Buffer)

var checkParameters = __webpack_require__(62787)
var defaultEncoding = __webpack_require__(22420)
var toBuffer = __webpack_require__(5839)

var ZEROS = Buffer.alloc(128)
var sizes = {
  md5: 16,
  sha1: 20,
  sha224: 28,
  sha256: 32,
  sha384: 48,
  sha512: 64,
  rmd160: 20,
  ripemd160: 20
}

function Hmac (alg, key, saltLen) {
  var hash = getDigest(alg)
  var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64

  if (key.length > blocksize) {
    key = hash(key)
  } else if (key.length < blocksize) {
    key = Buffer.concat([key, ZEROS], blocksize)
  }

  var ipad = Buffer.allocUnsafe(blocksize + sizes[alg])
  var opad = Buffer.allocUnsafe(blocksize + sizes[alg])
  for (var i = 0; i < blocksize; i++) {
    ipad[i] = key[i] ^ 0x36
    opad[i] = key[i] ^ 0x5C
  }

  var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4)
  ipad.copy(ipad1, 0, 0, blocksize)
  this.ipad1 = ipad1
  this.ipad2 = ipad
  this.opad = opad
  this.alg = alg
  this.blocksize = blocksize
  this.hash = hash
  this.size = sizes[alg]
}

Hmac.prototype.run = function (data, ipad) {
  data.copy(ipad, this.blocksize)
  var h = this.hash(ipad)
  h.copy(this.opad, this.blocksize)
  return this.hash(this.opad)
}

function getDigest (alg) {
  function shaFunc (data) {
    return sha(alg).update(data).digest()
  }
  function rmd160Func (data) {
    return new RIPEMD160().update(data).digest()
  }

  if (alg === 'rmd160' || alg === 'ripemd160') return rmd160Func
  if (alg === 'md5') return md5
  return shaFunc
}

function pbkdf2 (password, salt, iterations, keylen, digest) {
  checkParameters(iterations, keylen)
  password = toBuffer(password, defaultEncoding, 'Password')
  salt = toBuffer(salt, defaultEncoding, 'Salt')

  digest = digest || 'sha1'

  var hmac = new Hmac(digest, password, salt.length)

  var DK = Buffer.allocUnsafe(keylen)
  var block1 = Buffer.allocUnsafe(salt.length + 4)
  salt.copy(block1, 0, 0, salt.length)

  var destPos = 0
  var hLen = sizes[digest]
  var l = Math.ceil(keylen / hLen)

  for (var i = 1; i <= l; i++) {
    block1.writeUInt32BE(i, salt.length)

    var T = hmac.run(block1, hmac.ipad1)
    var U = T

    for (var j = 1; j < iterations; j++) {
      U = hmac.run(U, hmac.ipad2)
      for (var k = 0; k < hLen; k++) T[k] ^= U[k]
    }

    T.copy(DK, destPos)
    destPos += hLen
  }

  return DK
}

module.exports = pbkdf2


/***/ }),

/***/ 5839:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var Buffer = (__webpack_require__(60571).Buffer)

module.exports = function (thing, encoding, name) {
  if (Buffer.isBuffer(thing)) {
    return thing
  } else if (typeof thing === 'string') {
    return Buffer.from(thing, encoding)
  } else if (ArrayBuffer.isView(thing)) {
    return Buffer.from(thing.buffer)
  } else {
    throw new TypeError(name + ' must be a string, a Buffer, a typed array or a DataView')
  }
}


/***/ }),

/***/ 23792:
/***/ ((module) => {

"use strict";


if (typeof process === 'undefined' ||
    !process.version ||
    process.version.indexOf('v0.') === 0 ||
    process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  module.exports = { nextTick: nextTick };
} else {
  module.exports = process
}

function nextTick(fn, arg1, arg2, arg3) {
  if (typeof fn !== 'function') {
    throw new TypeError('"callback" argument must be a function');
  }
  var len = arguments.length;
  var args, i;
  switch (len) {
  case 0:
  case 1:
    return process.nextTick(fn);
  case 2:
    return process.nextTick(function afterTickOne() {
      fn.call(null, arg1);
    });
  case 3:
    return process.nextTick(function afterTickTwo() {
      fn.call(null, arg1, arg2);
    });
  case 4:
    return process.nextTick(function afterTickThree() {
      fn.call(null, arg1, arg2, arg3);
    });
  default:
    args = new Array(len - 1);
    i = 0;
    while (i < args.length) {
      args[i++] = arguments[i];
    }
    return process.nextTick(function afterTick() {
      fn.apply(null, args);
    });
  }
}



/***/ }),

/***/ 74352:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

exports.publicEncrypt = __webpack_require__(88806)
exports.privateDecrypt = __webpack_require__(50770)

exports.privateEncrypt = function privateEncrypt (key, buf) {
  return exports.publicEncrypt(key, buf, true)
}

exports.publicDecrypt = function publicDecrypt (key, buf) {
  return exports.privateDecrypt(key, buf, true)
}


/***/ }),

/***/ 37678:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var createHash = __webpack_require__(63044)
var Buffer = (__webpack_require__(60571).Buffer)

module.exports = function (seed, len) {
  var t = Buffer.alloc(0)
  var i = 0
  var c
  while (t.length < len) {
    c = i2ops(i++)
    t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()])
  }
  return t.slice(0, len)
}

function i2ops (c) {
  var out = Buffer.allocUnsafe(4)
  out.writeUInt32BE(c, 0)
  return out
}


/***/ }),

/***/ 50770:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var parseKeys = __webpack_require__(20672)
var mgf = __webpack_require__(37678)
var xor = __webpack_require__(25181)
var BN = __webpack_require__(89991)
var crt = __webpack_require__(19501)
var createHash = __webpack_require__(63044)
var withPublic = __webpack_require__(64207)
var Buffer = (__webpack_require__(60571).Buffer)

module.exports = function privateDecrypt (privateKey, enc, reverse) {
  var padding
  if (privateKey.padding) {
    padding = privateKey.padding
  } else if (reverse) {
    padding = 1
  } else {
    padding = 4
  }

  var key = parseKeys(privateKey)
  var k = key.modulus.byteLength()
  if (enc.length > k || new BN(enc).cmp(key.modulus) >= 0) {
    throw new Error('decryption error')
  }
  var msg
  if (reverse) {
    msg = withPublic(new BN(enc), key)
  } else {
    msg = crt(enc, key)
  }
  var zBuffer = Buffer.alloc(k - msg.length)
  msg = Buffer.concat([zBuffer, msg], k)
  if (padding === 4) {
    return oaep(key, msg)
  } else if (padding === 1) {
    return pkcs1(key, msg, reverse)
  } else if (padding === 3) {
    return msg
  } else {
    throw new Error('unknown padding')
  }
}

function oaep (key, msg) {
  var k = key.modulus.byteLength()
  var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()
  var hLen = iHash.length
  if (msg[0] !== 0) {
    throw new Error('decryption error')
  }
  var maskedSeed = msg.slice(1, hLen + 1)
  var maskedDb = msg.slice(hLen + 1)
  var seed = xor(maskedSeed, mgf(maskedDb, hLen))
  var db = xor(maskedDb, mgf(seed, k - hLen - 1))
  if (compare(iHash, db.slice(0, hLen))) {
    throw new Error('decryption error')
  }
  var i = hLen
  while (db[i] === 0) {
    i++
  }
  if (db[i++] !== 1) {
    throw new Error('decryption error')
  }
  return db.slice(i)
}

function pkcs1 (key, msg, reverse) {
  var p1 = msg.slice(0, 2)
  var i = 2
  var status = 0
  while (msg[i++] !== 0) {
    if (i >= msg.length) {
      status++
      break
    }
  }
  var ps = msg.slice(2, i - 1)

  if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)) {
    status++
  }
  if (ps.length < 8) {
    status++
  }
  if (status) {
    throw new Error('decryption error')
  }
  return msg.slice(i)
}
function compare (a, b) {
  a = Buffer.from(a)
  b = Buffer.from(b)
  var dif = 0
  var len = a.length
  if (a.length !== b.length) {
    dif++
    len = Math.min(a.length, b.length)
  }
  var i = -1
  while (++i < len) {
    dif += (a[i] ^ b[i])
  }
  return dif
}


/***/ }),

/***/ 88806:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var parseKeys = __webpack_require__(20672)
var randomBytes = __webpack_require__(66290)
var createHash = __webpack_require__(63044)
var mgf = __webpack_require__(37678)
var xor = __webpack_require__(25181)
var BN = __webpack_require__(89991)
var withPublic = __webpack_require__(64207)
var crt = __webpack_require__(19501)
var Buffer = (__webpack_require__(60571).Buffer)

module.exports = function publicEncrypt (publicKey, msg, reverse) {
  var padding
  if (publicKey.padding) {
    padding = publicKey.padding
  } else if (reverse) {
    padding = 1
  } else {
    padding = 4
  }
  var key = parseKeys(publicKey)
  var paddedMsg
  if (padding === 4) {
    paddedMsg = oaep(key, msg)
  } else if (padding === 1) {
    paddedMsg = pkcs1(key, msg, reverse)
  } else if (padding === 3) {
    paddedMsg = new BN(msg)
    if (paddedMsg.cmp(key.modulus) >= 0) {
      throw new Error('data too long for modulus')
    }
  } else {
    throw new Error('unknown padding')
  }
  if (reverse) {
    return crt(paddedMsg, key)
  } else {
    return withPublic(paddedMsg, key)
  }
}

function oaep (key, msg) {
  var k = key.modulus.byteLength()
  var mLen = msg.length
  var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()
  var hLen = iHash.length
  var hLen2 = 2 * hLen
  if (mLen > k - hLen2 - 2) {
    throw new Error('message too long')
  }
  var ps = Buffer.alloc(k - mLen - hLen2 - 2)
  var dblen = k - hLen - 1
  var seed = randomBytes(hLen)
  var maskedDb = xor(Buffer.concat([iHash, ps, Buffer.alloc(1, 1), msg], dblen), mgf(seed, dblen))
  var maskedSeed = xor(seed, mgf(maskedDb, hLen))
  return new BN(Buffer.concat([Buffer.alloc(1), maskedSeed, maskedDb], k))
}
function pkcs1 (key, msg, reverse) {
  var mLen = msg.length
  var k = key.modulus.byteLength()
  if (mLen > k - 11) {
    throw new Error('message too long')
  }
  var ps
  if (reverse) {
    ps = Buffer.alloc(k - mLen - 3, 0xff)
  } else {
    ps = nonZero(k - mLen - 3)
  }
  return new BN(Buffer.concat([Buffer.from([0, reverse ? 1 : 2]), ps, Buffer.alloc(1), msg], k))
}
function nonZero (len) {
  var out = Buffer.allocUnsafe(len)
  var i = 0
  var cache = randomBytes(len * 2)
  var cur = 0
  var num
  while (i < len) {
    if (cur === cache.length) {
      cache = randomBytes(len * 2)
      cur = 0
    }
    num = cache[cur++]
    if (num) {
      out[i++] = num
    }
  }
  return out
}


/***/ }),

/***/ 64207:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var BN = __webpack_require__(89991)
var Buffer = (__webpack_require__(60571).Buffer)

function withPublic (paddedMsg, key) {
  return Buffer.from(paddedMsg
    .toRed(BN.mont(key.modulus))
    .redPow(new BN(key.publicExponent))
    .fromRed()
    .toArray())
}

module.exports = withPublic


/***/ }),

/***/ 25181:
/***/ ((module) => {

module.exports = function xor (a, b) {
  var len = a.length
  var i = -1
  while (++i < len) {
    a[i] ^= b[i]
  }
  return a
}


/***/ }),

/***/ 13066:
/***/ ((module) => {

"use strict";


/** Highest positive signed 32-bit float value */
const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1

/** Bootstring parameters */
const base = 36;
const tMin = 1;
const tMax = 26;
const skew = 38;
const damp = 700;
const initialBias = 72;
const initialN = 128; // 0x80
const delimiter = '-'; // '\x2D'

/** Regular expressions */
const regexPunycode = /^xn--/;
const regexNonASCII = /[^\0-\x7F]/; // Note: U+007F DEL is excluded too.
const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators

/** Error messages */
const errors = {
	'overflow': 'Overflow: input needs wider integers to process',
	'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
	'invalid-input': 'Invalid input'
};

/** Convenience shortcuts */
const baseMinusTMin = base - tMin;
const floor = Math.floor;
const stringFromCharCode = String.fromCharCode;

/*--------------------------------------------------------------------------*/

/**
 * A generic error utility function.
 * @private
 * @param {String} type The error type.
 * @returns {Error} Throws a `RangeError` with the applicable error message.
 */
function error(type) {
	throw new RangeError(errors[type]);
}

/**
 * A generic `Array#map` utility function.
 * @private
 * @param {Array} array The array to iterate over.
 * @param {Function} callback The function that gets called for every array
 * item.
 * @returns {Array} A new array of values returned by the callback function.
 */
function map(array, callback) {
	const result = [];
	let length = array.length;
	while (length--) {
		result[length] = callback(array[length]);
	}
	return result;
}

/**
 * A simple `Array#map`-like wrapper to work with domain name strings or email
 * addresses.
 * @private
 * @param {String} domain The domain name or email address.
 * @param {Function} callback The function that gets called for every
 * character.
 * @returns {String} A new string of characters returned by the callback
 * function.
 */
function mapDomain(domain, callback) {
	const parts = domain.split('@');
	let result = '';
	if (parts.length > 1) {
		// In email addresses, only the domain name should be punycoded. Leave
		// the local part (i.e. everything up to `@`) intact.
		result = parts[0] + '@';
		domain = parts[1];
	}
	// Avoid `split(regex)` for IE8 compatibility. See #17.
	domain = domain.replace(regexSeparators, '\x2E');
	const labels = domain.split('.');
	const encoded = map(labels, callback).join('.');
	return result + encoded;
}

/**
 * Creates an array containing the numeric code points of each Unicode
 * character in the string. While JavaScript uses UCS-2 internally,
 * this function will convert a pair of surrogate halves (each of which
 * UCS-2 exposes as separate characters) into a single code point,
 * matching UTF-16.
 * @see `punycode.ucs2.encode`
 * @see <https://mathiasbynens.be/notes/javascript-encoding>
 * @memberOf punycode.ucs2
 * @name decode
 * @param {String} string The Unicode input string (UCS-2).
 * @returns {Array} The new array of code points.
 */
function ucs2decode(string) {
	const output = [];
	let counter = 0;
	const length = string.length;
	while (counter < length) {
		const value = string.charCodeAt(counter++);
		if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
			// It's a high surrogate, and there is a next character.
			const extra = string.charCodeAt(counter++);
			if ((extra & 0xFC00) == 0xDC00) { // Low surrogate.
				output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
			} else {
				// It's an unmatched surrogate; only append this code unit, in case the
				// next code unit is the high surrogate of a surrogate pair.
				output.push(value);
				counter--;
			}
		} else {
			output.push(value);
		}
	}
	return output;
}

/**
 * Creates a string based on an array of numeric code points.
 * @see `punycode.ucs2.decode`
 * @memberOf punycode.ucs2
 * @name encode
 * @param {Array} codePoints The array of numeric code points.
 * @returns {String} The new Unicode string (UCS-2).
 */
const ucs2encode = codePoints => String.fromCodePoint(...codePoints);

/**
 * Converts a basic code point into a digit/integer.
 * @see `digitToBasic()`
 * @private
 * @param {Number} codePoint The basic numeric code point value.
 * @returns {Number} The numeric value of a basic code point (for use in
 * representing integers) in the range `0` to `base - 1`, or `base` if
 * the code point does not represent a value.
 */
const basicToDigit = function(codePoint) {
	if (codePoint >= 0x30 && codePoint < 0x3A) {
		return 26 + (codePoint - 0x30);
	}
	if (codePoint >= 0x41 && codePoint < 0x5B) {
		return codePoint - 0x41;
	}
	if (codePoint >= 0x61 && codePoint < 0x7B) {
		return codePoint - 0x61;
	}
	return base;
};

/**
 * Converts a digit/integer into a basic code point.
 * @see `basicToDigit()`
 * @private
 * @param {Number} digit The numeric value of a basic code point.
 * @returns {Number} The basic code point whose value (when used for
 * representing integers) is `digit`, which needs to be in the range
 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
 * used; else, the lowercase form is used. The behavior is undefined
 * if `flag` is non-zero and `digit` has no uppercase form.
 */
const digitToBasic = function(digit, flag) {
	//  0..25 map to ASCII a..z or A..Z
	// 26..35 map to ASCII 0..9
	return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
};

/**
 * Bias adaptation function as per section 3.4 of RFC 3492.
 * https://tools.ietf.org/html/rfc3492#section-3.4
 * @private
 */
const adapt = function(delta, numPoints, firstTime) {
	let k = 0;
	delta = firstTime ? floor(delta / damp) : delta >> 1;
	delta += floor(delta / numPoints);
	for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
		delta = floor(delta / baseMinusTMin);
	}
	return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
};

/**
 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
 * symbols.
 * @memberOf punycode
 * @param {String} input The Punycode string of ASCII-only symbols.
 * @returns {String} The resulting string of Unicode symbols.
 */
const decode = function(input) {
	// Don't use UCS-2.
	const output = [];
	const inputLength = input.length;
	let i = 0;
	let n = initialN;
	let bias = initialBias;

	// Handle the basic code points: let `basic` be the number of input code
	// points before the last delimiter, or `0` if there is none, then copy
	// the first basic code points to the output.

	let basic = input.lastIndexOf(delimiter);
	if (basic < 0) {
		basic = 0;
	}

	for (let j = 0; j < basic; ++j) {
		// if it's not a basic code point
		if (input.charCodeAt(j) >= 0x80) {
			error('not-basic');
		}
		output.push(input.charCodeAt(j));
	}

	// Main decoding loop: start just after the last delimiter if any basic code
	// points were copied; start at the beginning otherwise.

	for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {

		// `index` is the index of the next character to be consumed.
		// Decode a generalized variable-length integer into `delta`,
		// which gets added to `i`. The overflow checking is easier
		// if we increase `i` as we go, then subtract off its starting
		// value at the end to obtain `delta`.
		const oldi = i;
		for (let w = 1, k = base; /* no condition */; k += base) {

			if (index >= inputLength) {
				error('invalid-input');
			}

			const digit = basicToDigit(input.charCodeAt(index++));

			if (digit >= base) {
				error('invalid-input');
			}
			if (digit > floor((maxInt - i) / w)) {
				error('overflow');
			}

			i += digit * w;
			const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);

			if (digit < t) {
				break;
			}

			const baseMinusT = base - t;
			if (w > floor(maxInt / baseMinusT)) {
				error('overflow');
			}

			w *= baseMinusT;

		}

		const out = output.length + 1;
		bias = adapt(i - oldi, out, oldi == 0);

		// `i` was supposed to wrap around from `out` to `0`,
		// incrementing `n` each time, so we'll fix that now:
		if (floor(i / out) > maxInt - n) {
			error('overflow');
		}

		n += floor(i / out);
		i %= out;

		// Insert `n` at position `i` of the output.
		output.splice(i++, 0, n);

	}

	return String.fromCodePoint(...output);
};

/**
 * Converts a string of Unicode symbols (e.g. a domain name label) to a
 * Punycode string of ASCII-only symbols.
 * @memberOf punycode
 * @param {String} input The string of Unicode symbols.
 * @returns {String} The resulting Punycode string of ASCII-only symbols.
 */
const encode = function(input) {
	const output = [];

	// Convert the input in UCS-2 to an array of Unicode code points.
	input = ucs2decode(input);

	// Cache the length.
	const inputLength = input.length;

	// Initialize the state.
	let n = initialN;
	let delta = 0;
	let bias = initialBias;

	// Handle the basic code points.
	for (const currentValue of input) {
		if (currentValue < 0x80) {
			output.push(stringFromCharCode(currentValue));
		}
	}

	const basicLength = output.length;
	let handledCPCount = basicLength;

	// `handledCPCount` is the number of code points that have been handled;
	// `basicLength` is the number of basic code points.

	// Finish the basic string with a delimiter unless it's empty.
	if (basicLength) {
		output.push(delimiter);
	}

	// Main encoding loop:
	while (handledCPCount < inputLength) {

		// All non-basic code points < n have been handled already. Find the next
		// larger one:
		let m = maxInt;
		for (const currentValue of input) {
			if (currentValue >= n && currentValue < m) {
				m = currentValue;
			}
		}

		// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
		// but guard against overflow.
		const handledCPCountPlusOne = handledCPCount + 1;
		if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
			error('overflow');
		}

		delta += (m - n) * handledCPCountPlusOne;
		n = m;

		for (const currentValue of input) {
			if (currentValue < n && ++delta > maxInt) {
				error('overflow');
			}
			if (currentValue === n) {
				// Represent delta as a generalized variable-length integer.
				let q = delta;
				for (let k = base; /* no condition */; k += base) {
					const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
					if (q < t) {
						break;
					}
					const qMinusT = q - t;
					const baseMinusT = base - t;
					output.push(
						stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
					);
					q = floor(qMinusT / baseMinusT);
				}

				output.push(stringFromCharCode(digitToBasic(q, 0)));
				bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength);
				delta = 0;
				++handledCPCount;
			}
		}

		++delta;
		++n;

	}
	return output.join('');
};

/**
 * Converts a Punycode string representing a domain name or an email address
 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
 * it doesn't matter if you call it on a string that has already been
 * converted to Unicode.
 * @memberOf punycode
 * @param {String} input The Punycoded domain name or email address to
 * convert to Unicode.
 * @returns {String} The Unicode representation of the given Punycode
 * string.
 */
const toUnicode = function(input) {
	return mapDomain(input, function(string) {
		return regexPunycode.test(string)
			? decode(string.slice(4).toLowerCase())
			: string;
	});
};

/**
 * Converts a Unicode string representing a domain name or an email address to
 * Punycode. Only the non-ASCII parts of the domain name will be converted,
 * i.e. it doesn't matter if you call it with a domain that's already in
 * ASCII.
 * @memberOf punycode
 * @param {String} input The domain name or email address to convert, as a
 * Unicode string.
 * @returns {String} The Punycode representation of the given domain name or
 * email address.
 */
const toASCII = function(input) {
	return mapDomain(input, function(string) {
		return regexNonASCII.test(string)
			? 'xn--' + encode(string)
			: string;
	});
};

/*--------------------------------------------------------------------------*/

/** Define the public API */
const punycode = {
	/**
	 * A string representing the current Punycode.js version number.
	 * @memberOf punycode
	 * @type String
	 */
	'version': '2.3.1',
	/**
	 * An object of methods to convert from JavaScript's internal character
	 * representation (UCS-2) to Unicode code points, and back.
	 * @see <https://mathiasbynens.be/notes/javascript-encoding>
	 * @memberOf punycode
	 * @type Object
	 */
	'ucs2': {
		'decode': ucs2decode,
		'encode': ucs2encode
	},
	'decode': decode,
	'encode': encode,
	'toASCII': toASCII,
	'toUnicode': toUnicode
};

module.exports = punycode;


/***/ }),

/***/ 66290:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


// limit of Crypto.getRandomValues()
// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
var MAX_BYTES = 65536

// Node supports requesting up to this number of bytes
// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48
var MAX_UINT32 = 4294967295

function oldBrowser () {
  throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11')
}

var Buffer = (__webpack_require__(60571).Buffer)
var crypto = __webpack_require__.g.crypto || __webpack_require__.g.msCrypto

if (crypto && crypto.getRandomValues) {
  module.exports = randomBytes
} else {
  module.exports = oldBrowser
}

function randomBytes (size, cb) {
  // phantomjs needs to throw
  if (size > MAX_UINT32) throw new RangeError('requested too many random bytes')

  var bytes = Buffer.allocUnsafe(size)

  if (size > 0) {  // getRandomValues fails on IE if size == 0
    if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues
      // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
      for (var generated = 0; generated < size; generated += MAX_BYTES) {
        // buffer.slice automatically checks if the end is past the end of
        // the buffer so we don't have to here
        crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES))
      }
    } else {
      crypto.getRandomValues(bytes)
    }
  }

  if (typeof cb === 'function') {
    return process.nextTick(function () {
      cb(null, bytes)
    })
  }

  return bytes
}


/***/ }),

/***/ 66026:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";


function oldBrowser () {
  throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
}
var safeBuffer = __webpack_require__(60571)
var randombytes = __webpack_require__(66290)
var Buffer = safeBuffer.Buffer
var kBufferMaxLength = safeBuffer.kMaxLength
var crypto = __webpack_require__.g.crypto || __webpack_require__.g.msCrypto
var kMaxUint32 = Math.pow(2, 32) - 1
function assertOffset (offset, length) {
  if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare
    throw new TypeError('offset must be a number')
  }

  if (offset > kMaxUint32 || offset < 0) {
    throw new TypeError('offset must be a uint32')
  }

  if (offset > kBufferMaxLength || offset > length) {
    throw new RangeError('offset out of range')
  }
}

function assertSize (size, offset, length) {
  if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare
    throw new TypeError('size must be a number')
  }

  if (size > kMaxUint32 || size < 0) {
    throw new TypeError('size must be a uint32')
  }

  if (size + offset > length || size > kBufferMaxLength) {
    throw new RangeError('buffer too small')
  }
}
if ((crypto && crypto.getRandomValues) || !process.browser) {
  exports.randomFill = randomFill
  exports.randomFillSync = randomFillSync
} else {
  exports.randomFill = oldBrowser
  exports.randomFillSync = oldBrowser
}
function randomFill (buf, offset, size, cb) {
  if (!Buffer.isBuffer(buf) && !(buf instanceof __webpack_require__.g.Uint8Array)) {
    throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
  }

  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    size = buf.length
  } else if (typeof size === 'function') {
    cb = size
    size = buf.length - offset
  } else if (typeof cb !== 'function') {
    throw new TypeError('"cb" argument must be a function')
  }
  assertOffset(offset, buf.length)
  assertSize(size, offset, buf.length)
  return actualFill(buf, offset, size, cb)
}

function actualFill (buf, offset, size, cb) {
  if (process.browser) {
    var ourBuf = buf.buffer
    var uint = new Uint8Array(ourBuf, offset, size)
    crypto.getRandomValues(uint)
    if (cb) {
      process.nextTick(function () {
        cb(null, buf)
      })
      return
    }
    return buf
  }
  if (cb) {
    randombytes(size, function (err, bytes) {
      if (err) {
        return cb(err)
      }
      bytes.copy(buf, offset)
      cb(null, buf)
    })
    return
  }
  var bytes = randombytes(size)
  bytes.copy(buf, offset)
  return buf
}
function randomFillSync (buf, offset, size) {
  if (typeof offset === 'undefined') {
    offset = 0
  }
  if (!Buffer.isBuffer(buf) && !(buf instanceof __webpack_require__.g.Uint8Array)) {
    throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
  }

  assertOffset(offset, buf.length)

  if (size === undefined) size = buf.length - offset

  assertSize(size, offset, buf.length)

  return actualFill(buf, offset, size)
}


/***/ }),

/***/ 3184:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.



/*<replacement>*/

var pna = __webpack_require__(23792);
/*</replacement>*/

/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
  var keys = [];
  for (var key in obj) {
    keys.push(key);
  }return keys;
};
/*</replacement>*/

module.exports = Duplex;

/*<replacement>*/
var util = Object.create(__webpack_require__(86731));
util.inherits = __webpack_require__(72116);
/*</replacement>*/

var Readable = __webpack_require__(29174);
var Writable = __webpack_require__(23066);

util.inherits(Duplex, Readable);

{
  // avoid scope creep, the keys array can then be collected
  var keys = objectKeys(Writable.prototype);
  for (var v = 0; v < keys.length; v++) {
    var method = keys[v];
    if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  }
}

function Duplex(options) {
  if (!(this instanceof Duplex)) return new Duplex(options);

  Readable.call(this, options);
  Writable.call(this, options);

  if (options && options.readable === false) this.readable = false;

  if (options && options.writable === false) this.writable = false;

  this.allowHalfOpen = true;
  if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;

  this.once('end', onend);
}

Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function () {
    return this._writableState.highWaterMark;
  }
});

// the no-half-open enforcer
function onend() {
  // if we allow half-open state, or if the writable side ended,
  // then we're ok.
  if (this.allowHalfOpen || this._writableState.ended) return;

  // no more data can be written.
  // But allow more writes to happen in this tick.
  pna.nextTick(onEndNT, this);
}

function onEndNT(self) {
  self.end();
}

Object.defineProperty(Duplex.prototype, 'destroyed', {
  get: function () {
    if (this._readableState === undefined || this._writableState === undefined) {
      return false;
    }
    return this._readableState.destroyed && this._writableState.destroyed;
  },
  set: function (value) {
    // we ignore the value if the stream
    // has not been initialized yet
    if (this._readableState === undefined || this._writableState === undefined) {
      return;
    }

    // backward compatibility, the user is explicitly
    // managing destroyed
    this._readableState.destroyed = value;
    this._writableState.destroyed = value;
  }
});

Duplex.prototype._destroy = function (err, cb) {
  this.push(null);
  this.end();

  pna.nextTick(cb, err);
};

/***/ }),

/***/ 79762:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.



module.exports = PassThrough;

var Transform = __webpack_require__(4224);

/*<replacement>*/
var util = Object.create(__webpack_require__(86731));
util.inherits = __webpack_require__(72116);
/*</replacement>*/

util.inherits(PassThrough, Transform);

function PassThrough(options) {
  if (!(this instanceof PassThrough)) return new PassThrough(options);

  Transform.call(this, options);
}

PassThrough.prototype._transform = function (chunk, encoding, cb) {
  cb(null, chunk);
};

/***/ }),

/***/ 29174:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.



/*<replacement>*/

var pna = __webpack_require__(23792);
/*</replacement>*/

module.exports = Readable;

/*<replacement>*/
var isArray = __webpack_require__(57082);
/*</replacement>*/

/*<replacement>*/
var Duplex;
/*</replacement>*/

Readable.ReadableState = ReadableState;

/*<replacement>*/
var EE = (__webpack_require__(93876).EventEmitter);

var EElistenerCount = function (emitter, type) {
  return emitter.listeners(type).length;
};
/*</replacement>*/

/*<replacement>*/
var Stream = __webpack_require__(93031);
/*</replacement>*/

/*<replacement>*/

var Buffer = (__webpack_require__(86399).Buffer);
var OurUint8Array = (typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
  return Buffer.from(chunk);
}
function _isUint8Array(obj) {
  return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}

/*</replacement>*/

/*<replacement>*/
var util = Object.create(__webpack_require__(86731));
util.inherits = __webpack_require__(72116);
/*</replacement>*/

/*<replacement>*/
var debugUtil = __webpack_require__(90124);
var debug = void 0;
if (debugUtil && debugUtil.debuglog) {
  debug = debugUtil.debuglog('stream');
} else {
  debug = function () {};
}
/*</replacement>*/

var BufferList = __webpack_require__(52952);
var destroyImpl = __webpack_require__(27582);
var StringDecoder;

util.inherits(Readable, Stream);

var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];

function prependListener(emitter, event, fn) {
  // Sadly this is not cacheable as some libraries bundle their own
  // event emitter implementation with them.
  if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);

  // This is a hack to make sure that our error handler is attached before any
  // userland ones.  NEVER DO THIS. This is here only because this code needs
  // to continue to work with older versions of Node.js that do not include
  // the prependListener() method. The goal is to eventually remove this hack.
  if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
}

function ReadableState(options, stream) {
  Duplex = Duplex || __webpack_require__(3184);

  options = options || {};

  // Duplex streams are both readable and writable, but share
  // the same options object.
  // However, some cases require setting options to different
  // values for the readable and the writable sides of the duplex stream.
  // These options can be provided separately as readableXXX and writableXXX.
  var isDuplex = stream instanceof Duplex;

  // object stream flag. Used to make read(n) ignore n and to
  // make all the buffer merging and length checks go away
  this.objectMode = !!options.objectMode;

  if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;

  // the point at which it stops calling _read() to fill the buffer
  // Note: 0 is a valid value, means "don't call _read preemptively ever"
  var hwm = options.highWaterMark;
  var readableHwm = options.readableHighWaterMark;
  var defaultHwm = this.objectMode ? 16 : 16 * 1024;

  if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;

  // cast to ints.
  this.highWaterMark = Math.floor(this.highWaterMark);

  // A linked list is used to store data chunks instead of an array because the
  // linked list can remove elements from the beginning faster than
  // array.shift()
  this.buffer = new BufferList();
  this.length = 0;
  this.pipes = null;
  this.pipesCount = 0;
  this.flowing = null;
  this.ended = false;
  this.endEmitted = false;
  this.reading = false;

  // a flag to be able to tell if the event 'readable'/'data' is emitted
  // immediately, or on a later tick.  We set this to true at first, because
  // any actions that shouldn't happen until "later" should generally also
  // not happen before the first read call.
  this.sync = true;

  // whenever we return null, then we set a flag to say
  // that we're awaiting a 'readable' event emission.
  this.needReadable = false;
  this.emittedReadable = false;
  this.readableListening = false;
  this.resumeScheduled = false;

  // has it been destroyed
  this.destroyed = false;

  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';

  // the number of writers that are awaiting a drain event in .pipe()s
  this.awaitDrain = 0;

  // if true, a maybeReadMore has been scheduled
  this.readingMore = false;

  this.decoder = null;
  this.encoding = null;
  if (options.encoding) {
    if (!StringDecoder) StringDecoder = (__webpack_require__(32630)/* .StringDecoder */ .I);
    this.decoder = new StringDecoder(options.encoding);
    this.encoding = options.encoding;
  }
}

function Readable(options) {
  Duplex = Duplex || __webpack_require__(3184);

  if (!(this instanceof Readable)) return new Readable(options);

  this._readableState = new ReadableState(options, this);

  // legacy
  this.readable = true;

  if (options) {
    if (typeof options.read === 'function') this._read = options.read;

    if (typeof options.destroy === 'function') this._destroy = options.destroy;
  }

  Stream.call(this);
}

Object.defineProperty(Readable.prototype, 'destroyed', {
  get: function () {
    if (this._readableState === undefined) {
      return false;
    }
    return this._readableState.destroyed;
  },
  set: function (value) {
    // we ignore the value if the stream
    // has not been initialized yet
    if (!this._readableState) {
      return;
    }

    // backward compatibility, the user is explicitly
    // managing destroyed
    this._readableState.destroyed = value;
  }
});

Readable.prototype.destroy = destroyImpl.destroy;
Readable.prototype._undestroy = destroyImpl.undestroy;
Readable.prototype._destroy = function (err, cb) {
  this.push(null);
  cb(err);
};

// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
  var state = this._readableState;
  var skipChunkCheck;

  if (!state.objectMode) {
    if (typeof chunk === 'string') {
      encoding = encoding || state.defaultEncoding;
      if (encoding !== state.encoding) {
        chunk = Buffer.from(chunk, encoding);
        encoding = '';
      }
      skipChunkCheck = true;
    }
  } else {
    skipChunkCheck = true;
  }

  return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
};

// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function (chunk) {
  return readableAddChunk(this, chunk, null, true, false);
};

function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  var state = stream._readableState;
  if (chunk === null) {
    state.reading = false;
    onEofChunk(stream, state);
  } else {
    var er;
    if (!skipChunkCheck) er = chunkInvalid(state, chunk);
    if (er) {
      stream.emit('error', er);
    } else if (state.objectMode || chunk && chunk.length > 0) {
      if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
        chunk = _uint8ArrayToBuffer(chunk);
      }

      if (addToFront) {
        if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
      } else if (state.ended) {
        stream.emit('error', new Error('stream.push() after EOF'));
      } else {
        state.reading = false;
        if (state.decoder && !encoding) {
          chunk = state.decoder.write(chunk);
          if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
        } else {
          addChunk(stream, state, chunk, false);
        }
      }
    } else if (!addToFront) {
      state.reading = false;
    }
  }

  return needMoreData(state);
}

function addChunk(stream, state, chunk, addToFront) {
  if (state.flowing && state.length === 0 && !state.sync) {
    stream.emit('data', chunk);
    stream.read(0);
  } else {
    // update the buffer info.
    state.length += state.objectMode ? 1 : chunk.length;
    if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);

    if (state.needReadable) emitReadable(stream);
  }
  maybeReadMore(stream, state);
}

function chunkInvalid(state, chunk) {
  var er;
  if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
    er = new TypeError('Invalid non-string/buffer chunk');
  }
  return er;
}

// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes.  This is to work around cases where hwm=0,
// such as the repl.  Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
  return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
}

Readable.prototype.isPaused = function () {
  return this._readableState.flowing === false;
};

// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
  if (!StringDecoder) StringDecoder = (__webpack_require__(32630)/* .StringDecoder */ .I);
  this._readableState.decoder = new StringDecoder(enc);
  this._readableState.encoding = enc;
  return this;
};

// Don't raise the hwm > 8MB
var MAX_HWM = 0x800000;
function computeNewHighWaterMark(n) {
  if (n >= MAX_HWM) {
    n = MAX_HWM;
  } else {
    // Get the next highest power of 2 to prevent increasing hwm excessively in
    // tiny amounts
    n--;
    n |= n >>> 1;
    n |= n >>> 2;
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;
    n++;
  }
  return n;
}

// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
  if (n <= 0 || state.length === 0 && state.ended) return 0;
  if (state.objectMode) return 1;
  if (n !== n) {
    // Only flow one buffer at a time
    if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  }
  // If we're asking for more than the current hwm, then raise the hwm.
  if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  if (n <= state.length) return n;
  // Don't have enough
  if (!state.ended) {
    state.needReadable = true;
    return 0;
  }
  return state.length;
}

// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
  debug('read', n);
  n = parseInt(n, 10);
  var state = this._readableState;
  var nOrig = n;

  if (n !== 0) state.emittedReadable = false;

  // if we're doing read(0) to trigger a readable event, but we
  // already have a bunch of data in the buffer, then just trigger
  // the 'readable' event and move on.
  if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
    debug('read: emitReadable', state.length, state.ended);
    if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
    return null;
  }

  n = howMuchToRead(n, state);

  // if we've ended, and we're now clear, then finish it up.
  if (n === 0 && state.ended) {
    if (state.length === 0) endReadable(this);
    return null;
  }

  // All the actual chunk generation logic needs to be
  // *below* the call to _read.  The reason is that in certain
  // synthetic stream cases, such as passthrough streams, _read
  // may be a completely synchronous operation which may change
  // the state of the read buffer, providing enough data when
  // before there was *not* enough.
  //
  // So, the steps are:
  // 1. Figure out what the state of things will be after we do
  // a read from the buffer.
  //
  // 2. If that resulting state will trigger a _read, then call _read.
  // Note that this may be asynchronous, or synchronous.  Yes, it is
  // deeply ugly to write APIs this way, but that still doesn't mean
  // that the Readable class should behave improperly, as streams are
  // designed to be sync/async agnostic.
  // Take note if the _read call is sync or async (ie, if the read call
  // has returned yet), so that we know whether or not it's safe to emit
  // 'readable' etc.
  //
  // 3. Actually pull the requested chunks out of the buffer and return.

  // if we need a readable event, then we need to do some reading.
  var doRead = state.needReadable;
  debug('need readable', doRead);

  // if we currently have less than the highWaterMark, then also read some
  if (state.length === 0 || state.length - n < state.highWaterMark) {
    doRead = true;
    debug('length less than watermark', doRead);
  }

  // however, if we've ended, then there's no point, and if we're already
  // reading, then it's unnecessary.
  if (state.ended || state.reading) {
    doRead = false;
    debug('reading or ended', doRead);
  } else if (doRead) {
    debug('do read');
    state.reading = true;
    state.sync = true;
    // if the length is currently zero, then we *need* a readable event.
    if (state.length === 0) state.needReadable = true;
    // call internal read method
    this._read(state.highWaterMark);
    state.sync = false;
    // If _read pushed data synchronously, then `reading` will be false,
    // and we need to re-evaluate how much data we can return to the user.
    if (!state.reading) n = howMuchToRead(nOrig, state);
  }

  var ret;
  if (n > 0) ret = fromList(n, state);else ret = null;

  if (ret === null) {
    state.needReadable = true;
    n = 0;
  } else {
    state.length -= n;
  }

  if (state.length === 0) {
    // If we have nothing in the buffer, then we want to know
    // as soon as we *do* get something into the buffer.
    if (!state.ended) state.needReadable = true;

    // If we tried to read() past the EOF, then emit end on the next tick.
    if (nOrig !== n && state.ended) endReadable(this);
  }

  if (ret !== null) this.emit('data', ret);

  return ret;
};

function onEofChunk(stream, state) {
  if (state.ended) return;
  if (state.decoder) {
    var chunk = state.decoder.end();
    if (chunk && chunk.length) {
      state.buffer.push(chunk);
      state.length += state.objectMode ? 1 : chunk.length;
    }
  }
  state.ended = true;

  // emit 'readable' now to make sure it gets picked up.
  emitReadable(stream);
}

// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow.  This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
  var state = stream._readableState;
  state.needReadable = false;
  if (!state.emittedReadable) {
    debug('emitReadable', state.flowing);
    state.emittedReadable = true;
    if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
  }
}

function emitReadable_(stream) {
  debug('emit readable');
  stream.emit('readable');
  flow(stream);
}

// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data.  that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
  if (!state.readingMore) {
    state.readingMore = true;
    pna.nextTick(maybeReadMore_, stream, state);
  }
}

function maybeReadMore_(stream, state) {
  var len = state.length;
  while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
    debug('maybeReadMore read 0');
    stream.read(0);
    if (len === state.length)
      // didn't get any data, stop spinning.
      break;else len = state.length;
  }
  state.readingMore = false;
}

// abstract method.  to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
  this.emit('error', new Error('_read() is not implemented'));
};

Readable.prototype.pipe = function (dest, pipeOpts) {
  var src = this;
  var state = this._readableState;

  switch (state.pipesCount) {
    case 0:
      state.pipes = dest;
      break;
    case 1:
      state.pipes = [state.pipes, dest];
      break;
    default:
      state.pipes.push(dest);
      break;
  }
  state.pipesCount += 1;
  debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);

  var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;

  var endFn = doEnd ? onend : unpipe;
  if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);

  dest.on('unpipe', onunpipe);
  function onunpipe(readable, unpipeInfo) {
    debug('onunpipe');
    if (readable === src) {
      if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
        unpipeInfo.hasUnpiped = true;
        cleanup();
      }
    }
  }

  function onend() {
    debug('onend');
    dest.end();
  }

  // when the dest drains, it reduces the awaitDrain counter
  // on the source.  This would be more elegant with a .once()
  // handler in flow(), but adding and removing repeatedly is
  // too slow.
  var ondrain = pipeOnDrain(src);
  dest.on('drain', ondrain);

  var cleanedUp = false;
  function cleanup() {
    debug('cleanup');
    // cleanup event handlers once the pipe is broken
    dest.removeListener('close', onclose);
    dest.removeListener('finish', onfinish);
    dest.removeListener('drain', ondrain);
    dest.removeListener('error', onerror);
    dest.removeListener('unpipe', onunpipe);
    src.removeListener('end', onend);
    src.removeListener('end', unpipe);
    src.removeListener('data', ondata);

    cleanedUp = true;

    // if the reader is waiting for a drain event from this
    // specific writer, then it would cause it to never start
    // flowing again.
    // So, if this is awaiting a drain, then we just call it now.
    // If we don't know, then assume that we are waiting for one.
    if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  }

  // If the user pushes more data while we're writing to dest then we'll end up
  // in ondata again. However, we only want to increase awaitDrain once because
  // dest will only emit one 'drain' event for the multiple writes.
  // => Introduce a guard on increasing awaitDrain.
  var increasedAwaitDrain = false;
  src.on('data', ondata);
  function ondata(chunk) {
    debug('ondata');
    increasedAwaitDrain = false;
    var ret = dest.write(chunk);
    if (false === ret && !increasedAwaitDrain) {
      // If the user unpiped during `dest.write()`, it is possible
      // to get stuck in a permanently paused state if that write
      // also returned false.
      // => Check whether `dest` is still a piping destination.
      if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
        debug('false write response, pause', state.awaitDrain);
        state.awaitDrain++;
        increasedAwaitDrain = true;
      }
      src.pause();
    }
  }

  // if the dest has an error, then stop piping into it.
  // however, don't suppress the throwing behavior for this.
  function onerror(er) {
    debug('onerror', er);
    unpipe();
    dest.removeListener('error', onerror);
    if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  }

  // Make sure our error handler is attached before userland ones.
  prependListener(dest, 'error', onerror);

  // Both close and finish should trigger unpipe, but only once.
  function onclose() {
    dest.removeListener('finish', onfinish);
    unpipe();
  }
  dest.once('close', onclose);
  function onfinish() {
    debug('onfinish');
    dest.removeListener('close', onclose);
    unpipe();
  }
  dest.once('finish', onfinish);

  function unpipe() {
    debug('unpipe');
    src.unpipe(dest);
  }

  // tell the dest that it's being piped to
  dest.emit('pipe', src);

  // start the flow if it hasn't been started already.
  if (!state.flowing) {
    debug('pipe resume');
    src.resume();
  }

  return dest;
};

function pipeOnDrain(src) {
  return function () {
    var state = src._readableState;
    debug('pipeOnDrain', state.awaitDrain);
    if (state.awaitDrain) state.awaitDrain--;
    if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
      state.flowing = true;
      flow(src);
    }
  };
}

Readable.prototype.unpipe = function (dest) {
  var state = this._readableState;
  var unpipeInfo = { hasUnpiped: false };

  // if we're not piping anywhere, then do nothing.
  if (state.pipesCount === 0) return this;

  // just one destination.  most common case.
  if (state.pipesCount === 1) {
    // passed in one, but it's not the right one.
    if (dest && dest !== state.pipes) return this;

    if (!dest) dest = state.pipes;

    // got a match.
    state.pipes = null;
    state.pipesCount = 0;
    state.flowing = false;
    if (dest) dest.emit('unpipe', this, unpipeInfo);
    return this;
  }

  // slow case. multiple pipe destinations.

  if (!dest) {
    // remove all.
    var dests = state.pipes;
    var len = state.pipesCount;
    state.pipes = null;
    state.pipesCount = 0;
    state.flowing = false;

    for (var i = 0; i < len; i++) {
      dests[i].emit('unpipe', this, { hasUnpiped: false });
    }return this;
  }

  // try to find the right one.
  var index = indexOf(state.pipes, dest);
  if (index === -1) return this;

  state.pipes.splice(index, 1);
  state.pipesCount -= 1;
  if (state.pipesCount === 1) state.pipes = state.pipes[0];

  dest.emit('unpipe', this, unpipeInfo);

  return this;
};

// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
  var res = Stream.prototype.on.call(this, ev, fn);

  if (ev === 'data') {
    // Start flowing on next tick if stream isn't explicitly paused
    if (this._readableState.flowing !== false) this.resume();
  } else if (ev === 'readable') {
    var state = this._readableState;
    if (!state.endEmitted && !state.readableListening) {
      state.readableListening = state.needReadable = true;
      state.emittedReadable = false;
      if (!state.reading) {
        pna.nextTick(nReadingNextTick, this);
      } else if (state.length) {
        emitReadable(this);
      }
    }
  }

  return res;
};
Readable.prototype.addListener = Readable.prototype.on;

function nReadingNextTick(self) {
  debug('readable nexttick read 0');
  self.read(0);
}

// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
  var state = this._readableState;
  if (!state.flowing) {
    debug('resume');
    state.flowing = true;
    resume(this, state);
  }
  return this;
};

function resume(stream, state) {
  if (!state.resumeScheduled) {
    state.resumeScheduled = true;
    pna.nextTick(resume_, stream, state);
  }
}

function resume_(stream, state) {
  if (!state.reading) {
    debug('resume read 0');
    stream.read(0);
  }

  state.resumeScheduled = false;
  state.awaitDrain = 0;
  stream.emit('resume');
  flow(stream);
  if (state.flowing && !state.reading) stream.read(0);
}

Readable.prototype.pause = function () {
  debug('call pause flowing=%j', this._readableState.flowing);
  if (false !== this._readableState.flowing) {
    debug('pause');
    this._readableState.flowing = false;
    this.emit('pause');
  }
  return this;
};

function flow(stream) {
  var state = stream._readableState;
  debug('flow', state.flowing);
  while (state.flowing && stream.read() !== null) {}
}

// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
  var _this = this;

  var state = this._readableState;
  var paused = false;

  stream.on('end', function () {
    debug('wrapped end');
    if (state.decoder && !state.ended) {
      var chunk = state.decoder.end();
      if (chunk && chunk.length) _this.push(chunk);
    }

    _this.push(null);
  });

  stream.on('data', function (chunk) {
    debug('wrapped data');
    if (state.decoder) chunk = state.decoder.write(chunk);

    // don't skip over falsy values in objectMode
    if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;

    var ret = _this.push(chunk);
    if (!ret) {
      paused = true;
      stream.pause();
    }
  });

  // proxy all the other methods.
  // important when wrapping filters and duplexes.
  for (var i in stream) {
    if (this[i] === undefined && typeof stream[i] === 'function') {
      this[i] = function (method) {
        return function () {
          return stream[method].apply(stream, arguments);
        };
      }(i);
    }
  }

  // proxy certain important events.
  for (var n = 0; n < kProxyEvents.length; n++) {
    stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  }

  // when we try to consume some more bytes, simply unpause the
  // underlying stream.
  this._read = function (n) {
    debug('wrapped _read', n);
    if (paused) {
      paused = false;
      stream.resume();
    }
  };

  return this;
};

Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function () {
    return this._readableState.highWaterMark;
  }
});

// exposed for testing purposes only.
Readable._fromList = fromList;

// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromList(n, state) {
  // nothing buffered
  if (state.length === 0) return null;

  var ret;
  if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
    // read it all, truncate the list
    if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
    state.buffer.clear();
  } else {
    // read part of list
    ret = fromListPartial(n, state.buffer, state.decoder);
  }

  return ret;
}

// Extracts only enough buffered data to satisfy the amount requested.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromListPartial(n, list, hasStrings) {
  var ret;
  if (n < list.head.data.length) {
    // slice is the same for buffers and strings
    ret = list.head.data.slice(0, n);
    list.head.data = list.head.data.slice(n);
  } else if (n === list.head.data.length) {
    // first chunk is a perfect match
    ret = list.shift();
  } else {
    // result spans more than one buffer
    ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  }
  return ret;
}

// Copies a specified amount of characters from the list of buffered data
// chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBufferString(n, list) {
  var p = list.head;
  var c = 1;
  var ret = p.data;
  n -= ret.length;
  while (p = p.next) {
    var str = p.data;
    var nb = n > str.length ? str.length : n;
    if (nb === str.length) ret += str;else ret += str.slice(0, n);
    n -= nb;
    if (n === 0) {
      if (nb === str.length) {
        ++c;
        if (p.next) list.head = p.next;else list.head = list.tail = null;
      } else {
        list.head = p;
        p.data = str.slice(nb);
      }
      break;
    }
    ++c;
  }
  list.length -= c;
  return ret;
}

// Copies a specified amount of bytes from the list of buffered data chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBuffer(n, list) {
  var ret = Buffer.allocUnsafe(n);
  var p = list.head;
  var c = 1;
  p.data.copy(ret);
  n -= p.data.length;
  while (p = p.next) {
    var buf = p.data;
    var nb = n > buf.length ? buf.length : n;
    buf.copy(ret, ret.length - n, 0, nb);
    n -= nb;
    if (n === 0) {
      if (nb === buf.length) {
        ++c;
        if (p.next) list.head = p.next;else list.head = list.tail = null;
      } else {
        list.head = p;
        p.data = buf.slice(nb);
      }
      break;
    }
    ++c;
  }
  list.length -= c;
  return ret;
}

function endReadable(stream) {
  var state = stream._readableState;

  // If we get here before consuming all the bytes, then that is a
  // bug in node.  Should never happen.
  if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');

  if (!state.endEmitted) {
    state.ended = true;
    pna.nextTick(endReadableNT, state, stream);
  }
}

function endReadableNT(state, stream) {
  // Check that we didn't get one last unshift.
  if (!state.endEmitted && state.length === 0) {
    state.endEmitted = true;
    stream.readable = false;
    stream.emit('end');
  }
}

function indexOf(xs, x) {
  for (var i = 0, l = xs.length; i < l; i++) {
    if (xs[i] === x) return i;
  }
  return -1;
}

/***/ }),

/***/ 4224:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// a transform stream is a readable/writable stream where you do
// something with the data.  Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored.  (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation.  For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes.  When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up.  When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer.  When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks.  If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk.  However,
// a pathological inflate type of transform can cause excessive buffering
// here.  For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output.  Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output.  In this case, you could write a very small
// amount of input, and end up with a very large amount of output.  In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform.  A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.



module.exports = Transform;

var Duplex = __webpack_require__(3184);

/*<replacement>*/
var util = Object.create(__webpack_require__(86731));
util.inherits = __webpack_require__(72116);
/*</replacement>*/

util.inherits(Transform, Duplex);

function afterTransform(er, data) {
  var ts = this._transformState;
  ts.transforming = false;

  var cb = ts.writecb;

  if (!cb) {
    return this.emit('error', new Error('write callback called multiple times'));
  }

  ts.writechunk = null;
  ts.writecb = null;

  if (data != null) // single equals check for both `null` and `undefined`
    this.push(data);

  cb(er);

  var rs = this._readableState;
  rs.reading = false;
  if (rs.needReadable || rs.length < rs.highWaterMark) {
    this._read(rs.highWaterMark);
  }
}

function Transform(options) {
  if (!(this instanceof Transform)) return new Transform(options);

  Duplex.call(this, options);

  this._transformState = {
    afterTransform: afterTransform.bind(this),
    needTransform: false,
    transforming: false,
    writecb: null,
    writechunk: null,
    writeencoding: null
  };

  // start out asking for a readable event once data is transformed.
  this._readableState.needReadable = true;

  // we have implemented the _read method, and done the other things
  // that Readable wants before the first _read call, so unset the
  // sync guard flag.
  this._readableState.sync = false;

  if (options) {
    if (typeof options.transform === 'function') this._transform = options.transform;

    if (typeof options.flush === 'function') this._flush = options.flush;
  }

  // When the writable side finishes, then flush out anything remaining.
  this.on('prefinish', prefinish);
}

function prefinish() {
  var _this = this;

  if (typeof this._flush === 'function') {
    this._flush(function (er, data) {
      done(_this, er, data);
    });
  } else {
    done(this, null, null);
  }
}

Transform.prototype.push = function (chunk, encoding) {
  this._transformState.needTransform = false;
  return Duplex.prototype.push.call(this, chunk, encoding);
};

// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side.  You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk.  If you pass
// an error, then that'll put the hurt on the whole operation.  If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
  throw new Error('_transform() is not implemented');
};

Transform.prototype._write = function (chunk, encoding, cb) {
  var ts = this._transformState;
  ts.writecb = cb;
  ts.writechunk = chunk;
  ts.writeencoding = encoding;
  if (!ts.transforming) {
    var rs = this._readableState;
    if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  }
};

// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
  var ts = this._transformState;

  if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
    ts.transforming = true;
    this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  } else {
    // mark that we need a transform, so that any data that comes in
    // will get processed, now that we've asked for it.
    ts.needTransform = true;
  }
};

Transform.prototype._destroy = function (err, cb) {
  var _this2 = this;

  Duplex.prototype._destroy.call(this, err, function (err2) {
    cb(err2);
    _this2.emit('close');
  });
};

function done(stream, er, data) {
  if (er) return stream.emit('error', er);

  if (data != null) // single equals check for both `null` and `undefined`
    stream.push(data);

  // if there's nothing in the write buffer, then that means
  // that nothing more will ever be provided
  if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');

  if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');

  return stream.push(null);
}

/***/ }),

/***/ 23066:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.



/*<replacement>*/

var pna = __webpack_require__(23792);
/*</replacement>*/

module.exports = Writable;

/* <replacement> */
function WriteReq(chunk, encoding, cb) {
  this.chunk = chunk;
  this.encoding = encoding;
  this.callback = cb;
  this.next = null;
}

// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
  var _this = this;

  this.next = null;
  this.entry = null;
  this.finish = function () {
    onCorkedFinish(_this, state);
  };
}
/* </replacement> */

/*<replacement>*/
var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
/*</replacement>*/

/*<replacement>*/
var Duplex;
/*</replacement>*/

Writable.WritableState = WritableState;

/*<replacement>*/
var util = Object.create(__webpack_require__(86731));
util.inherits = __webpack_require__(72116);
/*</replacement>*/

/*<replacement>*/
var internalUtil = {
  deprecate: __webpack_require__(88680)
};
/*</replacement>*/

/*<replacement>*/
var Stream = __webpack_require__(93031);
/*</replacement>*/

/*<replacement>*/

var Buffer = (__webpack_require__(86399).Buffer);
var OurUint8Array = (typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
  return Buffer.from(chunk);
}
function _isUint8Array(obj) {
  return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}

/*</replacement>*/

var destroyImpl = __webpack_require__(27582);

util.inherits(Writable, Stream);

function nop() {}

function WritableState(options, stream) {
  Duplex = Duplex || __webpack_require__(3184);

  options = options || {};

  // Duplex streams are both readable and writable, but share
  // the same options object.
  // However, some cases require setting options to different
  // values for the readable and the writable sides of the duplex stream.
  // These options can be provided separately as readableXXX and writableXXX.
  var isDuplex = stream instanceof Duplex;

  // object stream flag to indicate whether or not this stream
  // contains buffers or objects.
  this.objectMode = !!options.objectMode;

  if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;

  // the point at which write() starts returning false
  // Note: 0 is a valid value, means that we always return false if
  // the entire buffer is not flushed immediately on write()
  var hwm = options.highWaterMark;
  var writableHwm = options.writableHighWaterMark;
  var defaultHwm = this.objectMode ? 16 : 16 * 1024;

  if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;

  // cast to ints.
  this.highWaterMark = Math.floor(this.highWaterMark);

  // if _final has been called
  this.finalCalled = false;

  // drain event flag.
  this.needDrain = false;
  // at the start of calling end()
  this.ending = false;
  // when end() has been called, and returned
  this.ended = false;
  // when 'finish' is emitted
  this.finished = false;

  // has it been destroyed
  this.destroyed = false;

  // should we decode strings into buffers before passing to _write?
  // this is here so that some node-core streams can optimize string
  // handling at a lower level.
  var noDecode = options.decodeStrings === false;
  this.decodeStrings = !noDecode;

  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';

  // not an actual buffer we keep track of, but a measurement
  // of how much we're waiting to get pushed to some underlying
  // socket or file.
  this.length = 0;

  // a flag to see when we're in the middle of a write.
  this.writing = false;

  // when true all writes will be buffered until .uncork() call
  this.corked = 0;

  // a flag to be able to tell if the onwrite cb is called immediately,
  // or on a later tick.  We set this to true at first, because any
  // actions that shouldn't happen until "later" should generally also
  // not happen before the first write call.
  this.sync = true;

  // a flag to know if we're processing previously buffered items, which
  // may call the _write() callback in the same tick, so that we don't
  // end up in an overlapped onwrite situation.
  this.bufferProcessing = false;

  // the callback that's passed to _write(chunk,cb)
  this.onwrite = function (er) {
    onwrite(stream, er);
  };

  // the callback that the user supplies to write(chunk,encoding,cb)
  this.writecb = null;

  // the amount that is being written when _write is called.
  this.writelen = 0;

  this.bufferedRequest = null;
  this.lastBufferedRequest = null;

  // number of pending user-supplied write callbacks
  // this must be 0 before 'finish' can be emitted
  this.pendingcb = 0;

  // emit prefinish if the only thing we're waiting for is _write cbs
  // This is relevant for synchronous Transform streams
  this.prefinished = false;

  // True if the error was already emitted and should not be thrown again
  this.errorEmitted = false;

  // count buffered requests
  this.bufferedRequestCount = 0;

  // allocate the first CorkedRequest, there is always
  // one allocated and free to use, and we maintain at most two
  this.corkedRequestsFree = new CorkedRequest(this);
}

WritableState.prototype.getBuffer = function getBuffer() {
  var current = this.bufferedRequest;
  var out = [];
  while (current) {
    out.push(current);
    current = current.next;
  }
  return out;
};

(function () {
  try {
    Object.defineProperty(WritableState.prototype, 'buffer', {
      get: internalUtil.deprecate(function () {
        return this.getBuffer();
      }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
    });
  } catch (_) {}
})();

// Test _writableState for inheritance to account for Duplex streams,
// whose prototype chain only points to Readable.
var realHasInstance;
if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  realHasInstance = Function.prototype[Symbol.hasInstance];
  Object.defineProperty(Writable, Symbol.hasInstance, {
    value: function (object) {
      if (realHasInstance.call(this, object)) return true;
      if (this !== Writable) return false;

      return object && object._writableState instanceof WritableState;
    }
  });
} else {
  realHasInstance = function (object) {
    return object instanceof this;
  };
}

function Writable(options) {
  Duplex = Duplex || __webpack_require__(3184);

  // Writable ctor is applied to Duplexes, too.
  // `realHasInstance` is necessary because using plain `instanceof`
  // would return false, as no `_writableState` property is attached.

  // Trying to use the custom `instanceof` for Writable here will also break the
  // Node.js LazyTransform implementation, which has a non-trivial getter for
  // `_writableState` that would lead to infinite recursion.
  if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
    return new Writable(options);
  }

  this._writableState = new WritableState(options, this);

  // legacy.
  this.writable = true;

  if (options) {
    if (typeof options.write === 'function') this._write = options.write;

    if (typeof options.writev === 'function') this._writev = options.writev;

    if (typeof options.destroy === 'function') this._destroy = options.destroy;

    if (typeof options.final === 'function') this._final = options.final;
  }

  Stream.call(this);
}

// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
  this.emit('error', new Error('Cannot pipe, not readable'));
};

function writeAfterEnd(stream, cb) {
  var er = new Error('write after end');
  // TODO: defer error events consistently everywhere, not just the cb
  stream.emit('error', er);
  pna.nextTick(cb, er);
}

// Checks that a user-supplied chunk is valid, especially for the particular
// mode the stream is in. Currently this means that `null` is never accepted
// and undefined/non-string values are only allowed in object mode.
function validChunk(stream, state, chunk, cb) {
  var valid = true;
  var er = false;

  if (chunk === null) {
    er = new TypeError('May not write null values to stream');
  } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
    er = new TypeError('Invalid non-string/buffer chunk');
  }
  if (er) {
    stream.emit('error', er);
    pna.nextTick(cb, er);
    valid = false;
  }
  return valid;
}

Writable.prototype.write = function (chunk, encoding, cb) {
  var state = this._writableState;
  var ret = false;
  var isBuf = !state.objectMode && _isUint8Array(chunk);

  if (isBuf && !Buffer.isBuffer(chunk)) {
    chunk = _uint8ArrayToBuffer(chunk);
  }

  if (typeof encoding === 'function') {
    cb = encoding;
    encoding = null;
  }

  if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;

  if (typeof cb !== 'function') cb = nop;

  if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
    state.pendingcb++;
    ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  }

  return ret;
};

Writable.prototype.cork = function () {
  var state = this._writableState;

  state.corked++;
};

Writable.prototype.uncork = function () {
  var state = this._writableState;

  if (state.corked) {
    state.corked--;

    if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  }
};

Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  // node::ParseEncoding() requires lower case.
  if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
  this._writableState.defaultEncoding = encoding;
  return this;
};

function decodeChunk(state, chunk, encoding) {
  if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
    chunk = Buffer.from(chunk, encoding);
  }
  return chunk;
}

Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function () {
    return this._writableState.highWaterMark;
  }
});

// if we're already writing something, then just put this
// in the queue, and wait our turn.  Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  if (!isBuf) {
    var newChunk = decodeChunk(state, chunk, encoding);
    if (chunk !== newChunk) {
      isBuf = true;
      encoding = 'buffer';
      chunk = newChunk;
    }
  }
  var len = state.objectMode ? 1 : chunk.length;

  state.length += len;

  var ret = state.length < state.highWaterMark;
  // we must ensure that previous needDrain will not be reset to false.
  if (!ret) state.needDrain = true;

  if (state.writing || state.corked) {
    var last = state.lastBufferedRequest;
    state.lastBufferedRequest = {
      chunk: chunk,
      encoding: encoding,
      isBuf: isBuf,
      callback: cb,
      next: null
    };
    if (last) {
      last.next = state.lastBufferedRequest;
    } else {
      state.bufferedRequest = state.lastBufferedRequest;
    }
    state.bufferedRequestCount += 1;
  } else {
    doWrite(stream, state, false, len, chunk, encoding, cb);
  }

  return ret;
}

function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  state.writelen = len;
  state.writecb = cb;
  state.writing = true;
  state.sync = true;
  if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  state.sync = false;
}

function onwriteError(stream, state, sync, er, cb) {
  --state.pendingcb;

  if (sync) {
    // defer the callback if we are being called synchronously
    // to avoid piling up things on the stack
    pna.nextTick(cb, er);
    // this can emit finish, and it will always happen
    // after error
    pna.nextTick(finishMaybe, stream, state);
    stream._writableState.errorEmitted = true;
    stream.emit('error', er);
  } else {
    // the caller expect this to happen before if
    // it is async
    cb(er);
    stream._writableState.errorEmitted = true;
    stream.emit('error', er);
    // this can emit finish, but finish must
    // always follow error
    finishMaybe(stream, state);
  }
}

function onwriteStateUpdate(state) {
  state.writing = false;
  state.writecb = null;
  state.length -= state.writelen;
  state.writelen = 0;
}

function onwrite(stream, er) {
  var state = stream._writableState;
  var sync = state.sync;
  var cb = state.writecb;

  onwriteStateUpdate(state);

  if (er) onwriteError(stream, state, sync, er, cb);else {
    // Check if we're actually ready to finish, but don't emit yet
    var finished = needFinish(state);

    if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
      clearBuffer(stream, state);
    }

    if (sync) {
      /*<replacement>*/
      asyncWrite(afterWrite, stream, state, finished, cb);
      /*</replacement>*/
    } else {
      afterWrite(stream, state, finished, cb);
    }
  }
}

function afterWrite(stream, state, finished, cb) {
  if (!finished) onwriteDrain(stream, state);
  state.pendingcb--;
  cb();
  finishMaybe(stream, state);
}

// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
  if (state.length === 0 && state.needDrain) {
    state.needDrain = false;
    stream.emit('drain');
  }
}

// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
  state.bufferProcessing = true;
  var entry = state.bufferedRequest;

  if (stream._writev && entry && entry.next) {
    // Fast case, write everything using _writev()
    var l = state.bufferedRequestCount;
    var buffer = new Array(l);
    var holder = state.corkedRequestsFree;
    holder.entry = entry;

    var count = 0;
    var allBuffers = true;
    while (entry) {
      buffer[count] = entry;
      if (!entry.isBuf) allBuffers = false;
      entry = entry.next;
      count += 1;
    }
    buffer.allBuffers = allBuffers;

    doWrite(stream, state, true, state.length, buffer, '', holder.finish);

    // doWrite is almost always async, defer these to save a bit of time
    // as the hot path ends with doWrite
    state.pendingcb++;
    state.lastBufferedRequest = null;
    if (holder.next) {
      state.corkedRequestsFree = holder.next;
      holder.next = null;
    } else {
      state.corkedRequestsFree = new CorkedRequest(state);
    }
    state.bufferedRequestCount = 0;
  } else {
    // Slow case, write chunks one-by-one
    while (entry) {
      var chunk = entry.chunk;
      var encoding = entry.encoding;
      var cb = entry.callback;
      var len = state.objectMode ? 1 : chunk.length;

      doWrite(stream, state, false, len, chunk, encoding, cb);
      entry = entry.next;
      state.bufferedRequestCount--;
      // if we didn't call the onwrite immediately, then
      // it means that we need to wait until it does.
      // also, that means that the chunk and cb are currently
      // being processed, so move the buffer counter past them.
      if (state.writing) {
        break;
      }
    }

    if (entry === null) state.lastBufferedRequest = null;
  }

  state.bufferedRequest = entry;
  state.bufferProcessing = false;
}

Writable.prototype._write = function (chunk, encoding, cb) {
  cb(new Error('_write() is not implemented'));
};

Writable.prototype._writev = null;

Writable.prototype.end = function (chunk, encoding, cb) {
  var state = this._writableState;

  if (typeof chunk === 'function') {
    cb = chunk;
    chunk = null;
    encoding = null;
  } else if (typeof encoding === 'function') {
    cb = encoding;
    encoding = null;
  }

  if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);

  // .end() fully uncorks
  if (state.corked) {
    state.corked = 1;
    this.uncork();
  }

  // ignore unnecessary end() calls.
  if (!state.ending) endWritable(this, state, cb);
};

function needFinish(state) {
  return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function callFinal(stream, state) {
  stream._final(function (err) {
    state.pendingcb--;
    if (err) {
      stream.emit('error', err);
    }
    state.prefinished = true;
    stream.emit('prefinish');
    finishMaybe(stream, state);
  });
}
function prefinish(stream, state) {
  if (!state.prefinished && !state.finalCalled) {
    if (typeof stream._final === 'function') {
      state.pendingcb++;
      state.finalCalled = true;
      pna.nextTick(callFinal, stream, state);
    } else {
      state.prefinished = true;
      stream.emit('prefinish');
    }
  }
}

function finishMaybe(stream, state) {
  var need = needFinish(state);
  if (need) {
    prefinish(stream, state);
    if (state.pendingcb === 0) {
      state.finished = true;
      stream.emit('finish');
    }
  }
  return need;
}

function endWritable(stream, state, cb) {
  state.ending = true;
  finishMaybe(stream, state);
  if (cb) {
    if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
  }
  state.ended = true;
  stream.writable = false;
}

function onCorkedFinish(corkReq, state, err) {
  var entry = corkReq.entry;
  corkReq.entry = null;
  while (entry) {
    var cb = entry.callback;
    state.pendingcb--;
    cb(err);
    entry = entry.next;
  }

  // reuse the free corkReq.
  state.corkedRequestsFree.next = corkReq;
}

Object.defineProperty(Writable.prototype, 'destroyed', {
  get: function () {
    if (this._writableState === undefined) {
      return false;
    }
    return this._writableState.destroyed;
  },
  set: function (value) {
    // we ignore the value if the stream
    // has not been initialized yet
    if (!this._writableState) {
      return;
    }

    // backward compatibility, the user is explicitly
    // managing destroyed
    this._writableState.destroyed = value;
  }
});

Writable.prototype.destroy = destroyImpl.destroy;
Writable.prototype._undestroy = destroyImpl.undestroy;
Writable.prototype._destroy = function (err, cb) {
  this.end();
  cb(err);
};

/***/ }),

/***/ 52952:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Buffer = (__webpack_require__(86399).Buffer);
var util = __webpack_require__(99926);

function copyBuffer(src, target, offset) {
  src.copy(target, offset);
}

module.exports = function () {
  function BufferList() {
    _classCallCheck(this, BufferList);

    this.head = null;
    this.tail = null;
    this.length = 0;
  }

  BufferList.prototype.push = function push(v) {
    var entry = { data: v, next: null };
    if (this.length > 0) this.tail.next = entry;else this.head = entry;
    this.tail = entry;
    ++this.length;
  };

  BufferList.prototype.unshift = function unshift(v) {
    var entry = { data: v, next: this.head };
    if (this.length === 0) this.tail = entry;
    this.head = entry;
    ++this.length;
  };

  BufferList.prototype.shift = function shift() {
    if (this.length === 0) return;
    var ret = this.head.data;
    if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
    --this.length;
    return ret;
  };

  BufferList.prototype.clear = function clear() {
    this.head = this.tail = null;
    this.length = 0;
  };

  BufferList.prototype.join = function join(s) {
    if (this.length === 0) return '';
    var p = this.head;
    var ret = '' + p.data;
    while (p = p.next) {
      ret += s + p.data;
    }return ret;
  };

  BufferList.prototype.concat = function concat(n) {
    if (this.length === 0) return Buffer.alloc(0);
    var ret = Buffer.allocUnsafe(n >>> 0);
    var p = this.head;
    var i = 0;
    while (p) {
      copyBuffer(p.data, ret, i);
      i += p.data.length;
      p = p.next;
    }
    return ret;
  };

  return BufferList;
}();

if (util && util.inspect && util.inspect.custom) {
  module.exports.prototype[util.inspect.custom] = function () {
    var obj = util.inspect({ length: this.length });
    return this.constructor.name + ' ' + obj;
  };
}

/***/ }),

/***/ 27582:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


/*<replacement>*/

var pna = __webpack_require__(23792);
/*</replacement>*/

// undocumented cb() API, needed for core, not for public API
function destroy(err, cb) {
  var _this = this;

  var readableDestroyed = this._readableState && this._readableState.destroyed;
  var writableDestroyed = this._writableState && this._writableState.destroyed;

  if (readableDestroyed || writableDestroyed) {
    if (cb) {
      cb(err);
    } else if (err) {
      if (!this._writableState) {
        pna.nextTick(emitErrorNT, this, err);
      } else if (!this._writableState.errorEmitted) {
        this._writableState.errorEmitted = true;
        pna.nextTick(emitErrorNT, this, err);
      }
    }

    return this;
  }

  // we set destroyed to true before firing error callbacks in order
  // to make it re-entrance safe in case destroy() is called within callbacks

  if (this._readableState) {
    this._readableState.destroyed = true;
  }

  // if this is a duplex stream mark the writable part as destroyed as well
  if (this._writableState) {
    this._writableState.destroyed = true;
  }

  this._destroy(err || null, function (err) {
    if (!cb && err) {
      if (!_this._writableState) {
        pna.nextTick(emitErrorNT, _this, err);
      } else if (!_this._writableState.errorEmitted) {
        _this._writableState.errorEmitted = true;
        pna.nextTick(emitErrorNT, _this, err);
      }
    } else if (cb) {
      cb(err);
    }
  });

  return this;
}

function undestroy() {
  if (this._readableState) {
    this._readableState.destroyed = false;
    this._readableState.reading = false;
    this._readableState.ended = false;
    this._readableState.endEmitted = false;
  }

  if (this._writableState) {
    this._writableState.destroyed = false;
    this._writableState.ended = false;
    this._writableState.ending = false;
    this._writableState.finalCalled = false;
    this._writableState.prefinished = false;
    this._writableState.finished = false;
    this._writableState.errorEmitted = false;
  }
}

function emitErrorNT(self, err) {
  self.emit('error', err);
}

module.exports = {
  destroy: destroy,
  undestroy: undestroy
};

/***/ }),

/***/ 93031:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

module.exports = __webpack_require__(93876).EventEmitter;


/***/ }),

/***/ 4073:
/***/ ((module, exports, __webpack_require__) => {

exports = module.exports = __webpack_require__(29174);
exports.Stream = exports;
exports.Readable = exports;
exports.Writable = __webpack_require__(23066);
exports.Duplex = __webpack_require__(3184);
exports.Transform = __webpack_require__(4224);
exports.PassThrough = __webpack_require__(79762);


/***/ }),

/***/ 67772:
/***/ ((module) => {

"use strict";


function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }

var codes = {};

function createErrorType(code, message, Base) {
  if (!Base) {
    Base = Error;
  }

  function getMessage(arg1, arg2, arg3) {
    if (typeof message === 'string') {
      return message;
    } else {
      return message(arg1, arg2, arg3);
    }
  }

  var NodeError =
  /*#__PURE__*/
  function (_Base) {
    _inheritsLoose(NodeError, _Base);

    function NodeError(arg1, arg2, arg3) {
      return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
    }

    return NodeError;
  }(Base);

  NodeError.prototype.name = Base.name;
  NodeError.prototype.code = code;
  codes[code] = NodeError;
} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js


function oneOf(expected, thing) {
  if (Array.isArray(expected)) {
    var len = expected.length;
    expected = expected.map(function (i) {
      return String(i);
    });

    if (len > 2) {
      return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
    } else if (len === 2) {
      return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
    } else {
      return "of ".concat(thing, " ").concat(expected[0]);
    }
  } else {
    return "of ".concat(thing, " ").concat(String(expected));
  }
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith


function startsWith(str, search, pos) {
  return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith


function endsWith(str, search, this_len) {
  if (this_len === undefined || this_len > str.length) {
    this_len = str.length;
  }

  return str.substring(this_len - search.length, this_len) === search;
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes


function includes(str, search, start) {
  if (typeof start !== 'number') {
    start = 0;
  }

  if (start + search.length > str.length) {
    return false;
  } else {
    return str.indexOf(search, start) !== -1;
  }
}

createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
  return 'The value "' + value + '" is invalid for option "' + name + '"';
}, TypeError);
createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
  // determiner: 'must be' or 'must not be'
  var determiner;

  if (typeof expected === 'string' && startsWith(expected, 'not ')) {
    determiner = 'must not be';
    expected = expected.replace(/^not /, '');
  } else {
    determiner = 'must be';
  }

  var msg;

  if (endsWith(name, ' argument')) {
    // For cases like 'first argument'
    msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
  } else {
    var type = includes(name, '.') ? 'property' : 'argument';
    msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
  }

  msg += ". Received type ".concat(typeof actual);
  return msg;
}, TypeError);
createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
  return 'The ' + name + ' method is not implemented';
});
createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
createErrorType('ERR_STREAM_DESTROYED', function (name) {
  return 'Cannot call ' + name + ' after a stream was destroyed';
});
createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
  return 'Unknown encoding: ' + arg;
}, TypeError);
createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
module.exports.F = codes;


/***/ }),

/***/ 47514:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.



/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
  var keys = [];
  for (var key in obj) keys.push(key);
  return keys;
};
/*</replacement>*/

module.exports = Duplex;
var Readable = __webpack_require__(5960);
var Writable = __webpack_require__(26968);
__webpack_require__(72116)(Duplex, Readable);
{
  // Allow the keys array to be GC'ed.
  var keys = objectKeys(Writable.prototype);
  for (var v = 0; v < keys.length; v++) {
    var method = keys[v];
    if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  }
}
function Duplex(options) {
  if (!(this instanceof Duplex)) return new Duplex(options);
  Readable.call(this, options);
  Writable.call(this, options);
  this.allowHalfOpen = true;
  if (options) {
    if (options.readable === false) this.readable = false;
    if (options.writable === false) this.writable = false;
    if (options.allowHalfOpen === false) {
      this.allowHalfOpen = false;
      this.once('end', onend);
    }
  }
}
Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    return this._writableState.highWaterMark;
  }
});
Object.defineProperty(Duplex.prototype, 'writableBuffer', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    return this._writableState && this._writableState.getBuffer();
  }
});
Object.defineProperty(Duplex.prototype, 'writableLength', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    return this._writableState.length;
  }
});

// the no-half-open enforcer
function onend() {
  // If the writable side ended, then we're ok.
  if (this._writableState.ended) return;

  // no more data can be written.
  // But allow more writes to happen in this tick.
  process.nextTick(onEndNT, this);
}
function onEndNT(self) {
  self.end();
}
Object.defineProperty(Duplex.prototype, 'destroyed', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    if (this._readableState === undefined || this._writableState === undefined) {
      return false;
    }
    return this._readableState.destroyed && this._writableState.destroyed;
  },
  set: function set(value) {
    // we ignore the value if the stream
    // has not been initialized yet
    if (this._readableState === undefined || this._writableState === undefined) {
      return;
    }

    // backward compatibility, the user is explicitly
    // managing destroyed
    this._readableState.destroyed = value;
    this._writableState.destroyed = value;
  }
});

/***/ }),

/***/ 33308:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.



module.exports = PassThrough;
var Transform = __webpack_require__(96646);
__webpack_require__(72116)(PassThrough, Transform);
function PassThrough(options) {
  if (!(this instanceof PassThrough)) return new PassThrough(options);
  Transform.call(this, options);
}
PassThrough.prototype._transform = function (chunk, encoding, cb) {
  cb(null, chunk);
};

/***/ }),

/***/ 5960:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.



module.exports = Readable;

/*<replacement>*/
var Duplex;
/*</replacement>*/

Readable.ReadableState = ReadableState;

/*<replacement>*/
var EE = (__webpack_require__(93876).EventEmitter);
var EElistenerCount = function EElistenerCount(emitter, type) {
  return emitter.listeners(type).length;
};
/*</replacement>*/

/*<replacement>*/
var Stream = __webpack_require__(24181);
/*</replacement>*/

var Buffer = (__webpack_require__(78378).Buffer);
var OurUint8Array = (typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
  return Buffer.from(chunk);
}
function _isUint8Array(obj) {
  return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}

/*<replacement>*/
var debugUtil = __webpack_require__(38854);
var debug;
if (debugUtil && debugUtil.debuglog) {
  debug = debugUtil.debuglog('stream');
} else {
  debug = function debug() {};
}
/*</replacement>*/

var BufferList = __webpack_require__(19037);
var destroyImpl = __webpack_require__(30276);
var _require = __webpack_require__(975),
  getHighWaterMark = _require.getHighWaterMark;
var _require$codes = (__webpack_require__(67772)/* .codes */ .F),
  ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
  ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
  ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;

// Lazy loaded to improve the startup performance.
var StringDecoder;
var createReadableStreamAsyncIterator;
var from;
__webpack_require__(72116)(Readable, Stream);
var errorOrDestroy = destroyImpl.errorOrDestroy;
var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
function prependListener(emitter, event, fn) {
  // Sadly this is not cacheable as some libraries bundle their own
  // event emitter implementation with them.
  if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);

  // This is a hack to make sure that our error handler is attached before any
  // userland ones.  NEVER DO THIS. This is here only because this code needs
  // to continue to work with older versions of Node.js that do not include
  // the prependListener() method. The goal is to eventually remove this hack.
  if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
}
function ReadableState(options, stream, isDuplex) {
  Duplex = Duplex || __webpack_require__(47514);
  options = options || {};

  // Duplex streams are both readable and writable, but share
  // the same options object.
  // However, some cases require setting options to different
  // values for the readable and the writable sides of the duplex stream.
  // These options can be provided separately as readableXXX and writableXXX.
  if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;

  // object stream flag. Used to make read(n) ignore n and to
  // make all the buffer merging and length checks go away
  this.objectMode = !!options.objectMode;
  if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;

  // the point at which it stops calling _read() to fill the buffer
  // Note: 0 is a valid value, means "don't call _read preemptively ever"
  this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex);

  // A linked list is used to store data chunks instead of an array because the
  // linked list can remove elements from the beginning faster than
  // array.shift()
  this.buffer = new BufferList();
  this.length = 0;
  this.pipes = null;
  this.pipesCount = 0;
  this.flowing = null;
  this.ended = false;
  this.endEmitted = false;
  this.reading = false;

  // a flag to be able to tell if the event 'readable'/'data' is emitted
  // immediately, or on a later tick.  We set this to true at first, because
  // any actions that shouldn't happen until "later" should generally also
  // not happen before the first read call.
  this.sync = true;

  // whenever we return null, then we set a flag to say
  // that we're awaiting a 'readable' event emission.
  this.needReadable = false;
  this.emittedReadable = false;
  this.readableListening = false;
  this.resumeScheduled = false;
  this.paused = true;

  // Should close be emitted on destroy. Defaults to true.
  this.emitClose = options.emitClose !== false;

  // Should .destroy() be called after 'end' (and potentially 'finish')
  this.autoDestroy = !!options.autoDestroy;

  // has it been destroyed
  this.destroyed = false;

  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';

  // the number of writers that are awaiting a drain event in .pipe()s
  this.awaitDrain = 0;

  // if true, a maybeReadMore has been scheduled
  this.readingMore = false;
  this.decoder = null;
  this.encoding = null;
  if (options.encoding) {
    if (!StringDecoder) StringDecoder = (__webpack_require__(63205)/* .StringDecoder */ .I);
    this.decoder = new StringDecoder(options.encoding);
    this.encoding = options.encoding;
  }
}
function Readable(options) {
  Duplex = Duplex || __webpack_require__(47514);
  if (!(this instanceof Readable)) return new Readable(options);

  // Checking for a Stream.Duplex instance is faster here instead of inside
  // the ReadableState constructor, at least with V8 6.5
  var isDuplex = this instanceof Duplex;
  this._readableState = new ReadableState(options, this, isDuplex);

  // legacy
  this.readable = true;
  if (options) {
    if (typeof options.read === 'function') this._read = options.read;
    if (typeof options.destroy === 'function') this._destroy = options.destroy;
  }
  Stream.call(this);
}
Object.defineProperty(Readable.prototype, 'destroyed', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    if (this._readableState === undefined) {
      return false;
    }
    return this._readableState.destroyed;
  },
  set: function set(value) {
    // we ignore the value if the stream
    // has not been initialized yet
    if (!this._readableState) {
      return;
    }

    // backward compatibility, the user is explicitly
    // managing destroyed
    this._readableState.destroyed = value;
  }
});
Readable.prototype.destroy = destroyImpl.destroy;
Readable.prototype._undestroy = destroyImpl.undestroy;
Readable.prototype._destroy = function (err, cb) {
  cb(err);
};

// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
  var state = this._readableState;
  var skipChunkCheck;
  if (!state.objectMode) {
    if (typeof chunk === 'string') {
      encoding = encoding || state.defaultEncoding;
      if (encoding !== state.encoding) {
        chunk = Buffer.from(chunk, encoding);
        encoding = '';
      }
      skipChunkCheck = true;
    }
  } else {
    skipChunkCheck = true;
  }
  return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
};

// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function (chunk) {
  return readableAddChunk(this, chunk, null, true, false);
};
function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  debug('readableAddChunk', chunk);
  var state = stream._readableState;
  if (chunk === null) {
    state.reading = false;
    onEofChunk(stream, state);
  } else {
    var er;
    if (!skipChunkCheck) er = chunkInvalid(state, chunk);
    if (er) {
      errorOrDestroy(stream, er);
    } else if (state.objectMode || chunk && chunk.length > 0) {
      if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
        chunk = _uint8ArrayToBuffer(chunk);
      }
      if (addToFront) {
        if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
      } else if (state.ended) {
        errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
      } else if (state.destroyed) {
        return false;
      } else {
        state.reading = false;
        if (state.decoder && !encoding) {
          chunk = state.decoder.write(chunk);
          if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
        } else {
          addChunk(stream, state, chunk, false);
        }
      }
    } else if (!addToFront) {
      state.reading = false;
      maybeReadMore(stream, state);
    }
  }

  // We can push more data if we are below the highWaterMark.
  // Also, if we have no data yet, we can stand some more bytes.
  // This is to work around cases where hwm=0, such as the repl.
  return !state.ended && (state.length < state.highWaterMark || state.length === 0);
}
function addChunk(stream, state, chunk, addToFront) {
  if (state.flowing && state.length === 0 && !state.sync) {
    state.awaitDrain = 0;
    stream.emit('data', chunk);
  } else {
    // update the buffer info.
    state.length += state.objectMode ? 1 : chunk.length;
    if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
    if (state.needReadable) emitReadable(stream);
  }
  maybeReadMore(stream, state);
}
function chunkInvalid(state, chunk) {
  var er;
  if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
    er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
  }
  return er;
}
Readable.prototype.isPaused = function () {
  return this._readableState.flowing === false;
};

// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
  if (!StringDecoder) StringDecoder = (__webpack_require__(63205)/* .StringDecoder */ .I);
  var decoder = new StringDecoder(enc);
  this._readableState.decoder = decoder;
  // If setEncoding(null), decoder.encoding equals utf8
  this._readableState.encoding = this._readableState.decoder.encoding;

  // Iterate over current buffer to convert already stored Buffers:
  var p = this._readableState.buffer.head;
  var content = '';
  while (p !== null) {
    content += decoder.write(p.data);
    p = p.next;
  }
  this._readableState.buffer.clear();
  if (content !== '') this._readableState.buffer.push(content);
  this._readableState.length = content.length;
  return this;
};

// Don't raise the hwm > 1GB
var MAX_HWM = 0x40000000;
function computeNewHighWaterMark(n) {
  if (n >= MAX_HWM) {
    // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
    n = MAX_HWM;
  } else {
    // Get the next highest power of 2 to prevent increasing hwm excessively in
    // tiny amounts
    n--;
    n |= n >>> 1;
    n |= n >>> 2;
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;
    n++;
  }
  return n;
}

// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
  if (n <= 0 || state.length === 0 && state.ended) return 0;
  if (state.objectMode) return 1;
  if (n !== n) {
    // Only flow one buffer at a time
    if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  }
  // If we're asking for more than the current hwm, then raise the hwm.
  if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  if (n <= state.length) return n;
  // Don't have enough
  if (!state.ended) {
    state.needReadable = true;
    return 0;
  }
  return state.length;
}

// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
  debug('read', n);
  n = parseInt(n, 10);
  var state = this._readableState;
  var nOrig = n;
  if (n !== 0) state.emittedReadable = false;

  // if we're doing read(0) to trigger a readable event, but we
  // already have a bunch of data in the buffer, then just trigger
  // the 'readable' event and move on.
  if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
    debug('read: emitReadable', state.length, state.ended);
    if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
    return null;
  }
  n = howMuchToRead(n, state);

  // if we've ended, and we're now clear, then finish it up.
  if (n === 0 && state.ended) {
    if (state.length === 0) endReadable(this);
    return null;
  }

  // All the actual chunk generation logic needs to be
  // *below* the call to _read.  The reason is that in certain
  // synthetic stream cases, such as passthrough streams, _read
  // may be a completely synchronous operation which may change
  // the state of the read buffer, providing enough data when
  // before there was *not* enough.
  //
  // So, the steps are:
  // 1. Figure out what the state of things will be after we do
  // a read from the buffer.
  //
  // 2. If that resulting state will trigger a _read, then call _read.
  // Note that this may be asynchronous, or synchronous.  Yes, it is
  // deeply ugly to write APIs this way, but that still doesn't mean
  // that the Readable class should behave improperly, as streams are
  // designed to be sync/async agnostic.
  // Take note if the _read call is sync or async (ie, if the read call
  // has returned yet), so that we know whether or not it's safe to emit
  // 'readable' etc.
  //
  // 3. Actually pull the requested chunks out of the buffer and return.

  // if we need a readable event, then we need to do some reading.
  var doRead = state.needReadable;
  debug('need readable', doRead);

  // if we currently have less than the highWaterMark, then also read some
  if (state.length === 0 || state.length - n < state.highWaterMark) {
    doRead = true;
    debug('length less than watermark', doRead);
  }

  // however, if we've ended, then there's no point, and if we're already
  // reading, then it's unnecessary.
  if (state.ended || state.reading) {
    doRead = false;
    debug('reading or ended', doRead);
  } else if (doRead) {
    debug('do read');
    state.reading = true;
    state.sync = true;
    // if the length is currently zero, then we *need* a readable event.
    if (state.length === 0) state.needReadable = true;
    // call internal read method
    this._read(state.highWaterMark);
    state.sync = false;
    // If _read pushed data synchronously, then `reading` will be false,
    // and we need to re-evaluate how much data we can return to the user.
    if (!state.reading) n = howMuchToRead(nOrig, state);
  }
  var ret;
  if (n > 0) ret = fromList(n, state);else ret = null;
  if (ret === null) {
    state.needReadable = state.length <= state.highWaterMark;
    n = 0;
  } else {
    state.length -= n;
    state.awaitDrain = 0;
  }
  if (state.length === 0) {
    // If we have nothing in the buffer, then we want to know
    // as soon as we *do* get something into the buffer.
    if (!state.ended) state.needReadable = true;

    // If we tried to read() past the EOF, then emit end on the next tick.
    if (nOrig !== n && state.ended) endReadable(this);
  }
  if (ret !== null) this.emit('data', ret);
  return ret;
};
function onEofChunk(stream, state) {
  debug('onEofChunk');
  if (state.ended) return;
  if (state.decoder) {
    var chunk = state.decoder.end();
    if (chunk && chunk.length) {
      state.buffer.push(chunk);
      state.length += state.objectMode ? 1 : chunk.length;
    }
  }
  state.ended = true;
  if (state.sync) {
    // if we are sync, wait until next tick to emit the data.
    // Otherwise we risk emitting data in the flow()
    // the readable code triggers during a read() call
    emitReadable(stream);
  } else {
    // emit 'readable' now to make sure it gets picked up.
    state.needReadable = false;
    if (!state.emittedReadable) {
      state.emittedReadable = true;
      emitReadable_(stream);
    }
  }
}

// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow.  This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
  var state = stream._readableState;
  debug('emitReadable', state.needReadable, state.emittedReadable);
  state.needReadable = false;
  if (!state.emittedReadable) {
    debug('emitReadable', state.flowing);
    state.emittedReadable = true;
    process.nextTick(emitReadable_, stream);
  }
}
function emitReadable_(stream) {
  var state = stream._readableState;
  debug('emitReadable_', state.destroyed, state.length, state.ended);
  if (!state.destroyed && (state.length || state.ended)) {
    stream.emit('readable');
    state.emittedReadable = false;
  }

  // The stream needs another readable event if
  // 1. It is not flowing, as the flow mechanism will take
  //    care of it.
  // 2. It is not ended.
  // 3. It is below the highWaterMark, so we can schedule
  //    another readable later.
  state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
  flow(stream);
}

// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data.  that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
  if (!state.readingMore) {
    state.readingMore = true;
    process.nextTick(maybeReadMore_, stream, state);
  }
}
function maybeReadMore_(stream, state) {
  // Attempt to read more data if we should.
  //
  // The conditions for reading more data are (one of):
  // - Not enough data buffered (state.length < state.highWaterMark). The loop
  //   is responsible for filling the buffer with enough data if such data
  //   is available. If highWaterMark is 0 and we are not in the flowing mode
  //   we should _not_ attempt to buffer any extra data. We'll get more data
  //   when the stream consumer calls read() instead.
  // - No data in the buffer, and the stream is in flowing mode. In this mode
  //   the loop below is responsible for ensuring read() is called. Failing to
  //   call read here would abort the flow and there's no other mechanism for
  //   continuing the flow if the stream consumer has just subscribed to the
  //   'data' event.
  //
  // In addition to the above conditions to keep reading data, the following
  // conditions prevent the data from being read:
  // - The stream has ended (state.ended).
  // - There is already a pending 'read' operation (state.reading). This is a
  //   case where the the stream has called the implementation defined _read()
  //   method, but they are processing the call asynchronously and have _not_
  //   called push() with new data. In this case we skip performing more
  //   read()s. The execution ends in this method again after the _read() ends
  //   up calling push() with more data.
  while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
    var len = state.length;
    debug('maybeReadMore read 0');
    stream.read(0);
    if (len === state.length)
      // didn't get any data, stop spinning.
      break;
  }
  state.readingMore = false;
}

// abstract method.  to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
  errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
};
Readable.prototype.pipe = function (dest, pipeOpts) {
  var src = this;
  var state = this._readableState;
  switch (state.pipesCount) {
    case 0:
      state.pipes = dest;
      break;
    case 1:
      state.pipes = [state.pipes, dest];
      break;
    default:
      state.pipes.push(dest);
      break;
  }
  state.pipesCount += 1;
  debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  var endFn = doEnd ? onend : unpipe;
  if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
  dest.on('unpipe', onunpipe);
  function onunpipe(readable, unpipeInfo) {
    debug('onunpipe');
    if (readable === src) {
      if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
        unpipeInfo.hasUnpiped = true;
        cleanup();
      }
    }
  }
  function onend() {
    debug('onend');
    dest.end();
  }

  // when the dest drains, it reduces the awaitDrain counter
  // on the source.  This would be more elegant with a .once()
  // handler in flow(), but adding and removing repeatedly is
  // too slow.
  var ondrain = pipeOnDrain(src);
  dest.on('drain', ondrain);
  var cleanedUp = false;
  function cleanup() {
    debug('cleanup');
    // cleanup event handlers once the pipe is broken
    dest.removeListener('close', onclose);
    dest.removeListener('finish', onfinish);
    dest.removeListener('drain', ondrain);
    dest.removeListener('error', onerror);
    dest.removeListener('unpipe', onunpipe);
    src.removeListener('end', onend);
    src.removeListener('end', unpipe);
    src.removeListener('data', ondata);
    cleanedUp = true;

    // if the reader is waiting for a drain event from this
    // specific writer, then it would cause it to never start
    // flowing again.
    // So, if this is awaiting a drain, then we just call it now.
    // If we don't know, then assume that we are waiting for one.
    if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  }
  src.on('data', ondata);
  function ondata(chunk) {
    debug('ondata');
    var ret = dest.write(chunk);
    debug('dest.write', ret);
    if (ret === false) {
      // If the user unpiped during `dest.write()`, it is possible
      // to get stuck in a permanently paused state if that write
      // also returned false.
      // => Check whether `dest` is still a piping destination.
      if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
        debug('false write response, pause', state.awaitDrain);
        state.awaitDrain++;
      }
      src.pause();
    }
  }

  // if the dest has an error, then stop piping into it.
  // however, don't suppress the throwing behavior for this.
  function onerror(er) {
    debug('onerror', er);
    unpipe();
    dest.removeListener('error', onerror);
    if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
  }

  // Make sure our error handler is attached before userland ones.
  prependListener(dest, 'error', onerror);

  // Both close and finish should trigger unpipe, but only once.
  function onclose() {
    dest.removeListener('finish', onfinish);
    unpipe();
  }
  dest.once('close', onclose);
  function onfinish() {
    debug('onfinish');
    dest.removeListener('close', onclose);
    unpipe();
  }
  dest.once('finish', onfinish);
  function unpipe() {
    debug('unpipe');
    src.unpipe(dest);
  }

  // tell the dest that it's being piped to
  dest.emit('pipe', src);

  // start the flow if it hasn't been started already.
  if (!state.flowing) {
    debug('pipe resume');
    src.resume();
  }
  return dest;
};
function pipeOnDrain(src) {
  return function pipeOnDrainFunctionResult() {
    var state = src._readableState;
    debug('pipeOnDrain', state.awaitDrain);
    if (state.awaitDrain) state.awaitDrain--;
    if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
      state.flowing = true;
      flow(src);
    }
  };
}
Readable.prototype.unpipe = function (dest) {
  var state = this._readableState;
  var unpipeInfo = {
    hasUnpiped: false
  };

  // if we're not piping anywhere, then do nothing.
  if (state.pipesCount === 0) return this;

  // just one destination.  most common case.
  if (state.pipesCount === 1) {
    // passed in one, but it's not the right one.
    if (dest && dest !== state.pipes) return this;
    if (!dest) dest = state.pipes;

    // got a match.
    state.pipes = null;
    state.pipesCount = 0;
    state.flowing = false;
    if (dest) dest.emit('unpipe', this, unpipeInfo);
    return this;
  }

  // slow case. multiple pipe destinations.

  if (!dest) {
    // remove all.
    var dests = state.pipes;
    var len = state.pipesCount;
    state.pipes = null;
    state.pipesCount = 0;
    state.flowing = false;
    for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, {
      hasUnpiped: false
    });
    return this;
  }

  // try to find the right one.
  var index = indexOf(state.pipes, dest);
  if (index === -1) return this;
  state.pipes.splice(index, 1);
  state.pipesCount -= 1;
  if (state.pipesCount === 1) state.pipes = state.pipes[0];
  dest.emit('unpipe', this, unpipeInfo);
  return this;
};

// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
  var res = Stream.prototype.on.call(this, ev, fn);
  var state = this._readableState;
  if (ev === 'data') {
    // update readableListening so that resume() may be a no-op
    // a few lines down. This is needed to support once('readable').
    state.readableListening = this.listenerCount('readable') > 0;

    // Try start flowing on next tick if stream isn't explicitly paused
    if (state.flowing !== false) this.resume();
  } else if (ev === 'readable') {
    if (!state.endEmitted && !state.readableListening) {
      state.readableListening = state.needReadable = true;
      state.flowing = false;
      state.emittedReadable = false;
      debug('on readable', state.length, state.reading);
      if (state.length) {
        emitReadable(this);
      } else if (!state.reading) {
        process.nextTick(nReadingNextTick, this);
      }
    }
  }
  return res;
};
Readable.prototype.addListener = Readable.prototype.on;
Readable.prototype.removeListener = function (ev, fn) {
  var res = Stream.prototype.removeListener.call(this, ev, fn);
  if (ev === 'readable') {
    // We need to check if there is someone still listening to
    // readable and reset the state. However this needs to happen
    // after readable has been emitted but before I/O (nextTick) to
    // support once('readable', fn) cycles. This means that calling
    // resume within the same tick will have no
    // effect.
    process.nextTick(updateReadableListening, this);
  }
  return res;
};
Readable.prototype.removeAllListeners = function (ev) {
  var res = Stream.prototype.removeAllListeners.apply(this, arguments);
  if (ev === 'readable' || ev === undefined) {
    // We need to check if there is someone still listening to
    // readable and reset the state. However this needs to happen
    // after readable has been emitted but before I/O (nextTick) to
    // support once('readable', fn) cycles. This means that calling
    // resume within the same tick will have no
    // effect.
    process.nextTick(updateReadableListening, this);
  }
  return res;
};
function updateReadableListening(self) {
  var state = self._readableState;
  state.readableListening = self.listenerCount('readable') > 0;
  if (state.resumeScheduled && !state.paused) {
    // flowing needs to be set to true now, otherwise
    // the upcoming resume will not flow.
    state.flowing = true;

    // crude way to check if we should resume
  } else if (self.listenerCount('data') > 0) {
    self.resume();
  }
}
function nReadingNextTick(self) {
  debug('readable nexttick read 0');
  self.read(0);
}

// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
  var state = this._readableState;
  if (!state.flowing) {
    debug('resume');
    // we flow only if there is no one listening
    // for readable, but we still have to call
    // resume()
    state.flowing = !state.readableListening;
    resume(this, state);
  }
  state.paused = false;
  return this;
};
function resume(stream, state) {
  if (!state.resumeScheduled) {
    state.resumeScheduled = true;
    process.nextTick(resume_, stream, state);
  }
}
function resume_(stream, state) {
  debug('resume', state.reading);
  if (!state.reading) {
    stream.read(0);
  }
  state.resumeScheduled = false;
  stream.emit('resume');
  flow(stream);
  if (state.flowing && !state.reading) stream.read(0);
}
Readable.prototype.pause = function () {
  debug('call pause flowing=%j', this._readableState.flowing);
  if (this._readableState.flowing !== false) {
    debug('pause');
    this._readableState.flowing = false;
    this.emit('pause');
  }
  this._readableState.paused = true;
  return this;
};
function flow(stream) {
  var state = stream._readableState;
  debug('flow', state.flowing);
  while (state.flowing && stream.read() !== null);
}

// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
  var _this = this;
  var state = this._readableState;
  var paused = false;
  stream.on('end', function () {
    debug('wrapped end');
    if (state.decoder && !state.ended) {
      var chunk = state.decoder.end();
      if (chunk && chunk.length) _this.push(chunk);
    }
    _this.push(null);
  });
  stream.on('data', function (chunk) {
    debug('wrapped data');
    if (state.decoder) chunk = state.decoder.write(chunk);

    // don't skip over falsy values in objectMode
    if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
    var ret = _this.push(chunk);
    if (!ret) {
      paused = true;
      stream.pause();
    }
  });

  // proxy all the other methods.
  // important when wrapping filters and duplexes.
  for (var i in stream) {
    if (this[i] === undefined && typeof stream[i] === 'function') {
      this[i] = function methodWrap(method) {
        return function methodWrapReturnFunction() {
          return stream[method].apply(stream, arguments);
        };
      }(i);
    }
  }

  // proxy certain important events.
  for (var n = 0; n < kProxyEvents.length; n++) {
    stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  }

  // when we try to consume some more bytes, simply unpause the
  // underlying stream.
  this._read = function (n) {
    debug('wrapped _read', n);
    if (paused) {
      paused = false;
      stream.resume();
    }
  };
  return this;
};
if (typeof Symbol === 'function') {
  Readable.prototype[Symbol.asyncIterator] = function () {
    if (createReadableStreamAsyncIterator === undefined) {
      createReadableStreamAsyncIterator = __webpack_require__(43295);
    }
    return createReadableStreamAsyncIterator(this);
  };
}
Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    return this._readableState.highWaterMark;
  }
});
Object.defineProperty(Readable.prototype, 'readableBuffer', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    return this._readableState && this._readableState.buffer;
  }
});
Object.defineProperty(Readable.prototype, 'readableFlowing', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    return this._readableState.flowing;
  },
  set: function set(state) {
    if (this._readableState) {
      this._readableState.flowing = state;
    }
  }
});

// exposed for testing purposes only.
Readable._fromList = fromList;
Object.defineProperty(Readable.prototype, 'readableLength', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    return this._readableState.length;
  }
});

// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromList(n, state) {
  // nothing buffered
  if (state.length === 0) return null;
  var ret;
  if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
    // read it all, truncate the list
    if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
    state.buffer.clear();
  } else {
    // read part of list
    ret = state.buffer.consume(n, state.decoder);
  }
  return ret;
}
function endReadable(stream) {
  var state = stream._readableState;
  debug('endReadable', state.endEmitted);
  if (!state.endEmitted) {
    state.ended = true;
    process.nextTick(endReadableNT, state, stream);
  }
}
function endReadableNT(state, stream) {
  debug('endReadableNT', state.endEmitted, state.length);

  // Check that we didn't get one last unshift.
  if (!state.endEmitted && state.length === 0) {
    state.endEmitted = true;
    stream.readable = false;
    stream.emit('end');
    if (state.autoDestroy) {
      // In case of duplex streams we need a way to detect
      // if the writable side is ready for autoDestroy as well
      var wState = stream._writableState;
      if (!wState || wState.autoDestroy && wState.finished) {
        stream.destroy();
      }
    }
  }
}
if (typeof Symbol === 'function') {
  Readable.from = function (iterable, opts) {
    if (from === undefined) {
      from = __webpack_require__(41713);
    }
    return from(Readable, iterable, opts);
  };
}
function indexOf(xs, x) {
  for (var i = 0, l = xs.length; i < l; i++) {
    if (xs[i] === x) return i;
  }
  return -1;
}

/***/ }),

/***/ 96646:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// a transform stream is a readable/writable stream where you do
// something with the data.  Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored.  (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation.  For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes.  When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up.  When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer.  When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks.  If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk.  However,
// a pathological inflate type of transform can cause excessive buffering
// here.  For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output.  Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output.  In this case, you could write a very small
// amount of input, and end up with a very large amount of output.  In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform.  A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.



module.exports = Transform;
var _require$codes = (__webpack_require__(67772)/* .codes */ .F),
  ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
  ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
  ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
var Duplex = __webpack_require__(47514);
__webpack_require__(72116)(Transform, Duplex);
function afterTransform(er, data) {
  var ts = this._transformState;
  ts.transforming = false;
  var cb = ts.writecb;
  if (cb === null) {
    return this.emit('error', new ERR_MULTIPLE_CALLBACK());
  }
  ts.writechunk = null;
  ts.writecb = null;
  if (data != null)
    // single equals check for both `null` and `undefined`
    this.push(data);
  cb(er);
  var rs = this._readableState;
  rs.reading = false;
  if (rs.needReadable || rs.length < rs.highWaterMark) {
    this._read(rs.highWaterMark);
  }
}
function Transform(options) {
  if (!(this instanceof Transform)) return new Transform(options);
  Duplex.call(this, options);
  this._transformState = {
    afterTransform: afterTransform.bind(this),
    needTransform: false,
    transforming: false,
    writecb: null,
    writechunk: null,
    writeencoding: null
  };

  // start out asking for a readable event once data is transformed.
  this._readableState.needReadable = true;

  // we have implemented the _read method, and done the other things
  // that Readable wants before the first _read call, so unset the
  // sync guard flag.
  this._readableState.sync = false;
  if (options) {
    if (typeof options.transform === 'function') this._transform = options.transform;
    if (typeof options.flush === 'function') this._flush = options.flush;
  }

  // When the writable side finishes, then flush out anything remaining.
  this.on('prefinish', prefinish);
}
function prefinish() {
  var _this = this;
  if (typeof this._flush === 'function' && !this._readableState.destroyed) {
    this._flush(function (er, data) {
      done(_this, er, data);
    });
  } else {
    done(this, null, null);
  }
}
Transform.prototype.push = function (chunk, encoding) {
  this._transformState.needTransform = false;
  return Duplex.prototype.push.call(this, chunk, encoding);
};

// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side.  You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk.  If you pass
// an error, then that'll put the hurt on the whole operation.  If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
  cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
};
Transform.prototype._write = function (chunk, encoding, cb) {
  var ts = this._transformState;
  ts.writecb = cb;
  ts.writechunk = chunk;
  ts.writeencoding = encoding;
  if (!ts.transforming) {
    var rs = this._readableState;
    if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  }
};

// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
  var ts = this._transformState;
  if (ts.writechunk !== null && !ts.transforming) {
    ts.transforming = true;
    this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  } else {
    // mark that we need a transform, so that any data that comes in
    // will get processed, now that we've asked for it.
    ts.needTransform = true;
  }
};
Transform.prototype._destroy = function (err, cb) {
  Duplex.prototype._destroy.call(this, err, function (err2) {
    cb(err2);
  });
};
function done(stream, er, data) {
  if (er) return stream.emit('error', er);
  if (data != null)
    // single equals check for both `null` and `undefined`
    stream.push(data);

  // TODO(BridgeAR): Write a test for these two error cases
  // if there's nothing in the write buffer, then that means
  // that nothing more will ever be provided
  if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
  if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
  return stream.push(null);
}

/***/ }),

/***/ 26968:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.



module.exports = Writable;

/* <replacement> */
function WriteReq(chunk, encoding, cb) {
  this.chunk = chunk;
  this.encoding = encoding;
  this.callback = cb;
  this.next = null;
}

// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
  var _this = this;
  this.next = null;
  this.entry = null;
  this.finish = function () {
    onCorkedFinish(_this, state);
  };
}
/* </replacement> */

/*<replacement>*/
var Duplex;
/*</replacement>*/

Writable.WritableState = WritableState;

/*<replacement>*/
var internalUtil = {
  deprecate: __webpack_require__(88680)
};
/*</replacement>*/

/*<replacement>*/
var Stream = __webpack_require__(24181);
/*</replacement>*/

var Buffer = (__webpack_require__(78378).Buffer);
var OurUint8Array = (typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
  return Buffer.from(chunk);
}
function _isUint8Array(obj) {
  return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
var destroyImpl = __webpack_require__(30276);
var _require = __webpack_require__(975),
  getHighWaterMark = _require.getHighWaterMark;
var _require$codes = (__webpack_require__(67772)/* .codes */ .F),
  ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
  ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
  ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
  ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
  ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
  ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
  ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
var errorOrDestroy = destroyImpl.errorOrDestroy;
__webpack_require__(72116)(Writable, Stream);
function nop() {}
function WritableState(options, stream, isDuplex) {
  Duplex = Duplex || __webpack_require__(47514);
  options = options || {};

  // Duplex streams are both readable and writable, but share
  // the same options object.
  // However, some cases require setting options to different
  // values for the readable and the writable sides of the duplex stream,
  // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
  if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;

  // object stream flag to indicate whether or not this stream
  // contains buffers or objects.
  this.objectMode = !!options.objectMode;
  if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;

  // the point at which write() starts returning false
  // Note: 0 is a valid value, means that we always return false if
  // the entire buffer is not flushed immediately on write()
  this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex);

  // if _final has been called
  this.finalCalled = false;

  // drain event flag.
  this.needDrain = false;
  // at the start of calling end()
  this.ending = false;
  // when end() has been called, and returned
  this.ended = false;
  // when 'finish' is emitted
  this.finished = false;

  // has it been destroyed
  this.destroyed = false;

  // should we decode strings into buffers before passing to _write?
  // this is here so that some node-core streams can optimize string
  // handling at a lower level.
  var noDecode = options.decodeStrings === false;
  this.decodeStrings = !noDecode;

  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';

  // not an actual buffer we keep track of, but a measurement
  // of how much we're waiting to get pushed to some underlying
  // socket or file.
  this.length = 0;

  // a flag to see when we're in the middle of a write.
  this.writing = false;

  // when true all writes will be buffered until .uncork() call
  this.corked = 0;

  // a flag to be able to tell if the onwrite cb is called immediately,
  // or on a later tick.  We set this to true at first, because any
  // actions that shouldn't happen until "later" should generally also
  // not happen before the first write call.
  this.sync = true;

  // a flag to know if we're processing previously buffered items, which
  // may call the _write() callback in the same tick, so that we don't
  // end up in an overlapped onwrite situation.
  this.bufferProcessing = false;

  // the callback that's passed to _write(chunk,cb)
  this.onwrite = function (er) {
    onwrite(stream, er);
  };

  // the callback that the user supplies to write(chunk,encoding,cb)
  this.writecb = null;

  // the amount that is being written when _write is called.
  this.writelen = 0;
  this.bufferedRequest = null;
  this.lastBufferedRequest = null;

  // number of pending user-supplied write callbacks
  // this must be 0 before 'finish' can be emitted
  this.pendingcb = 0;

  // emit prefinish if the only thing we're waiting for is _write cbs
  // This is relevant for synchronous Transform streams
  this.prefinished = false;

  // True if the error was already emitted and should not be thrown again
  this.errorEmitted = false;

  // Should close be emitted on destroy. Defaults to true.
  this.emitClose = options.emitClose !== false;

  // Should .destroy() be called after 'finish' (and potentially 'end')
  this.autoDestroy = !!options.autoDestroy;

  // count buffered requests
  this.bufferedRequestCount = 0;

  // allocate the first CorkedRequest, there is always
  // one allocated and free to use, and we maintain at most two
  this.corkedRequestsFree = new CorkedRequest(this);
}
WritableState.prototype.getBuffer = function getBuffer() {
  var current = this.bufferedRequest;
  var out = [];
  while (current) {
    out.push(current);
    current = current.next;
  }
  return out;
};
(function () {
  try {
    Object.defineProperty(WritableState.prototype, 'buffer', {
      get: internalUtil.deprecate(function writableStateBufferGetter() {
        return this.getBuffer();
      }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
    });
  } catch (_) {}
})();

// Test _writableState for inheritance to account for Duplex streams,
// whose prototype chain only points to Readable.
var realHasInstance;
if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  realHasInstance = Function.prototype[Symbol.hasInstance];
  Object.defineProperty(Writable, Symbol.hasInstance, {
    value: function value(object) {
      if (realHasInstance.call(this, object)) return true;
      if (this !== Writable) return false;
      return object && object._writableState instanceof WritableState;
    }
  });
} else {
  realHasInstance = function realHasInstance(object) {
    return object instanceof this;
  };
}
function Writable(options) {
  Duplex = Duplex || __webpack_require__(47514);

  // Writable ctor is applied to Duplexes, too.
  // `realHasInstance` is necessary because using plain `instanceof`
  // would return false, as no `_writableState` property is attached.

  // Trying to use the custom `instanceof` for Writable here will also break the
  // Node.js LazyTransform implementation, which has a non-trivial getter for
  // `_writableState` that would lead to infinite recursion.

  // Checking for a Stream.Duplex instance is faster here instead of inside
  // the WritableState constructor, at least with V8 6.5
  var isDuplex = this instanceof Duplex;
  if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
  this._writableState = new WritableState(options, this, isDuplex);

  // legacy.
  this.writable = true;
  if (options) {
    if (typeof options.write === 'function') this._write = options.write;
    if (typeof options.writev === 'function') this._writev = options.writev;
    if (typeof options.destroy === 'function') this._destroy = options.destroy;
    if (typeof options.final === 'function') this._final = options.final;
  }
  Stream.call(this);
}

// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
  errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
};
function writeAfterEnd(stream, cb) {
  var er = new ERR_STREAM_WRITE_AFTER_END();
  // TODO: defer error events consistently everywhere, not just the cb
  errorOrDestroy(stream, er);
  process.nextTick(cb, er);
}

// Checks that a user-supplied chunk is valid, especially for the particular
// mode the stream is in. Currently this means that `null` is never accepted
// and undefined/non-string values are only allowed in object mode.
function validChunk(stream, state, chunk, cb) {
  var er;
  if (chunk === null) {
    er = new ERR_STREAM_NULL_VALUES();
  } else if (typeof chunk !== 'string' && !state.objectMode) {
    er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
  }
  if (er) {
    errorOrDestroy(stream, er);
    process.nextTick(cb, er);
    return false;
  }
  return true;
}
Writable.prototype.write = function (chunk, encoding, cb) {
  var state = this._writableState;
  var ret = false;
  var isBuf = !state.objectMode && _isUint8Array(chunk);
  if (isBuf && !Buffer.isBuffer(chunk)) {
    chunk = _uint8ArrayToBuffer(chunk);
  }
  if (typeof encoding === 'function') {
    cb = encoding;
    encoding = null;
  }
  if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  if (typeof cb !== 'function') cb = nop;
  if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
    state.pendingcb++;
    ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  }
  return ret;
};
Writable.prototype.cork = function () {
  this._writableState.corked++;
};
Writable.prototype.uncork = function () {
  var state = this._writableState;
  if (state.corked) {
    state.corked--;
    if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  }
};
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  // node::ParseEncoding() requires lower case.
  if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
  this._writableState.defaultEncoding = encoding;
  return this;
};
Object.defineProperty(Writable.prototype, 'writableBuffer', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    return this._writableState && this._writableState.getBuffer();
  }
});
function decodeChunk(state, chunk, encoding) {
  if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
    chunk = Buffer.from(chunk, encoding);
  }
  return chunk;
}
Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    return this._writableState.highWaterMark;
  }
});

// if we're already writing something, then just put this
// in the queue, and wait our turn.  Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  if (!isBuf) {
    var newChunk = decodeChunk(state, chunk, encoding);
    if (chunk !== newChunk) {
      isBuf = true;
      encoding = 'buffer';
      chunk = newChunk;
    }
  }
  var len = state.objectMode ? 1 : chunk.length;
  state.length += len;
  var ret = state.length < state.highWaterMark;
  // we must ensure that previous needDrain will not be reset to false.
  if (!ret) state.needDrain = true;
  if (state.writing || state.corked) {
    var last = state.lastBufferedRequest;
    state.lastBufferedRequest = {
      chunk: chunk,
      encoding: encoding,
      isBuf: isBuf,
      callback: cb,
      next: null
    };
    if (last) {
      last.next = state.lastBufferedRequest;
    } else {
      state.bufferedRequest = state.lastBufferedRequest;
    }
    state.bufferedRequestCount += 1;
  } else {
    doWrite(stream, state, false, len, chunk, encoding, cb);
  }
  return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  state.writelen = len;
  state.writecb = cb;
  state.writing = true;
  state.sync = true;
  if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
  --state.pendingcb;
  if (sync) {
    // defer the callback if we are being called synchronously
    // to avoid piling up things on the stack
    process.nextTick(cb, er);
    // this can emit finish, and it will always happen
    // after error
    process.nextTick(finishMaybe, stream, state);
    stream._writableState.errorEmitted = true;
    errorOrDestroy(stream, er);
  } else {
    // the caller expect this to happen before if
    // it is async
    cb(er);
    stream._writableState.errorEmitted = true;
    errorOrDestroy(stream, er);
    // this can emit finish, but finish must
    // always follow error
    finishMaybe(stream, state);
  }
}
function onwriteStateUpdate(state) {
  state.writing = false;
  state.writecb = null;
  state.length -= state.writelen;
  state.writelen = 0;
}
function onwrite(stream, er) {
  var state = stream._writableState;
  var sync = state.sync;
  var cb = state.writecb;
  if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
  onwriteStateUpdate(state);
  if (er) onwriteError(stream, state, sync, er, cb);else {
    // Check if we're actually ready to finish, but don't emit yet
    var finished = needFinish(state) || stream.destroyed;
    if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
      clearBuffer(stream, state);
    }
    if (sync) {
      process.nextTick(afterWrite, stream, state, finished, cb);
    } else {
      afterWrite(stream, state, finished, cb);
    }
  }
}
function afterWrite(stream, state, finished, cb) {
  if (!finished) onwriteDrain(stream, state);
  state.pendingcb--;
  cb();
  finishMaybe(stream, state);
}

// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
  if (state.length === 0 && state.needDrain) {
    state.needDrain = false;
    stream.emit('drain');
  }
}

// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
  state.bufferProcessing = true;
  var entry = state.bufferedRequest;
  if (stream._writev && entry && entry.next) {
    // Fast case, write everything using _writev()
    var l = state.bufferedRequestCount;
    var buffer = new Array(l);
    var holder = state.corkedRequestsFree;
    holder.entry = entry;
    var count = 0;
    var allBuffers = true;
    while (entry) {
      buffer[count] = entry;
      if (!entry.isBuf) allBuffers = false;
      entry = entry.next;
      count += 1;
    }
    buffer.allBuffers = allBuffers;
    doWrite(stream, state, true, state.length, buffer, '', holder.finish);

    // doWrite is almost always async, defer these to save a bit of time
    // as the hot path ends with doWrite
    state.pendingcb++;
    state.lastBufferedRequest = null;
    if (holder.next) {
      state.corkedRequestsFree = holder.next;
      holder.next = null;
    } else {
      state.corkedRequestsFree = new CorkedRequest(state);
    }
    state.bufferedRequestCount = 0;
  } else {
    // Slow case, write chunks one-by-one
    while (entry) {
      var chunk = entry.chunk;
      var encoding = entry.encoding;
      var cb = entry.callback;
      var len = state.objectMode ? 1 : chunk.length;
      doWrite(stream, state, false, len, chunk, encoding, cb);
      entry = entry.next;
      state.bufferedRequestCount--;
      // if we didn't call the onwrite immediately, then
      // it means that we need to wait until it does.
      // also, that means that the chunk and cb are currently
      // being processed, so move the buffer counter past them.
      if (state.writing) {
        break;
      }
    }
    if (entry === null) state.lastBufferedRequest = null;
  }
  state.bufferedRequest = entry;
  state.bufferProcessing = false;
}
Writable.prototype._write = function (chunk, encoding, cb) {
  cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function (chunk, encoding, cb) {
  var state = this._writableState;
  if (typeof chunk === 'function') {
    cb = chunk;
    chunk = null;
    encoding = null;
  } else if (typeof encoding === 'function') {
    cb = encoding;
    encoding = null;
  }
  if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);

  // .end() fully uncorks
  if (state.corked) {
    state.corked = 1;
    this.uncork();
  }

  // ignore unnecessary end() calls.
  if (!state.ending) endWritable(this, state, cb);
  return this;
};
Object.defineProperty(Writable.prototype, 'writableLength', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    return this._writableState.length;
  }
});
function needFinish(state) {
  return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function callFinal(stream, state) {
  stream._final(function (err) {
    state.pendingcb--;
    if (err) {
      errorOrDestroy(stream, err);
    }
    state.prefinished = true;
    stream.emit('prefinish');
    finishMaybe(stream, state);
  });
}
function prefinish(stream, state) {
  if (!state.prefinished && !state.finalCalled) {
    if (typeof stream._final === 'function' && !state.destroyed) {
      state.pendingcb++;
      state.finalCalled = true;
      process.nextTick(callFinal, stream, state);
    } else {
      state.prefinished = true;
      stream.emit('prefinish');
    }
  }
}
function finishMaybe(stream, state) {
  var need = needFinish(state);
  if (need) {
    prefinish(stream, state);
    if (state.pendingcb === 0) {
      state.finished = true;
      stream.emit('finish');
      if (state.autoDestroy) {
        // In case of duplex streams we need a way to detect
        // if the readable side is ready for autoDestroy as well
        var rState = stream._readableState;
        if (!rState || rState.autoDestroy && rState.endEmitted) {
          stream.destroy();
        }
      }
    }
  }
  return need;
}
function endWritable(stream, state, cb) {
  state.ending = true;
  finishMaybe(stream, state);
  if (cb) {
    if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
  }
  state.ended = true;
  stream.writable = false;
}
function onCorkedFinish(corkReq, state, err) {
  var entry = corkReq.entry;
  corkReq.entry = null;
  while (entry) {
    var cb = entry.callback;
    state.pendingcb--;
    cb(err);
    entry = entry.next;
  }

  // reuse the free corkReq.
  state.corkedRequestsFree.next = corkReq;
}
Object.defineProperty(Writable.prototype, 'destroyed', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    if (this._writableState === undefined) {
      return false;
    }
    return this._writableState.destroyed;
  },
  set: function set(value) {
    // we ignore the value if the stream
    // has not been initialized yet
    if (!this._writableState) {
      return;
    }

    // backward compatibility, the user is explicitly
    // managing destroyed
    this._writableState.destroyed = value;
  }
});
Writable.prototype.destroy = destroyImpl.destroy;
Writable.prototype._undestroy = destroyImpl.undestroy;
Writable.prototype._destroy = function (err, cb) {
  cb(err);
};

/***/ }),

/***/ 43295:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var _Object$setPrototypeO;
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var finished = __webpack_require__(21530);
var kLastResolve = Symbol('lastResolve');
var kLastReject = Symbol('lastReject');
var kError = Symbol('error');
var kEnded = Symbol('ended');
var kLastPromise = Symbol('lastPromise');
var kHandlePromise = Symbol('handlePromise');
var kStream = Symbol('stream');
function createIterResult(value, done) {
  return {
    value: value,
    done: done
  };
}
function readAndResolve(iter) {
  var resolve = iter[kLastResolve];
  if (resolve !== null) {
    var data = iter[kStream].read();
    // we defer if data is null
    // we can be expecting either 'end' or
    // 'error'
    if (data !== null) {
      iter[kLastPromise] = null;
      iter[kLastResolve] = null;
      iter[kLastReject] = null;
      resolve(createIterResult(data, false));
    }
  }
}
function onReadable(iter) {
  // we wait for the next tick, because it might
  // emit an error with process.nextTick
  process.nextTick(readAndResolve, iter);
}
function wrapForNext(lastPromise, iter) {
  return function (resolve, reject) {
    lastPromise.then(function () {
      if (iter[kEnded]) {
        resolve(createIterResult(undefined, true));
        return;
      }
      iter[kHandlePromise](resolve, reject);
    }, reject);
  };
}
var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
  get stream() {
    return this[kStream];
  },
  next: function next() {
    var _this = this;
    // if we have detected an error in the meanwhile
    // reject straight away
    var error = this[kError];
    if (error !== null) {
      return Promise.reject(error);
    }
    if (this[kEnded]) {
      return Promise.resolve(createIterResult(undefined, true));
    }
    if (this[kStream].destroyed) {
      // We need to defer via nextTick because if .destroy(err) is
      // called, the error will be emitted via nextTick, and
      // we cannot guarantee that there is no error lingering around
      // waiting to be emitted.
      return new Promise(function (resolve, reject) {
        process.nextTick(function () {
          if (_this[kError]) {
            reject(_this[kError]);
          } else {
            resolve(createIterResult(undefined, true));
          }
        });
      });
    }

    // if we have multiple next() calls
    // we will wait for the previous Promise to finish
    // this logic is optimized to support for await loops,
    // where next() is only called once at a time
    var lastPromise = this[kLastPromise];
    var promise;
    if (lastPromise) {
      promise = new Promise(wrapForNext(lastPromise, this));
    } else {
      // fast path needed to support multiple this.push()
      // without triggering the next() queue
      var data = this[kStream].read();
      if (data !== null) {
        return Promise.resolve(createIterResult(data, false));
      }
      promise = new Promise(this[kHandlePromise]);
    }
    this[kLastPromise] = promise;
    return promise;
  }
}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
  return this;
}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
  var _this2 = this;
  // destroy(err, cb) is a private API
  // we can guarantee we have that here, because we control the
  // Readable class this is attached to
  return new Promise(function (resolve, reject) {
    _this2[kStream].destroy(null, function (err) {
      if (err) {
        reject(err);
        return;
      }
      resolve(createIterResult(undefined, true));
    });
  });
}), _Object$setPrototypeO), AsyncIteratorPrototype);
var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
  var _Object$create;
  var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
    value: stream,
    writable: true
  }), _defineProperty(_Object$create, kLastResolve, {
    value: null,
    writable: true
  }), _defineProperty(_Object$create, kLastReject, {
    value: null,
    writable: true
  }), _defineProperty(_Object$create, kError, {
    value: null,
    writable: true
  }), _defineProperty(_Object$create, kEnded, {
    value: stream._readableState.endEmitted,
    writable: true
  }), _defineProperty(_Object$create, kHandlePromise, {
    value: function value(resolve, reject) {
      var data = iterator[kStream].read();
      if (data) {
        iterator[kLastPromise] = null;
        iterator[kLastResolve] = null;
        iterator[kLastReject] = null;
        resolve(createIterResult(data, false));
      } else {
        iterator[kLastResolve] = resolve;
        iterator[kLastReject] = reject;
      }
    },
    writable: true
  }), _Object$create));
  iterator[kLastPromise] = null;
  finished(stream, function (err) {
    if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
      var reject = iterator[kLastReject];
      // reject if we are waiting for data in the Promise
      // returned by next() and store the error
      if (reject !== null) {
        iterator[kLastPromise] = null;
        iterator[kLastResolve] = null;
        iterator[kLastReject] = null;
        reject(err);
      }
      iterator[kError] = err;
      return;
    }
    var resolve = iterator[kLastResolve];
    if (resolve !== null) {
      iterator[kLastPromise] = null;
      iterator[kLastResolve] = null;
      iterator[kLastReject] = null;
      resolve(createIterResult(undefined, true));
    }
    iterator[kEnded] = true;
  });
  stream.on('readable', onReadable.bind(null, iterator));
  return iterator;
};
module.exports = createReadableStreamAsyncIterator;

/***/ }),

/***/ 19037:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var _require = __webpack_require__(78378),
  Buffer = _require.Buffer;
var _require2 = __webpack_require__(71220),
  inspect = _require2.inspect;
var custom = inspect && inspect.custom || 'inspect';
function copyBuffer(src, target, offset) {
  Buffer.prototype.copy.call(src, target, offset);
}
module.exports = /*#__PURE__*/function () {
  function BufferList() {
    _classCallCheck(this, BufferList);
    this.head = null;
    this.tail = null;
    this.length = 0;
  }
  _createClass(BufferList, [{
    key: "push",
    value: function push(v) {
      var entry = {
        data: v,
        next: null
      };
      if (this.length > 0) this.tail.next = entry;else this.head = entry;
      this.tail = entry;
      ++this.length;
    }
  }, {
    key: "unshift",
    value: function unshift(v) {
      var entry = {
        data: v,
        next: this.head
      };
      if (this.length === 0) this.tail = entry;
      this.head = entry;
      ++this.length;
    }
  }, {
    key: "shift",
    value: function shift() {
      if (this.length === 0) return;
      var ret = this.head.data;
      if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
      --this.length;
      return ret;
    }
  }, {
    key: "clear",
    value: function clear() {
      this.head = this.tail = null;
      this.length = 0;
    }
  }, {
    key: "join",
    value: function join(s) {
      if (this.length === 0) return '';
      var p = this.head;
      var ret = '' + p.data;
      while (p = p.next) ret += s + p.data;
      return ret;
    }
  }, {
    key: "concat",
    value: function concat(n) {
      if (this.length === 0) return Buffer.alloc(0);
      var ret = Buffer.allocUnsafe(n >>> 0);
      var p = this.head;
      var i = 0;
      while (p) {
        copyBuffer(p.data, ret, i);
        i += p.data.length;
        p = p.next;
      }
      return ret;
    }

    // Consumes a specified amount of bytes or characters from the buffered data.
  }, {
    key: "consume",
    value: function consume(n, hasStrings) {
      var ret;
      if (n < this.head.data.length) {
        // `slice` is the same for buffers and strings.
        ret = this.head.data.slice(0, n);
        this.head.data = this.head.data.slice(n);
      } else if (n === this.head.data.length) {
        // First chunk is a perfect match.
        ret = this.shift();
      } else {
        // Result spans more than one buffer.
        ret = hasStrings ? this._getString(n) : this._getBuffer(n);
      }
      return ret;
    }
  }, {
    key: "first",
    value: function first() {
      return this.head.data;
    }

    // Consumes a specified amount of characters from the buffered data.
  }, {
    key: "_getString",
    value: function _getString(n) {
      var p = this.head;
      var c = 1;
      var ret = p.data;
      n -= ret.length;
      while (p = p.next) {
        var str = p.data;
        var nb = n > str.length ? str.length : n;
        if (nb === str.length) ret += str;else ret += str.slice(0, n);
        n -= nb;
        if (n === 0) {
          if (nb === str.length) {
            ++c;
            if (p.next) this.head = p.next;else this.head = this.tail = null;
          } else {
            this.head = p;
            p.data = str.slice(nb);
          }
          break;
        }
        ++c;
      }
      this.length -= c;
      return ret;
    }

    // Consumes a specified amount of bytes from the buffered data.
  }, {
    key: "_getBuffer",
    value: function _getBuffer(n) {
      var ret = Buffer.allocUnsafe(n);
      var p = this.head;
      var c = 1;
      p.data.copy(ret);
      n -= p.data.length;
      while (p = p.next) {
        var buf = p.data;
        var nb = n > buf.length ? buf.length : n;
        buf.copy(ret, ret.length - n, 0, nb);
        n -= nb;
        if (n === 0) {
          if (nb === buf.length) {
            ++c;
            if (p.next) this.head = p.next;else this.head = this.tail = null;
          } else {
            this.head = p;
            p.data = buf.slice(nb);
          }
          break;
        }
        ++c;
      }
      this.length -= c;
      return ret;
    }

    // Make sure the linked list only shows the minimal necessary information.
  }, {
    key: custom,
    value: function value(_, options) {
      return inspect(this, _objectSpread(_objectSpread({}, options), {}, {
        // Only inspect one level.
        depth: 0,
        // It should not recurse.
        customInspect: false
      }));
    }
  }]);
  return BufferList;
}();

/***/ }),

/***/ 30276:
/***/ ((module) => {

"use strict";


// undocumented cb() API, needed for core, not for public API
function destroy(err, cb) {
  var _this = this;
  var readableDestroyed = this._readableState && this._readableState.destroyed;
  var writableDestroyed = this._writableState && this._writableState.destroyed;
  if (readableDestroyed || writableDestroyed) {
    if (cb) {
      cb(err);
    } else if (err) {
      if (!this._writableState) {
        process.nextTick(emitErrorNT, this, err);
      } else if (!this._writableState.errorEmitted) {
        this._writableState.errorEmitted = true;
        process.nextTick(emitErrorNT, this, err);
      }
    }
    return this;
  }

  // we set destroyed to true before firing error callbacks in order
  // to make it re-entrance safe in case destroy() is called within callbacks

  if (this._readableState) {
    this._readableState.destroyed = true;
  }

  // if this is a duplex stream mark the writable part as destroyed as well
  if (this._writableState) {
    this._writableState.destroyed = true;
  }
  this._destroy(err || null, function (err) {
    if (!cb && err) {
      if (!_this._writableState) {
        process.nextTick(emitErrorAndCloseNT, _this, err);
      } else if (!_this._writableState.errorEmitted) {
        _this._writableState.errorEmitted = true;
        process.nextTick(emitErrorAndCloseNT, _this, err);
      } else {
        process.nextTick(emitCloseNT, _this);
      }
    } else if (cb) {
      process.nextTick(emitCloseNT, _this);
      cb(err);
    } else {
      process.nextTick(emitCloseNT, _this);
    }
  });
  return this;
}
function emitErrorAndCloseNT(self, err) {
  emitErrorNT(self, err);
  emitCloseNT(self);
}
function emitCloseNT(self) {
  if (self._writableState && !self._writableState.emitClose) return;
  if (self._readableState && !self._readableState.emitClose) return;
  self.emit('close');
}
function undestroy() {
  if (this._readableState) {
    this._readableState.destroyed = false;
    this._readableState.reading = false;
    this._readableState.ended = false;
    this._readableState.endEmitted = false;
  }
  if (this._writableState) {
    this._writableState.destroyed = false;
    this._writableState.ended = false;
    this._writableState.ending = false;
    this._writableState.finalCalled = false;
    this._writableState.prefinished = false;
    this._writableState.finished = false;
    this._writableState.errorEmitted = false;
  }
}
function emitErrorNT(self, err) {
  self.emit('error', err);
}
function errorOrDestroy(stream, err) {
  // We have tests that rely on errors being emitted
  // in the same tick, so changing this is semver major.
  // For now when you opt-in to autoDestroy we allow
  // the error to be emitted nextTick. In a future
  // semver major update we should change the default to this.

  var rState = stream._readableState;
  var wState = stream._writableState;
  if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
}
module.exports = {
  destroy: destroy,
  undestroy: undestroy,
  errorOrDestroy: errorOrDestroy
};

/***/ }),

/***/ 21530:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
// Ported from https://github.com/mafintosh/end-of-stream with
// permission from the author, Mathias Buus (@mafintosh).



var ERR_STREAM_PREMATURE_CLOSE = (__webpack_require__(67772)/* .codes */ .F).ERR_STREAM_PREMATURE_CLOSE;
function once(callback) {
  var called = false;
  return function () {
    if (called) return;
    called = true;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    callback.apply(this, args);
  };
}
function noop() {}
function isRequest(stream) {
  return stream.setHeader && typeof stream.abort === 'function';
}
function eos(stream, opts, callback) {
  if (typeof opts === 'function') return eos(stream, null, opts);
  if (!opts) opts = {};
  callback = once(callback || noop);
  var readable = opts.readable || opts.readable !== false && stream.readable;
  var writable = opts.writable || opts.writable !== false && stream.writable;
  var onlegacyfinish = function onlegacyfinish() {
    if (!stream.writable) onfinish();
  };
  var writableEnded = stream._writableState && stream._writableState.finished;
  var onfinish = function onfinish() {
    writable = false;
    writableEnded = true;
    if (!readable) callback.call(stream);
  };
  var readableEnded = stream._readableState && stream._readableState.endEmitted;
  var onend = function onend() {
    readable = false;
    readableEnded = true;
    if (!writable) callback.call(stream);
  };
  var onerror = function onerror(err) {
    callback.call(stream, err);
  };
  var onclose = function onclose() {
    var err;
    if (readable && !readableEnded) {
      if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
      return callback.call(stream, err);
    }
    if (writable && !writableEnded) {
      if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
      return callback.call(stream, err);
    }
  };
  var onrequest = function onrequest() {
    stream.req.on('finish', onfinish);
  };
  if (isRequest(stream)) {
    stream.on('complete', onfinish);
    stream.on('abort', onclose);
    if (stream.req) onrequest();else stream.on('request', onrequest);
  } else if (writable && !stream._writableState) {
    // legacy streams
    stream.on('end', onlegacyfinish);
    stream.on('close', onlegacyfinish);
  }
  stream.on('end', onend);
  stream.on('finish', onfinish);
  if (opts.error !== false) stream.on('error', onerror);
  stream.on('close', onclose);
  return function () {
    stream.removeListener('complete', onfinish);
    stream.removeListener('abort', onclose);
    stream.removeListener('request', onrequest);
    if (stream.req) stream.req.removeListener('finish', onfinish);
    stream.removeListener('end', onlegacyfinish);
    stream.removeListener('close', onlegacyfinish);
    stream.removeListener('finish', onfinish);
    stream.removeListener('end', onend);
    stream.removeListener('error', onerror);
    stream.removeListener('close', onclose);
  };
}
module.exports = eos;

/***/ }),

/***/ 41713:
/***/ ((module) => {

module.exports = function () {
  throw new Error('Readable.from is not available in the browser')
};


/***/ }),

/***/ 29586:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
// Ported from https://github.com/mafintosh/pump with
// permission from the author, Mathias Buus (@mafintosh).



var eos;
function once(callback) {
  var called = false;
  return function () {
    if (called) return;
    called = true;
    callback.apply(void 0, arguments);
  };
}
var _require$codes = (__webpack_require__(67772)/* .codes */ .F),
  ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
  ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
function noop(err) {
  // Rethrow the error if it exists to avoid swallowing it
  if (err) throw err;
}
function isRequest(stream) {
  return stream.setHeader && typeof stream.abort === 'function';
}
function destroyer(stream, reading, writing, callback) {
  callback = once(callback);
  var closed = false;
  stream.on('close', function () {
    closed = true;
  });
  if (eos === undefined) eos = __webpack_require__(21530);
  eos(stream, {
    readable: reading,
    writable: writing
  }, function (err) {
    if (err) return callback(err);
    closed = true;
    callback();
  });
  var destroyed = false;
  return function (err) {
    if (closed) return;
    if (destroyed) return;
    destroyed = true;

    // request.destroy just do .end - .abort is what we want
    if (isRequest(stream)) return stream.abort();
    if (typeof stream.destroy === 'function') return stream.destroy();
    callback(err || new ERR_STREAM_DESTROYED('pipe'));
  };
}
function call(fn) {
  fn();
}
function pipe(from, to) {
  return from.pipe(to);
}
function popCallback(streams) {
  if (!streams.length) return noop;
  if (typeof streams[streams.length - 1] !== 'function') return noop;
  return streams.pop();
}
function pipeline() {
  for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
    streams[_key] = arguments[_key];
  }
  var callback = popCallback(streams);
  if (Array.isArray(streams[0])) streams = streams[0];
  if (streams.length < 2) {
    throw new ERR_MISSING_ARGS('streams');
  }
  var error;
  var destroys = streams.map(function (stream, i) {
    var reading = i < streams.length - 1;
    var writing = i > 0;
    return destroyer(stream, reading, writing, function (err) {
      if (!error) error = err;
      if (err) destroys.forEach(call);
      if (reading) return;
      destroys.forEach(call);
      callback(error);
    });
  });
  return streams.reduce(pipe);
}
module.exports = pipeline;

/***/ }),

/***/ 975:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var ERR_INVALID_OPT_VALUE = (__webpack_require__(67772)/* .codes */ .F).ERR_INVALID_OPT_VALUE;
function highWaterMarkFrom(options, isDuplex, duplexKey) {
  return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
}
function getHighWaterMark(state, options, duplexKey, isDuplex) {
  var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
  if (hwm != null) {
    if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
      var name = isDuplex ? duplexKey : 'highWaterMark';
      throw new ERR_INVALID_OPT_VALUE(name, hwm);
    }
    return Math.floor(hwm);
  }

  // Default value
  return state.objectMode ? 16 : 16 * 1024;
}
module.exports = {
  getHighWaterMark: getHighWaterMark
};

/***/ }),

/***/ 24181:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

module.exports = __webpack_require__(93876).EventEmitter;


/***/ }),

/***/ 32891:
/***/ ((module, exports, __webpack_require__) => {

exports = module.exports = __webpack_require__(5960);
exports.Stream = exports;
exports.Readable = exports;
exports.Writable = __webpack_require__(26968);
exports.Duplex = __webpack_require__(47514);
exports.Transform = __webpack_require__(96646);
exports.PassThrough = __webpack_require__(33308);
exports.finished = __webpack_require__(21530);
exports.pipeline = __webpack_require__(29586);


/***/ }),

/***/ 84861:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var Buffer = (__webpack_require__(78378).Buffer)
var inherits = __webpack_require__(72116)
var HashBase = __webpack_require__(63871)

var ARRAY16 = new Array(16)

var zl = [
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
  3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
  1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
  4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
]

var zr = [
  5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
  6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
  15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
  8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
  12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
]

var sl = [
  11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
  7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
  11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
  11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
  9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
]

var sr = [
  8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
  9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
  9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
  15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
  8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
]

var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]
var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]

function RIPEMD160 () {
  HashBase.call(this, 64)

  // state
  this._a = 0x67452301
  this._b = 0xefcdab89
  this._c = 0x98badcfe
  this._d = 0x10325476
  this._e = 0xc3d2e1f0
}

inherits(RIPEMD160, HashBase)

RIPEMD160.prototype._update = function () {
  var words = ARRAY16
  for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4)

  var al = this._a | 0
  var bl = this._b | 0
  var cl = this._c | 0
  var dl = this._d | 0
  var el = this._e | 0

  var ar = this._a | 0
  var br = this._b | 0
  var cr = this._c | 0
  var dr = this._d | 0
  var er = this._e | 0

  // computation
  for (var i = 0; i < 80; i += 1) {
    var tl
    var tr
    if (i < 16) {
      tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i])
      tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i])
    } else if (i < 32) {
      tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i])
      tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i])
    } else if (i < 48) {
      tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i])
      tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i])
    } else if (i < 64) {
      tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i])
      tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i])
    } else { // if (i<80) {
      tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i])
      tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i])
    }

    al = el
    el = dl
    dl = rotl(cl, 10)
    cl = bl
    bl = tl

    ar = er
    er = dr
    dr = rotl(cr, 10)
    cr = br
    br = tr
  }

  // update state
  var t = (this._b + cl + dr) | 0
  this._b = (this._c + dl + er) | 0
  this._c = (this._d + el + ar) | 0
  this._d = (this._e + al + br) | 0
  this._e = (this._a + bl + cr) | 0
  this._a = t
}

RIPEMD160.prototype._digest = function () {
  // create padding and handle blocks
  this._block[this._blockOffset++] = 0x80
  if (this._blockOffset > 56) {
    this._block.fill(0, this._blockOffset, 64)
    this._update()
    this._blockOffset = 0
  }

  this._block.fill(0, this._blockOffset, 56)
  this._block.writeUInt32LE(this._length[0], 56)
  this._block.writeUInt32LE(this._length[1], 60)
  this._update()

  // produce result
  var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20)
  buffer.writeInt32LE(this._a, 0)
  buffer.writeInt32LE(this._b, 4)
  buffer.writeInt32LE(this._c, 8)
  buffer.writeInt32LE(this._d, 12)
  buffer.writeInt32LE(this._e, 16)
  return buffer
}

function rotl (x, n) {
  return (x << n) | (x >>> (32 - n))
}

function fn1 (a, b, c, d, e, m, k, s) {
  return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0
}

function fn2 (a, b, c, d, e, m, k, s) {
  return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0
}

function fn3 (a, b, c, d, e, m, k, s) {
  return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0
}

function fn4 (a, b, c, d, e, m, k, s) {
  return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0
}

function fn5 (a, b, c, d, e, m, k, s) {
  return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0
}

module.exports = RIPEMD160


/***/ }),

/***/ 86399:
/***/ ((module, exports, __webpack_require__) => {

/* eslint-disable node/no-deprecated-api */
var buffer = __webpack_require__(78378)
var Buffer = buffer.Buffer

// alternative to using Object.keys for old browsers
function copyProps (src, dst) {
  for (var key in src) {
    dst[key] = src[key]
  }
}
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  module.exports = buffer
} else {
  // Copy properties from require('buffer')
  copyProps(buffer, exports)
  exports.Buffer = SafeBuffer
}

function SafeBuffer (arg, encodingOrOffset, length) {
  return Buffer(arg, encodingOrOffset, length)
}

// Copy static methods from Buffer
copyProps(Buffer, SafeBuffer)

SafeBuffer.from = function (arg, encodingOrOffset, length) {
  if (typeof arg === 'number') {
    throw new TypeError('Argument must not be a number')
  }
  return Buffer(arg, encodingOrOffset, length)
}

SafeBuffer.alloc = function (size, fill, encoding) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  var buf = Buffer(size)
  if (fill !== undefined) {
    if (typeof encoding === 'string') {
      buf.fill(fill, encoding)
    } else {
      buf.fill(fill)
    }
  } else {
    buf.fill(0)
  }
  return buf
}

SafeBuffer.allocUnsafe = function (size) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  return Buffer(size)
}

SafeBuffer.allocUnsafeSlow = function (size) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  return buffer.SlowBuffer(size)
}


/***/ }),

/***/ 60571:
/***/ ((module, exports, __webpack_require__) => {

/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
/* eslint-disable node/no-deprecated-api */
var buffer = __webpack_require__(78378)
var Buffer = buffer.Buffer

// alternative to using Object.keys for old browsers
function copyProps (src, dst) {
  for (var key in src) {
    dst[key] = src[key]
  }
}
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  module.exports = buffer
} else {
  // Copy properties from require('buffer')
  copyProps(buffer, exports)
  exports.Buffer = SafeBuffer
}

function SafeBuffer (arg, encodingOrOffset, length) {
  return Buffer(arg, encodingOrOffset, length)
}

SafeBuffer.prototype = Object.create(Buffer.prototype)

// Copy static methods from Buffer
copyProps(Buffer, SafeBuffer)

SafeBuffer.from = function (arg, encodingOrOffset, length) {
  if (typeof arg === 'number') {
    throw new TypeError('Argument must not be a number')
  }
  return Buffer(arg, encodingOrOffset, length)
}

SafeBuffer.alloc = function (size, fill, encoding) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  var buf = Buffer(size)
  if (fill !== undefined) {
    if (typeof encoding === 'string') {
      buf.fill(fill, encoding)
    } else {
      buf.fill(fill)
    }
  } else {
    buf.fill(0)
  }
  return buf
}

SafeBuffer.allocUnsafe = function (size) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  return Buffer(size)
}

SafeBuffer.allocUnsafeSlow = function (size) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  return buffer.SlowBuffer(size)
}


/***/ }),

/***/ 73725:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var Buffer = (__webpack_require__(60571).Buffer)

// prototype class for hash functions
function Hash (blockSize, finalSize) {
  this._block = Buffer.alloc(blockSize)
  this._finalSize = finalSize
  this._blockSize = blockSize
  this._len = 0
}

Hash.prototype.update = function (data, enc) {
  if (typeof data === 'string') {
    enc = enc || 'utf8'
    data = Buffer.from(data, enc)
  }

  var block = this._block
  var blockSize = this._blockSize
  var length = data.length
  var accum = this._len

  for (var offset = 0; offset < length;) {
    var assigned = accum % blockSize
    var remainder = Math.min(length - offset, blockSize - assigned)

    for (var i = 0; i < remainder; i++) {
      block[assigned + i] = data[offset + i]
    }

    accum += remainder
    offset += remainder

    if ((accum % blockSize) === 0) {
      this._update(block)
    }
  }

  this._len += length
  return this
}

Hash.prototype.digest = function (enc) {
  var rem = this._len % this._blockSize

  this._block[rem] = 0x80

  // zero (rem + 1) trailing bits, where (rem + 1) is the smallest
  // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
  this._block.fill(0, rem + 1)

  if (rem >= this._finalSize) {
    this._update(this._block)
    this._block.fill(0)
  }

  var bits = this._len * 8

  // uint32
  if (bits <= 0xffffffff) {
    this._block.writeUInt32BE(bits, this._blockSize - 4)

  // uint64
  } else {
    var lowBits = (bits & 0xffffffff) >>> 0
    var highBits = (bits - lowBits) / 0x100000000

    this._block.writeUInt32BE(highBits, this._blockSize - 8)
    this._block.writeUInt32BE(lowBits, this._blockSize - 4)
  }

  this._update(this._block)
  var hash = this._hash()

  return enc ? hash.toString(enc) : hash
}

Hash.prototype._update = function () {
  throw new Error('_update must be implemented by subclass')
}

module.exports = Hash


/***/ }),

/***/ 79997:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var exports = module.exports = function SHA (algorithm) {
  algorithm = algorithm.toLowerCase()

  var Algorithm = exports[algorithm]
  if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')

  return new Algorithm()
}

exports.sha = __webpack_require__(78139)
exports.sha1 = __webpack_require__(85956)
exports.sha224 = __webpack_require__(54467)
exports.sha256 = __webpack_require__(60330)
exports.sha384 = __webpack_require__(37378)
exports.sha512 = __webpack_require__(20288)


/***/ }),

/***/ 78139:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

/*
 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
 * in FIPS PUB 180-1
 * This source code is derived from sha1.js of the same repository.
 * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
 * operation was added.
 */

var inherits = __webpack_require__(72116)
var Hash = __webpack_require__(73725)
var Buffer = (__webpack_require__(60571).Buffer)

var K = [
  0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
]

var W = new Array(80)

function Sha () {
  this.init()
  this._w = W

  Hash.call(this, 64, 56)
}

inherits(Sha, Hash)

Sha.prototype.init = function () {
  this._a = 0x67452301
  this._b = 0xefcdab89
  this._c = 0x98badcfe
  this._d = 0x10325476
  this._e = 0xc3d2e1f0

  return this
}

function rotl5 (num) {
  return (num << 5) | (num >>> 27)
}

function rotl30 (num) {
  return (num << 30) | (num >>> 2)
}

function ft (s, b, c, d) {
  if (s === 0) return (b & c) | ((~b) & d)
  if (s === 2) return (b & c) | (b & d) | (c & d)
  return b ^ c ^ d
}

Sha.prototype._update = function (M) {
  var W = this._w

  var a = this._a | 0
  var b = this._b | 0
  var c = this._c | 0
  var d = this._d | 0
  var e = this._e | 0

  for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
  for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]

  for (var j = 0; j < 80; ++j) {
    var s = ~~(j / 20)
    var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0

    e = d
    d = c
    c = rotl30(b)
    b = a
    a = t
  }

  this._a = (a + this._a) | 0
  this._b = (b + this._b) | 0
  this._c = (c + this._c) | 0
  this._d = (d + this._d) | 0
  this._e = (e + this._e) | 0
}

Sha.prototype._hash = function () {
  var H = Buffer.allocUnsafe(20)

  H.writeInt32BE(this._a | 0, 0)
  H.writeInt32BE(this._b | 0, 4)
  H.writeInt32BE(this._c | 0, 8)
  H.writeInt32BE(this._d | 0, 12)
  H.writeInt32BE(this._e | 0, 16)

  return H
}

module.exports = Sha


/***/ }),

/***/ 85956:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

/*
 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
 * in FIPS PUB 180-1
 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for details.
 */

var inherits = __webpack_require__(72116)
var Hash = __webpack_require__(73725)
var Buffer = (__webpack_require__(60571).Buffer)

var K = [
  0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
]

var W = new Array(80)

function Sha1 () {
  this.init()
  this._w = W

  Hash.call(this, 64, 56)
}

inherits(Sha1, Hash)

Sha1.prototype.init = function () {
  this._a = 0x67452301
  this._b = 0xefcdab89
  this._c = 0x98badcfe
  this._d = 0x10325476
  this._e = 0xc3d2e1f0

  return this
}

function rotl1 (num) {
  return (num << 1) | (num >>> 31)
}

function rotl5 (num) {
  return (num << 5) | (num >>> 27)
}

function rotl30 (num) {
  return (num << 30) | (num >>> 2)
}

function ft (s, b, c, d) {
  if (s === 0) return (b & c) | ((~b) & d)
  if (s === 2) return (b & c) | (b & d) | (c & d)
  return b ^ c ^ d
}

Sha1.prototype._update = function (M) {
  var W = this._w

  var a = this._a | 0
  var b = this._b | 0
  var c = this._c | 0
  var d = this._d | 0
  var e = this._e | 0

  for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
  for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])

  for (var j = 0; j < 80; ++j) {
    var s = ~~(j / 20)
    var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0

    e = d
    d = c
    c = rotl30(b)
    b = a
    a = t
  }

  this._a = (a + this._a) | 0
  this._b = (b + this._b) | 0
  this._c = (c + this._c) | 0
  this._d = (d + this._d) | 0
  this._e = (e + this._e) | 0
}

Sha1.prototype._hash = function () {
  var H = Buffer.allocUnsafe(20)

  H.writeInt32BE(this._a | 0, 0)
  H.writeInt32BE(this._b | 0, 4)
  H.writeInt32BE(this._c | 0, 8)
  H.writeInt32BE(this._d | 0, 12)
  H.writeInt32BE(this._e | 0, 16)

  return H
}

module.exports = Sha1


/***/ }),

/***/ 54467:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

/**
 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
 * in FIPS 180-2
 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 *
 */

var inherits = __webpack_require__(72116)
var Sha256 = __webpack_require__(60330)
var Hash = __webpack_require__(73725)
var Buffer = (__webpack_require__(60571).Buffer)

var W = new Array(64)

function Sha224 () {
  this.init()

  this._w = W // new Array(64)

  Hash.call(this, 64, 56)
}

inherits(Sha224, Sha256)

Sha224.prototype.init = function () {
  this._a = 0xc1059ed8
  this._b = 0x367cd507
  this._c = 0x3070dd17
  this._d = 0xf70e5939
  this._e = 0xffc00b31
  this._f = 0x68581511
  this._g = 0x64f98fa7
  this._h = 0xbefa4fa4

  return this
}

Sha224.prototype._hash = function () {
  var H = Buffer.allocUnsafe(28)

  H.writeInt32BE(this._a, 0)
  H.writeInt32BE(this._b, 4)
  H.writeInt32BE(this._c, 8)
  H.writeInt32BE(this._d, 12)
  H.writeInt32BE(this._e, 16)
  H.writeInt32BE(this._f, 20)
  H.writeInt32BE(this._g, 24)

  return H
}

module.exports = Sha224


/***/ }),

/***/ 60330:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

/**
 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
 * in FIPS 180-2
 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 *
 */

var inherits = __webpack_require__(72116)
var Hash = __webpack_require__(73725)
var Buffer = (__webpack_require__(60571).Buffer)

var K = [
  0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
  0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
  0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
  0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
  0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
  0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
  0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
  0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
  0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
  0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
  0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
  0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
  0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
  0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
  0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
  0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
]

var W = new Array(64)

function Sha256 () {
  this.init()

  this._w = W // new Array(64)

  Hash.call(this, 64, 56)
}

inherits(Sha256, Hash)

Sha256.prototype.init = function () {
  this._a = 0x6a09e667
  this._b = 0xbb67ae85
  this._c = 0x3c6ef372
  this._d = 0xa54ff53a
  this._e = 0x510e527f
  this._f = 0x9b05688c
  this._g = 0x1f83d9ab
  this._h = 0x5be0cd19

  return this
}

function ch (x, y, z) {
  return z ^ (x & (y ^ z))
}

function maj (x, y, z) {
  return (x & y) | (z & (x | y))
}

function sigma0 (x) {
  return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
}

function sigma1 (x) {
  return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
}

function gamma0 (x) {
  return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
}

function gamma1 (x) {
  return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
}

Sha256.prototype._update = function (M) {
  var W = this._w

  var a = this._a | 0
  var b = this._b | 0
  var c = this._c | 0
  var d = this._d | 0
  var e = this._e | 0
  var f = this._f | 0
  var g = this._g | 0
  var h = this._h | 0

  for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
  for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0

  for (var j = 0; j < 64; ++j) {
    var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
    var T2 = (sigma0(a) + maj(a, b, c)) | 0

    h = g
    g = f
    f = e
    e = (d + T1) | 0
    d = c
    c = b
    b = a
    a = (T1 + T2) | 0
  }

  this._a = (a + this._a) | 0
  this._b = (b + this._b) | 0
  this._c = (c + this._c) | 0
  this._d = (d + this._d) | 0
  this._e = (e + this._e) | 0
  this._f = (f + this._f) | 0
  this._g = (g + this._g) | 0
  this._h = (h + this._h) | 0
}

Sha256.prototype._hash = function () {
  var H = Buffer.allocUnsafe(32)

  H.writeInt32BE(this._a, 0)
  H.writeInt32BE(this._b, 4)
  H.writeInt32BE(this._c, 8)
  H.writeInt32BE(this._d, 12)
  H.writeInt32BE(this._e, 16)
  H.writeInt32BE(this._f, 20)
  H.writeInt32BE(this._g, 24)
  H.writeInt32BE(this._h, 28)

  return H
}

module.exports = Sha256


/***/ }),

/***/ 37378:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var inherits = __webpack_require__(72116)
var SHA512 = __webpack_require__(20288)
var Hash = __webpack_require__(73725)
var Buffer = (__webpack_require__(60571).Buffer)

var W = new Array(160)

function Sha384 () {
  this.init()
  this._w = W

  Hash.call(this, 128, 112)
}

inherits(Sha384, SHA512)

Sha384.prototype.init = function () {
  this._ah = 0xcbbb9d5d
  this._bh = 0x629a292a
  this._ch = 0x9159015a
  this._dh = 0x152fecd8
  this._eh = 0x67332667
  this._fh = 0x8eb44a87
  this._gh = 0xdb0c2e0d
  this._hh = 0x47b5481d

  this._al = 0xc1059ed8
  this._bl = 0x367cd507
  this._cl = 0x3070dd17
  this._dl = 0xf70e5939
  this._el = 0xffc00b31
  this._fl = 0x68581511
  this._gl = 0x64f98fa7
  this._hl = 0xbefa4fa4

  return this
}

Sha384.prototype._hash = function () {
  var H = Buffer.allocUnsafe(48)

  function writeInt64BE (h, l, offset) {
    H.writeInt32BE(h, offset)
    H.writeInt32BE(l, offset + 4)
  }

  writeInt64BE(this._ah, this._al, 0)
  writeInt64BE(this._bh, this._bl, 8)
  writeInt64BE(this._ch, this._cl, 16)
  writeInt64BE(this._dh, this._dl, 24)
  writeInt64BE(this._eh, this._el, 32)
  writeInt64BE(this._fh, this._fl, 40)

  return H
}

module.exports = Sha384


/***/ }),

/***/ 20288:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var inherits = __webpack_require__(72116)
var Hash = __webpack_require__(73725)
var Buffer = (__webpack_require__(60571).Buffer)

var K = [
  0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
  0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
  0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
  0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
  0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
  0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
  0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
  0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
  0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
  0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
  0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
  0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
  0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
  0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
  0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
  0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
  0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
  0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
  0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
  0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
  0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
  0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
  0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
  0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
  0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
  0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
  0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
  0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
  0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
  0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
  0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
  0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
  0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
  0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
  0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
  0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
  0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
  0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
  0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
  0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
]

var W = new Array(160)

function Sha512 () {
  this.init()
  this._w = W

  Hash.call(this, 128, 112)
}

inherits(Sha512, Hash)

Sha512.prototype.init = function () {
  this._ah = 0x6a09e667
  this._bh = 0xbb67ae85
  this._ch = 0x3c6ef372
  this._dh = 0xa54ff53a
  this._eh = 0x510e527f
  this._fh = 0x9b05688c
  this._gh = 0x1f83d9ab
  this._hh = 0x5be0cd19

  this._al = 0xf3bcc908
  this._bl = 0x84caa73b
  this._cl = 0xfe94f82b
  this._dl = 0x5f1d36f1
  this._el = 0xade682d1
  this._fl = 0x2b3e6c1f
  this._gl = 0xfb41bd6b
  this._hl = 0x137e2179

  return this
}

function Ch (x, y, z) {
  return z ^ (x & (y ^ z))
}

function maj (x, y, z) {
  return (x & y) | (z & (x | y))
}

function sigma0 (x, xl) {
  return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
}

function sigma1 (x, xl) {
  return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
}

function Gamma0 (x, xl) {
  return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
}

function Gamma0l (x, xl) {
  return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
}

function Gamma1 (x, xl) {
  return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
}

function Gamma1l (x, xl) {
  return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
}

function getCarry (a, b) {
  return (a >>> 0) < (b >>> 0) ? 1 : 0
}

Sha512.prototype._update = function (M) {
  var W = this._w

  var ah = this._ah | 0
  var bh = this._bh | 0
  var ch = this._ch | 0
  var dh = this._dh | 0
  var eh = this._eh | 0
  var fh = this._fh | 0
  var gh = this._gh | 0
  var hh = this._hh | 0

  var al = this._al | 0
  var bl = this._bl | 0
  var cl = this._cl | 0
  var dl = this._dl | 0
  var el = this._el | 0
  var fl = this._fl | 0
  var gl = this._gl | 0
  var hl = this._hl | 0

  for (var i = 0; i < 32; i += 2) {
    W[i] = M.readInt32BE(i * 4)
    W[i + 1] = M.readInt32BE(i * 4 + 4)
  }
  for (; i < 160; i += 2) {
    var xh = W[i - 15 * 2]
    var xl = W[i - 15 * 2 + 1]
    var gamma0 = Gamma0(xh, xl)
    var gamma0l = Gamma0l(xl, xh)

    xh = W[i - 2 * 2]
    xl = W[i - 2 * 2 + 1]
    var gamma1 = Gamma1(xh, xl)
    var gamma1l = Gamma1l(xl, xh)

    // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
    var Wi7h = W[i - 7 * 2]
    var Wi7l = W[i - 7 * 2 + 1]

    var Wi16h = W[i - 16 * 2]
    var Wi16l = W[i - 16 * 2 + 1]

    var Wil = (gamma0l + Wi7l) | 0
    var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
    Wil = (Wil + gamma1l) | 0
    Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
    Wil = (Wil + Wi16l) | 0
    Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0

    W[i] = Wih
    W[i + 1] = Wil
  }

  for (var j = 0; j < 160; j += 2) {
    Wih = W[j]
    Wil = W[j + 1]

    var majh = maj(ah, bh, ch)
    var majl = maj(al, bl, cl)

    var sigma0h = sigma0(ah, al)
    var sigma0l = sigma0(al, ah)
    var sigma1h = sigma1(eh, el)
    var sigma1l = sigma1(el, eh)

    // t1 = h + sigma1 + ch + K[j] + W[j]
    var Kih = K[j]
    var Kil = K[j + 1]

    var chh = Ch(eh, fh, gh)
    var chl = Ch(el, fl, gl)

    var t1l = (hl + sigma1l) | 0
    var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
    t1l = (t1l + chl) | 0
    t1h = (t1h + chh + getCarry(t1l, chl)) | 0
    t1l = (t1l + Kil) | 0
    t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
    t1l = (t1l + Wil) | 0
    t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0

    // t2 = sigma0 + maj
    var t2l = (sigma0l + majl) | 0
    var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0

    hh = gh
    hl = gl
    gh = fh
    gl = fl
    fh = eh
    fl = el
    el = (dl + t1l) | 0
    eh = (dh + t1h + getCarry(el, dl)) | 0
    dh = ch
    dl = cl
    ch = bh
    cl = bl
    bh = ah
    bl = al
    al = (t1l + t2l) | 0
    ah = (t1h + t2h + getCarry(al, t1l)) | 0
  }

  this._al = (this._al + al) | 0
  this._bl = (this._bl + bl) | 0
  this._cl = (this._cl + cl) | 0
  this._dl = (this._dl + dl) | 0
  this._el = (this._el + el) | 0
  this._fl = (this._fl + fl) | 0
  this._gl = (this._gl + gl) | 0
  this._hl = (this._hl + hl) | 0

  this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
  this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
  this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
  this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
  this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
  this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
  this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
  this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
}

Sha512.prototype._hash = function () {
  var H = Buffer.allocUnsafe(64)

  function writeInt64BE (h, l, offset) {
    H.writeInt32BE(h, offset)
    H.writeInt32BE(l, offset + 4)
  }

  writeInt64BE(this._ah, this._al, 0)
  writeInt64BE(this._bh, this._bl, 8)
  writeInt64BE(this._ch, this._cl, 16)
  writeInt64BE(this._dh, this._dl, 24)
  writeInt64BE(this._eh, this._el, 32)
  writeInt64BE(this._fh, this._fl, 40)
  writeInt64BE(this._gh, this._gl, 48)
  writeInt64BE(this._hh, this._hl, 56)

  return H
}

module.exports = Sha512


/***/ }),

/***/ 4031:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
/*!
 * shallow-clone <https://github.com/jonschlinkert/shallow-clone>
 *
 * Copyright (c) 2015-present, Jon Schlinkert.
 * Released under the MIT License.
 */



const valueOf = Symbol.prototype.valueOf;
const typeOf = __webpack_require__(17884);

function clone(val, deep) {
  switch (typeOf(val)) {
    case 'array':
      return val.slice();
    case 'object':
      return Object.assign({}, val);
    case 'date':
      return new val.constructor(Number(val));
    case 'map':
      return new Map(val);
    case 'set':
      return new Set(val);
    case 'buffer':
      return cloneBuffer(val);
    case 'symbol':
      return cloneSymbol(val);
    case 'arraybuffer':
      return cloneArrayBuffer(val);
    case 'float32array':
    case 'float64array':
    case 'int16array':
    case 'int32array':
    case 'int8array':
    case 'uint16array':
    case 'uint32array':
    case 'uint8clampedarray':
    case 'uint8array':
      return cloneTypedArray(val);
    case 'regexp':
      return cloneRegExp(val);
    case 'error':
      return Object.create(val);
    default: {
      return val;
    }
  }
}

function cloneRegExp(val) {
  const flags = val.flags !== void 0 ? val.flags : (/\w+$/.exec(val) || void 0);
  const re = new val.constructor(val.source, flags);
  re.lastIndex = val.lastIndex;
  return re;
}

function cloneArrayBuffer(val) {
  const res = new val.constructor(val.byteLength);
  new Uint8Array(res).set(new Uint8Array(val));
  return res;
}

function cloneTypedArray(val, deep) {
  return new val.constructor(val.buffer, val.byteOffset, val.length);
}

function cloneBuffer(val) {
  const len = val.length;
  const buf = Buffer.allocUnsafe ? Buffer.allocUnsafe(len) : Buffer.from(len);
  val.copy(buf);
  return buf;
}

function cloneSymbol(val) {
  return valueOf ? Object(valueOf.call(val)) : {};
}

/**
 * Expose `clone`
 */

module.exports = clone;


/***/ }),

/***/ 63607:
/***/ ((module, exports, __webpack_require__) => {

var __WEBPACK_AMD_DEFINE_RESULT__;/* global window, exports, define */

!function() {
    'use strict'

    var re = {
        not_string: /[^s]/,
        not_bool: /[^t]/,
        not_type: /[^T]/,
        not_primitive: /[^v]/,
        number: /[diefg]/,
        numeric_arg: /[bcdiefguxX]/,
        json: /[j]/,
        not_json: /[^j]/,
        text: /^[^\x25]+/,
        modulo: /^\x25{2}/,
        placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
        key: /^([a-z_][a-z_\d]*)/i,
        key_access: /^\.([a-z_][a-z_\d]*)/i,
        index_access: /^\[(\d+)\]/,
        sign: /^[+-]/
    }

    function sprintf(key) {
        // `arguments` is not an array, but should be fine for this call
        return sprintf_format(sprintf_parse(key), arguments)
    }

    function vsprintf(fmt, argv) {
        return sprintf.apply(null, [fmt].concat(argv || []))
    }

    function sprintf_format(parse_tree, argv) {
        var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign
        for (i = 0; i < tree_length; i++) {
            if (typeof parse_tree[i] === 'string') {
                output += parse_tree[i]
            }
            else if (typeof parse_tree[i] === 'object') {
                ph = parse_tree[i] // convenience purposes only
                if (ph.keys) { // keyword argument
                    arg = argv[cursor]
                    for (k = 0; k < ph.keys.length; k++) {
                        if (arg == undefined) {
                            throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k-1]))
                        }
                        arg = arg[ph.keys[k]]
                    }
                }
                else if (ph.param_no) { // positional argument (explicit)
                    arg = argv[ph.param_no]
                }
                else { // positional argument (implicit)
                    arg = argv[cursor++]
                }

                if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
                    arg = arg()
                }

                if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {
                    throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))
                }

                if (re.number.test(ph.type)) {
                    is_positive = arg >= 0
                }

                switch (ph.type) {
                    case 'b':
                        arg = parseInt(arg, 10).toString(2)
                        break
                    case 'c':
                        arg = String.fromCharCode(parseInt(arg, 10))
                        break
                    case 'd':
                    case 'i':
                        arg = parseInt(arg, 10)
                        break
                    case 'j':
                        arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0)
                        break
                    case 'e':
                        arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential()
                        break
                    case 'f':
                        arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg)
                        break
                    case 'g':
                        arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg)
                        break
                    case 'o':
                        arg = (parseInt(arg, 10) >>> 0).toString(8)
                        break
                    case 's':
                        arg = String(arg)
                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
                        break
                    case 't':
                        arg = String(!!arg)
                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
                        break
                    case 'T':
                        arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()
                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
                        break
                    case 'u':
                        arg = parseInt(arg, 10) >>> 0
                        break
                    case 'v':
                        arg = arg.valueOf()
                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
                        break
                    case 'x':
                        arg = (parseInt(arg, 10) >>> 0).toString(16)
                        break
                    case 'X':
                        arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()
                        break
                }
                if (re.json.test(ph.type)) {
                    output += arg
                }
                else {
                    if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
                        sign = is_positive ? '+' : '-'
                        arg = arg.toString().replace(re.sign, '')
                    }
                    else {
                        sign = ''
                    }
                    pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' '
                    pad_length = ph.width - (sign + arg).length
                    pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''
                    output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)
                }
            }
        }
        return output
    }

    var sprintf_cache = Object.create(null)

    function sprintf_parse(fmt) {
        if (sprintf_cache[fmt]) {
            return sprintf_cache[fmt]
        }

        var _fmt = fmt, match, parse_tree = [], arg_names = 0
        while (_fmt) {
            if ((match = re.text.exec(_fmt)) !== null) {
                parse_tree.push(match[0])
            }
            else if ((match = re.modulo.exec(_fmt)) !== null) {
                parse_tree.push('%')
            }
            else if ((match = re.placeholder.exec(_fmt)) !== null) {
                if (match[2]) {
                    arg_names |= 1
                    var field_list = [], replacement_field = match[2], field_match = []
                    if ((field_match = re.key.exec(replacement_field)) !== null) {
                        field_list.push(field_match[1])
                        while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
                            if ((field_match = re.key_access.exec(replacement_field)) !== null) {
                                field_list.push(field_match[1])
                            }
                            else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
                                field_list.push(field_match[1])
                            }
                            else {
                                throw new SyntaxError('[sprintf] failed to parse named argument key')
                            }
                        }
                    }
                    else {
                        throw new SyntaxError('[sprintf] failed to parse named argument key')
                    }
                    match[2] = field_list
                }
                else {
                    arg_names |= 2
                }
                if (arg_names === 3) {
                    throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')
                }

                parse_tree.push(
                    {
                        placeholder: match[0],
                        param_no:    match[1],
                        keys:        match[2],
                        sign:        match[3],
                        pad_char:    match[4],
                        align:       match[5],
                        width:       match[6],
                        precision:   match[7],
                        type:        match[8]
                    }
                )
            }
            else {
                throw new SyntaxError('[sprintf] unexpected placeholder')
            }
            _fmt = _fmt.substring(match[0].length)
        }
        return sprintf_cache[fmt] = parse_tree
    }

    /**
     * export to either browser or node.js
     */
    /* eslint-disable quote-props */
    if (true) {
        exports.sprintf = sprintf
        exports.vsprintf = vsprintf
    }
    if (typeof window !== 'undefined') {
        window['sprintf'] = sprintf
        window['vsprintf'] = vsprintf

        if (true) {
            !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
                return {
                    'sprintf': sprintf,
                    'vsprintf': vsprintf
                }
            }).call(exports, __webpack_require__, exports, module),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))
        }
    }
    /* eslint-enable quote-props */
}(); // eslint-disable-line


/***/ }),

/***/ 51940:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

module.exports = Stream;

var EE = (__webpack_require__(93876).EventEmitter);
var inherits = __webpack_require__(72116);

inherits(Stream, EE);
Stream.Readable = __webpack_require__(5960);
Stream.Writable = __webpack_require__(26968);
Stream.Duplex = __webpack_require__(47514);
Stream.Transform = __webpack_require__(96646);
Stream.PassThrough = __webpack_require__(33308);
Stream.finished = __webpack_require__(21530)
Stream.pipeline = __webpack_require__(29586)

// Backwards-compat with node 0.4.x
Stream.Stream = Stream;



// old-style streams.  Note that the pipe method (the only relevant
// part of this class) is overridden in the Readable class.

function Stream() {
  EE.call(this);
}

Stream.prototype.pipe = function(dest, options) {
  var source = this;

  function ondata(chunk) {
    if (dest.writable) {
      if (false === dest.write(chunk) && source.pause) {
        source.pause();
      }
    }
  }

  source.on('data', ondata);

  function ondrain() {
    if (source.readable && source.resume) {
      source.resume();
    }
  }

  dest.on('drain', ondrain);

  // If the 'end' option is not supplied, dest.end() will be called when
  // source gets the 'end' or 'close' events.  Only dest.end() once.
  if (!dest._isStdio && (!options || options.end !== false)) {
    source.on('end', onend);
    source.on('close', onclose);
  }

  var didOnEnd = false;
  function onend() {
    if (didOnEnd) return;
    didOnEnd = true;

    dest.end();
  }


  function onclose() {
    if (didOnEnd) return;
    didOnEnd = true;

    if (typeof dest.destroy === 'function') dest.destroy();
  }

  // don't leave dangling pipes when there are errors.
  function onerror(er) {
    cleanup();
    if (EE.listenerCount(this, 'error') === 0) {
      throw er; // Unhandled stream error in pipe.
    }
  }

  source.on('error', onerror);
  dest.on('error', onerror);

  // remove all the event listeners that were added.
  function cleanup() {
    source.removeListener('data', ondata);
    dest.removeListener('drain', ondrain);

    source.removeListener('end', onend);
    source.removeListener('close', onclose);

    source.removeListener('error', onerror);
    dest.removeListener('error', onerror);

    source.removeListener('end', cleanup);
    source.removeListener('close', cleanup);

    dest.removeListener('close', cleanup);
  }

  source.on('end', cleanup);
  source.on('close', cleanup);

  dest.on('close', cleanup);

  dest.emit('pipe', source);

  // Allow for unix-like usage: A.pipe(B).pipe(C)
  return dest;
};


/***/ }),

/***/ 34156:
/***/ ((module) => {

"use strict";


const defaultAlphabetIndexMap = [];

function isNumberCode(code) {
  return code >= 48/* '0' */ && code <= 57/* '9' */;
}

function naturalCompare(a, b, opts) {
  if (typeof a !== 'string') {
    throw new TypeError(`The first argument must be a string. Received type '${typeof a}'`);
  }
  if (typeof b !== 'string') {
    throw new TypeError(`The second argument must be a string. Received type '${typeof b}'`);
  }

  const lengthA = a.length;
  const lengthB = b.length;
  let indexA = 0;
  let indexB = 0;
  let alphabetIndexMap = defaultAlphabetIndexMap;
  let firstDifferenceInLeadingZeros = 0;

  if (opts) {
    if (opts.caseInsensitive) {
      a = a.toLowerCase();
      b = b.toLowerCase();
    }

    if (opts.alphabet) {
      alphabetIndexMap = buildAlphabetIndexMap(opts.alphabet);
    }
  }

  while (indexA < lengthA && indexB < lengthB) {
    let charCodeA = a.charCodeAt(indexA);
    let charCodeB = b.charCodeAt(indexB);

    if (isNumberCode(charCodeA)) {
      if (!isNumberCode(charCodeB)) {
        return charCodeA - charCodeB;
      }

      let numStartA = indexA;
      let numStartB = indexB;

      while (charCodeA === 48/* '0' */ && ++numStartA < lengthA) {
        charCodeA = a.charCodeAt(numStartA);
      }
      while (charCodeB === 48/* '0' */ && ++numStartB < lengthB) {
        charCodeB = b.charCodeAt(numStartB);
      }

      if (numStartA !== numStartB && firstDifferenceInLeadingZeros === 0) {
        firstDifferenceInLeadingZeros = numStartA - numStartB;
      }

      let numEndA = numStartA;
      let numEndB = numStartB;

      while (numEndA < lengthA && isNumberCode(a.charCodeAt(numEndA))) {
        ++numEndA;
      }
      while (numEndB < lengthB && isNumberCode(b.charCodeAt(numEndB))) {
        ++numEndB;
      }

      let difference = numEndA - numStartA - numEndB + numStartB; // numA length - numB length
      if (difference !== 0) {
        return difference;
      }

      while (numStartA < numEndA) {
        difference = a.charCodeAt(numStartA++) - b.charCodeAt(numStartB++);
        if (difference !== 0) {
          return difference;
        }
      }

      indexA = numEndA;
      indexB = numEndB;
      continue;
    }

    if (charCodeA !== charCodeB) {
      if (
        charCodeA < alphabetIndexMap.length &&
        charCodeB < alphabetIndexMap.length &&
        alphabetIndexMap[charCodeA] !== -1 &&
        alphabetIndexMap[charCodeB] !== -1
      ) {
        return alphabetIndexMap[charCodeA] - alphabetIndexMap[charCodeB];
      }

      return charCodeA - charCodeB;
    }

    ++indexA;
    ++indexB;
  }

  if (indexA < lengthA) { // `b` is a substring of `a`
    return 1;
  }

  if (indexB < lengthB) { // `a` is a substring of `b`
    return -1;
  }

  return firstDifferenceInLeadingZeros;
}

const alphabetIndexMapCache = {};

function buildAlphabetIndexMap(alphabet) {
  const existingMap = alphabetIndexMapCache[alphabet];
  if (existingMap !== undefined) {
    return existingMap;
  }

  const indexMap = [];
  const maxCharCode = alphabet.split('').reduce((maxCode, char) => {
    return Math.max(maxCode, char.charCodeAt(0));
  }, 0);

  for (let i = 0; i <= maxCharCode; i++) {
    indexMap.push(-1);
  }

  for (let i = 0; i < alphabet.length; i++) {
    indexMap[alphabet.charCodeAt(i)] = i;
  }

  alphabetIndexMapCache[alphabet] = indexMap;

  return indexMap;
}

module.exports = naturalCompare;


/***/ }),

/***/ 32630:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.



/*<replacement>*/

var Buffer = (__webpack_require__(86399).Buffer);
/*</replacement>*/

var isEncoding = Buffer.isEncoding || function (encoding) {
  encoding = '' + encoding;
  switch (encoding && encoding.toLowerCase()) {
    case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
      return true;
    default:
      return false;
  }
};

function _normalizeEncoding(enc) {
  if (!enc) return 'utf8';
  var retried;
  while (true) {
    switch (enc) {
      case 'utf8':
      case 'utf-8':
        return 'utf8';
      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return 'utf16le';
      case 'latin1':
      case 'binary':
        return 'latin1';
      case 'base64':
      case 'ascii':
      case 'hex':
        return enc;
      default:
        if (retried) return; // undefined
        enc = ('' + enc).toLowerCase();
        retried = true;
    }
  }
};

// Do not cache `Buffer.isEncoding` when checking encoding names as some
// modules monkey-patch it to support additional encodings
function normalizeEncoding(enc) {
  var nenc = _normalizeEncoding(enc);
  if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  return nenc || enc;
}

// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters.
exports.I = StringDecoder;
function StringDecoder(encoding) {
  this.encoding = normalizeEncoding(encoding);
  var nb;
  switch (this.encoding) {
    case 'utf16le':
      this.text = utf16Text;
      this.end = utf16End;
      nb = 4;
      break;
    case 'utf8':
      this.fillLast = utf8FillLast;
      nb = 4;
      break;
    case 'base64':
      this.text = base64Text;
      this.end = base64End;
      nb = 3;
      break;
    default:
      this.write = simpleWrite;
      this.end = simpleEnd;
      return;
  }
  this.lastNeed = 0;
  this.lastTotal = 0;
  this.lastChar = Buffer.allocUnsafe(nb);
}

StringDecoder.prototype.write = function (buf) {
  if (buf.length === 0) return '';
  var r;
  var i;
  if (this.lastNeed) {
    r = this.fillLast(buf);
    if (r === undefined) return '';
    i = this.lastNeed;
    this.lastNeed = 0;
  } else {
    i = 0;
  }
  if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  return r || '';
};

StringDecoder.prototype.end = utf8End;

// Returns only complete characters in a Buffer
StringDecoder.prototype.text = utf8Text;

// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
StringDecoder.prototype.fillLast = function (buf) {
  if (this.lastNeed <= buf.length) {
    buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
    return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  }
  buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  this.lastNeed -= buf.length;
};

// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
// continuation byte. If an invalid byte is detected, -2 is returned.
function utf8CheckByte(byte) {
  if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
  return byte >> 6 === 0x02 ? -1 : -2;
}

// Checks at most 3 bytes at the end of a Buffer in order to detect an
// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
// needed to complete the UTF-8 character (if applicable) are returned.
function utf8CheckIncomplete(self, buf, i) {
  var j = buf.length - 1;
  if (j < i) return 0;
  var nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) self.lastNeed = nb - 1;
    return nb;
  }
  if (--j < i || nb === -2) return 0;
  nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) self.lastNeed = nb - 2;
    return nb;
  }
  if (--j < i || nb === -2) return 0;
  nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) {
      if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
    }
    return nb;
  }
  return 0;
}

// Validates as many continuation bytes for a multi-byte UTF-8 character as
// needed or are available. If we see a non-continuation byte where we expect
// one, we "replace" the validated continuation bytes we've seen so far with
// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
// behavior. The continuation byte check is included three times in the case
// where all of the continuation bytes for a character exist in the same buffer.
// It is also done this way as a slight performance increase instead of using a
// loop.
function utf8CheckExtraBytes(self, buf, p) {
  if ((buf[0] & 0xC0) !== 0x80) {
    self.lastNeed = 0;
    return '\ufffd';
  }
  if (self.lastNeed > 1 && buf.length > 1) {
    if ((buf[1] & 0xC0) !== 0x80) {
      self.lastNeed = 1;
      return '\ufffd';
    }
    if (self.lastNeed > 2 && buf.length > 2) {
      if ((buf[2] & 0xC0) !== 0x80) {
        self.lastNeed = 2;
        return '\ufffd';
      }
    }
  }
}

// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
function utf8FillLast(buf) {
  var p = this.lastTotal - this.lastNeed;
  var r = utf8CheckExtraBytes(this, buf, p);
  if (r !== undefined) return r;
  if (this.lastNeed <= buf.length) {
    buf.copy(this.lastChar, p, 0, this.lastNeed);
    return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  }
  buf.copy(this.lastChar, p, 0, buf.length);
  this.lastNeed -= buf.length;
}

// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
// partial character, the character's bytes are buffered until the required
// number of bytes are available.
function utf8Text(buf, i) {
  var total = utf8CheckIncomplete(this, buf, i);
  if (!this.lastNeed) return buf.toString('utf8', i);
  this.lastTotal = total;
  var end = buf.length - (total - this.lastNeed);
  buf.copy(this.lastChar, 0, end);
  return buf.toString('utf8', i, end);
}

// For UTF-8, a replacement character is added when ending on a partial
// character.
function utf8End(buf) {
  var r = buf && buf.length ? this.write(buf) : '';
  if (this.lastNeed) return r + '\ufffd';
  return r;
}

// UTF-16LE typically needs two bytes per character, but even if we have an even
// number of bytes available, we need to check if we end on a leading/high
// surrogate. In that case, we need to wait for the next two bytes in order to
// decode the last character properly.
function utf16Text(buf, i) {
  if ((buf.length - i) % 2 === 0) {
    var r = buf.toString('utf16le', i);
    if (r) {
      var c = r.charCodeAt(r.length - 1);
      if (c >= 0xD800 && c <= 0xDBFF) {
        this.lastNeed = 2;
        this.lastTotal = 4;
        this.lastChar[0] = buf[buf.length - 2];
        this.lastChar[1] = buf[buf.length - 1];
        return r.slice(0, -1);
      }
    }
    return r;
  }
  this.lastNeed = 1;
  this.lastTotal = 2;
  this.lastChar[0] = buf[buf.length - 1];
  return buf.toString('utf16le', i, buf.length - 1);
}

// For UTF-16LE we do not explicitly append special replacement characters if we
// end on a partial character, we simply let v8 handle that.
function utf16End(buf) {
  var r = buf && buf.length ? this.write(buf) : '';
  if (this.lastNeed) {
    var end = this.lastTotal - this.lastNeed;
    return r + this.lastChar.toString('utf16le', 0, end);
  }
  return r;
}

function base64Text(buf, i) {
  var n = (buf.length - i) % 3;
  if (n === 0) return buf.toString('base64', i);
  this.lastNeed = 3 - n;
  this.lastTotal = 3;
  if (n === 1) {
    this.lastChar[0] = buf[buf.length - 1];
  } else {
    this.lastChar[0] = buf[buf.length - 2];
    this.lastChar[1] = buf[buf.length - 1];
  }
  return buf.toString('base64', i, buf.length - n);
}

function base64End(buf) {
  var r = buf && buf.length ? this.write(buf) : '';
  if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  return r;
}

// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
function simpleWrite(buf) {
  return buf.toString(this.encoding);
}

function simpleEnd(buf) {
  return buf && buf.length ? this.write(buf) : '';
}

/***/ }),

/***/ 63205:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.



/*<replacement>*/

var Buffer = (__webpack_require__(60571).Buffer);
/*</replacement>*/

var isEncoding = Buffer.isEncoding || function (encoding) {
  encoding = '' + encoding;
  switch (encoding && encoding.toLowerCase()) {
    case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
      return true;
    default:
      return false;
  }
};

function _normalizeEncoding(enc) {
  if (!enc) return 'utf8';
  var retried;
  while (true) {
    switch (enc) {
      case 'utf8':
      case 'utf-8':
        return 'utf8';
      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return 'utf16le';
      case 'latin1':
      case 'binary':
        return 'latin1';
      case 'base64':
      case 'ascii':
      case 'hex':
        return enc;
      default:
        if (retried) return; // undefined
        enc = ('' + enc).toLowerCase();
        retried = true;
    }
  }
};

// Do not cache `Buffer.isEncoding` when checking encoding names as some
// modules monkey-patch it to support additional encodings
function normalizeEncoding(enc) {
  var nenc = _normalizeEncoding(enc);
  if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  return nenc || enc;
}

// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters.
exports.I = StringDecoder;
function StringDecoder(encoding) {
  this.encoding = normalizeEncoding(encoding);
  var nb;
  switch (this.encoding) {
    case 'utf16le':
      this.text = utf16Text;
      this.end = utf16End;
      nb = 4;
      break;
    case 'utf8':
      this.fillLast = utf8FillLast;
      nb = 4;
      break;
    case 'base64':
      this.text = base64Text;
      this.end = base64End;
      nb = 3;
      break;
    default:
      this.write = simpleWrite;
      this.end = simpleEnd;
      return;
  }
  this.lastNeed = 0;
  this.lastTotal = 0;
  this.lastChar = Buffer.allocUnsafe(nb);
}

StringDecoder.prototype.write = function (buf) {
  if (buf.length === 0) return '';
  var r;
  var i;
  if (this.lastNeed) {
    r = this.fillLast(buf);
    if (r === undefined) return '';
    i = this.lastNeed;
    this.lastNeed = 0;
  } else {
    i = 0;
  }
  if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  return r || '';
};

StringDecoder.prototype.end = utf8End;

// Returns only complete characters in a Buffer
StringDecoder.prototype.text = utf8Text;

// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
StringDecoder.prototype.fillLast = function (buf) {
  if (this.lastNeed <= buf.length) {
    buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
    return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  }
  buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  this.lastNeed -= buf.length;
};

// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
// continuation byte. If an invalid byte is detected, -2 is returned.
function utf8CheckByte(byte) {
  if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
  return byte >> 6 === 0x02 ? -1 : -2;
}

// Checks at most 3 bytes at the end of a Buffer in order to detect an
// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
// needed to complete the UTF-8 character (if applicable) are returned.
function utf8CheckIncomplete(self, buf, i) {
  var j = buf.length - 1;
  if (j < i) return 0;
  var nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) self.lastNeed = nb - 1;
    return nb;
  }
  if (--j < i || nb === -2) return 0;
  nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) self.lastNeed = nb - 2;
    return nb;
  }
  if (--j < i || nb === -2) return 0;
  nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) {
      if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
    }
    return nb;
  }
  return 0;
}

// Validates as many continuation bytes for a multi-byte UTF-8 character as
// needed or are available. If we see a non-continuation byte where we expect
// one, we "replace" the validated continuation bytes we've seen so far with
// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
// behavior. The continuation byte check is included three times in the case
// where all of the continuation bytes for a character exist in the same buffer.
// It is also done this way as a slight performance increase instead of using a
// loop.
function utf8CheckExtraBytes(self, buf, p) {
  if ((buf[0] & 0xC0) !== 0x80) {
    self.lastNeed = 0;
    return '\ufffd';
  }
  if (self.lastNeed > 1 && buf.length > 1) {
    if ((buf[1] & 0xC0) !== 0x80) {
      self.lastNeed = 1;
      return '\ufffd';
    }
    if (self.lastNeed > 2 && buf.length > 2) {
      if ((buf[2] & 0xC0) !== 0x80) {
        self.lastNeed = 2;
        return '\ufffd';
      }
    }
  }
}

// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
function utf8FillLast(buf) {
  var p = this.lastTotal - this.lastNeed;
  var r = utf8CheckExtraBytes(this, buf, p);
  if (r !== undefined) return r;
  if (this.lastNeed <= buf.length) {
    buf.copy(this.lastChar, p, 0, this.lastNeed);
    return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  }
  buf.copy(this.lastChar, p, 0, buf.length);
  this.lastNeed -= buf.length;
}

// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
// partial character, the character's bytes are buffered until the required
// number of bytes are available.
function utf8Text(buf, i) {
  var total = utf8CheckIncomplete(this, buf, i);
  if (!this.lastNeed) return buf.toString('utf8', i);
  this.lastTotal = total;
  var end = buf.length - (total - this.lastNeed);
  buf.copy(this.lastChar, 0, end);
  return buf.toString('utf8', i, end);
}

// For UTF-8, a replacement character is added when ending on a partial
// character.
function utf8End(buf) {
  var r = buf && buf.length ? this.write(buf) : '';
  if (this.lastNeed) return r + '\ufffd';
  return r;
}

// UTF-16LE typically needs two bytes per character, but even if we have an even
// number of bytes available, we need to check if we end on a leading/high
// surrogate. In that case, we need to wait for the next two bytes in order to
// decode the last character properly.
function utf16Text(buf, i) {
  if ((buf.length - i) % 2 === 0) {
    var r = buf.toString('utf16le', i);
    if (r) {
      var c = r.charCodeAt(r.length - 1);
      if (c >= 0xD800 && c <= 0xDBFF) {
        this.lastNeed = 2;
        this.lastTotal = 4;
        this.lastChar[0] = buf[buf.length - 2];
        this.lastChar[1] = buf[buf.length - 1];
        return r.slice(0, -1);
      }
    }
    return r;
  }
  this.lastNeed = 1;
  this.lastTotal = 2;
  this.lastChar[0] = buf[buf.length - 1];
  return buf.toString('utf16le', i, buf.length - 1);
}

// For UTF-16LE we do not explicitly append special replacement characters if we
// end on a partial character, we simply let v8 handle that.
function utf16End(buf) {
  var r = buf && buf.length ? this.write(buf) : '';
  if (this.lastNeed) {
    var end = this.lastTotal - this.lastNeed;
    return r + this.lastChar.toString('utf16le', 0, end);
  }
  return r;
}

function base64Text(buf, i) {
  var n = (buf.length - i) % 3;
  if (n === 0) return buf.toString('base64', i);
  this.lastNeed = 3 - n;
  this.lastTotal = 3;
  if (n === 1) {
    this.lastChar[0] = buf[buf.length - 1];
  } else {
    this.lastChar[0] = buf[buf.length - 2];
    this.lastChar[1] = buf[buf.length - 1];
  }
  return buf.toString('base64', i, buf.length - n);
}

function base64End(buf) {
  var r = buf && buf.length ? this.write(buf) : '';
  if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  return r;
}

// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
function simpleWrite(buf) {
  return buf.toString(this.encoding);
}

function simpleEnd(buf) {
  return buf && buf.length ? this.write(buf) : '';
}

/***/ }),

/***/ 13548:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  FB: () => (/* binding */ es6_getDomain),
  EW: () => (/* binding */ getHostname),
  pj: () => (/* binding */ getPublicSuffix),
  qg: () => (/* binding */ parse)
});

// UNUSED EXPORTS: getDomainWithoutSuffix, getSubdomain

;// ./node_modules/.pnpm/tldts-core@5.7.112/node_modules/tldts-core/dist/es6/src/domain.js
/**
 * Check if `vhost` is a valid suffix of `hostname` (top-domain)
 *
 * It means that `vhost` needs to be a suffix of `hostname` and we then need to
 * make sure that: either they are equal, or the character preceding `vhost` in
 * `hostname` is a '.' (it should not be a partial label).
 *
 * * hostname = 'not.evil.com' and vhost = 'vil.com'      => not ok
 * * hostname = 'not.evil.com' and vhost = 'evil.com'     => ok
 * * hostname = 'not.evil.com' and vhost = 'not.evil.com' => ok
 */
function shareSameDomainSuffix(hostname, vhost) {
    if (hostname.endsWith(vhost)) {
        return (hostname.length === vhost.length ||
            hostname[hostname.length - vhost.length - 1] === '.');
    }
    return false;
}
/**
 * Given a hostname and its public suffix, extract the general domain.
 */
function extractDomainWithSuffix(hostname, publicSuffix) {
    // Locate the index of the last '.' in the part of the `hostname` preceding
    // the public suffix.
    //
    // examples:
    //   1. not.evil.co.uk  => evil.co.uk
    //         ^    ^
    //         |    | start of public suffix
    //         | index of the last dot
    //
    //   2. example.co.uk   => example.co.uk
    //     ^       ^
    //     |       | start of public suffix
    //     |
    //     | (-1) no dot found before the public suffix
    const publicSuffixIndex = hostname.length - publicSuffix.length - 2;
    const lastDotBeforeSuffixIndex = hostname.lastIndexOf('.', publicSuffixIndex);
    // No '.' found, then `hostname` is the general domain (no sub-domain)
    if (lastDotBeforeSuffixIndex === -1) {
        return hostname;
    }
    // Extract the part between the last '.'
    return hostname.slice(lastDotBeforeSuffixIndex + 1);
}
/**
 * Detects the domain based on rules and upon and a host string
 */
function getDomain(suffix, hostname, options) {
    // Check if `hostname` ends with a member of `validHosts`.
    if (options.validHosts !== null) {
        const validHosts = options.validHosts;
        for (let i = 0; i < validHosts.length; i += 1) {
            const vhost = validHosts[i];
            if ( /*@__INLINE__*/shareSameDomainSuffix(hostname, vhost) === true) {
                return vhost;
            }
        }
    }
    // If `hostname` is a valid public suffix, then there is no domain to return.
    // Since we already know that `getPublicSuffix` returns a suffix of `hostname`
    // there is no need to perform a string comparison and we only compare the
    // size.
    if (suffix.length === hostname.length) {
        return null;
    }
    // To extract the general domain, we start by identifying the public suffix
    // (if any), then consider the domain to be the public suffix with one added
    // level of depth. (e.g.: if hostname is `not.evil.co.uk` and public suffix:
    // `co.uk`, then we take one more level: `evil`, giving the final result:
    // `evil.co.uk`).
    return /*@__INLINE__*/ extractDomainWithSuffix(hostname, suffix);
}

;// ./node_modules/.pnpm/tldts-core@5.7.112/node_modules/tldts-core/dist/es6/src/domain-without-suffix.js
/**
 * Return the part of domain without suffix.
 *
 * Example: for domain 'foo.com', the result would be 'foo'.
 */
function getDomainWithoutSuffix(domain, suffix) {
    // Note: here `domain` and `suffix` cannot have the same length because in
    // this case we set `domain` to `null` instead. It is thus safe to assume
    // that `suffix` is shorter than `domain`.
    return domain.slice(0, -suffix.length - 1);
}

;// ./node_modules/.pnpm/tldts-core@5.7.112/node_modules/tldts-core/dist/es6/src/extract-hostname.js
/**
 * @param url - URL we want to extract a hostname from.
 * @param urlIsValidHostname - hint from caller; true if `url` is already a valid hostname.
 */
function extractHostname(url, urlIsValidHostname) {
    let start = 0;
    let end = url.length;
    let hasUpper = false;
    // If url is not already a valid hostname, then try to extract hostname.
    if (urlIsValidHostname === false) {
        // Special handling of data URLs
        if (url.startsWith('data:') === true) {
            return null;
        }
        // Trim leading spaces
        while (start < url.length && url.charCodeAt(start) <= 32) {
            start += 1;
        }
        // Trim trailing spaces
        while (end > start + 1 && url.charCodeAt(end - 1) <= 32) {
            end -= 1;
        }
        // Skip scheme.
        if (url.charCodeAt(start) === 47 /* '/' */ &&
            url.charCodeAt(start + 1) === 47 /* '/' */) {
            start += 2;
        }
        else {
            const indexOfProtocol = url.indexOf(':/', start);
            if (indexOfProtocol !== -1) {
                // Implement fast-path for common protocols. We expect most protocols
                // should be one of these 4 and thus we will not need to perform the
                // more expansive validity check most of the time.
                const protocolSize = indexOfProtocol - start;
                const c0 = url.charCodeAt(start);
                const c1 = url.charCodeAt(start + 1);
                const c2 = url.charCodeAt(start + 2);
                const c3 = url.charCodeAt(start + 3);
                const c4 = url.charCodeAt(start + 4);
                if (protocolSize === 5 &&
                    c0 === 104 /* 'h' */ &&
                    c1 === 116 /* 't' */ &&
                    c2 === 116 /* 't' */ &&
                    c3 === 112 /* 'p' */ &&
                    c4 === 115 /* 's' */) {
                    // https
                }
                else if (protocolSize === 4 &&
                    c0 === 104 /* 'h' */ &&
                    c1 === 116 /* 't' */ &&
                    c2 === 116 /* 't' */ &&
                    c3 === 112 /* 'p' */) {
                    // http
                }
                else if (protocolSize === 3 &&
                    c0 === 119 /* 'w' */ &&
                    c1 === 115 /* 's' */ &&
                    c2 === 115 /* 's' */) {
                    // wss
                }
                else if (protocolSize === 2 &&
                    c0 === 119 /* 'w' */ &&
                    c1 === 115 /* 's' */) {
                    // ws
                }
                else {
                    // Check that scheme is valid
                    for (let i = start; i < indexOfProtocol; i += 1) {
                        const lowerCaseCode = url.charCodeAt(i) | 32;
                        if (((lowerCaseCode >= 97 && lowerCaseCode <= 122) || // [a, z]
                            (lowerCaseCode >= 48 && lowerCaseCode <= 57) || // [0, 9]
                            lowerCaseCode === 46 || // '.'
                            lowerCaseCode === 45 || // '-'
                            lowerCaseCode === 43) === false // '+'
                        ) {
                            return null;
                        }
                    }
                }
                // Skip 0, 1 or more '/' after ':/'
                start = indexOfProtocol + 2;
                while (url.charCodeAt(start) === 47 /* '/' */) {
                    start += 1;
                }
            }
        }
        // Detect first occurrence of '/', '?' or '#'. We also keep track of the
        // last occurrence of '@', ']' or ':' to speed-up subsequent parsing of
        // (respectively), identifier, ipv6 or port.
        let indexOfIdentifier = -1;
        let indexOfClosingBracket = -1;
        let indexOfPort = -1;
        for (let i = start; i < end; i += 1) {
            const code = url.charCodeAt(i);
            if (code === 35 || // '#'
                code === 47 || // '/'
                code === 63 // '?'
            ) {
                end = i;
                break;
            }
            else if (code === 64) {
                // '@'
                indexOfIdentifier = i;
            }
            else if (code === 93) {
                // ']'
                indexOfClosingBracket = i;
            }
            else if (code === 58) {
                // ':'
                indexOfPort = i;
            }
            else if (code >= 65 && code <= 90) {
                hasUpper = true;
            }
        }
        // Detect identifier: '@'
        if (indexOfIdentifier !== -1 &&
            indexOfIdentifier > start &&
            indexOfIdentifier < end) {
            start = indexOfIdentifier + 1;
        }
        // Handle ipv6 addresses
        if (url.charCodeAt(start) === 91 /* '[' */) {
            if (indexOfClosingBracket !== -1) {
                return url.slice(start + 1, indexOfClosingBracket).toLowerCase();
            }
            return null;
        }
        else if (indexOfPort !== -1 && indexOfPort > start && indexOfPort < end) {
            // Detect port: ':'
            end = indexOfPort;
        }
    }
    // Trim trailing dots
    while (end > start + 1 && url.charCodeAt(end - 1) === 46 /* '.' */) {
        end -= 1;
    }
    const hostname = start !== 0 || end !== url.length ? url.slice(start, end) : url;
    if (hasUpper) {
        return hostname.toLowerCase();
    }
    return hostname;
}

;// ./node_modules/.pnpm/tldts-core@5.7.112/node_modules/tldts-core/dist/es6/src/is-ip.js
/**
 * Check if a hostname is an IP. You should be aware that this only works
 * because `hostname` is already garanteed to be a valid hostname!
 */
function isProbablyIpv4(hostname) {
    // Cannot be shorted than 1.1.1.1
    if (hostname.length < 7) {
        return false;
    }
    // Cannot be longer than: 255.255.255.255
    if (hostname.length > 15) {
        return false;
    }
    let numberOfDots = 0;
    for (let i = 0; i < hostname.length; i += 1) {
        const code = hostname.charCodeAt(i);
        if (code === 46 /* '.' */) {
            numberOfDots += 1;
        }
        else if (code < 48 /* '0' */ || code > 57 /* '9' */) {
            return false;
        }
    }
    return (numberOfDots === 3 &&
        hostname.charCodeAt(0) !== 46 /* '.' */ &&
        hostname.charCodeAt(hostname.length - 1) !== 46 /* '.' */);
}
/**
 * Similar to isProbablyIpv4.
 */
function isProbablyIpv6(hostname) {
    if (hostname.length < 3) {
        return false;
    }
    let start = hostname[0] === '[' ? 1 : 0;
    let end = hostname.length;
    if (hostname[end - 1] === ']') {
        end -= 1;
    }
    // We only consider the maximum size of a normal IPV6. Note that this will
    // fail on so-called "IPv4 mapped IPv6 addresses" but this is a corner-case
    // and a proper validation library should be used for these.
    if (end - start > 39) {
        return false;
    }
    let hasColon = false;
    for (; start < end; start += 1) {
        const code = hostname.charCodeAt(start);
        if (code === 58 /* ':' */) {
            hasColon = true;
        }
        else if (((code >= 48 && code <= 57) || // 0-9
            (code >= 97 && code <= 102) || // a-f
            (code >= 65 && code <= 90)) === // A-F
            false) {
            return false;
        }
    }
    return hasColon;
}
/**
 * Check if `hostname` is *probably* a valid ip addr (either ipv6 or ipv4).
 * This *will not* work on any string. We need `hostname` to be a valid
 * hostname.
 */
function isIp(hostname) {
    return isProbablyIpv6(hostname) || isProbablyIpv4(hostname);
}

;// ./node_modules/.pnpm/tldts-core@5.7.112/node_modules/tldts-core/dist/es6/src/is-valid.js
/**
 * Implements fast shallow verification of hostnames. This does not perform a
 * struct check on the content of labels (classes of Unicode characters, etc.)
 * but instead check that the structure is valid (number of labels, length of
 * labels, etc.).
 *
 * If you need stricter validation, consider using an external library.
 */
function isValidAscii(code) {
    return ((code >= 97 && code <= 122) || (code >= 48 && code <= 57) || code > 127);
}
/**
 * Check if a hostname string is valid. It's usually a preliminary check before
 * trying to use getDomain or anything else.
 *
 * Beware: it does not check if the TLD exists.
 */
/* harmony default export */ function is_valid(hostname) {
    if (hostname.length > 255) {
        return false;
    }
    if (hostname.length === 0) {
        return false;
    }
    if ( /*@__INLINE__*/isValidAscii(hostname.charCodeAt(0)) === false) {
        return false;
    }
    // Validate hostname according to RFC
    let lastDotIndex = -1;
    let lastCharCode = -1;
    const len = hostname.length;
    for (let i = 0; i < len; i += 1) {
        const code = hostname.charCodeAt(i);
        if (code === 46 /* '.' */) {
            if (
            // Check that previous label is < 63 bytes long (64 = 63 + '.')
            i - lastDotIndex > 64 ||
                // Check that previous character was not already a '.'
                lastCharCode === 46 ||
                // Check that the previous label does not end with a '-' (dash)
                lastCharCode === 45 ||
                // Check that the previous label does not end with a '_' (underscore)
                lastCharCode === 95) {
                return false;
            }
            lastDotIndex = i;
        }
        else if (( /*@__INLINE__*/isValidAscii(code) || code === 45 || code === 95) ===
            false) {
            // Check if there is a forbidden character in the label
            return false;
        }
        lastCharCode = code;
    }
    return (
    // Check that last label is shorter than 63 chars
    len - lastDotIndex - 1 <= 63 &&
        // Check that the last character is an allowed trailing label character.
        // Since we already checked that the char is a valid hostname character,
        // we only need to check that it's different from '-'.
        lastCharCode !== 45);
}

;// ./node_modules/.pnpm/tldts-core@5.7.112/node_modules/tldts-core/dist/es6/src/options.js
function setDefaultsImpl({ allowIcannDomains = true, allowPrivateDomains = false, detectIp = true, extractHostname = true, mixedInputs = true, validHosts = null, validateHostname = true, }) {
    return {
        allowIcannDomains,
        allowPrivateDomains,
        detectIp,
        extractHostname,
        mixedInputs,
        validHosts,
        validateHostname,
    };
}
const DEFAULT_OPTIONS = /*@__INLINE__*/ setDefaultsImpl({});
function setDefaults(options) {
    if (options === undefined) {
        return DEFAULT_OPTIONS;
    }
    return /*@__INLINE__*/ setDefaultsImpl(options);
}

;// ./node_modules/.pnpm/tldts-core@5.7.112/node_modules/tldts-core/dist/es6/src/subdomain.js
/**
 * Returns the subdomain of a hostname string
 */
function getSubdomain(hostname, domain) {
    // If `hostname` and `domain` are the same, then there is no sub-domain
    if (domain.length === hostname.length) {
        return '';
    }
    return hostname.slice(0, -domain.length - 1);
}

;// ./node_modules/.pnpm/tldts-core@5.7.112/node_modules/tldts-core/dist/es6/src/factory.js
/**
 * Implement a factory allowing to plug different implementations of suffix
 * lookup (e.g.: using a trie or the packed hashes datastructures). This is used
 * and exposed in `tldts.ts` and `tldts-experimental.ts` bundle entrypoints.
 */







function getEmptyResult() {
    return {
        domain: null,
        domainWithoutSuffix: null,
        hostname: null,
        isIcann: null,
        isIp: null,
        isPrivate: null,
        publicSuffix: null,
        subdomain: null,
    };
}
function factory_resetResult(result) {
    result.domain = null;
    result.domainWithoutSuffix = null;
    result.hostname = null;
    result.isIcann = null;
    result.isIp = null;
    result.isPrivate = null;
    result.publicSuffix = null;
    result.subdomain = null;
}
function factory_parseImpl(url, step, suffixLookup, partialOptions, result) {
    const options = /*@__INLINE__*/ setDefaults(partialOptions);
    // Very fast approximate check to make sure `url` is a string. This is needed
    // because the library will not necessarily be used in a typed setup and
    // values of arbitrary types might be given as argument.
    if (typeof url !== 'string') {
        return result;
    }
    // Extract hostname from `url` only if needed. This can be made optional
    // using `options.extractHostname`. This option will typically be used
    // whenever we are sure the inputs to `parse` are already hostnames and not
    // arbitrary URLs.
    //
    // `mixedInput` allows to specify if we expect a mix of URLs and hostnames
    // as input. If only hostnames are expected then `extractHostname` can be
    // set to `false` to speed-up parsing. If only URLs are expected then
    // `mixedInputs` can be set to `false`. The `mixedInputs` is only a hint
    // and will not change the behavior of the library.
    if (options.extractHostname === false) {
        result.hostname = url;
    }
    else if (options.mixedInputs === true) {
        result.hostname = extractHostname(url, is_valid(url));
    }
    else {
        result.hostname = extractHostname(url, false);
    }
    if (step === 0 /* FLAG.HOSTNAME */ || result.hostname === null) {
        return result;
    }
    // Check if `hostname` is a valid ip address
    if (options.detectIp === true) {
        result.isIp = isIp(result.hostname);
        if (result.isIp === true) {
            return result;
        }
    }
    // Perform optional hostname validation. If hostname is not valid, no need to
    // go further as there will be no valid domain or sub-domain.
    if (options.validateHostname === true &&
        options.extractHostname === true &&
        is_valid(result.hostname) === false) {
        result.hostname = null;
        return result;
    }
    // Extract public suffix
    suffixLookup(result.hostname, options, result);
    if (step === 2 /* FLAG.PUBLIC_SUFFIX */ || result.publicSuffix === null) {
        return result;
    }
    // Extract domain
    result.domain = getDomain(result.publicSuffix, result.hostname, options);
    if (step === 3 /* FLAG.DOMAIN */ || result.domain === null) {
        return result;
    }
    // Extract subdomain
    result.subdomain = getSubdomain(result.hostname, result.domain);
    if (step === 4 /* FLAG.SUB_DOMAIN */) {
        return result;
    }
    // Extract domain without suffix
    result.domainWithoutSuffix = getDomainWithoutSuffix(result.domain, result.publicSuffix);
    return result;
}

;// ./node_modules/.pnpm/tldts-core@5.7.112/node_modules/tldts-core/dist/es6/src/lookup/fast-path.js
/* harmony default export */ function fast_path(hostname, options, out) {
    // Fast path for very popular suffixes; this allows to by-pass lookup
    // completely as well as any extra allocation or string manipulation.
    if (options.allowPrivateDomains === false && hostname.length > 3) {
        const last = hostname.length - 1;
        const c3 = hostname.charCodeAt(last);
        const c2 = hostname.charCodeAt(last - 1);
        const c1 = hostname.charCodeAt(last - 2);
        const c0 = hostname.charCodeAt(last - 3);
        if (c3 === 109 /* 'm' */ &&
            c2 === 111 /* 'o' */ &&
            c1 === 99 /* 'c' */ &&
            c0 === 46 /* '.' */) {
            out.isIcann = true;
            out.isPrivate = false;
            out.publicSuffix = 'com';
            return true;
        }
        else if (c3 === 103 /* 'g' */ &&
            c2 === 114 /* 'r' */ &&
            c1 === 111 /* 'o' */ &&
            c0 === 46 /* '.' */) {
            out.isIcann = true;
            out.isPrivate = false;
            out.publicSuffix = 'org';
            return true;
        }
        else if (c3 === 117 /* 'u' */ &&
            c2 === 100 /* 'd' */ &&
            c1 === 101 /* 'e' */ &&
            c0 === 46 /* '.' */) {
            out.isIcann = true;
            out.isPrivate = false;
            out.publicSuffix = 'edu';
            return true;
        }
        else if (c3 === 118 /* 'v' */ &&
            c2 === 111 /* 'o' */ &&
            c1 === 103 /* 'g' */ &&
            c0 === 46 /* '.' */) {
            out.isIcann = true;
            out.isPrivate = false;
            out.publicSuffix = 'gov';
            return true;
        }
        else if (c3 === 116 /* 't' */ &&
            c2 === 101 /* 'e' */ &&
            c1 === 110 /* 'n' */ &&
            c0 === 46 /* '.' */) {
            out.isIcann = true;
            out.isPrivate = false;
            out.publicSuffix = 'net';
            return true;
        }
        else if (c3 === 101 /* 'e' */ &&
            c2 === 100 /* 'd' */ &&
            c1 === 46 /* '.' */) {
            out.isIcann = true;
            out.isPrivate = false;
            out.publicSuffix = 'de';
            return true;
        }
    }
    return false;
}

;// ./node_modules/.pnpm/tldts-core@5.7.112/node_modules/tldts-core/dist/es6/index.js




;// ./node_modules/.pnpm/tldts@5.7.112/node_modules/tldts/dist/es6/src/data/trie.js
const exceptions = (function () {
    const _0 = { "$": 1, "succ": {} }, _1 = { "$": 0, "succ": { "city": _0 } };
    const exceptions = { "$": 0, "succ": { "ck": { "$": 0, "succ": { "www": _0 } }, "jp": { "$": 0, "succ": { "kawasaki": _1, "kitakyushu": _1, "kobe": _1, "nagoya": _1, "sapporo": _1, "sendai": _1, "yokohama": _1 } } } };
    ;
    return exceptions;
})();
const rules = (function () {
    const _2 = { "$": 1, "succ": {} }, _3 = { "$": 2, "succ": {} }, _4 = { "$": 1, "succ": { "gov": _2, "com": _2, "org": _2, "net": _2, "edu": _2 } }, _5 = { "$": 0, "succ": { "*": _3 } }, _6 = { "$": 1, "succ": { "blogspot": _3 } }, _7 = { "$": 1, "succ": { "gov": _2 } }, _8 = { "$": 0, "succ": { "*": _2 } }, _9 = { "$": 0, "succ": { "cloud": _3 } }, _10 = { "$": 1, "succ": { "co": _3 } }, _11 = { "$": 2, "succ": { "nodes": _3 } }, _12 = { "$": 0, "succ": { "s3": _3 } }, _13 = { "$": 0, "succ": { "direct": _3 } }, _14 = { "$": 2, "succ": { "id": _3 } }, _15 = { "$": 0, "succ": { "vfs": _3, "webview-assets": _3 } }, _16 = { "$": 0, "succ": { "cloud9": _15 } }, _17 = { "$": 0, "succ": { "dualstack": _12, "cloud9": _15 } }, _18 = { "$": 0, "succ": { "dualstack": _12, "s3": _3, "s3-website": _3, "cloud9": _15 } }, _19 = { "$": 0, "succ": { "apps": _3 } }, _20 = { "$": 0, "succ": { "paas": _3 } }, _21 = { "$": 0, "succ": { "app": _3 } }, _22 = { "$": 2, "succ": { "eu": _3 } }, _23 = { "$": 0, "succ": { "site": _3 } }, _24 = { "$": 0, "succ": { "pages": _3 } }, _25 = { "$": 1, "succ": { "com": _2, "edu": _2, "net": _2, "org": _2 } }, _26 = { "$": 0, "succ": { "j": _3 } }, _27 = { "$": 0, "succ": { "jelastic": _3 } }, _28 = { "$": 0, "succ": { "user": _3 } }, _29 = { "$": 1, "succ": { "ybo": _3 } }, _30 = { "$": 0, "succ": { "cust": _3, "reservd": _3 } }, _31 = { "$": 0, "succ": { "cust": _3 } }, _32 = { "$": 1, "succ": { "gov": _2, "edu": _2, "mil": _2, "com": _2, "org": _2, "net": _2 } }, _33 = { "$": 1, "succ": { "edu": _2, "biz": _2, "net": _2, "org": _2, "gov": _2, "info": _2, "com": _2 } }, _34 = { "$": 1, "succ": { "gov": _2, "blogspot": _3 } }, _35 = { "$": 1, "succ": { "framer": _3 } }, _36 = { "$": 1, "succ": { "barsy": _3 } }, _37 = { "$": 0, "succ": { "forgot": _3 } }, _38 = { "$": 1, "succ": { "gs": _2 } }, _39 = { "$": 0, "succ": { "nes": _2 } }, _40 = { "$": 1, "succ": { "k12": _2, "cc": _2, "lib": _2 } }, _41 = { "$": 1, "succ": { "cc": _2, "lib": _2 } };
    const rules = { "$": 0, "succ": { "ac": { "$": 1, "succ": { "com": _2, "edu": _2, "gov": _2, "net": _2, "mil": _2, "org": _2, "drr": _3 } }, "ad": { "$": 1, "succ": { "nom": _2 } }, "ae": { "$": 1, "succ": { "co": _2, "net": _2, "org": _2, "sch": _2, "ac": _2, "gov": _2, "mil": _2, "blogspot": _3 } }, "aero": { "$": 1, "succ": { "accident-investigation": _2, "accident-prevention": _2, "aerobatic": _2, "aeroclub": _2, "aerodrome": _2, "agents": _2, "aircraft": _2, "airline": _2, "airport": _2, "air-surveillance": _2, "airtraffic": _2, "air-traffic-control": _2, "ambulance": _2, "amusement": _2, "association": _2, "author": _2, "ballooning": _2, "broker": _2, "caa": _2, "cargo": _2, "catering": _2, "certification": _2, "championship": _2, "charter": _2, "civilaviation": _2, "club": _2, "conference": _2, "consultant": _2, "consulting": _2, "control": _2, "council": _2, "crew": _2, "design": _2, "dgca": _2, "educator": _2, "emergency": _2, "engine": _2, "engineer": _2, "entertainment": _2, "equipment": _2, "exchange": _2, "express": _2, "federation": _2, "flight": _2, "fuel": _2, "gliding": _2, "government": _2, "groundhandling": _2, "group": _2, "hanggliding": _2, "homebuilt": _2, "insurance": _2, "journal": _2, "journalist": _2, "leasing": _2, "logistics": _2, "magazine": _2, "maintenance": _2, "media": _2, "microlight": _2, "modelling": _2, "navigation": _2, "parachuting": _2, "paragliding": _2, "passenger-association": _2, "pilot": _2, "press": _2, "production": _2, "recreation": _2, "repbody": _2, "res": _2, "research": _2, "rotorcraft": _2, "safety": _2, "scientist": _2, "services": _2, "show": _2, "skydiving": _2, "software": _2, "student": _2, "trader": _2, "trading": _2, "trainer": _2, "union": _2, "workinggroup": _2, "works": _2 } }, "af": _4, "ag": { "$": 1, "succ": { "com": _2, "org": _2, "net": _2, "co": _2, "nom": _2 } }, "ai": { "$": 1, "succ": { "off": _2, "com": _2, "net": _2, "org": _2, "uwu": _3 } }, "al": { "$": 1, "succ": { "com": _2, "edu": _2, "gov": _2, "mil": _2, "net": _2, "org": _2, "blogspot": _3 } }, "am": { "$": 1, "succ": { "co": _2, "com": _2, "commune": _2, "net": _2, "org": _2, "radio": _3, "blogspot": _3, "neko": _3, "nyaa": _3 } }, "ao": { "$": 1, "succ": { "ed": _2, "gv": _2, "og": _2, "co": _2, "pb": _2, "it": _2 } }, "aq": _2, "ar": { "$": 1, "succ": { "bet": _2, "com": _6, "coop": _2, "edu": _2, "gob": _2, "gov": _2, "int": _2, "mil": _2, "musica": _2, "mutual": _2, "net": _2, "org": _2, "senasa": _2, "tur": _2 } }, "arpa": { "$": 1, "succ": { "e164": _2, "in-addr": _2, "ip6": _2, "iris": _2, "uri": _2, "urn": _2 } }, "as": _7, "asia": { "$": 1, "succ": { "cloudns": _3 } }, "at": { "$": 1, "succ": { "ac": { "$": 1, "succ": { "sth": _2 } }, "co": _6, "gv": _2, "or": _2, "funkfeuer": { "$": 0, "succ": { "wien": _3 } }, "futurecms": { "$": 0, "succ": { "*": _3, "ex": _5, "in": _5 } }, "futurehosting": _3, "futuremailing": _3, "ortsinfo": { "$": 0, "succ": { "ex": _5, "kunden": _5 } }, "biz": _3, "info": _3, "123webseite": _3, "priv": _3, "myspreadshop": _3, "12hp": _3, "2ix": _3, "4lima": _3, "lima-city": _3 } }, "au": { "$": 1, "succ": { "com": { "$": 1, "succ": { "blogspot": _3, "cloudlets": { "$": 0, "succ": { "mel": _3 } }, "myspreadshop": _3 } }, "net": _2, "org": _2, "edu": { "$": 1, "succ": { "act": _2, "catholic": _2, "nsw": { "$": 1, "succ": { "schools": _2 } }, "nt": _2, "qld": _2, "sa": _2, "tas": _2, "vic": _2, "wa": _2 } }, "gov": { "$": 1, "succ": { "qld": _2, "sa": _2, "tas": _2, "vic": _2, "wa": _2 } }, "asn": _2, "id": _2, "info": _2, "conf": _2, "oz": _2, "act": _2, "nsw": _2, "nt": _2, "qld": _2, "sa": _2, "tas": _2, "vic": _2, "wa": _2 } }, "aw": { "$": 1, "succ": { "com": _2 } }, "ax": { "$": 1, "succ": { "be": _3, "cat": _3, "es": _3, "eu": _3, "gg": _3, "mc": _3, "us": _3, "xy": _3 } }, "az": { "$": 1, "succ": { "com": _2, "net": _2, "int": _2, "gov": _2, "org": _2, "edu": _2, "info": _2, "pp": _2, "mil": _2, "name": _2, "pro": _2, "biz": _2 } }, "ba": { "$": 1, "succ": { "com": _2, "edu": _2, "gov": _2, "mil": _2, "net": _2, "org": _2, "rs": _3, "blogspot": _3 } }, "bb": { "$": 1, "succ": { "biz": _2, "co": _2, "com": _2, "edu": _2, "gov": _2, "info": _2, "net": _2, "org": _2, "store": _2, "tv": _2 } }, "bd": _8, "be": { "$": 1, "succ": { "ac": _2, "webhosting": _3, "blogspot": _3, "interhostsolutions": _9, "kuleuven": { "$": 0, "succ": { "ezproxy": _3 } }, "123website": _3, "myspreadshop": _3, "transurl": _5 } }, "bf": _7, "bg": { "$": 1, "succ": { "0": _2, "1": _2, "2": _2, "3": _2, "4": _2, "5": _2, "6": _2, "7": _2, "8": _2, "9": _2, "a": _2, "b": _2, "c": _2, "d": _2, "e": _2, "f": _2, "g": _2, "h": _2, "i": _2, "j": _2, "k": _2, "l": _2, "m": _2, "n": _2, "o": _2, "p": _2, "q": _2, "r": _2, "s": _2, "t": _2, "u": _2, "v": _2, "w": _2, "x": _2, "y": _2, "z": _2, "blogspot": _3, "barsy": _3 } }, "bh": _4, "bi": { "$": 1, "succ": { "co": _2, "com": _2, "edu": _2, "or": _2, "org": _2 } }, "biz": { "$": 1, "succ": { "activetrail": _3, "cloudns": _3, "jozi": _3, "dyndns": _3, "for-better": _3, "for-more": _3, "for-some": _3, "for-the": _3, "selfip": _3, "webhop": _3, "orx": _3, "mmafan": _3, "myftp": _3, "no-ip": _3, "dscloud": _3 } }, "bj": { "$": 1, "succ": { "africa": _2, "agro": _2, "architectes": _2, "assur": _2, "avocats": _2, "co": _2, "com": _2, "eco": _2, "econo": _2, "edu": _2, "info": _2, "loisirs": _2, "money": _2, "net": _2, "org": _2, "ote": _2, "resto": _2, "restaurant": _2, "tourism": _2, "univ": _2, "blogspot": _3 } }, "bm": _4, "bn": { "$": 1, "succ": { "com": _2, "edu": _2, "gov": _2, "net": _2, "org": _2, "co": _3 } }, "bo": { "$": 1, "succ": { "com": _2, "edu": _2, "gob": _2, "int": _2, "org": _2, "net": _2, "mil": _2, "tv": _2, "web": _2, "academia": _2, "agro": _2, "arte": _2, "blog": _2, "bolivia": _2, "ciencia": _2, "cooperativa": _2, "democracia": _2, "deporte": _2, "ecologia": _2, "economia": _2, "empresa": _2, "indigena": _2, "industria": _2, "info": _2, "medicina": _2, "movimiento": _2, "musica": _2, "natural": _2, "nombre": _2, "noticias": _2, "patria": _2, "politica": _2, "profesional": _2, "plurinacional": _2, "pueblo": _2, "revista": _2, "salud": _2, "tecnologia": _2, "tksat": _2, "transporte": _2, "wiki": _2 } }, "br": { "$": 1, "succ": { "9guacu": _2, "abc": _2, "adm": _2, "adv": _2, "agr": _2, "aju": _2, "am": _2, "anani": _2, "aparecida": _2, "app": _2, "arq": _2, "art": _2, "ato": _2, "b": _2, "barueri": _2, "belem": _2, "bhz": _2, "bib": _2, "bio": _2, "blog": _2, "bmd": _2, "boavista": _2, "bsb": _2, "campinagrande": _2, "campinas": _2, "caxias": _2, "cim": _2, "cng": _2, "cnt": _2, "com": { "$": 1, "succ": { "blogspot": _3, "virtualcloud": { "$": 0, "succ": { "scale": { "$": 0, "succ": { "users": _3 } } } }, "simplesite": _3 } }, "contagem": _2, "coop": _2, "coz": _2, "cri": _2, "cuiaba": _2, "curitiba": _2, "def": _2, "des": _2, "det": _2, "dev": _2, "ecn": _2, "eco": _2, "edu": _2, "emp": _2, "enf": _2, "eng": _2, "esp": _2, "etc": _2, "eti": _2, "far": _2, "feira": _2, "flog": _2, "floripa": _2, "fm": _2, "fnd": _2, "fortal": _2, "fot": _2, "foz": _2, "fst": _2, "g12": _2, "geo": _2, "ggf": _2, "goiania": _2, "gov": { "$": 1, "succ": { "ac": _2, "al": _2, "am": _2, "ap": _2, "ba": _2, "ce": _2, "df": _2, "es": _2, "go": _2, "ma": _2, "mg": _2, "ms": _2, "mt": _2, "pa": _2, "pb": _2, "pe": _2, "pi": _2, "pr": _2, "rj": _2, "rn": _2, "ro": _2, "rr": _2, "rs": _2, "sc": _2, "se": _2, "sp": _2, "to": _2 } }, "gru": _2, "imb": _2, "ind": _2, "inf": _2, "jab": _2, "jampa": _2, "jdf": _2, "joinville": _2, "jor": _2, "jus": _2, "leg": { "$": 1, "succ": { "ac": _3, "al": _3, "am": _3, "ap": _3, "ba": _3, "ce": _3, "df": _3, "es": _3, "go": _3, "ma": _3, "mg": _3, "ms": _3, "mt": _3, "pa": _3, "pb": _3, "pe": _3, "pi": _3, "pr": _3, "rj": _3, "rn": _3, "ro": _3, "rr": _3, "rs": _3, "sc": _3, "se": _3, "sp": _3, "to": _3 } }, "lel": _2, "log": _2, "londrina": _2, "macapa": _2, "maceio": _2, "manaus": _2, "maringa": _2, "mat": _2, "med": _2, "mil": _2, "morena": _2, "mp": _2, "mus": _2, "natal": _2, "net": _2, "niteroi": _2, "nom": _8, "not": _2, "ntr": _2, "odo": _2, "ong": _2, "org": _2, "osasco": _2, "palmas": _2, "poa": _2, "ppg": _2, "pro": _2, "psc": _2, "psi": _2, "pvh": _2, "qsl": _2, "radio": _2, "rec": _2, "recife": _2, "rep": _2, "ribeirao": _2, "rio": _2, "riobranco": _2, "riopreto": _2, "salvador": _2, "sampa": _2, "santamaria": _2, "santoandre": _2, "saobernardo": _2, "saogonca": _2, "seg": _2, "sjc": _2, "slg": _2, "slz": _2, "sorocaba": _2, "srv": _2, "taxi": _2, "tc": _2, "tec": _2, "teo": _2, "the": _2, "tmp": _2, "trd": _2, "tur": _2, "tv": _2, "udi": _2, "vet": _2, "vix": _2, "vlog": _2, "wiki": _2, "zlg": _2 } }, "bs": { "$": 1, "succ": { "com": _2, "net": _2, "org": _2, "edu": _2, "gov": _2, "we": _3 } }, "bt": _4, "bv": _2, "bw": { "$": 1, "succ": { "co": _2, "org": _2 } }, "by": { "$": 1, "succ": { "gov": _2, "mil": _2, "com": _6, "of": _2, "mycloud": _3, "mediatech": _3 } }, "bz": { "$": 1, "succ": { "com": _2, "net": _2, "org": _2, "edu": _2, "gov": _2, "za": _3, "gsj": _3 } }, "ca": { "$": 1, "succ": { "ab": _2, "bc": _2, "mb": _2, "nb": _2, "nf": _2, "nl": _2, "ns": _2, "nt": _2, "nu": _2, "on": _2, "pe": _2, "qc": _2, "sk": _2, "yk": _2, "gc": _2, "barsy": _3, "awdev": _5, "co": _3, "blogspot": _3, "no-ip": _3, "myspreadshop": _3 } }, "cat": _2, "cc": { "$": 1, "succ": { "cloudns": _3, "ftpaccess": _3, "game-server": _3, "myphotos": _3, "scrapping": _3, "twmail": _3, "csx": _3, "fantasyleague": _3, "spawn": { "$": 0, "succ": { "instances": _3 } } } }, "cd": _7, "cf": _6, "cg": _2, "ch": { "$": 1, "succ": { "square7": _3, "blogspot": _3, "flow": { "$": 0, "succ": { "ae": { "$": 0, "succ": { "alp1": _3 } }, "appengine": _3 } }, "linkyard-cloud": _3, "dnsking": _3, "gotdns": _3, "123website": _3, "myspreadshop": _3, "firenet": { "$": 0, "succ": { "*": _3, "svc": _5 } }, "12hp": _3, "2ix": _3, "4lima": _3, "lima-city": _3 } }, "ci": { "$": 1, "succ": { "org": _2, "or": _2, "com": _2, "co": _2, "edu": _2, "ed": _2, "ac": _2, "net": _2, "go": _2, "asso": _2, "xn--aroport-bya": _2, "aéroport": _2, "int": _2, "presse": _2, "md": _2, "gouv": _2, "fin": _3, "nl": _3 } }, "ck": _8, "cl": { "$": 1, "succ": { "co": _2, "gob": _2, "gov": _2, "mil": _2, "blogspot": _3 } }, "cm": { "$": 1, "succ": { "co": _2, "com": _2, "gov": _2, "net": _2 } }, "cn": { "$": 1, "succ": { "ac": _2, "com": { "$": 1, "succ": { "amazonaws": { "$": 0, "succ": { "compute": _5, "cn-north-1": _12, "eb": { "$": 0, "succ": { "cn-north-1": _3, "cn-northwest-1": _3 } }, "elb": _5 } } } }, "edu": _2, "gov": _2, "net": _2, "org": _2, "mil": _2, "xn--55qx5d": _2, "公司": _2, "xn--io0a7i": _2, "网络": _2, "xn--od0alg": _2, "網絡": _2, "ah": _2, "bj": _2, "cq": _2, "fj": _2, "gd": _2, "gs": _2, "gz": _2, "gx": _2, "ha": _2, "hb": _2, "he": _2, "hi": _2, "hl": _2, "hn": _2, "jl": _2, "js": _2, "jx": _2, "ln": _2, "nm": _2, "nx": _2, "qh": _2, "sc": _2, "sd": _2, "sh": _2, "sn": _2, "sx": _2, "tj": _2, "xj": _2, "xz": _2, "yn": _2, "zj": _2, "hk": _2, "mo": _2, "tw": _2, "canva-apps": _3, "instantcloud": _3, "quickconnect": _13 } }, "co": { "$": 1, "succ": { "arts": _2, "com": _6, "edu": _2, "firm": _2, "gov": _2, "info": _2, "int": _2, "mil": _2, "net": _2, "nom": _2, "org": _2, "rec": _2, "web": _2, "carrd": _3, "crd": _3, "otap": _5, "leadpages": _3, "lpages": _3, "mypi": _3, "n4t": _3, "firewalledreplit": _14, "repl": _14, "supabase": _3 } }, "com": { "$": 1, "succ": { "devcdnaccesso": _5, "adobeaemcloud": { "$": 2, "succ": { "dev": _5 } }, "airkitapps": _3, "airkitapps-au": _3, "aivencloud": _3, "kasserver": _3, "amazonaws": { "$": 0, "succ": { "compute": _5, "compute-1": _5, "us-east-1": { "$": 2, "succ": { "dualstack": _12, "cloud9": _15 } }, "ap-northeast-1": _17, "ap-northeast-2": _18, "ap-south-1": _18, "ap-southeast-1": _17, "ap-southeast-2": _17, "ca-central-1": _18, "eu-central-1": _18, "eu-west-1": _17, "eu-west-2": _18, "eu-west-3": _18, "s3": _3, "s3-ap-northeast-1": _3, "s3-ap-northeast-2": _3, "s3-ap-south-1": _3, "s3-ap-southeast-1": _3, "s3-ap-southeast-2": _3, "s3-ca-central-1": _3, "s3-eu-central-1": _3, "s3-eu-west-1": _3, "s3-eu-west-2": _3, "s3-eu-west-3": _3, "s3-external-1": _3, "s3-fips-us-gov-west-1": _3, "s3-sa-east-1": _3, "s3-us-east-2": _3, "s3-us-gov-west-1": _3, "s3-us-west-1": _3, "s3-us-west-2": _3, "s3-website-ap-northeast-1": _3, "s3-website-ap-southeast-1": _3, "s3-website-ap-southeast-2": _3, "s3-website-eu-west-1": _3, "s3-website-sa-east-1": _3, "s3-website-us-east-1": _3, "s3-website-us-west-1": _3, "s3-website-us-west-2": _3, "sa-east-1": _17, "us-east-2": _18, "af-south-1": _16, "ap-east-1": _16, "ap-northeast-3": _16, "eu-north-1": _16, "eu-south-1": _16, "me-south-1": _16, "us-west-1": _16, "us-west-2": _16, "elb": _5 } }, "elasticbeanstalk": { "$": 2, "succ": { "ap-northeast-1": _3, "ap-northeast-2": _3, "ap-northeast-3": _3, "ap-south-1": _3, "ap-southeast-1": _3, "ap-southeast-2": _3, "ca-central-1": _3, "eu-central-1": _3, "eu-west-1": _3, "eu-west-2": _3, "eu-west-3": _3, "sa-east-1": _3, "us-east-1": _3, "us-east-2": _3, "us-gov-west-1": _3, "us-west-1": _3, "us-west-2": _3 } }, "awsglobalaccelerator": _3, "siiites": _3, "appspacehosted": _3, "appspaceusercontent": _3, "on-aptible": _3, "myasustor": _3, "balena-devices": _3, "betainabox": _3, "boutir": _3, "bplaced": _3, "cafjs": _3, "canva-apps": _3, "br": _3, "cn": _3, "de": _3, "eu": _3, "jpn": _3, "mex": _3, "ru": _3, "sa": _3, "uk": _3, "us": _3, "za": _3, "ar": _3, "hu": _3, "kr": _3, "no": _3, "qc": _3, "uy": _3, "africa": _3, "gr": _3, "co": _3, "jdevcloud": _3, "wpdevcloud": _3, "cloudcontrolled": _3, "cloudcontrolapp": _3, "cf-ipfs": _3, "cloudflare-ipfs": _3, "trycloudflare": _3, "customer-oci": { "$": 0, "succ": { "*": _3, "oci": _5, "ocp": _5, "ocs": _5 } }, "dattolocal": _3, "dattorelay": _3, "dattoweb": _3, "mydatto": _3, "builtwithdark": _3, "datadetect": { "$": 0, "succ": { "demo": _3, "instance": _3 } }, "ddns5": _3, "discordsays": _3, "discordsez": _3, "drayddns": _3, "dreamhosters": _3, "mydrobo": _3, "dyndns-at-home": _3, "dyndns-at-work": _3, "dyndns-blog": _3, "dyndns-free": _3, "dyndns-home": _3, "dyndns-ip": _3, "dyndns-mail": _3, "dyndns-office": _3, "dyndns-pics": _3, "dyndns-remote": _3, "dyndns-server": _3, "dyndns-web": _3, "dyndns-wiki": _3, "dyndns-work": _3, "blogdns": _3, "cechire": _3, "dnsalias": _3, "dnsdojo": _3, "doesntexist": _3, "dontexist": _3, "doomdns": _3, "dyn-o-saur": _3, "dynalias": _3, "est-a-la-maison": _3, "est-a-la-masion": _3, "est-le-patron": _3, "est-mon-blogueur": _3, "from-ak": _3, "from-al": _3, "from-ar": _3, "from-ca": _3, "from-ct": _3, "from-dc": _3, "from-de": _3, "from-fl": _3, "from-ga": _3, "from-hi": _3, "from-ia": _3, "from-id": _3, "from-il": _3, "from-in": _3, "from-ks": _3, "from-ky": _3, "from-ma": _3, "from-md": _3, "from-mi": _3, "from-mn": _3, "from-mo": _3, "from-ms": _3, "from-mt": _3, "from-nc": _3, "from-nd": _3, "from-ne": _3, "from-nh": _3, "from-nj": _3, "from-nm": _3, "from-nv": _3, "from-oh": _3, "from-ok": _3, "from-or": _3, "from-pa": _3, "from-pr": _3, "from-ri": _3, "from-sc": _3, "from-sd": _3, "from-tn": _3, "from-tx": _3, "from-ut": _3, "from-va": _3, "from-vt": _3, "from-wa": _3, "from-wi": _3, "from-wv": _3, "from-wy": _3, "getmyip": _3, "gotdns": _3, "hobby-site": _3, "homelinux": _3, "homeunix": _3, "iamallama": _3, "is-a-anarchist": _3, "is-a-blogger": _3, "is-a-bookkeeper": _3, "is-a-bulls-fan": _3, "is-a-caterer": _3, "is-a-chef": _3, "is-a-conservative": _3, "is-a-cpa": _3, "is-a-cubicle-slave": _3, "is-a-democrat": _3, "is-a-designer": _3, "is-a-doctor": _3, "is-a-financialadvisor": _3, "is-a-geek": _3, "is-a-green": _3, "is-a-guru": _3, "is-a-hard-worker": _3, "is-a-hunter": _3, "is-a-landscaper": _3, "is-a-lawyer": _3, "is-a-liberal": _3, "is-a-libertarian": _3, "is-a-llama": _3, "is-a-musician": _3, "is-a-nascarfan": _3, "is-a-nurse": _3, "is-a-painter": _3, "is-a-personaltrainer": _3, "is-a-photographer": _3, "is-a-player": _3, "is-a-republican": _3, "is-a-rockstar": _3, "is-a-socialist": _3, "is-a-student": _3, "is-a-teacher": _3, "is-a-techie": _3, "is-a-therapist": _3, "is-an-accountant": _3, "is-an-actor": _3, "is-an-actress": _3, "is-an-anarchist": _3, "is-an-artist": _3, "is-an-engineer": _3, "is-an-entertainer": _3, "is-certified": _3, "is-gone": _3, "is-into-anime": _3, "is-into-cars": _3, "is-into-cartoons": _3, "is-into-games": _3, "is-leet": _3, "is-not-certified": _3, "is-slick": _3, "is-uberleet": _3, "is-with-theband": _3, "isa-geek": _3, "isa-hockeynut": _3, "issmarterthanyou": _3, "likes-pie": _3, "likescandy": _3, "neat-url": _3, "saves-the-whales": _3, "selfip": _3, "sells-for-less": _3, "sells-for-u": _3, "servebbs": _3, "simple-url": _3, "space-to-rent": _3, "teaches-yoga": _3, "writesthisblog": _3, "digitaloceanspaces": _5, "ddnsfree": _3, "ddnsgeek": _3, "giize": _3, "gleeze": _3, "kozow": _3, "loseyourip": _3, "ooguy": _3, "theworkpc": _3, "mytuleap": _3, "tuleap-partners": _3, "encoreapi": _3, "evennode": { "$": 0, "succ": { "eu-1": _3, "eu-2": _3, "eu-3": _3, "eu-4": _3, "us-1": _3, "us-2": _3, "us-3": _3, "us-4": _3 } }, "onfabrica": _3, "fbsbx": _19, "fastly-edge": _3, "fastly-terrarium": _3, "fastvps-server": _3, "mydobiss": _3, "firebaseapp": _3, "fldrv": _3, "forgeblocks": _3, "framercanvas": _3, "freebox-os": _3, "freeboxos": _3, "freemyip": _3, "gentapps": _3, "gentlentapis": _3, "githubusercontent": _3, "0emm": _5, "appspot": { "$": 2, "succ": { "r": _5 } }, "codespot": _3, "googleapis": _3, "googlecode": _3, "pagespeedmobilizer": _3, "publishproxy": _3, "withgoogle": _3, "withyoutube": _3, "blogspot": _3, "awsmppl": _3, "herokuapp": _3, "herokussl": _3, "impertrixcdn": _3, "impertrix": _3, "smushcdn": _3, "wphostedmail": _3, "wpmucdn": _3, "pixolino": _3, "amscompute": _3, "clicketcloud": _3, "dopaas": _3, "hidora": _3, "hosted-by-previder": _20, "hosteur": { "$": 0, "succ": { "rag-cloud": _3, "rag-cloud-ch": _3 } }, "ik-server": { "$": 0, "succ": { "jcloud": _3, "jcloud-ver-jpc": _3 } }, "jelastic": { "$": 0, "succ": { "demo": _3 } }, "kilatiron": _3, "massivegrid": _20, "wafaicloud": { "$": 0, "succ": { "jed": _3, "lon": _3, "ryd": _3 } }, "joyent": { "$": 0, "succ": { "cns": _5 } }, "ktistory": _3, "lpusercontent": _3, "lmpm": _21, "linode": { "$": 0, "succ": { "members": _3, "nodebalancer": _5 } }, "linodeobjects": _5, "linodeusercontent": { "$": 0, "succ": { "ip": _3 } }, "barsycenter": _3, "barsyonline": _3, "mazeplay": _3, "miniserver": _3, "meteorapp": _22, "hostedpi": _3, "mythic-beasts": { "$": 0, "succ": { "customer": _3, "caracal": _3, "fentiger": _3, "lynx": _3, "ocelot": _3, "oncilla": _3, "onza": _3, "sphinx": _3, "vs": _3, "x": _3, "yali": _3 } }, "nospamproxy": _9, "4u": _3, "nfshost": _3, "001www": _3, "ddnslive": _3, "myiphost": _3, "blogsyte": _3, "ciscofreak": _3, "damnserver": _3, "ditchyourip": _3, "dnsiskinky": _3, "dynns": _3, "geekgalaxy": _3, "health-carereform": _3, "homesecuritymac": _3, "homesecuritypc": _3, "myactivedirectory": _3, "mysecuritycamera": _3, "net-freaks": _3, "onthewifi": _3, "point2this": _3, "quicksytes": _3, "securitytactics": _3, "serveexchange": _3, "servehumour": _3, "servep2p": _3, "servesarcasm": _3, "stufftoread": _3, "unusualperson": _3, "workisboring": _3, "3utilities": _3, "ddnsking": _3, "myvnc": _3, "servebeer": _3, "servecounterstrike": _3, "serveftp": _3, "servegame": _3, "servehalflife": _3, "servehttp": _3, "serveirc": _3, "servemp3": _3, "servepics": _3, "servequake": _3, "observableusercontent": { "$": 0, "succ": { "static": _3 } }, "simplesite": _3, "orsites": _3, "operaunite": _3, "authgear-staging": _3, "authgearapps": _3, "skygearapp": _3, "outsystemscloud": _3, "ownprovider": _3, "pgfog": _3, "pagefrontapp": _3, "pagexl": _3, "paywhirl": _5, "gotpantheon": _3, "platter-app": _3, "pleskns": _3, "postman-echo": _3, "prgmr": { "$": 0, "succ": { "xen": _3 } }, "pythonanywhere": _22, "qualifioapp": _3, "qbuser": _3, "qa2": _3, "dev-myqnapcloud": _3, "alpha-myqnapcloud": _3, "myqnapcloud": _3, "quipelements": _5, "rackmaze": _3, "rhcloud": _3, "render": _21, "onrender": _3, "180r": _3, "dojin": _3, "sakuratan": _3, "sakuraweb": _3, "x0": _3, "code": { "$": 0, "succ": { "builder": _5, "dev-builder": _5, "stg-builder": _5 } }, "logoip": _3, "scrysec": _3, "firewall-gateway": _3, "myshopblocks": _3, "myshopify": _3, "shopitsite": _3, "1kapp": _3, "appchizi": _3, "applinzi": _3, "sinaapp": _3, "vipsinaapp": _3, "bounty-full": { "$": 2, "succ": { "alpha": _3, "beta": _3 } }, "streamlitapp": _3, "try-snowplow": _3, "stackhero-network": _3, "playstation-cloud": _3, "myspreadshop": _3, "stdlib": { "$": 0, "succ": { "api": _3 } }, "temp-dns": _3, "dsmynas": _3, "familyds": _3, "mytabit": _3, "tb-hosting": _23, "reservd": _3, "thingdustdata": _3, "bloxcms": _3, "townnews-staging": _3, "typeform": { "$": 0, "succ": { "pro": _3 } }, "hk": _3, "it": _3, "vultrobjects": _5, "wafflecell": _3, "reserve-online": _3, "hotelwithflight": _3, "remotewd": _3, "wiardweb": _24, "messwithdns": _3, "woltlab-demo": _3, "wpenginepowered": { "$": 2, "succ": { "js": _3 } }, "wixsite": _3, "xnbay": { "$": 2, "succ": { "u2": _3, "u2-local": _3 } }, "yolasite": _3 } }, "coop": _2, "cr": { "$": 1, "succ": { "ac": _2, "co": _2, "ed": _2, "fi": _2, "go": _2, "or": _2, "sa": _2 } }, "cu": { "$": 1, "succ": { "com": _2, "edu": _2, "org": _2, "net": _2, "gov": _2, "inf": _2 } }, "cv": { "$": 1, "succ": { "com": _2, "edu": _2, "int": _2, "nome": _2, "org": _2, "blogspot": _3 } }, "cw": _25, "cx": { "$": 1, "succ": { "gov": _2, "ath": _3, "info": _3 } }, "cy": { "$": 1, "succ": { "ac": _2, "biz": _2, "com": { "$": 1, "succ": { "blogspot": _3, "scaleforce": _26 } }, "ekloges": _2, "gov": _2, "ltd": _2, "mil": _2, "net": _2, "org": _2, "press": _2, "pro": _2, "tm": _2 } }, "cz": { "$": 1, "succ": { "co": _3, "realm": _3, "e4": _3, "blogspot": _3, "metacentrum": { "$": 0, "succ": { "cloud": _5, "custom": _3 } }, "muni": { "$": 0, "succ": { "cloud": { "$": 0, "succ": { "flt": _3, "usr": _3 } } } } } }, "de": { "$": 1, "succ": { "bplaced": _3, "square7": _3, "com": _3, "cosidns": { "$": 0, "succ": { "dyn": _3 } }, "dynamisches-dns": _3, "dnsupdater": _3, "internet-dns": _3, "l-o-g-i-n": _3, "dnshome": _3, "fuettertdasnetz": _3, "isteingeek": _3, "istmein": _3, "lebtimnetz": _3, "leitungsen": _3, "traeumtgerade": _3, "ddnss": { "$": 2, "succ": { "dyn": _3, "dyndns": _3 } }, "dyndns1": _3, "dyn-ip24": _3, "home-webserver": { "$": 2, "succ": { "dyn": _3 } }, "myhome-server": _3, "frusky": _5, "goip": _3, "blogspot": _3, "xn--gnstigbestellen-zvb": _3, "günstigbestellen": _3, "xn--gnstigliefern-wob": _3, "günstigliefern": _3, "hs-heilbronn": { "$": 0, "succ": { "it": _24 } }, "dyn-berlin": _3, "in-berlin": _3, "in-brb": _3, "in-butter": _3, "in-dsl": _3, "in-vpn": _3, "iservschule": _3, "mein-iserv": _3, "schulplattform": _3, "schulserver": _3, "test-iserv": _3, "keymachine": _3, "git-repos": _3, "lcube-server": _3, "svn-repos": _3, "barsy": _3, "123webseite": _3, "logoip": _3, "firewall-gateway": _3, "my-gateway": _3, "my-router": _3, "spdns": _3, "speedpartner": { "$": 0, "succ": { "customer": _3 } }, "myspreadshop": _3, "taifun-dns": _3, "12hp": _3, "2ix": _3, "4lima": _3, "lima-city": _3, "dd-dns": _3, "dray-dns": _3, "draydns": _3, "dyn-vpn": _3, "dynvpn": _3, "mein-vigor": _3, "my-vigor": _3, "my-wan": _3, "syno-ds": _3, "synology-diskstation": _3, "synology-ds": _3, "uberspace": _5, "virtualuser": _3, "virtual-user": _3, "community-pro": _3, "diskussionsbereich": _3 } }, "dj": _2, "dk": { "$": 1, "succ": { "biz": _3, "co": _3, "firm": _3, "reg": _3, "store": _3, "blogspot": _3, "123hjemmeside": _3, "myspreadshop": _3 } }, "dm": _4, "do": { "$": 1, "succ": { "art": _2, "com": _2, "edu": _2, "gob": _2, "gov": _2, "mil": _2, "net": _2, "org": _2, "sld": _2, "web": _2 } }, "dz": { "$": 1, "succ": { "art": _2, "asso": _2, "com": _2, "edu": _2, "gov": _2, "org": _2, "net": _2, "pol": _2, "soc": _2, "tm": _2 } }, "ec": { "$": 1, "succ": { "com": _2, "info": _2, "net": _2, "fin": _2, "k12": _2, "med": _2, "pro": _2, "org": _2, "edu": _2, "gov": _2, "gob": _2, "mil": _2, "base": _3, "official": _3 } }, "edu": { "$": 1, "succ": { "rit": { "$": 0, "succ": { "git-pages": _3 } } } }, "ee": { "$": 1, "succ": { "edu": _2, "gov": _2, "riik": _2, "lib": _2, "med": _2, "com": _6, "pri": _2, "aip": _2, "org": _2, "fie": _2 } }, "eg": { "$": 1, "succ": { "com": _6, "edu": _2, "eun": _2, "gov": _2, "mil": _2, "name": _2, "net": _2, "org": _2, "sci": _2 } }, "er": _8, "es": { "$": 1, "succ": { "com": _6, "nom": _2, "org": _2, "gob": _2, "edu": _2, "123miweb": _3, "myspreadshop": _3 } }, "et": { "$": 1, "succ": { "com": _2, "gov": _2, "org": _2, "edu": _2, "biz": _2, "name": _2, "info": _2, "net": _2 } }, "eu": { "$": 1, "succ": { "airkitapps": _3, "mycd": _3, "cloudns": _3, "dogado": _27, "barsy": _3, "wellbeingzone": _3, "spdns": _3, "transurl": _5, "diskstation": _3 } }, "fi": { "$": 1, "succ": { "aland": _2, "dy": _3, "blogspot": _3, "xn--hkkinen-5wa": _3, "häkkinen": _3, "iki": _3, "cloudplatform": { "$": 0, "succ": { "fi": _3 } }, "datacenter": { "$": 0, "succ": { "demo": _3, "paas": _3 } }, "kapsi": _3, "123kotisivu": _3, "myspreadshop": _3 } }, "fj": { "$": 1, "succ": { "ac": _2, "biz": _2, "com": _2, "gov": _2, "info": _2, "mil": _2, "name": _2, "net": _2, "org": _2, "pro": _2 } }, "fk": _8, "fm": { "$": 1, "succ": { "com": _2, "edu": _2, "net": _2, "org": _2, "radio": _3, "user": _5 } }, "fo": _2, "fr": { "$": 1, "succ": { "asso": _2, "com": _2, "gouv": _2, "nom": _2, "prd": _2, "tm": _2, "aeroport": _2, "avocat": _2, "avoues": _2, "cci": _2, "chambagri": _2, "chirurgiens-dentistes": _2, "experts-comptables": _2, "geometre-expert": _2, "greta": _2, "huissier-justice": _2, "medecin": _2, "notaires": _2, "pharmacien": _2, "port": _2, "veterinaire": _2, "en-root": _3, "fbx-os": _3, "fbxos": _3, "freebox-os": _3, "freeboxos": _3, "blogspot": _3, "goupile": _3, "123siteweb": _3, "on-web": _3, "chirurgiens-dentistes-en-france": _3, "dedibox": _3, "myspreadshop": _3, "ynh": _3 } }, "ga": _2, "gb": _2, "gd": { "$": 1, "succ": { "edu": _2, "gov": _2 } }, "ge": { "$": 1, "succ": { "com": _2, "edu": _2, "gov": _2, "org": _2, "mil": _2, "net": _2, "pvt": _2 } }, "gf": _2, "gg": { "$": 1, "succ": { "co": _2, "net": _2, "org": _2, "kaas": _3, "cya": _3, "panel": { "$": 2, "succ": { "daemon": _3 } } } }, "gh": { "$": 1, "succ": { "com": _2, "edu": _2, "gov": _2, "org": _2, "mil": _2 } }, "gi": { "$": 1, "succ": { "com": _2, "ltd": _2, "gov": _2, "mod": _2, "edu": _2, "org": _2 } }, "gl": { "$": 1, "succ": { "co": _2, "com": _2, "edu": _2, "net": _2, "org": _2, "biz": _3, "xx": _3 } }, "gm": _2, "gn": { "$": 1, "succ": { "ac": _2, "com": _2, "edu": _2, "gov": _2, "org": _2, "net": _2 } }, "gov": _2, "gp": { "$": 1, "succ": { "com": _2, "net": _2, "mobi": _2, "edu": _2, "org": _2, "asso": _2, "app": _3 } }, "gq": _2, "gr": { "$": 1, "succ": { "com": _2, "edu": _2, "net": _2, "org": _2, "gov": _2, "blogspot": _3, "simplesite": _3 } }, "gs": _2, "gt": { "$": 1, "succ": { "com": _2, "edu": _2, "gob": _2, "ind": _2, "mil": _2, "net": _2, "org": _2, "blog": _3, "de": _3, "to": _3 } }, "gu": { "$": 1, "succ": { "com": _2, "edu": _2, "gov": _2, "guam": _2, "info": _2, "net": _2, "org": _2, "web": _2 } }, "gw": _2, "gy": { "$": 1, "succ": { "co": _2, "com": _2, "edu": _2, "gov": _2, "net": _2, "org": _2, "be": _3 } }, "hk": { "$": 1, "succ": { "com": _2, "edu": _2, "gov": _2, "idv": _2, "net": _2, "org": _2, "xn--55qx5d": _2, "公司": _2, "xn--wcvs22d": _2, "教育": _2, "xn--lcvr32d": _2, "敎育": _2, "xn--mxtq1m": _2, "政府": _2, "xn--gmqw5a": _2, "個人": _2, "xn--ciqpn": _2, "个人": _2, "xn--gmq050i": _2, "箇人": _2, "xn--zf0avx": _2, "網络": _2, "xn--io0a7i": _2, "网络": _2, "xn--mk0axi": _2, "组織": _2, "xn--od0alg": _2, "網絡": _2, "xn--od0aq3b": _2, "网絡": _2, "xn--tn0ag": _2, "组织": _2, "xn--uc0atv": _2, "組織": _2, "xn--uc0ay4a": _2, "組织": _2, "blogspot": _3, "secaas": _3, "ltd": _3, "inc": _3 } }, "hm": _2, "hn": { "$": 1, "succ": { "com": _2, "edu": _2, "org": _2, "net": _2, "mil": _2, "gob": _2, "cc": _3 } }, "hr": { "$": 1, "succ": { "iz": _2, "from": _2, "name": _2, "com": _2, "blogspot": _3, "free": _3 } }, "ht": { "$": 1, "succ": { "com": _2, "shop": _2, "firm": _2, "info": _2, "adult": _2, "net": _2, "pro": _2, "org": _2, "med": _2, "art": _2, "coop": _2, "pol": _2, "asso": _2, "edu": _2, "rel": _2, "gouv": _2, "perso": _2 } }, "hu": { "$": 1, "succ": { "2000": _2, "co": _2, "info": _2, "org": _2, "priv": _2, "sport": _2, "tm": _2, "agrar": _2, "bolt": _2, "casino": _2, "city": _2, "erotica": _2, "erotika": _2, "film": _2, "forum": _2, "games": _2, "hotel": _2, "ingatlan": _2, "jogasz": _2, "konyvelo": _2, "lakas": _2, "media": _2, "news": _2, "reklam": _2, "sex": _2, "shop": _2, "suli": _2, "szex": _2, "tozsde": _2, "utazas": _2, "video": _2, "blogspot": _3 } }, "id": { "$": 1, "succ": { "ac": _2, "biz": _2, "co": _6, "desa": _2, "go": _2, "mil": _2, "my": { "$": 1, "succ": { "rss": _5 } }, "net": _2, "or": _2, "ponpes": _2, "sch": _2, "web": _2, "flap": _3, "forte": _3 } }, "ie": { "$": 1, "succ": { "gov": _2, "blogspot": _3, "myspreadshop": _3 } }, "il": { "$": 1, "succ": { "ac": _2, "co": { "$": 1, "succ": { "ravpage": _3, "blogspot": _3, "tabitorder": _3, "mytabit": _3 } }, "gov": _2, "idf": _2, "k12": _2, "muni": _2, "net": _2, "org": _2 } }, "xn--4dbrk0ce": { "$": 1, "succ": { "xn--4dbgdty6c": _2, "xn--5dbhl8d": _2, "xn--8dbq2a": _2, "xn--hebda8b": _2 } }, "ישראל": { "$": 1, "succ": { "אקדמיה": _2, "ישוב": _2, "צהל": _2, "ממשל": _2 } }, "im": { "$": 1, "succ": { "ac": _2, "co": { "$": 1, "succ": { "ltd": _2, "plc": _2 } }, "com": _2, "net": _2, "org": _2, "tt": _2, "tv": _2, "ro": _3 } }, "in": { "$": 1, "succ": { "5g": _2, "6g": _2, "ac": _2, "ai": _2, "am": _2, "bihar": _2, "biz": _2, "business": _2, "ca": _2, "cn": _2, "co": _2, "com": _2, "coop": _2, "cs": _2, "delhi": _2, "dr": _2, "edu": _2, "er": _2, "firm": _2, "gen": _2, "gov": _2, "gujarat": _2, "ind": _2, "info": _2, "int": _2, "internet": _2, "io": _2, "me": _2, "mil": _2, "net": _2, "nic": _2, "org": _2, "pg": _2, "post": _2, "pro": _2, "res": _2, "travel": _2, "tv": _2, "uk": _2, "up": _2, "us": _2, "web": _3, "cloudns": _3, "blogspot": _3, "barsy": _3, "supabase": _3 } }, "info": { "$": 1, "succ": { "cloudns": _3, "dynamic-dns": _3, "dyndns": _3, "barrel-of-knowledge": _3, "barrell-of-knowledge": _3, "for-our": _3, "groks-the": _3, "groks-this": _3, "here-for-more": _3, "knowsitall": _3, "selfip": _3, "webhop": _3, "barsy": _3, "mayfirst": _3, "forumz": _3, "nsupdate": _3, "dvrcam": _3, "ilovecollege": _3, "no-ip": _3, "dnsupdate": _3, "v-info": _3 } }, "int": { "$": 1, "succ": { "eu": _2 } }, "io": { "$": 1, "succ": { "2038": _3, "com": _2, "on-acorn": _5, "apigee": _3, "b-data": _3, "backplaneapp": _3, "banzaicloud": { "$": 0, "succ": { "app": _3, "backyards": _5 } }, "beagleboard": _3, "bitbucket": _3, "bluebite": _3, "boxfuse": _3, "browsersafetymark": _3, "bigv": { "$": 0, "succ": { "uk0": _3 } }, "cleverapps": _3, "dappnode": { "$": 0, "succ": { "dyndns": _3 } }, "dedyn": _3, "drud": _3, "definima": _3, "fh-muenster": _3, "shw": _3, "forgerock": { "$": 0, "succ": { "id": _3 } }, "ghost": _3, "github": _3, "gitlab": _3, "lolipop": _3, "hasura-app": _3, "hostyhosting": _3, "moonscale": _5, "beebyte": _20, "beebyteapp": { "$": 0, "succ": { "sekd1": _3 } }, "jele": _3, "unispace": { "$": 0, "succ": { "cloud-fr1": _3 } }, "webthings": _3, "loginline": _3, "barsy": _3, "azurecontainer": _5, "ngrok": { "$": 2, "succ": { "ap": _3, "au": _3, "eu": _3, "in": _3, "jp": _3, "sa": _3, "us": _3 } }, "nodeart": { "$": 0, "succ": { "stage": _3 } }, "nid": _3, "pantheonsite": _3, "dyn53": _3, "pstmn": { "$": 2, "succ": { "mock": _3 } }, "protonet": _3, "qoto": _3, "qcx": { "$": 2, "succ": { "sys": _5 } }, "vaporcloud": _3, "vbrplsbx": { "$": 0, "succ": { "g": _3 } }, "on-k3s": _5, "on-rio": _5, "readthedocs": _3, "resindevice": _3, "resinstaging": { "$": 0, "succ": { "devices": _3 } }, "hzc": _3, "sandcats": _3, "shiftcrypto": _3, "shiftedit": _3, "mo-siemens": _3, "musician": _3, "lair": _19, "stolos": _5, "spacekit": _3, "utwente": _3, "s5y": _5, "edugit": _3, "telebit": _3, "thingdust": { "$": 0, "succ": { "dev": _30, "disrec": _30, "prod": _31, "testing": _30 } }, "tickets": _3, "upli": _3, "wedeploy": _3, "editorx": _3, "basicserver": _3, "virtualserver": _3 } }, "iq": _32, "ir": { "$": 1, "succ": { "ac": _2, "co": _2, "gov": _2, "id": _2, "net": _2, "org": _2, "sch": _2, "xn--mgba3a4f16a": _2, "ایران": _2, "xn--mgba3a4fra": _2, "ايران": _2 } }, "is": { "$": 1, "succ": { "net": _2, "com": _2, "edu": _2, "gov": _2, "org": _2, "int": _2, "cupcake": _3, "blogspot": _3 } }, "it": { "$": 1, "succ": { "gov": _2, "edu": _2, "abr": _2, "abruzzo": _2, "aosta-valley": _2, "aostavalley": _2, "bas": _2, "basilicata": _2, "cal": _2, "calabria": _2, "cam": _2, "campania": _2, "emilia-romagna": _2, "emiliaromagna": _2, "emr": _2, "friuli-v-giulia": _2, "friuli-ve-giulia": _2, "friuli-vegiulia": _2, "friuli-venezia-giulia": _2, "friuli-veneziagiulia": _2, "friuli-vgiulia": _2, "friuliv-giulia": _2, "friulive-giulia": _2, "friulivegiulia": _2, "friulivenezia-giulia": _2, "friuliveneziagiulia": _2, "friulivgiulia": _2, "fvg": _2, "laz": _2, "lazio": _2, "lig": _2, "liguria": _2, "lom": _2, "lombardia": _2, "lombardy": _2, "lucania": _2, "mar": _2, "marche": _2, "mol": _2, "molise": _2, "piedmont": _2, "piemonte": _2, "pmn": _2, "pug": _2, "puglia": _2, "sar": _2, "sardegna": _2, "sardinia": _2, "sic": _2, "sicilia": _2, "sicily": _2, "taa": _2, "tos": _2, "toscana": _2, "trentin-sud-tirol": _2, "xn--trentin-sd-tirol-rzb": _2, "trentin-süd-tirol": _2, "trentin-sudtirol": _2, "xn--trentin-sdtirol-7vb": _2, "trentin-südtirol": _2, "trentin-sued-tirol": _2, "trentin-suedtirol": _2, "trentino-a-adige": _2, "trentino-aadige": _2, "trentino-alto-adige": _2, "trentino-altoadige": _2, "trentino-s-tirol": _2, "trentino-stirol": _2, "trentino-sud-tirol": _2, "xn--trentino-sd-tirol-c3b": _2, "trentino-süd-tirol": _2, "trentino-sudtirol": _2, "xn--trentino-sdtirol-szb": _2, "trentino-südtirol": _2, "trentino-sued-tirol": _2, "trentino-suedtirol": _2, "trentino": _2, "trentinoa-adige": _2, "trentinoaadige": _2, "trentinoalto-adige": _2, "trentinoaltoadige": _2, "trentinos-tirol": _2, "trentinostirol": _2, "trentinosud-tirol": _2, "xn--trentinosd-tirol-rzb": _2, "trentinosüd-tirol": _2, "trentinosudtirol": _2, "xn--trentinosdtirol-7vb": _2, "trentinosüdtirol": _2, "trentinosued-tirol": _2, "trentinosuedtirol": _2, "trentinsud-tirol": _2, "xn--trentinsd-tirol-6vb": _2, "trentinsüd-tirol": _2, "trentinsudtirol": _2, "xn--trentinsdtirol-nsb": _2, "trentinsüdtirol": _2, "trentinsued-tirol": _2, "trentinsuedtirol": _2, "tuscany": _2, "umb": _2, "umbria": _2, "val-d-aosta": _2, "val-daosta": _2, "vald-aosta": _2, "valdaosta": _2, "valle-aosta": _2, "valle-d-aosta": _2, "valle-daosta": _2, "valleaosta": _2, "valled-aosta": _2, "valledaosta": _2, "vallee-aoste": _2, "xn--valle-aoste-ebb": _2, "vallée-aoste": _2, "vallee-d-aoste": _2, "xn--valle-d-aoste-ehb": _2, "vallée-d-aoste": _2, "valleeaoste": _2, "xn--valleaoste-e7a": _2, "valléeaoste": _2, "valleedaoste": _2, "xn--valledaoste-ebb": _2, "valléedaoste": _2, "vao": _2, "vda": _2, "ven": _2, "veneto": _2, "ag": _2, "agrigento": _2, "al": _2, "alessandria": _2, "alto-adige": _2, "altoadige": _2, "an": _2, "ancona": _2, "andria-barletta-trani": _2, "andria-trani-barletta": _2, "andriabarlettatrani": _2, "andriatranibarletta": _2, "ao": _2, "aosta": _2, "aoste": _2, "ap": _2, "aq": _2, "aquila": _2, "ar": _2, "arezzo": _2, "ascoli-piceno": _2, "ascolipiceno": _2, "asti": _2, "at": _2, "av": _2, "avellino": _2, "ba": _2, "balsan-sudtirol": _2, "xn--balsan-sdtirol-nsb": _2, "balsan-südtirol": _2, "balsan-suedtirol": _2, "balsan": _2, "bari": _2, "barletta-trani-andria": _2, "barlettatraniandria": _2, "belluno": _2, "benevento": _2, "bergamo": _2, "bg": _2, "bi": _2, "biella": _2, "bl": _2, "bn": _2, "bo": _2, "bologna": _2, "bolzano-altoadige": _2, "bolzano": _2, "bozen-sudtirol": _2, "xn--bozen-sdtirol-2ob": _2, "bozen-südtirol": _2, "bozen-suedtirol": _2, "bozen": _2, "br": _2, "brescia": _2, "brindisi": _2, "bs": _2, "bt": _2, "bulsan-sudtirol": _2, "xn--bulsan-sdtirol-nsb": _2, "bulsan-südtirol": _2, "bulsan-suedtirol": _2, "bulsan": _2, "bz": _2, "ca": _2, "cagliari": _2, "caltanissetta": _2, "campidano-medio": _2, "campidanomedio": _2, "campobasso": _2, "carbonia-iglesias": _2, "carboniaiglesias": _2, "carrara-massa": _2, "carraramassa": _2, "caserta": _2, "catania": _2, "catanzaro": _2, "cb": _2, "ce": _2, "cesena-forli": _2, "xn--cesena-forl-mcb": _2, "cesena-forlì": _2, "cesenaforli": _2, "xn--cesenaforl-i8a": _2, "cesenaforlì": _2, "ch": _2, "chieti": _2, "ci": _2, "cl": _2, "cn": _2, "co": _2, "como": _2, "cosenza": _2, "cr": _2, "cremona": _2, "crotone": _2, "cs": _2, "ct": _2, "cuneo": _2, "cz": _2, "dell-ogliastra": _2, "dellogliastra": _2, "en": _2, "enna": _2, "fc": _2, "fe": _2, "fermo": _2, "ferrara": _2, "fg": _2, "fi": _2, "firenze": _2, "florence": _2, "fm": _2, "foggia": _2, "forli-cesena": _2, "xn--forl-cesena-fcb": _2, "forlì-cesena": _2, "forlicesena": _2, "xn--forlcesena-c8a": _2, "forlìcesena": _2, "fr": _2, "frosinone": _2, "ge": _2, "genoa": _2, "genova": _2, "go": _2, "gorizia": _2, "gr": _2, "grosseto": _2, "iglesias-carbonia": _2, "iglesiascarbonia": _2, "im": _2, "imperia": _2, "is": _2, "isernia": _2, "kr": _2, "la-spezia": _2, "laquila": _2, "laspezia": _2, "latina": _2, "lc": _2, "le": _2, "lecce": _2, "lecco": _2, "li": _2, "livorno": _2, "lo": _2, "lodi": _2, "lt": _2, "lu": _2, "lucca": _2, "macerata": _2, "mantova": _2, "massa-carrara": _2, "massacarrara": _2, "matera": _2, "mb": _2, "mc": _2, "me": _2, "medio-campidano": _2, "mediocampidano": _2, "messina": _2, "mi": _2, "milan": _2, "milano": _2, "mn": _2, "mo": _2, "modena": _2, "monza-brianza": _2, "monza-e-della-brianza": _2, "monza": _2, "monzabrianza": _2, "monzaebrianza": _2, "monzaedellabrianza": _2, "ms": _2, "mt": _2, "na": _2, "naples": _2, "napoli": _2, "no": _2, "novara": _2, "nu": _2, "nuoro": _2, "og": _2, "ogliastra": _2, "olbia-tempio": _2, "olbiatempio": _2, "or": _2, "oristano": _2, "ot": _2, "pa": _2, "padova": _2, "padua": _2, "palermo": _2, "parma": _2, "pavia": _2, "pc": _2, "pd": _2, "pe": _2, "perugia": _2, "pesaro-urbino": _2, "pesarourbino": _2, "pescara": _2, "pg": _2, "pi": _2, "piacenza": _2, "pisa": _2, "pistoia": _2, "pn": _2, "po": _2, "pordenone": _2, "potenza": _2, "pr": _2, "prato": _2, "pt": _2, "pu": _2, "pv": _2, "pz": _2, "ra": _2, "ragusa": _2, "ravenna": _2, "rc": _2, "re": _2, "reggio-calabria": _2, "reggio-emilia": _2, "reggiocalabria": _2, "reggioemilia": _2, "rg": _2, "ri": _2, "rieti": _2, "rimini": _2, "rm": _2, "rn": _2, "ro": _2, "roma": _2, "rome": _2, "rovigo": _2, "sa": _2, "salerno": _2, "sassari": _2, "savona": _2, "si": _2, "siena": _2, "siracusa": _2, "so": _2, "sondrio": _2, "sp": _2, "sr": _2, "ss": _2, "suedtirol": _2, "xn--sdtirol-n2a": _2, "südtirol": _2, "sv": _2, "ta": _2, "taranto": _2, "te": _2, "tempio-olbia": _2, "tempioolbia": _2, "teramo": _2, "terni": _2, "tn": _2, "to": _2, "torino": _2, "tp": _2, "tr": _2, "trani-andria-barletta": _2, "trani-barletta-andria": _2, "traniandriabarletta": _2, "tranibarlettaandria": _2, "trapani": _2, "trento": _2, "treviso": _2, "trieste": _2, "ts": _2, "turin": _2, "tv": _2, "ud": _2, "udine": _2, "urbino-pesaro": _2, "urbinopesaro": _2, "va": _2, "varese": _2, "vb": _2, "vc": _2, "ve": _2, "venezia": _2, "venice": _2, "verbania": _2, "vercelli": _2, "verona": _2, "vi": _2, "vibo-valentia": _2, "vibovalentia": _2, "vicenza": _2, "viterbo": _2, "vr": _2, "vs": _2, "vt": _2, "vv": _2, "blogspot": _3, "ibxos": _3, "iliadboxos": _3, "neen": { "$": 0, "succ": { "jc": _3 } }, "tim": { "$": 0, "succ": { "open": { "$": 0, "succ": { "jelastic": _9 } } } }, "16-b": _3, "32-b": _3, "64-b": _3, "123homepage": _3, "myspreadshop": _3, "syncloud": _3 } }, "je": { "$": 1, "succ": { "co": _2, "net": _2, "org": _2, "of": _3 } }, "jm": _8, "jo": { "$": 1, "succ": { "com": _2, "org": _2, "net": _2, "edu": _2, "sch": _2, "gov": _2, "mil": _2, "name": _2 } }, "jobs": _2, "jp": { "$": 1, "succ": { "ac": _2, "ad": _2, "co": _2, "ed": _2, "go": _2, "gr": _2, "lg": _2, "ne": { "$": 1, "succ": { "aseinet": _28, "gehirn": _3, "ivory": _3, "mail-box": _3, "mints": _3, "mokuren": _3, "opal": _3, "sakura": _3, "sumomo": _3, "topaz": _3 } }, "or": _2, "aichi": { "$": 1, "succ": { "aisai": _2, "ama": _2, "anjo": _2, "asuke": _2, "chiryu": _2, "chita": _2, "fuso": _2, "gamagori": _2, "handa": _2, "hazu": _2, "hekinan": _2, "higashiura": _2, "ichinomiya": _2, "inazawa": _2, "inuyama": _2, "isshiki": _2, "iwakura": _2, "kanie": _2, "kariya": _2, "kasugai": _2, "kira": _2, "kiyosu": _2, "komaki": _2, "konan": _2, "kota": _2, "mihama": _2, "miyoshi": _2, "nishio": _2, "nisshin": _2, "obu": _2, "oguchi": _2, "oharu": _2, "okazaki": _2, "owariasahi": _2, "seto": _2, "shikatsu": _2, "shinshiro": _2, "shitara": _2, "tahara": _2, "takahama": _2, "tobishima": _2, "toei": _2, "togo": _2, "tokai": _2, "tokoname": _2, "toyoake": _2, "toyohashi": _2, "toyokawa": _2, "toyone": _2, "toyota": _2, "tsushima": _2, "yatomi": _2 } }, "akita": { "$": 1, "succ": { "akita": _2, "daisen": _2, "fujisato": _2, "gojome": _2, "hachirogata": _2, "happou": _2, "higashinaruse": _2, "honjo": _2, "honjyo": _2, "ikawa": _2, "kamikoani": _2, "kamioka": _2, "katagami": _2, "kazuno": _2, "kitaakita": _2, "kosaka": _2, "kyowa": _2, "misato": _2, "mitane": _2, "moriyoshi": _2, "nikaho": _2, "noshiro": _2, "odate": _2, "oga": _2, "ogata": _2, "semboku": _2, "yokote": _2, "yurihonjo": _2 } }, "aomori": { "$": 1, "succ": { "aomori": _2, "gonohe": _2, "hachinohe": _2, "hashikami": _2, "hiranai": _2, "hirosaki": _2, "itayanagi": _2, "kuroishi": _2, "misawa": _2, "mutsu": _2, "nakadomari": _2, "noheji": _2, "oirase": _2, "owani": _2, "rokunohe": _2, "sannohe": _2, "shichinohe": _2, "shingo": _2, "takko": _2, "towada": _2, "tsugaru": _2, "tsuruta": _2 } }, "chiba": { "$": 1, "succ": { "abiko": _2, "asahi": _2, "chonan": _2, "chosei": _2, "choshi": _2, "chuo": _2, "funabashi": _2, "futtsu": _2, "hanamigawa": _2, "ichihara": _2, "ichikawa": _2, "ichinomiya": _2, "inzai": _2, "isumi": _2, "kamagaya": _2, "kamogawa": _2, "kashiwa": _2, "katori": _2, "katsuura": _2, "kimitsu": _2, "kisarazu": _2, "kozaki": _2, "kujukuri": _2, "kyonan": _2, "matsudo": _2, "midori": _2, "mihama": _2, "minamiboso": _2, "mobara": _2, "mutsuzawa": _2, "nagara": _2, "nagareyama": _2, "narashino": _2, "narita": _2, "noda": _2, "oamishirasato": _2, "omigawa": _2, "onjuku": _2, "otaki": _2, "sakae": _2, "sakura": _2, "shimofusa": _2, "shirako": _2, "shiroi": _2, "shisui": _2, "sodegaura": _2, "sosa": _2, "tako": _2, "tateyama": _2, "togane": _2, "tohnosho": _2, "tomisato": _2, "urayasu": _2, "yachimata": _2, "yachiyo": _2, "yokaichiba": _2, "yokoshibahikari": _2, "yotsukaido": _2 } }, "ehime": { "$": 1, "succ": { "ainan": _2, "honai": _2, "ikata": _2, "imabari": _2, "iyo": _2, "kamijima": _2, "kihoku": _2, "kumakogen": _2, "masaki": _2, "matsuno": _2, "matsuyama": _2, "namikata": _2, "niihama": _2, "ozu": _2, "saijo": _2, "seiyo": _2, "shikokuchuo": _2, "tobe": _2, "toon": _2, "uchiko": _2, "uwajima": _2, "yawatahama": _2 } }, "fukui": { "$": 1, "succ": { "echizen": _2, "eiheiji": _2, "fukui": _2, "ikeda": _2, "katsuyama": _2, "mihama": _2, "minamiechizen": _2, "obama": _2, "ohi": _2, "ono": _2, "sabae": _2, "sakai": _2, "takahama": _2, "tsuruga": _2, "wakasa": _2 } }, "fukuoka": { "$": 1, "succ": { "ashiya": _2, "buzen": _2, "chikugo": _2, "chikuho": _2, "chikujo": _2, "chikushino": _2, "chikuzen": _2, "chuo": _2, "dazaifu": _2, "fukuchi": _2, "hakata": _2, "higashi": _2, "hirokawa": _2, "hisayama": _2, "iizuka": _2, "inatsuki": _2, "kaho": _2, "kasuga": _2, "kasuya": _2, "kawara": _2, "keisen": _2, "koga": _2, "kurate": _2, "kurogi": _2, "kurume": _2, "minami": _2, "miyako": _2, "miyama": _2, "miyawaka": _2, "mizumaki": _2, "munakata": _2, "nakagawa": _2, "nakama": _2, "nishi": _2, "nogata": _2, "ogori": _2, "okagaki": _2, "okawa": _2, "oki": _2, "omuta": _2, "onga": _2, "onojo": _2, "oto": _2, "saigawa": _2, "sasaguri": _2, "shingu": _2, "shinyoshitomi": _2, "shonai": _2, "soeda": _2, "sue": _2, "tachiarai": _2, "tagawa": _2, "takata": _2, "toho": _2, "toyotsu": _2, "tsuiki": _2, "ukiha": _2, "umi": _2, "usui": _2, "yamada": _2, "yame": _2, "yanagawa": _2, "yukuhashi": _2 } }, "fukushima": { "$": 1, "succ": { "aizubange": _2, "aizumisato": _2, "aizuwakamatsu": _2, "asakawa": _2, "bandai": _2, "date": _2, "fukushima": _2, "furudono": _2, "futaba": _2, "hanawa": _2, "higashi": _2, "hirata": _2, "hirono": _2, "iitate": _2, "inawashiro": _2, "ishikawa": _2, "iwaki": _2, "izumizaki": _2, "kagamiishi": _2, "kaneyama": _2, "kawamata": _2, "kitakata": _2, "kitashiobara": _2, "koori": _2, "koriyama": _2, "kunimi": _2, "miharu": _2, "mishima": _2, "namie": _2, "nango": _2, "nishiaizu": _2, "nishigo": _2, "okuma": _2, "omotego": _2, "ono": _2, "otama": _2, "samegawa": _2, "shimogo": _2, "shirakawa": _2, "showa": _2, "soma": _2, "sukagawa": _2, "taishin": _2, "tamakawa": _2, "tanagura": _2, "tenei": _2, "yabuki": _2, "yamato": _2, "yamatsuri": _2, "yanaizu": _2, "yugawa": _2 } }, "gifu": { "$": 1, "succ": { "anpachi": _2, "ena": _2, "gifu": _2, "ginan": _2, "godo": _2, "gujo": _2, "hashima": _2, "hichiso": _2, "hida": _2, "higashishirakawa": _2, "ibigawa": _2, "ikeda": _2, "kakamigahara": _2, "kani": _2, "kasahara": _2, "kasamatsu": _2, "kawaue": _2, "kitagata": _2, "mino": _2, "minokamo": _2, "mitake": _2, "mizunami": _2, "motosu": _2, "nakatsugawa": _2, "ogaki": _2, "sakahogi": _2, "seki": _2, "sekigahara": _2, "shirakawa": _2, "tajimi": _2, "takayama": _2, "tarui": _2, "toki": _2, "tomika": _2, "wanouchi": _2, "yamagata": _2, "yaotsu": _2, "yoro": _2 } }, "gunma": { "$": 1, "succ": { "annaka": _2, "chiyoda": _2, "fujioka": _2, "higashiagatsuma": _2, "isesaki": _2, "itakura": _2, "kanna": _2, "kanra": _2, "katashina": _2, "kawaba": _2, "kiryu": _2, "kusatsu": _2, "maebashi": _2, "meiwa": _2, "midori": _2, "minakami": _2, "naganohara": _2, "nakanojo": _2, "nanmoku": _2, "numata": _2, "oizumi": _2, "ora": _2, "ota": _2, "shibukawa": _2, "shimonita": _2, "shinto": _2, "showa": _2, "takasaki": _2, "takayama": _2, "tamamura": _2, "tatebayashi": _2, "tomioka": _2, "tsukiyono": _2, "tsumagoi": _2, "ueno": _2, "yoshioka": _2 } }, "hiroshima": { "$": 1, "succ": { "asaminami": _2, "daiwa": _2, "etajima": _2, "fuchu": _2, "fukuyama": _2, "hatsukaichi": _2, "higashihiroshima": _2, "hongo": _2, "jinsekikogen": _2, "kaita": _2, "kui": _2, "kumano": _2, "kure": _2, "mihara": _2, "miyoshi": _2, "naka": _2, "onomichi": _2, "osakikamijima": _2, "otake": _2, "saka": _2, "sera": _2, "seranishi": _2, "shinichi": _2, "shobara": _2, "takehara": _2 } }, "hokkaido": { "$": 1, "succ": { "abashiri": _2, "abira": _2, "aibetsu": _2, "akabira": _2, "akkeshi": _2, "asahikawa": _2, "ashibetsu": _2, "ashoro": _2, "assabu": _2, "atsuma": _2, "bibai": _2, "biei": _2, "bifuka": _2, "bihoro": _2, "biratori": _2, "chippubetsu": _2, "chitose": _2, "date": _2, "ebetsu": _2, "embetsu": _2, "eniwa": _2, "erimo": _2, "esan": _2, "esashi": _2, "fukagawa": _2, "fukushima": _2, "furano": _2, "furubira": _2, "haboro": _2, "hakodate": _2, "hamatonbetsu": _2, "hidaka": _2, "higashikagura": _2, "higashikawa": _2, "hiroo": _2, "hokuryu": _2, "hokuto": _2, "honbetsu": _2, "horokanai": _2, "horonobe": _2, "ikeda": _2, "imakane": _2, "ishikari": _2, "iwamizawa": _2, "iwanai": _2, "kamifurano": _2, "kamikawa": _2, "kamishihoro": _2, "kamisunagawa": _2, "kamoenai": _2, "kayabe": _2, "kembuchi": _2, "kikonai": _2, "kimobetsu": _2, "kitahiroshima": _2, "kitami": _2, "kiyosato": _2, "koshimizu": _2, "kunneppu": _2, "kuriyama": _2, "kuromatsunai": _2, "kushiro": _2, "kutchan": _2, "kyowa": _2, "mashike": _2, "matsumae": _2, "mikasa": _2, "minamifurano": _2, "mombetsu": _2, "moseushi": _2, "mukawa": _2, "muroran": _2, "naie": _2, "nakagawa": _2, "nakasatsunai": _2, "nakatombetsu": _2, "nanae": _2, "nanporo": _2, "nayoro": _2, "nemuro": _2, "niikappu": _2, "niki": _2, "nishiokoppe": _2, "noboribetsu": _2, "numata": _2, "obihiro": _2, "obira": _2, "oketo": _2, "okoppe": _2, "otaru": _2, "otobe": _2, "otofuke": _2, "otoineppu": _2, "oumu": _2, "ozora": _2, "pippu": _2, "rankoshi": _2, "rebun": _2, "rikubetsu": _2, "rishiri": _2, "rishirifuji": _2, "saroma": _2, "sarufutsu": _2, "shakotan": _2, "shari": _2, "shibecha": _2, "shibetsu": _2, "shikabe": _2, "shikaoi": _2, "shimamaki": _2, "shimizu": _2, "shimokawa": _2, "shinshinotsu": _2, "shintoku": _2, "shiranuka": _2, "shiraoi": _2, "shiriuchi": _2, "sobetsu": _2, "sunagawa": _2, "taiki": _2, "takasu": _2, "takikawa": _2, "takinoue": _2, "teshikaga": _2, "tobetsu": _2, "tohma": _2, "tomakomai": _2, "tomari": _2, "toya": _2, "toyako": _2, "toyotomi": _2, "toyoura": _2, "tsubetsu": _2, "tsukigata": _2, "urakawa": _2, "urausu": _2, "uryu": _2, "utashinai": _2, "wakkanai": _2, "wassamu": _2, "yakumo": _2, "yoichi": _2 } }, "hyogo": { "$": 1, "succ": { "aioi": _2, "akashi": _2, "ako": _2, "amagasaki": _2, "aogaki": _2, "asago": _2, "ashiya": _2, "awaji": _2, "fukusaki": _2, "goshiki": _2, "harima": _2, "himeji": _2, "ichikawa": _2, "inagawa": _2, "itami": _2, "kakogawa": _2, "kamigori": _2, "kamikawa": _2, "kasai": _2, "kasuga": _2, "kawanishi": _2, "miki": _2, "minamiawaji": _2, "nishinomiya": _2, "nishiwaki": _2, "ono": _2, "sanda": _2, "sannan": _2, "sasayama": _2, "sayo": _2, "shingu": _2, "shinonsen": _2, "shiso": _2, "sumoto": _2, "taishi": _2, "taka": _2, "takarazuka": _2, "takasago": _2, "takino": _2, "tamba": _2, "tatsuno": _2, "toyooka": _2, "yabu": _2, "yashiro": _2, "yoka": _2, "yokawa": _2 } }, "ibaraki": { "$": 1, "succ": { "ami": _2, "asahi": _2, "bando": _2, "chikusei": _2, "daigo": _2, "fujishiro": _2, "hitachi": _2, "hitachinaka": _2, "hitachiomiya": _2, "hitachiota": _2, "ibaraki": _2, "ina": _2, "inashiki": _2, "itako": _2, "iwama": _2, "joso": _2, "kamisu": _2, "kasama": _2, "kashima": _2, "kasumigaura": _2, "koga": _2, "miho": _2, "mito": _2, "moriya": _2, "naka": _2, "namegata": _2, "oarai": _2, "ogawa": _2, "omitama": _2, "ryugasaki": _2, "sakai": _2, "sakuragawa": _2, "shimodate": _2, "shimotsuma": _2, "shirosato": _2, "sowa": _2, "suifu": _2, "takahagi": _2, "tamatsukuri": _2, "tokai": _2, "tomobe": _2, "tone": _2, "toride": _2, "tsuchiura": _2, "tsukuba": _2, "uchihara": _2, "ushiku": _2, "yachiyo": _2, "yamagata": _2, "yawara": _2, "yuki": _2 } }, "ishikawa": { "$": 1, "succ": { "anamizu": _2, "hakui": _2, "hakusan": _2, "kaga": _2, "kahoku": _2, "kanazawa": _2, "kawakita": _2, "komatsu": _2, "nakanoto": _2, "nanao": _2, "nomi": _2, "nonoichi": _2, "noto": _2, "shika": _2, "suzu": _2, "tsubata": _2, "tsurugi": _2, "uchinada": _2, "wajima": _2 } }, "iwate": { "$": 1, "succ": { "fudai": _2, "fujisawa": _2, "hanamaki": _2, "hiraizumi": _2, "hirono": _2, "ichinohe": _2, "ichinoseki": _2, "iwaizumi": _2, "iwate": _2, "joboji": _2, "kamaishi": _2, "kanegasaki": _2, "karumai": _2, "kawai": _2, "kitakami": _2, "kuji": _2, "kunohe": _2, "kuzumaki": _2, "miyako": _2, "mizusawa": _2, "morioka": _2, "ninohe": _2, "noda": _2, "ofunato": _2, "oshu": _2, "otsuchi": _2, "rikuzentakata": _2, "shiwa": _2, "shizukuishi": _2, "sumita": _2, "tanohata": _2, "tono": _2, "yahaba": _2, "yamada": _2 } }, "kagawa": { "$": 1, "succ": { "ayagawa": _2, "higashikagawa": _2, "kanonji": _2, "kotohira": _2, "manno": _2, "marugame": _2, "mitoyo": _2, "naoshima": _2, "sanuki": _2, "tadotsu": _2, "takamatsu": _2, "tonosho": _2, "uchinomi": _2, "utazu": _2, "zentsuji": _2 } }, "kagoshima": { "$": 1, "succ": { "akune": _2, "amami": _2, "hioki": _2, "isa": _2, "isen": _2, "izumi": _2, "kagoshima": _2, "kanoya": _2, "kawanabe": _2, "kinko": _2, "kouyama": _2, "makurazaki": _2, "matsumoto": _2, "minamitane": _2, "nakatane": _2, "nishinoomote": _2, "satsumasendai": _2, "soo": _2, "tarumizu": _2, "yusui": _2 } }, "kanagawa": { "$": 1, "succ": { "aikawa": _2, "atsugi": _2, "ayase": _2, "chigasaki": _2, "ebina": _2, "fujisawa": _2, "hadano": _2, "hakone": _2, "hiratsuka": _2, "isehara": _2, "kaisei": _2, "kamakura": _2, "kiyokawa": _2, "matsuda": _2, "minamiashigara": _2, "miura": _2, "nakai": _2, "ninomiya": _2, "odawara": _2, "oi": _2, "oiso": _2, "sagamihara": _2, "samukawa": _2, "tsukui": _2, "yamakita": _2, "yamato": _2, "yokosuka": _2, "yugawara": _2, "zama": _2, "zushi": _2 } }, "kochi": { "$": 1, "succ": { "aki": _2, "geisei": _2, "hidaka": _2, "higashitsuno": _2, "ino": _2, "kagami": _2, "kami": _2, "kitagawa": _2, "kochi": _2, "mihara": _2, "motoyama": _2, "muroto": _2, "nahari": _2, "nakamura": _2, "nankoku": _2, "nishitosa": _2, "niyodogawa": _2, "ochi": _2, "okawa": _2, "otoyo": _2, "otsuki": _2, "sakawa": _2, "sukumo": _2, "susaki": _2, "tosa": _2, "tosashimizu": _2, "toyo": _2, "tsuno": _2, "umaji": _2, "yasuda": _2, "yusuhara": _2 } }, "kumamoto": { "$": 1, "succ": { "amakusa": _2, "arao": _2, "aso": _2, "choyo": _2, "gyokuto": _2, "kamiamakusa": _2, "kikuchi": _2, "kumamoto": _2, "mashiki": _2, "mifune": _2, "minamata": _2, "minamioguni": _2, "nagasu": _2, "nishihara": _2, "oguni": _2, "ozu": _2, "sumoto": _2, "takamori": _2, "uki": _2, "uto": _2, "yamaga": _2, "yamato": _2, "yatsushiro": _2 } }, "kyoto": { "$": 1, "succ": { "ayabe": _2, "fukuchiyama": _2, "higashiyama": _2, "ide": _2, "ine": _2, "joyo": _2, "kameoka": _2, "kamo": _2, "kita": _2, "kizu": _2, "kumiyama": _2, "kyotamba": _2, "kyotanabe": _2, "kyotango": _2, "maizuru": _2, "minami": _2, "minamiyamashiro": _2, "miyazu": _2, "muko": _2, "nagaokakyo": _2, "nakagyo": _2, "nantan": _2, "oyamazaki": _2, "sakyo": _2, "seika": _2, "tanabe": _2, "uji": _2, "ujitawara": _2, "wazuka": _2, "yamashina": _2, "yawata": _2 } }, "mie": { "$": 1, "succ": { "asahi": _2, "inabe": _2, "ise": _2, "kameyama": _2, "kawagoe": _2, "kiho": _2, "kisosaki": _2, "kiwa": _2, "komono": _2, "kumano": _2, "kuwana": _2, "matsusaka": _2, "meiwa": _2, "mihama": _2, "minamiise": _2, "misugi": _2, "miyama": _2, "nabari": _2, "shima": _2, "suzuka": _2, "tado": _2, "taiki": _2, "taki": _2, "tamaki": _2, "toba": _2, "tsu": _2, "udono": _2, "ureshino": _2, "watarai": _2, "yokkaichi": _2 } }, "miyagi": { "$": 1, "succ": { "furukawa": _2, "higashimatsushima": _2, "ishinomaki": _2, "iwanuma": _2, "kakuda": _2, "kami": _2, "kawasaki": _2, "marumori": _2, "matsushima": _2, "minamisanriku": _2, "misato": _2, "murata": _2, "natori": _2, "ogawara": _2, "ohira": _2, "onagawa": _2, "osaki": _2, "rifu": _2, "semine": _2, "shibata": _2, "shichikashuku": _2, "shikama": _2, "shiogama": _2, "shiroishi": _2, "tagajo": _2, "taiwa": _2, "tome": _2, "tomiya": _2, "wakuya": _2, "watari": _2, "yamamoto": _2, "zao": _2 } }, "miyazaki": { "$": 1, "succ": { "aya": _2, "ebino": _2, "gokase": _2, "hyuga": _2, "kadogawa": _2, "kawaminami": _2, "kijo": _2, "kitagawa": _2, "kitakata": _2, "kitaura": _2, "kobayashi": _2, "kunitomi": _2, "kushima": _2, "mimata": _2, "miyakonojo": _2, "miyazaki": _2, "morotsuka": _2, "nichinan": _2, "nishimera": _2, "nobeoka": _2, "saito": _2, "shiiba": _2, "shintomi": _2, "takaharu": _2, "takanabe": _2, "takazaki": _2, "tsuno": _2 } }, "nagano": { "$": 1, "succ": { "achi": _2, "agematsu": _2, "anan": _2, "aoki": _2, "asahi": _2, "azumino": _2, "chikuhoku": _2, "chikuma": _2, "chino": _2, "fujimi": _2, "hakuba": _2, "hara": _2, "hiraya": _2, "iida": _2, "iijima": _2, "iiyama": _2, "iizuna": _2, "ikeda": _2, "ikusaka": _2, "ina": _2, "karuizawa": _2, "kawakami": _2, "kiso": _2, "kisofukushima": _2, "kitaaiki": _2, "komagane": _2, "komoro": _2, "matsukawa": _2, "matsumoto": _2, "miasa": _2, "minamiaiki": _2, "minamimaki": _2, "minamiminowa": _2, "minowa": _2, "miyada": _2, "miyota": _2, "mochizuki": _2, "nagano": _2, "nagawa": _2, "nagiso": _2, "nakagawa": _2, "nakano": _2, "nozawaonsen": _2, "obuse": _2, "ogawa": _2, "okaya": _2, "omachi": _2, "omi": _2, "ookuwa": _2, "ooshika": _2, "otaki": _2, "otari": _2, "sakae": _2, "sakaki": _2, "saku": _2, "sakuho": _2, "shimosuwa": _2, "shinanomachi": _2, "shiojiri": _2, "suwa": _2, "suzaka": _2, "takagi": _2, "takamori": _2, "takayama": _2, "tateshina": _2, "tatsuno": _2, "togakushi": _2, "togura": _2, "tomi": _2, "ueda": _2, "wada": _2, "yamagata": _2, "yamanouchi": _2, "yasaka": _2, "yasuoka": _2 } }, "nagasaki": { "$": 1, "succ": { "chijiwa": _2, "futsu": _2, "goto": _2, "hasami": _2, "hirado": _2, "iki": _2, "isahaya": _2, "kawatana": _2, "kuchinotsu": _2, "matsuura": _2, "nagasaki": _2, "obama": _2, "omura": _2, "oseto": _2, "saikai": _2, "sasebo": _2, "seihi": _2, "shimabara": _2, "shinkamigoto": _2, "togitsu": _2, "tsushima": _2, "unzen": _2 } }, "nara": { "$": 1, "succ": { "ando": _2, "gose": _2, "heguri": _2, "higashiyoshino": _2, "ikaruga": _2, "ikoma": _2, "kamikitayama": _2, "kanmaki": _2, "kashiba": _2, "kashihara": _2, "katsuragi": _2, "kawai": _2, "kawakami": _2, "kawanishi": _2, "koryo": _2, "kurotaki": _2, "mitsue": _2, "miyake": _2, "nara": _2, "nosegawa": _2, "oji": _2, "ouda": _2, "oyodo": _2, "sakurai": _2, "sango": _2, "shimoichi": _2, "shimokitayama": _2, "shinjo": _2, "soni": _2, "takatori": _2, "tawaramoto": _2, "tenkawa": _2, "tenri": _2, "uda": _2, "yamatokoriyama": _2, "yamatotakada": _2, "yamazoe": _2, "yoshino": _2 } }, "niigata": { "$": 1, "succ": { "aga": _2, "agano": _2, "gosen": _2, "itoigawa": _2, "izumozaki": _2, "joetsu": _2, "kamo": _2, "kariwa": _2, "kashiwazaki": _2, "minamiuonuma": _2, "mitsuke": _2, "muika": _2, "murakami": _2, "myoko": _2, "nagaoka": _2, "niigata": _2, "ojiya": _2, "omi": _2, "sado": _2, "sanjo": _2, "seiro": _2, "seirou": _2, "sekikawa": _2, "shibata": _2, "tagami": _2, "tainai": _2, "tochio": _2, "tokamachi": _2, "tsubame": _2, "tsunan": _2, "uonuma": _2, "yahiko": _2, "yoita": _2, "yuzawa": _2 } }, "oita": { "$": 1, "succ": { "beppu": _2, "bungoono": _2, "bungotakada": _2, "hasama": _2, "hiji": _2, "himeshima": _2, "hita": _2, "kamitsue": _2, "kokonoe": _2, "kuju": _2, "kunisaki": _2, "kusu": _2, "oita": _2, "saiki": _2, "taketa": _2, "tsukumi": _2, "usa": _2, "usuki": _2, "yufu": _2 } }, "okayama": { "$": 1, "succ": { "akaiwa": _2, "asakuchi": _2, "bizen": _2, "hayashima": _2, "ibara": _2, "kagamino": _2, "kasaoka": _2, "kibichuo": _2, "kumenan": _2, "kurashiki": _2, "maniwa": _2, "misaki": _2, "nagi": _2, "niimi": _2, "nishiawakura": _2, "okayama": _2, "satosho": _2, "setouchi": _2, "shinjo": _2, "shoo": _2, "soja": _2, "takahashi": _2, "tamano": _2, "tsuyama": _2, "wake": _2, "yakage": _2 } }, "okinawa": { "$": 1, "succ": { "aguni": _2, "ginowan": _2, "ginoza": _2, "gushikami": _2, "haebaru": _2, "higashi": _2, "hirara": _2, "iheya": _2, "ishigaki": _2, "ishikawa": _2, "itoman": _2, "izena": _2, "kadena": _2, "kin": _2, "kitadaito": _2, "kitanakagusuku": _2, "kumejima": _2, "kunigami": _2, "minamidaito": _2, "motobu": _2, "nago": _2, "naha": _2, "nakagusuku": _2, "nakijin": _2, "nanjo": _2, "nishihara": _2, "ogimi": _2, "okinawa": _2, "onna": _2, "shimoji": _2, "taketomi": _2, "tarama": _2, "tokashiki": _2, "tomigusuku": _2, "tonaki": _2, "urasoe": _2, "uruma": _2, "yaese": _2, "yomitan": _2, "yonabaru": _2, "yonaguni": _2, "zamami": _2 } }, "osaka": { "$": 1, "succ": { "abeno": _2, "chihayaakasaka": _2, "chuo": _2, "daito": _2, "fujiidera": _2, "habikino": _2, "hannan": _2, "higashiosaka": _2, "higashisumiyoshi": _2, "higashiyodogawa": _2, "hirakata": _2, "ibaraki": _2, "ikeda": _2, "izumi": _2, "izumiotsu": _2, "izumisano": _2, "kadoma": _2, "kaizuka": _2, "kanan": _2, "kashiwara": _2, "katano": _2, "kawachinagano": _2, "kishiwada": _2, "kita": _2, "kumatori": _2, "matsubara": _2, "minato": _2, "minoh": _2, "misaki": _2, "moriguchi": _2, "neyagawa": _2, "nishi": _2, "nose": _2, "osakasayama": _2, "sakai": _2, "sayama": _2, "sennan": _2, "settsu": _2, "shijonawate": _2, "shimamoto": _2, "suita": _2, "tadaoka": _2, "taishi": _2, "tajiri": _2, "takaishi": _2, "takatsuki": _2, "tondabayashi": _2, "toyonaka": _2, "toyono": _2, "yao": _2 } }, "saga": { "$": 1, "succ": { "ariake": _2, "arita": _2, "fukudomi": _2, "genkai": _2, "hamatama": _2, "hizen": _2, "imari": _2, "kamimine": _2, "kanzaki": _2, "karatsu": _2, "kashima": _2, "kitagata": _2, "kitahata": _2, "kiyama": _2, "kouhoku": _2, "kyuragi": _2, "nishiarita": _2, "ogi": _2, "omachi": _2, "ouchi": _2, "saga": _2, "shiroishi": _2, "taku": _2, "tara": _2, "tosu": _2, "yoshinogari": _2 } }, "saitama": { "$": 1, "succ": { "arakawa": _2, "asaka": _2, "chichibu": _2, "fujimi": _2, "fujimino": _2, "fukaya": _2, "hanno": _2, "hanyu": _2, "hasuda": _2, "hatogaya": _2, "hatoyama": _2, "hidaka": _2, "higashichichibu": _2, "higashimatsuyama": _2, "honjo": _2, "ina": _2, "iruma": _2, "iwatsuki": _2, "kamiizumi": _2, "kamikawa": _2, "kamisato": _2, "kasukabe": _2, "kawagoe": _2, "kawaguchi": _2, "kawajima": _2, "kazo": _2, "kitamoto": _2, "koshigaya": _2, "kounosu": _2, "kuki": _2, "kumagaya": _2, "matsubushi": _2, "minano": _2, "misato": _2, "miyashiro": _2, "miyoshi": _2, "moroyama": _2, "nagatoro": _2, "namegawa": _2, "niiza": _2, "ogano": _2, "ogawa": _2, "ogose": _2, "okegawa": _2, "omiya": _2, "otaki": _2, "ranzan": _2, "ryokami": _2, "saitama": _2, "sakado": _2, "satte": _2, "sayama": _2, "shiki": _2, "shiraoka": _2, "soka": _2, "sugito": _2, "toda": _2, "tokigawa": _2, "tokorozawa": _2, "tsurugashima": _2, "urawa": _2, "warabi": _2, "yashio": _2, "yokoze": _2, "yono": _2, "yorii": _2, "yoshida": _2, "yoshikawa": _2, "yoshimi": _2 } }, "shiga": { "$": 1, "succ": { "aisho": _2, "gamo": _2, "higashiomi": _2, "hikone": _2, "koka": _2, "konan": _2, "kosei": _2, "koto": _2, "kusatsu": _2, "maibara": _2, "moriyama": _2, "nagahama": _2, "nishiazai": _2, "notogawa": _2, "omihachiman": _2, "otsu": _2, "ritto": _2, "ryuoh": _2, "takashima": _2, "takatsuki": _2, "torahime": _2, "toyosato": _2, "yasu": _2 } }, "shimane": { "$": 1, "succ": { "akagi": _2, "ama": _2, "gotsu": _2, "hamada": _2, "higashiizumo": _2, "hikawa": _2, "hikimi": _2, "izumo": _2, "kakinoki": _2, "masuda": _2, "matsue": _2, "misato": _2, "nishinoshima": _2, "ohda": _2, "okinoshima": _2, "okuizumo": _2, "shimane": _2, "tamayu": _2, "tsuwano": _2, "unnan": _2, "yakumo": _2, "yasugi": _2, "yatsuka": _2 } }, "shizuoka": { "$": 1, "succ": { "arai": _2, "atami": _2, "fuji": _2, "fujieda": _2, "fujikawa": _2, "fujinomiya": _2, "fukuroi": _2, "gotemba": _2, "haibara": _2, "hamamatsu": _2, "higashiizu": _2, "ito": _2, "iwata": _2, "izu": _2, "izunokuni": _2, "kakegawa": _2, "kannami": _2, "kawanehon": _2, "kawazu": _2, "kikugawa": _2, "kosai": _2, "makinohara": _2, "matsuzaki": _2, "minamiizu": _2, "mishima": _2, "morimachi": _2, "nishiizu": _2, "numazu": _2, "omaezaki": _2, "shimada": _2, "shimizu": _2, "shimoda": _2, "shizuoka": _2, "susono": _2, "yaizu": _2, "yoshida": _2 } }, "tochigi": { "$": 1, "succ": { "ashikaga": _2, "bato": _2, "haga": _2, "ichikai": _2, "iwafune": _2, "kaminokawa": _2, "kanuma": _2, "karasuyama": _2, "kuroiso": _2, "mashiko": _2, "mibu": _2, "moka": _2, "motegi": _2, "nasu": _2, "nasushiobara": _2, "nikko": _2, "nishikata": _2, "nogi": _2, "ohira": _2, "ohtawara": _2, "oyama": _2, "sakura": _2, "sano": _2, "shimotsuke": _2, "shioya": _2, "takanezawa": _2, "tochigi": _2, "tsuga": _2, "ujiie": _2, "utsunomiya": _2, "yaita": _2 } }, "tokushima": { "$": 1, "succ": { "aizumi": _2, "anan": _2, "ichiba": _2, "itano": _2, "kainan": _2, "komatsushima": _2, "matsushige": _2, "mima": _2, "minami": _2, "miyoshi": _2, "mugi": _2, "nakagawa": _2, "naruto": _2, "sanagochi": _2, "shishikui": _2, "tokushima": _2, "wajiki": _2 } }, "tokyo": { "$": 1, "succ": { "adachi": _2, "akiruno": _2, "akishima": _2, "aogashima": _2, "arakawa": _2, "bunkyo": _2, "chiyoda": _2, "chofu": _2, "chuo": _2, "edogawa": _2, "fuchu": _2, "fussa": _2, "hachijo": _2, "hachioji": _2, "hamura": _2, "higashikurume": _2, "higashimurayama": _2, "higashiyamato": _2, "hino": _2, "hinode": _2, "hinohara": _2, "inagi": _2, "itabashi": _2, "katsushika": _2, "kita": _2, "kiyose": _2, "kodaira": _2, "koganei": _2, "kokubunji": _2, "komae": _2, "koto": _2, "kouzushima": _2, "kunitachi": _2, "machida": _2, "meguro": _2, "minato": _2, "mitaka": _2, "mizuho": _2, "musashimurayama": _2, "musashino": _2, "nakano": _2, "nerima": _2, "ogasawara": _2, "okutama": _2, "ome": _2, "oshima": _2, "ota": _2, "setagaya": _2, "shibuya": _2, "shinagawa": _2, "shinjuku": _2, "suginami": _2, "sumida": _2, "tachikawa": _2, "taito": _2, "tama": _2, "toshima": _2 } }, "tottori": { "$": 1, "succ": { "chizu": _2, "hino": _2, "kawahara": _2, "koge": _2, "kotoura": _2, "misasa": _2, "nanbu": _2, "nichinan": _2, "sakaiminato": _2, "tottori": _2, "wakasa": _2, "yazu": _2, "yonago": _2 } }, "toyama": { "$": 1, "succ": { "asahi": _2, "fuchu": _2, "fukumitsu": _2, "funahashi": _2, "himi": _2, "imizu": _2, "inami": _2, "johana": _2, "kamiichi": _2, "kurobe": _2, "nakaniikawa": _2, "namerikawa": _2, "nanto": _2, "nyuzen": _2, "oyabe": _2, "taira": _2, "takaoka": _2, "tateyama": _2, "toga": _2, "tonami": _2, "toyama": _2, "unazuki": _2, "uozu": _2, "yamada": _2 } }, "wakayama": { "$": 1, "succ": { "arida": _2, "aridagawa": _2, "gobo": _2, "hashimoto": _2, "hidaka": _2, "hirogawa": _2, "inami": _2, "iwade": _2, "kainan": _2, "kamitonda": _2, "katsuragi": _2, "kimino": _2, "kinokawa": _2, "kitayama": _2, "koya": _2, "koza": _2, "kozagawa": _2, "kudoyama": _2, "kushimoto": _2, "mihama": _2, "misato": _2, "nachikatsuura": _2, "shingu": _2, "shirahama": _2, "taiji": _2, "tanabe": _2, "wakayama": _2, "yuasa": _2, "yura": _2 } }, "yamagata": { "$": 1, "succ": { "asahi": _2, "funagata": _2, "higashine": _2, "iide": _2, "kahoku": _2, "kaminoyama": _2, "kaneyama": _2, "kawanishi": _2, "mamurogawa": _2, "mikawa": _2, "murayama": _2, "nagai": _2, "nakayama": _2, "nanyo": _2, "nishikawa": _2, "obanazawa": _2, "oe": _2, "oguni": _2, "ohkura": _2, "oishida": _2, "sagae": _2, "sakata": _2, "sakegawa": _2, "shinjo": _2, "shirataka": _2, "shonai": _2, "takahata": _2, "tendo": _2, "tozawa": _2, "tsuruoka": _2, "yamagata": _2, "yamanobe": _2, "yonezawa": _2, "yuza": _2 } }, "yamaguchi": { "$": 1, "succ": { "abu": _2, "hagi": _2, "hikari": _2, "hofu": _2, "iwakuni": _2, "kudamatsu": _2, "mitou": _2, "nagato": _2, "oshima": _2, "shimonoseki": _2, "shunan": _2, "tabuse": _2, "tokuyama": _2, "toyota": _2, "ube": _2, "yuu": _2 } }, "yamanashi": { "$": 1, "succ": { "chuo": _2, "doshi": _2, "fuefuki": _2, "fujikawa": _2, "fujikawaguchiko": _2, "fujiyoshida": _2, "hayakawa": _2, "hokuto": _2, "ichikawamisato": _2, "kai": _2, "kofu": _2, "koshu": _2, "kosuge": _2, "minami-alps": _2, "minobu": _2, "nakamichi": _2, "nanbu": _2, "narusawa": _2, "nirasaki": _2, "nishikatsura": _2, "oshino": _2, "otsuki": _2, "showa": _2, "tabayama": _2, "tsuru": _2, "uenohara": _2, "yamanakako": _2, "yamanashi": _2 } }, "xn--4pvxs": _2, "栃木": _2, "xn--vgu402c": _2, "愛知": _2, "xn--c3s14m": _2, "愛媛": _2, "xn--f6qx53a": _2, "兵庫": _2, "xn--8pvr4u": _2, "熊本": _2, "xn--uist22h": _2, "茨城": _2, "xn--djrs72d6uy": _2, "北海道": _2, "xn--mkru45i": _2, "千葉": _2, "xn--0trq7p7nn": _2, "和歌山": _2, "xn--8ltr62k": _2, "長崎": _2, "xn--2m4a15e": _2, "長野": _2, "xn--efvn9s": _2, "新潟": _2, "xn--32vp30h": _2, "青森": _2, "xn--4it797k": _2, "静岡": _2, "xn--1lqs71d": _2, "東京": _2, "xn--5rtp49c": _2, "石川": _2, "xn--5js045d": _2, "埼玉": _2, "xn--ehqz56n": _2, "三重": _2, "xn--1lqs03n": _2, "京都": _2, "xn--qqqt11m": _2, "佐賀": _2, "xn--kbrq7o": _2, "大分": _2, "xn--pssu33l": _2, "大阪": _2, "xn--ntsq17g": _2, "奈良": _2, "xn--uisz3g": _2, "宮城": _2, "xn--6btw5a": _2, "宮崎": _2, "xn--1ctwo": _2, "富山": _2, "xn--6orx2r": _2, "山口": _2, "xn--rht61e": _2, "山形": _2, "xn--rht27z": _2, "山梨": _2, "xn--djty4k": _2, "岩手": _2, "xn--nit225k": _2, "岐阜": _2, "xn--rht3d": _2, "岡山": _2, "xn--klty5x": _2, "島根": _2, "xn--kltx9a": _2, "広島": _2, "xn--kltp7d": _2, "徳島": _2, "xn--uuwu58a": _2, "沖縄": _2, "xn--zbx025d": _2, "滋賀": _2, "xn--ntso0iqx3a": _2, "神奈川": _2, "xn--elqq16h": _2, "福井": _2, "xn--4it168d": _2, "福岡": _2, "xn--klt787d": _2, "福島": _2, "xn--rny31h": _2, "秋田": _2, "xn--7t0a264c": _2, "群馬": _2, "xn--5rtq34k": _2, "香川": _2, "xn--k7yn95e": _2, "高知": _2, "xn--tor131o": _2, "鳥取": _2, "xn--d5qv7z876c": _2, "鹿児島": _2, "kawasaki": _8, "kitakyushu": _8, "kobe": _8, "nagoya": _8, "sapporo": _8, "sendai": _8, "yokohama": _8, "buyshop": _3, "fashionstore": _3, "handcrafted": _3, "kawaiishop": _3, "supersale": _3, "theshop": _3, "usercontent": _3, "angry": _3, "babyblue": _3, "babymilk": _3, "backdrop": _3, "bambina": _3, "bitter": _3, "blush": _3, "boo": _3, "boy": _3, "boyfriend": _3, "but": _3, "candypop": _3, "capoo": _3, "catfood": _3, "cheap": _3, "chicappa": _3, "chillout": _3, "chips": _3, "chowder": _3, "chu": _3, "ciao": _3, "cocotte": _3, "coolblog": _3, "cranky": _3, "cutegirl": _3, "daa": _3, "deca": _3, "deci": _3, "digick": _3, "egoism": _3, "fakefur": _3, "fem": _3, "flier": _3, "floppy": _3, "fool": _3, "frenchkiss": _3, "girlfriend": _3, "girly": _3, "gloomy": _3, "gonna": _3, "greater": _3, "hacca": _3, "heavy": _3, "her": _3, "hiho": _3, "hippy": _3, "holy": _3, "hungry": _3, "icurus": _3, "itigo": _3, "jellybean": _3, "kikirara": _3, "kill": _3, "kilo": _3, "kuron": _3, "littlestar": _3, "lolipopmc": _3, "lolitapunk": _3, "lomo": _3, "lovepop": _3, "lovesick": _3, "main": _3, "mods": _3, "mond": _3, "mongolian": _3, "moo": _3, "namaste": _3, "nikita": _3, "nobushi": _3, "noor": _3, "oops": _3, "parallel": _3, "parasite": _3, "pecori": _3, "peewee": _3, "penne": _3, "pepper": _3, "perma": _3, "pigboat": _3, "pinoko": _3, "punyu": _3, "pupu": _3, "pussycat": _3, "pya": _3, "raindrop": _3, "readymade": _3, "sadist": _3, "schoolbus": _3, "secret": _3, "staba": _3, "stripper": _3, "sub": _3, "sunnyday": _3, "thick": _3, "tonkotsu": _3, "under": _3, "upper": _3, "velvet": _3, "verse": _3, "versus": _3, "vivian": _3, "watson": _3, "weblike": _3, "whitesnow": _3, "zombie": _3, "blogspot": _3, "2-d": _3, "bona": _3, "crap": _3, "daynight": _3, "eek": _3, "flop": _3, "halfmoon": _3, "jeez": _3, "matrix": _3, "mimoza": _3, "netgamers": _3, "nyanta": _3, "o0o0": _3, "rdy": _3, "rgr": _3, "rulez": _3, "sakurastorage": { "$": 0, "succ": { "isk01": _12, "isk02": _12 } }, "saloon": _3, "sblo": _3, "skr": _3, "tank": _3, "uh-oh": _3, "undo": _3, "webaccel": { "$": 0, "succ": { "rs": _3, "user": _3 } }, "websozai": _3, "xii": _3 } }, "ke": { "$": 1, "succ": { "ac": _2, "co": _6, "go": _2, "info": _2, "me": _2, "mobi": _2, "ne": _2, "or": _2, "sc": _2 } }, "kg": { "$": 1, "succ": { "org": _2, "net": _2, "com": _2, "edu": _2, "gov": _2, "mil": _2, "blog": _3, "io": _3, "jp": _3, "tv": _3, "uk": _3, "us": _3 } }, "kh": _8, "ki": _33, "km": { "$": 1, "succ": { "org": _2, "nom": _2, "gov": _2, "prd": _2, "tm": _2, "edu": _2, "mil": _2, "ass": _2, "com": _2, "coop": _2, "asso": _2, "presse": _2, "medecin": _2, "notaires": _2, "pharmaciens": _2, "veterinaire": _2, "gouv": _2 } }, "kn": { "$": 1, "succ": { "net": _2, "org": _2, "edu": _2, "gov": _2 } }, "kp": { "$": 1, "succ": { "com": _2, "edu": _2, "gov": _2, "org": _2, "rep": _2, "tra": _2 } }, "kr": { "$": 1, "succ": { "ac": _2, "co": _2, "es": _2, "go": _2, "hs": _2, "kg": _2, "mil": _2, "ms": _2, "ne": _2, "or": _2, "pe": _2, "re": _2, "sc": _2, "busan": _2, "chungbuk": _2, "chungnam": _2, "daegu": _2, "daejeon": _2, "gangwon": _2, "gwangju": _2, "gyeongbuk": _2, "gyeonggi": _2, "gyeongnam": _2, "incheon": _2, "jeju": _2, "jeonbuk": _2, "jeonnam": _2, "seoul": _2, "ulsan": _2, "blogspot": _3 } }, "kw": { "$": 1, "succ": { "com": _2, "edu": _2, "emb": _2, "gov": _2, "ind": _2, "net": _2, "org": _2 } }, "ky": _25, "kz": { "$": 1, "succ": { "org": _2, "edu": _2, "net": _2, "gov": _2, "mil": _2, "com": _2, "jcloud": _3, "kazteleport": { "$": 0, "succ": { "upaas": _3 } } } }, "la": { "$": 1, "succ": { "int": _2, "net": _2, "info": _2, "edu": _2, "gov": _2, "per": _2, "com": _2, "org": _2, "bnr": _3, "c": _3 } }, "lb": _4, "lc": { "$": 1, "succ": { "com": _2, "net": _2, "co": _2, "org": _2, "edu": _2, "gov": _2, "oy": _3 } }, "li": { "$": 1, "succ": { "blogspot": _3, "caa": _3 } }, "lk": { "$": 1, "succ": { "gov": _2, "sch": _2, "net": _2, "int": _2, "com": _2, "org": _2, "edu": _2, "ngo": _2, "soc": _2, "web": _2, "ltd": _2, "assn": _2, "grp": _2, "hotel": _2, "ac": _2 } }, "lr": _4, "ls": { "$": 1, "succ": { "ac": _2, "biz": _2, "co": _2, "edu": _2, "gov": _2, "info": _2, "net": _2, "org": _2, "sc": _2, "de": _3 } }, "lt": _34, "lu": { "$": 1, "succ": { "blogspot": _3, "123website": _3 } }, "lv": { "$": 1, "succ": { "com": _2, "edu": _2, "gov": _2, "org": _2, "mil": _2, "id": _2, "net": _2, "asn": _2, "conf": _2 } }, "ly": { "$": 1, "succ": { "com": _2, "net": _2, "gov": _2, "plc": _2, "edu": _2, "sch": _2, "med": _2, "org": _2, "id": _2 } }, "ma": { "$": 1, "succ": { "co": _2, "net": _2, "gov": _2, "org": _2, "ac": _2, "press": _2 } }, "mc": { "$": 1, "succ": { "tm": _2, "asso": _2 } }, "md": { "$": 1, "succ": { "blogspot": _3, "at": _3, "de": _3, "jp": _3, "to": _3 } }, "me": { "$": 1, "succ": { "co": _2, "net": _2, "org": _2, "edu": _2, "ac": _2, "gov": _2, "its": _2, "priv": _2, "c66": _3, "daplie": { "$": 2, "succ": { "localhost": _3 } }, "edgestack": _3, "filegear": _3, "filegear-au": _3, "filegear-de": _3, "filegear-gb": _3, "filegear-ie": _3, "filegear-jp": _3, "filegear-sg": _3, "glitch": _3, "ravendb": _3, "lohmus": _3, "barsy": _3, "mcpe": _3, "mcdir": _3, "soundcast": _3, "tcp4": _3, "brasilia": _3, "ddns": _3, "dnsfor": _3, "hopto": _3, "loginto": _3, "noip": _3, "webhop": _3, "vp4": _3, "diskstation": _3, "dscloud": _3, "i234": _3, "myds": _3, "synology": _3, "transip": _23, "wedeploy": _3, "yombo": _3, "nohost": _3 } }, "mg": { "$": 1, "succ": { "org": _2, "nom": _2, "gov": _2, "prd": _2, "tm": _2, "edu": _2, "mil": _2, "com": _2, "co": _2 } }, "mh": _2, "mil": _2, "mk": { "$": 1, "succ": { "com": _2, "org": _2, "net": _2, "edu": _2, "gov": _2, "inf": _2, "name": _2, "blogspot": _3 } }, "ml": { "$": 1, "succ": { "com": _2, "edu": _2, "gouv": _2, "gov": _2, "net": _2, "org": _2, "presse": _2 } }, "mm": _8, "mn": { "$": 1, "succ": { "gov": _2, "edu": _2, "org": _2, "nyc": _3 } }, "mo": _4, "mobi": { "$": 1, "succ": { "barsy": _3, "dscloud": _3 } }, "mp": { "$": 1, "succ": { "ju": _3 } }, "mq": _2, "mr": _34, "ms": { "$": 1, "succ": { "com": _2, "edu": _2, "gov": _2, "net": _2, "org": _2, "lab": _3, "minisite": _3 } }, "mt": { "$": 1, "succ": { "com": _6, "edu": _2, "net": _2, "org": _2 } }, "mu": { "$": 1, "succ": { "com": _2, "net": _2, "org": _2, "gov": _2, "ac": _2, "co": _2, "or": _2 } }, "museum": { "$": 1, "succ": { "academy": _2, "agriculture": _2, "air": _2, "airguard": _2, "alabama": _2, "alaska": _2, "amber": _2, "ambulance": _2, "american": _2, "americana": _2, "americanantiques": _2, "americanart": _2, "amsterdam": _2, "and": _2, "annefrank": _2, "anthro": _2, "anthropology": _2, "antiques": _2, "aquarium": _2, "arboretum": _2, "archaeological": _2, "archaeology": _2, "architecture": _2, "art": _2, "artanddesign": _2, "artcenter": _2, "artdeco": _2, "arteducation": _2, "artgallery": _2, "arts": _2, "artsandcrafts": _2, "asmatart": _2, "assassination": _2, "assisi": _2, "association": _2, "astronomy": _2, "atlanta": _2, "austin": _2, "australia": _2, "automotive": _2, "aviation": _2, "axis": _2, "badajoz": _2, "baghdad": _2, "bahn": _2, "bale": _2, "baltimore": _2, "barcelona": _2, "baseball": _2, "basel": _2, "baths": _2, "bauern": _2, "beauxarts": _2, "beeldengeluid": _2, "bellevue": _2, "bergbau": _2, "berkeley": _2, "berlin": _2, "bern": _2, "bible": _2, "bilbao": _2, "bill": _2, "birdart": _2, "birthplace": _2, "bonn": _2, "boston": _2, "botanical": _2, "botanicalgarden": _2, "botanicgarden": _2, "botany": _2, "brandywinevalley": _2, "brasil": _2, "bristol": _2, "british": _2, "britishcolumbia": _2, "broadcast": _2, "brunel": _2, "brussel": _2, "brussels": _2, "bruxelles": _2, "building": _2, "burghof": _2, "bus": _2, "bushey": _2, "cadaques": _2, "california": _2, "cambridge": _2, "can": _2, "canada": _2, "capebreton": _2, "carrier": _2, "cartoonart": _2, "casadelamoneda": _2, "castle": _2, "castres": _2, "celtic": _2, "center": _2, "chattanooga": _2, "cheltenham": _2, "chesapeakebay": _2, "chicago": _2, "children": _2, "childrens": _2, "childrensgarden": _2, "chiropractic": _2, "chocolate": _2, "christiansburg": _2, "cincinnati": _2, "cinema": _2, "circus": _2, "civilisation": _2, "civilization": _2, "civilwar": _2, "clinton": _2, "clock": _2, "coal": _2, "coastaldefence": _2, "cody": _2, "coldwar": _2, "collection": _2, "colonialwilliamsburg": _2, "coloradoplateau": _2, "columbia": _2, "columbus": _2, "communication": _2, "communications": _2, "community": _2, "computer": _2, "computerhistory": _2, "xn--comunicaes-v6a2o": _2, "comunicações": _2, "contemporary": _2, "contemporaryart": _2, "convent": _2, "copenhagen": _2, "corporation": _2, "xn--correios-e-telecomunicaes-ghc29a": _2, "correios-e-telecomunicações": _2, "corvette": _2, "costume": _2, "countryestate": _2, "county": _2, "crafts": _2, "cranbrook": _2, "creation": _2, "cultural": _2, "culturalcenter": _2, "culture": _2, "cyber": _2, "cymru": _2, "dali": _2, "dallas": _2, "database": _2, "ddr": _2, "decorativearts": _2, "delaware": _2, "delmenhorst": _2, "denmark": _2, "depot": _2, "design": _2, "detroit": _2, "dinosaur": _2, "discovery": _2, "dolls": _2, "donostia": _2, "durham": _2, "eastafrica": _2, "eastcoast": _2, "education": _2, "educational": _2, "egyptian": _2, "eisenbahn": _2, "elburg": _2, "elvendrell": _2, "embroidery": _2, "encyclopedic": _2, "england": _2, "entomology": _2, "environment": _2, "environmentalconservation": _2, "epilepsy": _2, "essex": _2, "estate": _2, "ethnology": _2, "exeter": _2, "exhibition": _2, "family": _2, "farm": _2, "farmequipment": _2, "farmers": _2, "farmstead": _2, "field": _2, "figueres": _2, "filatelia": _2, "film": _2, "fineart": _2, "finearts": _2, "finland": _2, "flanders": _2, "florida": _2, "force": _2, "fortmissoula": _2, "fortworth": _2, "foundation": _2, "francaise": _2, "frankfurt": _2, "franziskaner": _2, "freemasonry": _2, "freiburg": _2, "fribourg": _2, "frog": _2, "fundacio": _2, "furniture": _2, "gallery": _2, "garden": _2, "gateway": _2, "geelvinck": _2, "gemological": _2, "geology": _2, "georgia": _2, "giessen": _2, "glas": _2, "glass": _2, "gorge": _2, "grandrapids": _2, "graz": _2, "guernsey": _2, "halloffame": _2, "hamburg": _2, "handson": _2, "harvestcelebration": _2, "hawaii": _2, "health": _2, "heimatunduhren": _2, "hellas": _2, "helsinki": _2, "hembygdsforbund": _2, "heritage": _2, "histoire": _2, "historical": _2, "historicalsociety": _2, "historichouses": _2, "historisch": _2, "historisches": _2, "history": _2, "historyofscience": _2, "horology": _2, "house": _2, "humanities": _2, "illustration": _2, "imageandsound": _2, "indian": _2, "indiana": _2, "indianapolis": _2, "indianmarket": _2, "intelligence": _2, "interactive": _2, "iraq": _2, "iron": _2, "isleofman": _2, "jamison": _2, "jefferson": _2, "jerusalem": _2, "jewelry": _2, "jewish": _2, "jewishart": _2, "jfk": _2, "journalism": _2, "judaica": _2, "judygarland": _2, "juedisches": _2, "juif": _2, "karate": _2, "karikatur": _2, "kids": _2, "koebenhavn": _2, "koeln": _2, "kunst": _2, "kunstsammlung": _2, "kunstunddesign": _2, "labor": _2, "labour": _2, "lajolla": _2, "lancashire": _2, "landes": _2, "lans": _2, "xn--lns-qla": _2, "läns": _2, "larsson": _2, "lewismiller": _2, "lincoln": _2, "linz": _2, "living": _2, "livinghistory": _2, "localhistory": _2, "london": _2, "losangeles": _2, "louvre": _2, "loyalist": _2, "lucerne": _2, "luxembourg": _2, "luzern": _2, "mad": _2, "madrid": _2, "mallorca": _2, "manchester": _2, "mansion": _2, "mansions": _2, "manx": _2, "marburg": _2, "maritime": _2, "maritimo": _2, "maryland": _2, "marylhurst": _2, "media": _2, "medical": _2, "medizinhistorisches": _2, "meeres": _2, "memorial": _2, "mesaverde": _2, "michigan": _2, "midatlantic": _2, "military": _2, "mill": _2, "miners": _2, "mining": _2, "minnesota": _2, "missile": _2, "missoula": _2, "modern": _2, "moma": _2, "money": _2, "monmouth": _2, "monticello": _2, "montreal": _2, "moscow": _2, "motorcycle": _2, "muenchen": _2, "muenster": _2, "mulhouse": _2, "muncie": _2, "museet": _2, "museumcenter": _2, "museumvereniging": _2, "music": _2, "national": _2, "nationalfirearms": _2, "nationalheritage": _2, "nativeamerican": _2, "naturalhistory": _2, "naturalhistorymuseum": _2, "naturalsciences": _2, "nature": _2, "naturhistorisches": _2, "natuurwetenschappen": _2, "naumburg": _2, "naval": _2, "nebraska": _2, "neues": _2, "newhampshire": _2, "newjersey": _2, "newmexico": _2, "newport": _2, "newspaper": _2, "newyork": _2, "niepce": _2, "norfolk": _2, "north": _2, "nrw": _2, "nyc": _2, "nyny": _2, "oceanographic": _2, "oceanographique": _2, "omaha": _2, "online": _2, "ontario": _2, "openair": _2, "oregon": _2, "oregontrail": _2, "otago": _2, "oxford": _2, "pacific": _2, "paderborn": _2, "palace": _2, "paleo": _2, "palmsprings": _2, "panama": _2, "paris": _2, "pasadena": _2, "pharmacy": _2, "philadelphia": _2, "philadelphiaarea": _2, "philately": _2, "phoenix": _2, "photography": _2, "pilots": _2, "pittsburgh": _2, "planetarium": _2, "plantation": _2, "plants": _2, "plaza": _2, "portal": _2, "portland": _2, "portlligat": _2, "posts-and-telecommunications": _2, "preservation": _2, "presidio": _2, "press": _2, "project": _2, "public": _2, "pubol": _2, "quebec": _2, "railroad": _2, "railway": _2, "research": _2, "resistance": _2, "riodejaneiro": _2, "rochester": _2, "rockart": _2, "roma": _2, "russia": _2, "saintlouis": _2, "salem": _2, "salvadordali": _2, "salzburg": _2, "sandiego": _2, "sanfrancisco": _2, "santabarbara": _2, "santacruz": _2, "santafe": _2, "saskatchewan": _2, "satx": _2, "savannahga": _2, "schlesisches": _2, "schoenbrunn": _2, "schokoladen": _2, "school": _2, "schweiz": _2, "science": _2, "scienceandhistory": _2, "scienceandindustry": _2, "sciencecenter": _2, "sciencecenters": _2, "science-fiction": _2, "sciencehistory": _2, "sciences": _2, "sciencesnaturelles": _2, "scotland": _2, "seaport": _2, "settlement": _2, "settlers": _2, "shell": _2, "sherbrooke": _2, "sibenik": _2, "silk": _2, "ski": _2, "skole": _2, "society": _2, "sologne": _2, "soundandvision": _2, "southcarolina": _2, "southwest": _2, "space": _2, "spy": _2, "square": _2, "stadt": _2, "stalbans": _2, "starnberg": _2, "state": _2, "stateofdelaware": _2, "station": _2, "steam": _2, "steiermark": _2, "stjohn": _2, "stockholm": _2, "stpetersburg": _2, "stuttgart": _2, "suisse": _2, "surgeonshall": _2, "surrey": _2, "svizzera": _2, "sweden": _2, "sydney": _2, "tank": _2, "tcm": _2, "technology": _2, "telekommunikation": _2, "television": _2, "texas": _2, "textile": _2, "theater": _2, "time": _2, "timekeeping": _2, "topology": _2, "torino": _2, "touch": _2, "town": _2, "transport": _2, "tree": _2, "trolley": _2, "trust": _2, "trustee": _2, "uhren": _2, "ulm": _2, "undersea": _2, "university": _2, "usa": _2, "usantiques": _2, "usarts": _2, "uscountryestate": _2, "usculture": _2, "usdecorativearts": _2, "usgarden": _2, "ushistory": _2, "ushuaia": _2, "uslivinghistory": _2, "utah": _2, "uvic": _2, "valley": _2, "vantaa": _2, "versailles": _2, "viking": _2, "village": _2, "virginia": _2, "virtual": _2, "virtuel": _2, "vlaanderen": _2, "volkenkunde": _2, "wales": _2, "wallonie": _2, "war": _2, "washingtondc": _2, "watchandclock": _2, "watch-and-clock": _2, "western": _2, "westfalen": _2, "whaling": _2, "wildlife": _2, "williamsburg": _2, "windmill": _2, "workshop": _2, "york": _2, "yorkshire": _2, "yosemite": _2, "youth": _2, "zoological": _2, "zoology": _2, "xn--9dbhblg6di": _2, "ירושלים": _2, "xn--h1aegh": _2, "иком": _2 } }, "mv": { "$": 1, "succ": { "aero": _2, "biz": _2, "com": _2, "coop": _2, "edu": _2, "gov": _2, "info": _2, "int": _2, "mil": _2, "museum": _2, "name": _2, "net": _2, "org": _2, "pro": _2 } }, "mw": { "$": 1, "succ": { "ac": _2, "biz": _2, "co": _2, "com": _2, "coop": _2, "edu": _2, "gov": _2, "int": _2, "museum": _2, "net": _2, "org": _2 } }, "mx": { "$": 1, "succ": { "com": _2, "org": _2, "gob": _2, "edu": _2, "net": _2, "blogspot": _3 } }, "my": { "$": 1, "succ": { "biz": _2, "com": _2, "edu": _2, "gov": _2, "mil": _2, "name": _2, "net": _2, "org": _2, "blogspot": _3 } }, "mz": { "$": 1, "succ": { "ac": _2, "adv": _2, "co": _2, "edu": _2, "gov": _2, "mil": _2, "net": _2, "org": _2 } }, "na": { "$": 1, "succ": { "info": _2, "pro": _2, "name": _2, "school": _2, "or": _2, "dr": _2, "us": _2, "mx": _2, "ca": _2, "in": _2, "cc": _2, "tv": _2, "ws": _2, "mobi": _2, "co": _2, "com": _2, "org": _2 } }, "name": { "$": 1, "succ": { "her": _37, "his": _37 } }, "nc": { "$": 1, "succ": { "asso": _2, "nom": _2 } }, "ne": _2, "net": { "$": 1, "succ": { "adobeaemcloud": _3, "adobeio-static": _3, "adobeioruntime": _3, "akadns": _3, "akamai": _3, "akamai-staging": _3, "akamaiedge": _3, "akamaiedge-staging": _3, "akamaihd": _3, "akamaihd-staging": _3, "akamaiorigin": _3, "akamaiorigin-staging": _3, "akamaized": _3, "akamaized-staging": _3, "edgekey": _3, "edgekey-staging": _3, "edgesuite": _3, "edgesuite-staging": _3, "alwaysdata": _3, "myamaze": _3, "cloudfront": _3, "t3l3p0rt": _3, "appudo": _3, "atlassian-dev": { "$": 0, "succ": { "prod": { "$": 0, "succ": { "cdn": _3 } } } }, "myfritz": _3, "onavstack": _3, "shopselect": _3, "blackbaudcdn": _3, "boomla": _3, "bplaced": _3, "square7": _3, "gb": _3, "hu": _3, "jp": _3, "se": _3, "uk": _3, "in": _3, "clickrising": _3, "cloudaccess": _3, "cdn77-ssl": _3, "cdn77": { "$": 0, "succ": { "r": _3 } }, "feste-ip": _3, "knx-server": _3, "static-access": _3, "cryptonomic": _5, "dattolocal": _3, "mydatto": _3, "debian": _3, "bitbridge": _3, "at-band-camp": _3, "blogdns": _3, "broke-it": _3, "buyshouses": _3, "dnsalias": _3, "dnsdojo": _3, "does-it": _3, "dontexist": _3, "dynalias": _3, "dynathome": _3, "endofinternet": _3, "from-az": _3, "from-co": _3, "from-la": _3, "from-ny": _3, "gets-it": _3, "ham-radio-op": _3, "homeftp": _3, "homeip": _3, "homelinux": _3, "homeunix": _3, "in-the-band": _3, "is-a-chef": _3, "is-a-geek": _3, "isa-geek": _3, "kicks-ass": _3, "office-on-the": _3, "podzone": _3, "scrapper-site": _3, "selfip": _3, "sells-it": _3, "servebbs": _3, "serveftp": _3, "thruhere": _3, "webhop": _3, "definima": _3, "casacam": _3, "dynu": _3, "dynv6": _3, "twmail": _3, "ru": _3, "channelsdvr": { "$": 2, "succ": { "u": _3 } }, "fastlylb": { "$": 2, "succ": { "map": _3 } }, "fastly": { "$": 0, "succ": { "freetls": _3, "map": _3, "prod": { "$": 0, "succ": { "a": _3, "global": _3 } }, "ssl": { "$": 0, "succ": { "a": _3, "b": _3, "global": _3 } } } }, "edgeapp": _3, "flynnhosting": _3, "cdn-edges": _3, "heteml": _3, "cloudfunctions": _3, "moonscale": _3, "in-dsl": _3, "in-vpn": _3, "ipifony": _3, "iobb": _3, "cloudjiffy": { "$": 2, "succ": { "fra1-de": _3, "west1-us": _3 } }, "elastx": { "$": 0, "succ": { "jls-sto1": _3, "jls-sto2": _3, "jls-sto3": _3 } }, "faststacks": _3, "massivegrid": { "$": 0, "succ": { "paas": { "$": 0, "succ": { "fr-1": _3, "lon-1": _3, "lon-2": _3, "ny-1": _3, "ny-2": _3, "sg-1": _3 } } } }, "saveincloud": { "$": 0, "succ": { "jelastic": _3, "nordeste-idc": _3 } }, "scaleforce": _26, "tsukaeru": _27, "kinghost": _3, "uni5": _3, "krellian": _3, "barsy": _3, "memset": _3, "azurewebsites": _3, "azure-mobile": _3, "cloudapp": _3, "azurestaticapps": { "$": 2, "succ": { "1": _3, "2": _3, "3": _3, "centralus": _3, "eastasia": _3, "eastus2": _3, "westeurope": _3, "westus2": _3 } }, "dnsup": _3, "hicam": _3, "now-dns": _3, "ownip": _3, "vpndns": _3, "eating-organic": _3, "mydissent": _3, "myeffect": _3, "mymediapc": _3, "mypsx": _3, "mysecuritycamera": _3, "nhlfan": _3, "no-ip": _3, "pgafan": _3, "privatizehealthinsurance": _3, "bounceme": _3, "ddns": _3, "redirectme": _3, "serveblog": _3, "serveminecraft": _3, "sytes": _3, "cloudycluster": _3, "ovh": { "$": 0, "succ": { "webpaas": _5, "hosting": _5 } }, "bar0": _3, "bar1": _3, "bar2": _3, "rackmaze": _3, "squares": _3, "schokokeks": _3, "firewall-gateway": _3, "seidat": _3, "senseering": _3, "siteleaf": _3, "vps-host": { "$": 2, "succ": { "jelastic": { "$": 0, "succ": { "atl": _3, "njs": _3, "ric": _3 } } } }, "myspreadshop": _3, "srcf": { "$": 0, "succ": { "soc": _3, "user": _3 } }, "supabase": _3, "dsmynas": _3, "familyds": _3, "tailscale": { "$": 0, "succ": { "beta": _3 } }, "ts": _3, "torproject": { "$": 2, "succ": { "pages": _3 } }, "reserve-online": _3, "community-pro": _3, "meinforum": _3, "yandexcloud": { "$": 2, "succ": { "storage": _3, "website": _3 } }, "za": _3 } }, "nf": { "$": 1, "succ": { "com": _2, "net": _2, "per": _2, "rec": _2, "web": _2, "arts": _2, "firm": _2, "info": _2, "other": _2, "store": _2 } }, "ng": { "$": 1, "succ": { "com": _6, "edu": _2, "gov": _2, "i": _2, "mil": _2, "mobi": _2, "name": _2, "net": _2, "org": _2, "sch": _2, "col": _3, "firm": _3, "gen": _3, "ltd": _3, "ngo": _3 } }, "ni": { "$": 1, "succ": { "ac": _2, "biz": _2, "co": _2, "com": _2, "edu": _2, "gob": _2, "in": _2, "info": _2, "int": _2, "mil": _2, "net": _2, "nom": _2, "org": _2, "web": _2 } }, "nl": { "$": 1, "succ": { "co": _3, "hosting-cluster": _3, "blogspot": _3, "gov": _3, "khplay": _3, "123website": _3, "myspreadshop": _3, "transurl": _5, "cistron": _3, "demon": _3 } }, "no": { "$": 1, "succ": { "fhs": _2, "vgs": _2, "fylkesbibl": _2, "folkebibl": _2, "museum": _2, "idrett": _2, "priv": _2, "mil": _2, "stat": _2, "dep": _2, "kommune": _2, "herad": _2, "aa": _38, "ah": _38, "bu": _38, "fm": _38, "hl": _38, "hm": _38, "jan-mayen": _38, "mr": _38, "nl": _38, "nt": _38, "of": _38, "ol": _38, "oslo": _38, "rl": _38, "sf": _38, "st": _38, "svalbard": _38, "tm": _38, "tr": _38, "va": _38, "vf": _38, "akrehamn": _2, "xn--krehamn-dxa": _2, "åkrehamn": _2, "algard": _2, "xn--lgrd-poac": _2, "ålgård": _2, "arna": _2, "brumunddal": _2, "bryne": _2, "bronnoysund": _2, "xn--brnnysund-m8ac": _2, "brønnøysund": _2, "drobak": _2, "xn--drbak-wua": _2, "drøbak": _2, "egersund": _2, "fetsund": _2, "floro": _2, "xn--flor-jra": _2, "florø": _2, "fredrikstad": _2, "hokksund": _2, "honefoss": _2, "xn--hnefoss-q1a": _2, "hønefoss": _2, "jessheim": _2, "jorpeland": _2, "xn--jrpeland-54a": _2, "jørpeland": _2, "kirkenes": _2, "kopervik": _2, "krokstadelva": _2, "langevag": _2, "xn--langevg-jxa": _2, "langevåg": _2, "leirvik": _2, "mjondalen": _2, "xn--mjndalen-64a": _2, "mjøndalen": _2, "mo-i-rana": _2, "mosjoen": _2, "xn--mosjen-eya": _2, "mosjøen": _2, "nesoddtangen": _2, "orkanger": _2, "osoyro": _2, "xn--osyro-wua": _2, "osøyro": _2, "raholt": _2, "xn--rholt-mra": _2, "råholt": _2, "sandnessjoen": _2, "xn--sandnessjen-ogb": _2, "sandnessjøen": _2, "skedsmokorset": _2, "slattum": _2, "spjelkavik": _2, "stathelle": _2, "stavern": _2, "stjordalshalsen": _2, "xn--stjrdalshalsen-sqb": _2, "stjørdalshalsen": _2, "tananger": _2, "tranby": _2, "vossevangen": _2, "afjord": _2, "xn--fjord-lra": _2, "åfjord": _2, "agdenes": _2, "al": _2, "xn--l-1fa": _2, "ål": _2, "alesund": _2, "xn--lesund-hua": _2, "ålesund": _2, "alstahaug": _2, "alta": _2, "xn--lt-liac": _2, "áltá": _2, "alaheadju": _2, "xn--laheadju-7ya": _2, "álaheadju": _2, "alvdal": _2, "amli": _2, "xn--mli-tla": _2, "åmli": _2, "amot": _2, "xn--mot-tla": _2, "åmot": _2, "andebu": _2, "andoy": _2, "xn--andy-ira": _2, "andøy": _2, "andasuolo": _2, "ardal": _2, "xn--rdal-poa": _2, "årdal": _2, "aremark": _2, "arendal": _2, "xn--s-1fa": _2, "ås": _2, "aseral": _2, "xn--seral-lra": _2, "åseral": _2, "asker": _2, "askim": _2, "askvoll": _2, "askoy": _2, "xn--asky-ira": _2, "askøy": _2, "asnes": _2, "xn--snes-poa": _2, "åsnes": _2, "audnedaln": _2, "aukra": _2, "aure": _2, "aurland": _2, "aurskog-holand": _2, "xn--aurskog-hland-jnb": _2, "aurskog-høland": _2, "austevoll": _2, "austrheim": _2, "averoy": _2, "xn--avery-yua": _2, "averøy": _2, "balestrand": _2, "ballangen": _2, "balat": _2, "xn--blt-elab": _2, "bálát": _2, "balsfjord": _2, "bahccavuotna": _2, "xn--bhccavuotna-k7a": _2, "báhccavuotna": _2, "bamble": _2, "bardu": _2, "beardu": _2, "beiarn": _2, "bajddar": _2, "xn--bjddar-pta": _2, "bájddar": _2, "baidar": _2, "xn--bidr-5nac": _2, "báidár": _2, "berg": _2, "bergen": _2, "berlevag": _2, "xn--berlevg-jxa": _2, "berlevåg": _2, "bearalvahki": _2, "xn--bearalvhki-y4a": _2, "bearalváhki": _2, "bindal": _2, "birkenes": _2, "bjarkoy": _2, "xn--bjarky-fya": _2, "bjarkøy": _2, "bjerkreim": _2, "bjugn": _2, "bodo": _2, "xn--bod-2na": _2, "bodø": _2, "badaddja": _2, "xn--bdddj-mrabd": _2, "bådåddjå": _2, "budejju": _2, "bokn": _2, "bremanger": _2, "bronnoy": _2, "xn--brnny-wuac": _2, "brønnøy": _2, "bygland": _2, "bykle": _2, "barum": _2, "xn--brum-voa": _2, "bærum": _2, "telemark": { "$": 0, "succ": { "bo": _2, "xn--b-5ga": _2, "bø": _2 } }, "nordland": { "$": 0, "succ": { "bo": _2, "xn--b-5ga": _2, "bø": _2, "heroy": _2, "xn--hery-ira": _2, "herøy": _2 } }, "bievat": _2, "xn--bievt-0qa": _2, "bievát": _2, "bomlo": _2, "xn--bmlo-gra": _2, "bømlo": _2, "batsfjord": _2, "xn--btsfjord-9za": _2, "båtsfjord": _2, "bahcavuotna": _2, "xn--bhcavuotna-s4a": _2, "báhcavuotna": _2, "dovre": _2, "drammen": _2, "drangedal": _2, "dyroy": _2, "xn--dyry-ira": _2, "dyrøy": _2, "donna": _2, "xn--dnna-gra": _2, "dønna": _2, "eid": _2, "eidfjord": _2, "eidsberg": _2, "eidskog": _2, "eidsvoll": _2, "eigersund": _2, "elverum": _2, "enebakk": _2, "engerdal": _2, "etne": _2, "etnedal": _2, "evenes": _2, "evenassi": _2, "xn--eveni-0qa01ga": _2, "evenášši": _2, "evje-og-hornnes": _2, "farsund": _2, "fauske": _2, "fuossko": _2, "fuoisku": _2, "fedje": _2, "fet": _2, "finnoy": _2, "xn--finny-yua": _2, "finnøy": _2, "fitjar": _2, "fjaler": _2, "fjell": _2, "flakstad": _2, "flatanger": _2, "flekkefjord": _2, "flesberg": _2, "flora": _2, "fla": _2, "xn--fl-zia": _2, "flå": _2, "folldal": _2, "forsand": _2, "fosnes": _2, "frei": _2, "frogn": _2, "froland": _2, "frosta": _2, "frana": _2, "xn--frna-woa": _2, "fræna": _2, "froya": _2, "xn--frya-hra": _2, "frøya": _2, "fusa": _2, "fyresdal": _2, "forde": _2, "xn--frde-gra": _2, "førde": _2, "gamvik": _2, "gangaviika": _2, "xn--ggaviika-8ya47h": _2, "gáŋgaviika": _2, "gaular": _2, "gausdal": _2, "gildeskal": _2, "xn--gildeskl-g0a": _2, "gildeskål": _2, "giske": _2, "gjemnes": _2, "gjerdrum": _2, "gjerstad": _2, "gjesdal": _2, "gjovik": _2, "xn--gjvik-wua": _2, "gjøvik": _2, "gloppen": _2, "gol": _2, "gran": _2, "grane": _2, "granvin": _2, "gratangen": _2, "grimstad": _2, "grong": _2, "kraanghke": _2, "xn--kranghke-b0a": _2, "kråanghke": _2, "grue": _2, "gulen": _2, "hadsel": _2, "halden": _2, "halsa": _2, "hamar": _2, "hamaroy": _2, "habmer": _2, "xn--hbmer-xqa": _2, "hábmer": _2, "hapmir": _2, "xn--hpmir-xqa": _2, "hápmir": _2, "hammerfest": _2, "hammarfeasta": _2, "xn--hmmrfeasta-s4ac": _2, "hámmárfeasta": _2, "haram": _2, "hareid": _2, "harstad": _2, "hasvik": _2, "aknoluokta": _2, "xn--koluokta-7ya57h": _2, "ákŋoluokta": _2, "hattfjelldal": _2, "aarborte": _2, "haugesund": _2, "hemne": _2, "hemnes": _2, "hemsedal": _2, "more-og-romsdal": { "$": 0, "succ": { "heroy": _2, "sande": _2 } }, "xn--mre-og-romsdal-qqb": { "$": 0, "succ": { "xn--hery-ira": _2, "sande": _2 } }, "møre-og-romsdal": { "$": 0, "succ": { "herøy": _2, "sande": _2 } }, "hitra": _2, "hjartdal": _2, "hjelmeland": _2, "hobol": _2, "xn--hobl-ira": _2, "hobøl": _2, "hof": _2, "hol": _2, "hole": _2, "holmestrand": _2, "holtalen": _2, "xn--holtlen-hxa": _2, "holtålen": _2, "hornindal": _2, "horten": _2, "hurdal": _2, "hurum": _2, "hvaler": _2, "hyllestad": _2, "hagebostad": _2, "xn--hgebostad-g3a": _2, "hægebostad": _2, "hoyanger": _2, "xn--hyanger-q1a": _2, "høyanger": _2, "hoylandet": _2, "xn--hylandet-54a": _2, "høylandet": _2, "ha": _2, "xn--h-2fa": _2, "hå": _2, "ibestad": _2, "inderoy": _2, "xn--indery-fya": _2, "inderøy": _2, "iveland": _2, "jevnaker": _2, "jondal": _2, "jolster": _2, "xn--jlster-bya": _2, "jølster": _2, "karasjok": _2, "karasjohka": _2, "xn--krjohka-hwab49j": _2, "kárášjohka": _2, "karlsoy": _2, "galsa": _2, "xn--gls-elac": _2, "gálsá": _2, "karmoy": _2, "xn--karmy-yua": _2, "karmøy": _2, "kautokeino": _2, "guovdageaidnu": _2, "klepp": _2, "klabu": _2, "xn--klbu-woa": _2, "klæbu": _2, "kongsberg": _2, "kongsvinger": _2, "kragero": _2, "xn--krager-gya": _2, "kragerø": _2, "kristiansand": _2, "kristiansund": _2, "krodsherad": _2, "xn--krdsherad-m8a": _2, "krødsherad": _2, "kvalsund": _2, "rahkkeravju": _2, "xn--rhkkervju-01af": _2, "ráhkkerávju": _2, "kvam": _2, "kvinesdal": _2, "kvinnherad": _2, "kviteseid": _2, "kvitsoy": _2, "xn--kvitsy-fya": _2, "kvitsøy": _2, "kvafjord": _2, "xn--kvfjord-nxa": _2, "kvæfjord": _2, "giehtavuoatna": _2, "kvanangen": _2, "xn--kvnangen-k0a": _2, "kvænangen": _2, "navuotna": _2, "xn--nvuotna-hwa": _2, "návuotna": _2, "kafjord": _2, "xn--kfjord-iua": _2, "kåfjord": _2, "gaivuotna": _2, "xn--givuotna-8ya": _2, "gáivuotna": _2, "larvik": _2, "lavangen": _2, "lavagis": _2, "loabat": _2, "xn--loabt-0qa": _2, "loabát": _2, "lebesby": _2, "davvesiida": _2, "leikanger": _2, "leirfjord": _2, "leka": _2, "leksvik": _2, "lenvik": _2, "leangaviika": _2, "xn--leagaviika-52b": _2, "leaŋgaviika": _2, "lesja": _2, "levanger": _2, "lier": _2, "lierne": _2, "lillehammer": _2, "lillesand": _2, "lindesnes": _2, "lindas": _2, "xn--linds-pra": _2, "lindås": _2, "lom": _2, "loppa": _2, "lahppi": _2, "xn--lhppi-xqa": _2, "láhppi": _2, "lund": _2, "lunner": _2, "luroy": _2, "xn--lury-ira": _2, "lurøy": _2, "luster": _2, "lyngdal": _2, "lyngen": _2, "ivgu": _2, "lardal": _2, "lerdal": _2, "xn--lrdal-sra": _2, "lærdal": _2, "lodingen": _2, "xn--ldingen-q1a": _2, "lødingen": _2, "lorenskog": _2, "xn--lrenskog-54a": _2, "lørenskog": _2, "loten": _2, "xn--lten-gra": _2, "løten": _2, "malvik": _2, "masoy": _2, "xn--msy-ula0h": _2, "måsøy": _2, "muosat": _2, "xn--muost-0qa": _2, "muosát": _2, "mandal": _2, "marker": _2, "marnardal": _2, "masfjorden": _2, "meland": _2, "meldal": _2, "melhus": _2, "meloy": _2, "xn--mely-ira": _2, "meløy": _2, "meraker": _2, "xn--merker-kua": _2, "meråker": _2, "moareke": _2, "xn--moreke-jua": _2, "moåreke": _2, "midsund": _2, "midtre-gauldal": _2, "modalen": _2, "modum": _2, "molde": _2, "moskenes": _2, "moss": _2, "mosvik": _2, "malselv": _2, "xn--mlselv-iua": _2, "målselv": _2, "malatvuopmi": _2, "xn--mlatvuopmi-s4a": _2, "málatvuopmi": _2, "namdalseid": _2, "aejrie": _2, "namsos": _2, "namsskogan": _2, "naamesjevuemie": _2, "xn--nmesjevuemie-tcba": _2, "nååmesjevuemie": _2, "laakesvuemie": _2, "nannestad": _2, "narvik": _2, "narviika": _2, "naustdal": _2, "nedre-eiker": _2, "akershus": _39, "buskerud": _39, "nesna": _2, "nesodden": _2, "nesseby": _2, "unjarga": _2, "xn--unjrga-rta": _2, "unjárga": _2, "nesset": _2, "nissedal": _2, "nittedal": _2, "nord-aurdal": _2, "nord-fron": _2, "nord-odal": _2, "norddal": _2, "nordkapp": _2, "davvenjarga": _2, "xn--davvenjrga-y4a": _2, "davvenjárga": _2, "nordre-land": _2, "nordreisa": _2, "raisa": _2, "xn--risa-5na": _2, "ráisa": _2, "nore-og-uvdal": _2, "notodden": _2, "naroy": _2, "xn--nry-yla5g": _2, "nærøy": _2, "notteroy": _2, "xn--nttery-byae": _2, "nøtterøy": _2, "odda": _2, "oksnes": _2, "xn--ksnes-uua": _2, "øksnes": _2, "oppdal": _2, "oppegard": _2, "xn--oppegrd-ixa": _2, "oppegård": _2, "orkdal": _2, "orland": _2, "xn--rland-uua": _2, "ørland": _2, "orskog": _2, "xn--rskog-uua": _2, "ørskog": _2, "orsta": _2, "xn--rsta-fra": _2, "ørsta": _2, "hedmark": { "$": 0, "succ": { "os": _2, "valer": _2, "xn--vler-qoa": _2, "våler": _2 } }, "hordaland": { "$": 0, "succ": { "os": _2 } }, "osen": _2, "osteroy": _2, "xn--ostery-fya": _2, "osterøy": _2, "ostre-toten": _2, "xn--stre-toten-zcb": _2, "østre-toten": _2, "overhalla": _2, "ovre-eiker": _2, "xn--vre-eiker-k8a": _2, "øvre-eiker": _2, "oyer": _2, "xn--yer-zna": _2, "øyer": _2, "oygarden": _2, "xn--ygarden-p1a": _2, "øygarden": _2, "oystre-slidre": _2, "xn--ystre-slidre-ujb": _2, "øystre-slidre": _2, "porsanger": _2, "porsangu": _2, "xn--porsgu-sta26f": _2, "porsáŋgu": _2, "porsgrunn": _2, "radoy": _2, "xn--rady-ira": _2, "radøy": _2, "rakkestad": _2, "rana": _2, "ruovat": _2, "randaberg": _2, "rauma": _2, "rendalen": _2, "rennebu": _2, "rennesoy": _2, "xn--rennesy-v1a": _2, "rennesøy": _2, "rindal": _2, "ringebu": _2, "ringerike": _2, "ringsaker": _2, "rissa": _2, "risor": _2, "xn--risr-ira": _2, "risør": _2, "roan": _2, "rollag": _2, "rygge": _2, "ralingen": _2, "xn--rlingen-mxa": _2, "rælingen": _2, "rodoy": _2, "xn--rdy-0nab": _2, "rødøy": _2, "romskog": _2, "xn--rmskog-bya": _2, "rømskog": _2, "roros": _2, "xn--rros-gra": _2, "røros": _2, "rost": _2, "xn--rst-0na": _2, "røst": _2, "royken": _2, "xn--ryken-vua": _2, "røyken": _2, "royrvik": _2, "xn--ryrvik-bya": _2, "røyrvik": _2, "rade": _2, "xn--rde-ula": _2, "råde": _2, "salangen": _2, "siellak": _2, "saltdal": _2, "salat": _2, "xn--slt-elab": _2, "sálát": _2, "xn--slat-5na": _2, "sálat": _2, "samnanger": _2, "vestfold": { "$": 0, "succ": { "sande": _2 } }, "sandefjord": _2, "sandnes": _2, "sandoy": _2, "xn--sandy-yua": _2, "sandøy": _2, "sarpsborg": _2, "sauda": _2, "sauherad": _2, "sel": _2, "selbu": _2, "selje": _2, "seljord": _2, "sigdal": _2, "siljan": _2, "sirdal": _2, "skaun": _2, "skedsmo": _2, "ski": _2, "skien": _2, "skiptvet": _2, "skjervoy": _2, "xn--skjervy-v1a": _2, "skjervøy": _2, "skierva": _2, "xn--skierv-uta": _2, "skiervá": _2, "skjak": _2, "xn--skjk-soa": _2, "skjåk": _2, "skodje": _2, "skanland": _2, "xn--sknland-fxa": _2, "skånland": _2, "skanit": _2, "xn--sknit-yqa": _2, "skánit": _2, "smola": _2, "xn--smla-hra": _2, "smøla": _2, "snillfjord": _2, "snasa": _2, "xn--snsa-roa": _2, "snåsa": _2, "snoasa": _2, "snaase": _2, "xn--snase-nra": _2, "snåase": _2, "sogndal": _2, "sokndal": _2, "sola": _2, "solund": _2, "songdalen": _2, "sortland": _2, "spydeberg": _2, "stange": _2, "stavanger": _2, "steigen": _2, "steinkjer": _2, "stjordal": _2, "xn--stjrdal-s1a": _2, "stjørdal": _2, "stokke": _2, "stor-elvdal": _2, "stord": _2, "stordal": _2, "storfjord": _2, "omasvuotna": _2, "strand": _2, "stranda": _2, "stryn": _2, "sula": _2, "suldal": _2, "sund": _2, "sunndal": _2, "surnadal": _2, "sveio": _2, "svelvik": _2, "sykkylven": _2, "sogne": _2, "xn--sgne-gra": _2, "søgne": _2, "somna": _2, "xn--smna-gra": _2, "sømna": _2, "sondre-land": _2, "xn--sndre-land-0cb": _2, "søndre-land": _2, "sor-aurdal": _2, "xn--sr-aurdal-l8a": _2, "sør-aurdal": _2, "sor-fron": _2, "xn--sr-fron-q1a": _2, "sør-fron": _2, "sor-odal": _2, "xn--sr-odal-q1a": _2, "sør-odal": _2, "sor-varanger": _2, "xn--sr-varanger-ggb": _2, "sør-varanger": _2, "matta-varjjat": _2, "xn--mtta-vrjjat-k7af": _2, "mátta-várjjat": _2, "sorfold": _2, "xn--srfold-bya": _2, "sørfold": _2, "sorreisa": _2, "xn--srreisa-q1a": _2, "sørreisa": _2, "sorum": _2, "xn--srum-gra": _2, "sørum": _2, "tana": _2, "deatnu": _2, "time": _2, "tingvoll": _2, "tinn": _2, "tjeldsund": _2, "dielddanuorri": _2, "tjome": _2, "xn--tjme-hra": _2, "tjøme": _2, "tokke": _2, "tolga": _2, "torsken": _2, "tranoy": _2, "xn--trany-yua": _2, "tranøy": _2, "tromso": _2, "xn--troms-zua": _2, "tromsø": _2, "tromsa": _2, "romsa": _2, "trondheim": _2, "troandin": _2, "trysil": _2, "trana": _2, "xn--trna-woa": _2, "træna": _2, "trogstad": _2, "xn--trgstad-r1a": _2, "trøgstad": _2, "tvedestrand": _2, "tydal": _2, "tynset": _2, "tysfjord": _2, "divtasvuodna": _2, "divttasvuotna": _2, "tysnes": _2, "tysvar": _2, "xn--tysvr-vra": _2, "tysvær": _2, "tonsberg": _2, "xn--tnsberg-q1a": _2, "tønsberg": _2, "ullensaker": _2, "ullensvang": _2, "ulvik": _2, "utsira": _2, "vadso": _2, "xn--vads-jra": _2, "vadsø": _2, "cahcesuolo": _2, "xn--hcesuolo-7ya35b": _2, "čáhcesuolo": _2, "vaksdal": _2, "valle": _2, "vang": _2, "vanylven": _2, "vardo": _2, "xn--vard-jra": _2, "vardø": _2, "varggat": _2, "xn--vrggt-xqad": _2, "várggát": _2, "vefsn": _2, "vaapste": _2, "vega": _2, "vegarshei": _2, "xn--vegrshei-c0a": _2, "vegårshei": _2, "vennesla": _2, "verdal": _2, "verran": _2, "vestby": _2, "vestnes": _2, "vestre-slidre": _2, "vestre-toten": _2, "vestvagoy": _2, "xn--vestvgy-ixa6o": _2, "vestvågøy": _2, "vevelstad": _2, "vik": _2, "vikna": _2, "vindafjord": _2, "volda": _2, "voss": _2, "varoy": _2, "xn--vry-yla5g": _2, "værøy": _2, "vagan": _2, "xn--vgan-qoa": _2, "vågan": _2, "voagat": _2, "vagsoy": _2, "xn--vgsy-qoa0j": _2, "vågsøy": _2, "vaga": _2, "xn--vg-yiab": _2, "vågå": _2, "ostfold": { "$": 0, "succ": { "valer": _2 } }, "xn--stfold-9xa": { "$": 0, "succ": { "xn--vler-qoa": _2 } }, "østfold": { "$": 0, "succ": { "våler": _2 } }, "co": _3, "blogspot": _3, "123hjemmeside": _3, "myspreadshop": _3 } }, "np": _8, "nr": _33, "nu": { "$": 1, "succ": { "merseine": _3, "mine": _3, "shacknet": _3, "enterprisecloud": _3 } }, "nz": { "$": 1, "succ": { "ac": _2, "co": _6, "cri": _2, "geek": _2, "gen": _2, "govt": _2, "health": _2, "iwi": _2, "kiwi": _2, "maori": _2, "mil": _2, "xn--mori-qsa": _2, "māori": _2, "net": _2, "org": _2, "parliament": _2, "school": _2 } }, "om": { "$": 1, "succ": { "co": _2, "com": _2, "edu": _2, "gov": _2, "med": _2, "museum": _2, "net": _2, "org": _2, "pro": _2 } }, "onion": _2, "org": { "$": 1, "succ": { "altervista": _3, "amune": { "$": 0, "succ": { "tele": _3 } }, "pimienta": _3, "poivron": _3, "potager": _3, "sweetpepper": _3, "ae": _3, "us": _3, "certmgr": _3, "cdn77": { "$": 0, "succ": { "c": _3, "rsc": _3 } }, "cdn77-secure": { "$": 0, "succ": { "origin": { "$": 0, "succ": { "ssl": _3 } } } }, "cloudns": _3, "duckdns": _3, "tunk": _3, "dyndns": { "$": 2, "succ": { "go": _3, "home": _3 } }, "blogdns": _3, "blogsite": _3, "boldlygoingnowhere": _3, "dnsalias": _3, "dnsdojo": _3, "doesntexist": _3, "dontexist": _3, "doomdns": _3, "dvrdns": _3, "dynalias": _3, "endofinternet": _3, "endoftheinternet": _3, "from-me": _3, "game-host": _3, "gotdns": _3, "hobby-site": _3, "homedns": _3, "homeftp": _3, "homelinux": _3, "homeunix": _3, "is-a-bruinsfan": _3, "is-a-candidate": _3, "is-a-celticsfan": _3, "is-a-chef": _3, "is-a-geek": _3, "is-a-knight": _3, "is-a-linux-user": _3, "is-a-patsfan": _3, "is-a-soxfan": _3, "is-found": _3, "is-lost": _3, "is-saved": _3, "is-very-bad": _3, "is-very-evil": _3, "is-very-good": _3, "is-very-nice": _3, "is-very-sweet": _3, "isa-geek": _3, "kicks-ass": _3, "misconfused": _3, "podzone": _3, "readmyblog": _3, "selfip": _3, "sellsyourhome": _3, "servebbs": _3, "serveftp": _3, "servegame": _3, "stuff-4-sale": _3, "webhop": _3, "ddnss": _3, "accesscam": _3, "camdvr": _3, "freeddns": _3, "mywire": _3, "webredirect": _3, "eu": { "$": 2, "succ": { "al": _3, "asso": _3, "at": _3, "au": _3, "be": _3, "bg": _3, "ca": _3, "cd": _3, "ch": _3, "cn": _3, "cy": _3, "cz": _3, "de": _3, "dk": _3, "edu": _3, "ee": _3, "es": _3, "fi": _3, "fr": _3, "gr": _3, "hr": _3, "hu": _3, "ie": _3, "il": _3, "in": _3, "int": _3, "is": _3, "it": _3, "jp": _3, "kr": _3, "lt": _3, "lu": _3, "lv": _3, "mc": _3, "me": _3, "mk": _3, "mt": _3, "my": _3, "net": _3, "ng": _3, "nl": _3, "no": _3, "nz": _3, "paris": _3, "pl": _3, "pt": _3, "q-a": _3, "ro": _3, "ru": _3, "se": _3, "si": _3, "sk": _3, "tr": _3, "uk": _3, "us": _3 } }, "twmail": _3, "fedorainfracloud": _3, "fedorapeople": _3, "fedoraproject": { "$": 0, "succ": { "cloud": _3, "os": _21, "stg": { "$": 0, "succ": { "os": _21 } } } }, "freedesktop": _3, "hepforge": _3, "in-dsl": _3, "in-vpn": _3, "js": _3, "barsy": _3, "mayfirst": _3, "mozilla-iot": _3, "bmoattachments": _3, "dynserv": _3, "now-dns": _3, "cable-modem": _3, "collegefan": _3, "couchpotatofries": _3, "mlbfan": _3, "mysecuritycamera": _3, "nflfan": _3, "read-books": _3, "ufcfan": _3, "hopto": _3, "myftp": _3, "no-ip": _3, "zapto": _3, "httpbin": _3, "pubtls": _3, "jpn": _3, "my-firewall": _3, "myfirewall": _3, "spdns": _3, "small-web": _3, "dsmynas": _3, "familyds": _3, "teckids": _12, "tuxfamily": _3, "diskstation": _3, "hk": _3, "wmflabs": _3, "toolforge": _3, "wmcloud": _3, "za": _3 } }, "pa": { "$": 1, "succ": { "ac": _2, "gob": _2, "com": _2, "org": _2, "sld": _2, "edu": _2, "net": _2, "ing": _2, "abo": _2, "med": _2, "nom": _2 } }, "pe": { "$": 1, "succ": { "edu": _2, "gob": _2, "nom": _2, "mil": _2, "org": _2, "com": _2, "net": _2, "blogspot": _3 } }, "pf": { "$": 1, "succ": { "com": _2, "org": _2, "edu": _2 } }, "pg": _8, "ph": { "$": 1, "succ": { "com": _2, "net": _2, "org": _2, "gov": _2, "edu": _2, "ngo": _2, "mil": _2, "i": _2 } }, "pk": { "$": 1, "succ": { "com": _2, "net": _2, "edu": _2, "org": _2, "fam": _2, "biz": _2, "web": _2, "gov": _2, "gob": _2, "gok": _2, "gon": _2, "gop": _2, "gos": _2, "info": _2 } }, "pl": { "$": 1, "succ": { "com": _2, "net": _2, "org": _2, "aid": _2, "agro": _2, "atm": _2, "auto": _2, "biz": _2, "edu": _2, "gmina": _2, "gsm": _2, "info": _2, "mail": _2, "miasta": _2, "media": _2, "mil": _2, "nieruchomosci": _2, "nom": _2, "pc": _2, "powiat": _2, "priv": _2, "realestate": _2, "rel": _2, "sex": _2, "shop": _2, "sklep": _2, "sos": _2, "szkola": _2, "targi": _2, "tm": _2, "tourism": _2, "travel": _2, "turystyka": _2, "gov": { "$": 1, "succ": { "ap": _2, "ic": _2, "is": _2, "us": _2, "kmpsp": _2, "kppsp": _2, "kwpsp": _2, "psp": _2, "wskr": _2, "kwp": _2, "mw": _2, "ug": _2, "um": _2, "umig": _2, "ugim": _2, "upow": _2, "uw": _2, "starostwo": _2, "pa": _2, "po": _2, "psse": _2, "pup": _2, "rzgw": _2, "sa": _2, "so": _2, "sr": _2, "wsa": _2, "sko": _2, "uzs": _2, "wiih": _2, "winb": _2, "pinb": _2, "wios": _2, "witd": _2, "wzmiuw": _2, "piw": _2, "wiw": _2, "griw": _2, "wif": _2, "oum": _2, "sdn": _2, "zp": _2, "uppo": _2, "mup": _2, "wuoz": _2, "konsulat": _2, "oirm": _2 } }, "augustow": _2, "babia-gora": _2, "bedzin": _2, "beskidy": _2, "bialowieza": _2, "bialystok": _2, "bielawa": _2, "bieszczady": _2, "boleslawiec": _2, "bydgoszcz": _2, "bytom": _2, "cieszyn": _2, "czeladz": _2, "czest": _2, "dlugoleka": _2, "elblag": _2, "elk": _2, "glogow": _2, "gniezno": _2, "gorlice": _2, "grajewo": _2, "ilawa": _2, "jaworzno": _2, "jelenia-gora": _2, "jgora": _2, "kalisz": _2, "kazimierz-dolny": _2, "karpacz": _2, "kartuzy": _2, "kaszuby": _2, "katowice": _2, "kepno": _2, "ketrzyn": _2, "klodzko": _2, "kobierzyce": _2, "kolobrzeg": _2, "konin": _2, "konskowola": _2, "kutno": _2, "lapy": _2, "lebork": _2, "legnica": _2, "lezajsk": _2, "limanowa": _2, "lomza": _2, "lowicz": _2, "lubin": _2, "lukow": _2, "malbork": _2, "malopolska": _2, "mazowsze": _2, "mazury": _2, "mielec": _2, "mielno": _2, "mragowo": _2, "naklo": _2, "nowaruda": _2, "nysa": _2, "olawa": _2, "olecko": _2, "olkusz": _2, "olsztyn": _2, "opoczno": _2, "opole": _2, "ostroda": _2, "ostroleka": _2, "ostrowiec": _2, "ostrowwlkp": _2, "pila": _2, "pisz": _2, "podhale": _2, "podlasie": _2, "polkowice": _2, "pomorze": _2, "pomorskie": _2, "prochowice": _2, "pruszkow": _2, "przeworsk": _2, "pulawy": _2, "radom": _2, "rawa-maz": _2, "rybnik": _2, "rzeszow": _2, "sanok": _2, "sejny": _2, "slask": _2, "slupsk": _2, "sosnowiec": _2, "stalowa-wola": _2, "skoczow": _2, "starachowice": _2, "stargard": _2, "suwalki": _2, "swidnica": _2, "swiebodzin": _2, "swinoujscie": _2, "szczecin": _2, "szczytno": _2, "tarnobrzeg": _2, "tgory": _2, "turek": _2, "tychy": _2, "ustka": _2, "walbrzych": _2, "warmia": _2, "warszawa": _2, "waw": _2, "wegrow": _2, "wielun": _2, "wlocl": _2, "wloclawek": _2, "wodzislaw": _2, "wolomin": _2, "wroclaw": _2, "zachpomor": _2, "zagan": _2, "zarow": _2, "zgora": _2, "zgorzelec": _2, "beep": _3, "ecommerce-shop": _3, "shoparena": _3, "homesklep": _3, "sdscloud": _3, "unicloud": _3, "krasnik": _3, "leczna": _3, "lubartow": _3, "lublin": _3, "poniatowa": _3, "swidnik": _3, "co": _3, "simplesite": _3, "art": _3, "gliwice": _3, "krakow": _3, "poznan": _3, "wroc": _3, "zakopane": _3, "myspreadshop": _3, "gda": _3, "gdansk": _3, "gdynia": _3, "med": _3, "sopot": _3 } }, "pm": { "$": 1, "succ": { "own": _3, "name": _3 } }, "pn": { "$": 1, "succ": { "gov": _2, "co": _2, "org": _2, "edu": _2, "net": _2 } }, "post": _2, "pr": { "$": 1, "succ": { "com": _2, "net": _2, "org": _2, "gov": _2, "edu": _2, "isla": _2, "pro": _2, "biz": _2, "info": _2, "name": _2, "est": _2, "prof": _2, "ac": _2 } }, "pro": { "$": 1, "succ": { "aaa": _2, "aca": _2, "acct": _2, "avocat": _2, "bar": _2, "cpa": _2, "eng": _2, "jur": _2, "law": _2, "med": _2, "recht": _2, "cloudns": _3, "dnstrace": { "$": 0, "succ": { "bci": _3 } }, "barsy": _3 } }, "ps": { "$": 1, "succ": { "edu": _2, "gov": _2, "sec": _2, "plo": _2, "com": _2, "org": _2, "net": _2 } }, "pt": { "$": 1, "succ": { "net": _2, "gov": _2, "org": _2, "edu": _2, "int": _2, "publ": _2, "com": _2, "nome": _2, "blogspot": _3, "123paginaweb": _3 } }, "pw": { "$": 1, "succ": { "co": _2, "ne": _2, "or": _2, "ed": _2, "go": _2, "belau": _2, "cloudns": _3, "x443": _3 } }, "py": { "$": 1, "succ": { "com": _2, "coop": _2, "edu": _2, "gov": _2, "mil": _2, "net": _2, "org": _2 } }, "qa": { "$": 1, "succ": { "com": _2, "edu": _2, "gov": _2, "mil": _2, "name": _2, "net": _2, "org": _2, "sch": _2, "blogspot": _3 } }, "re": { "$": 1, "succ": { "asso": _2, "com": _2, "nom": _2, "blogspot": _3 } }, "ro": { "$": 1, "succ": { "arts": _2, "com": _2, "firm": _2, "info": _2, "nom": _2, "nt": _2, "org": _2, "rec": _2, "store": _2, "tm": _2, "www": _2, "co": _3, "shop": _3, "blogspot": _3, "barsy": _3 } }, "rs": { "$": 1, "succ": { "ac": _2, "co": _2, "edu": _2, "gov": _2, "in": _2, "org": _2, "brendly": { "$": 0, "succ": { "shop": _3 } }, "blogspot": _3, "ua": _3, "ox": _3 } }, "ru": { "$": 1, "succ": { "ac": _3, "edu": _3, "gov": _3, "int": _3, "mil": _3, "test": _3, "eurodir": _3, "adygeya": _3, "bashkiria": _3, "bir": _3, "cbg": _3, "com": _3, "dagestan": _3, "grozny": _3, "kalmykia": _3, "kustanai": _3, "marine": _3, "mordovia": _3, "msk": _3, "mytis": _3, "nalchik": _3, "nov": _3, "pyatigorsk": _3, "spb": _3, "vladikavkaz": _3, "vladimir": _3, "blogspot": _3, "na4u": _3, "mircloud": _3, "regruhosting": _27, "myjino": { "$": 2, "succ": { "hosting": _5, "landing": _5, "spectrum": _5, "vps": _5 } }, "cldmail": { "$": 0, "succ": { "hb": _3 } }, "mcdir": { "$": 2, "succ": { "vps": _3 } }, "mcpre": _3, "net": _3, "org": _3, "pp": _3, "123sait": _3, "lk3": _3, "ras": _3 } }, "rw": { "$": 1, "succ": { "ac": _2, "co": _2, "coop": _2, "gov": _2, "mil": _2, "net": _2, "org": _2 } }, "sa": { "$": 1, "succ": { "com": _2, "net": _2, "org": _2, "gov": _2, "med": _2, "pub": _2, "edu": _2, "sch": _2 } }, "sb": _4, "sc": _4, "sd": { "$": 1, "succ": { "com": _2, "net": _2, "org": _2, "edu": _2, "med": _2, "tv": _2, "gov": _2, "info": _2 } }, "se": { "$": 1, "succ": { "a": _2, "ac": _2, "b": _2, "bd": _2, "brand": _2, "c": _2, "d": _2, "e": _2, "f": _2, "fh": _2, "fhsk": _2, "fhv": _2, "g": _2, "h": _2, "i": _2, "k": _2, "komforb": _2, "kommunalforbund": _2, "komvux": _2, "l": _2, "lanbib": _2, "m": _2, "n": _2, "naturbruksgymn": _2, "o": _2, "org": _2, "p": _2, "parti": _2, "pp": _2, "press": _2, "r": _2, "s": _2, "t": _2, "tm": _2, "u": _2, "w": _2, "x": _2, "y": _2, "z": _2, "com": _3, "blogspot": _3, "conf": _3, "iopsys": _3, "123minsida": _3, "itcouldbewor": _3, "myspreadshop": _3, "paba": { "$": 0, "succ": { "su": _3 } } } }, "sg": { "$": 1, "succ": { "com": _2, "net": _2, "org": _2, "gov": _2, "edu": _2, "per": _2, "blogspot": _3, "enscaled": _3 } }, "sh": { "$": 1, "succ": { "com": _2, "net": _2, "gov": _2, "org": _2, "mil": _2, "bip": _3, "hashbang": _3, "platform": { "$": 0, "succ": { "bc": _3, "ent": _3, "eu": _3, "us": _3 } }, "now": _3, "vxl": _3, "wedeploy": _3 } }, "si": { "$": 1, "succ": { "gitapp": _3, "gitpage": _3, "blogspot": _3 } }, "sj": _2, "sk": _6, "sl": _4, "sm": _2, "sn": { "$": 1, "succ": { "art": _2, "com": _2, "edu": _2, "gouv": _2, "org": _2, "perso": _2, "univ": _2, "blogspot": _3 } }, "so": { "$": 1, "succ": { "com": _2, "edu": _2, "gov": _2, "me": _2, "net": _2, "org": _2, "sch": _3 } }, "sr": _2, "ss": { "$": 1, "succ": { "biz": _2, "com": _2, "edu": _2, "gov": _2, "me": _2, "net": _2, "org": _2, "sch": _2 } }, "st": { "$": 1, "succ": { "co": _2, "com": _2, "consulado": _2, "edu": _2, "embaixada": _2, "mil": _2, "net": _2, "org": _2, "principe": _2, "saotome": _2, "store": _2, "kirara": _3, "noho": _3 } }, "su": { "$": 1, "succ": { "abkhazia": _3, "adygeya": _3, "aktyubinsk": _3, "arkhangelsk": _3, "armenia": _3, "ashgabad": _3, "azerbaijan": _3, "balashov": _3, "bashkiria": _3, "bryansk": _3, "bukhara": _3, "chimkent": _3, "dagestan": _3, "east-kazakhstan": _3, "exnet": _3, "georgia": _3, "grozny": _3, "ivanovo": _3, "jambyl": _3, "kalmykia": _3, "kaluga": _3, "karacol": _3, "karaganda": _3, "karelia": _3, "khakassia": _3, "krasnodar": _3, "kurgan": _3, "kustanai": _3, "lenug": _3, "mangyshlak": _3, "mordovia": _3, "msk": _3, "murmansk": _3, "nalchik": _3, "navoi": _3, "north-kazakhstan": _3, "nov": _3, "obninsk": _3, "penza": _3, "pokrovsk": _3, "sochi": _3, "spb": _3, "tashkent": _3, "termez": _3, "togliatti": _3, "troitsk": _3, "tselinograd": _3, "tula": _3, "tuva": _3, "vladikavkaz": _3, "vladimir": _3, "vologda": _3 } }, "sv": { "$": 1, "succ": { "com": _2, "edu": _2, "gob": _2, "org": _2, "red": _2 } }, "sx": _7, "sy": _32, "sz": { "$": 1, "succ": { "co": _2, "ac": _2, "org": _2 } }, "tc": { "$": 1, "succ": { "ch": _3, "me": _3, "we": _3 } }, "td": _6, "tel": _2, "tf": { "$": 1, "succ": { "sch": _3 } }, "tg": _2, "th": { "$": 1, "succ": { "ac": _2, "co": _2, "go": _2, "in": _2, "mi": _2, "net": _2, "or": _2, "online": _3, "shop": _3 } }, "tj": { "$": 1, "succ": { "ac": _2, "biz": _2, "co": _2, "com": _2, "edu": _2, "go": _2, "gov": _2, "int": _2, "mil": _2, "name": _2, "net": _2, "nic": _2, "org": _2, "test": _2, "web": _2 } }, "tk": _2, "tl": _7, "tm": { "$": 1, "succ": { "com": _2, "co": _2, "org": _2, "net": _2, "nom": _2, "gov": _2, "mil": _2, "edu": _2 } }, "tn": { "$": 1, "succ": { "com": _2, "ens": _2, "fin": _2, "gov": _2, "ind": _2, "info": _2, "intl": _2, "mincom": _2, "nat": _2, "net": _2, "org": _2, "perso": _2, "tourism": _2, "orangecloud": _3 } }, "to": { "$": 1, "succ": { "611": _3, "com": _2, "gov": _2, "net": _2, "org": _2, "edu": _2, "mil": _2, "oya": _3, "rdv": _3, "x0": _3, "vpnplus": _3, "quickconnect": _13, "nyan": _3 } }, "tr": { "$": 1, "succ": { "av": _2, "bbs": _2, "bel": _2, "biz": _2, "com": _6, "dr": _2, "edu": _2, "gen": _2, "gov": _2, "info": _2, "mil": _2, "k12": _2, "kep": _2, "name": _2, "net": _2, "org": _2, "pol": _2, "tel": _2, "tsk": _2, "tv": _2, "web": _2, "nc": _7 } }, "tt": { "$": 1, "succ": { "co": _2, "com": _2, "org": _2, "net": _2, "biz": _2, "info": _2, "pro": _2, "int": _2, "coop": _2, "jobs": _2, "mobi": _2, "travel": _2, "museum": _2, "aero": _2, "name": _2, "gov": _2, "edu": _2 } }, "tv": { "$": 1, "succ": { "dyndns": _3, "better-than": _3, "on-the-web": _3, "worse-than": _3, "from": _3, "sakura": _3 } }, "tw": { "$": 1, "succ": { "edu": _2, "gov": _2, "mil": _2, "com": { "$": 1, "succ": { "mymailer": _3 } }, "net": _2, "org": _2, "idv": _2, "game": _2, "ebiz": _2, "club": _2, "xn--zf0ao64a": _2, "網路": _2, "xn--uc0atv": _2, "組織": _2, "xn--czrw28b": _2, "商業": _2, "url": _3, "blogspot": _3 } }, "tz": { "$": 1, "succ": { "ac": _2, "co": _2, "go": _2, "hotel": _2, "info": _2, "me": _2, "mil": _2, "mobi": _2, "ne": _2, "or": _2, "sc": _2, "tv": _2 } }, "ua": { "$": 1, "succ": { "com": _2, "edu": _2, "gov": _2, "in": _2, "net": _2, "org": _2, "cherkassy": _2, "cherkasy": _2, "chernigov": _2, "chernihiv": _2, "chernivtsi": _2, "chernovtsy": _2, "ck": _2, "cn": _2, "cr": _2, "crimea": _2, "cv": _2, "dn": _2, "dnepropetrovsk": _2, "dnipropetrovsk": _2, "donetsk": _2, "dp": _2, "if": _2, "ivano-frankivsk": _2, "kh": _2, "kharkiv": _2, "kharkov": _2, "kherson": _2, "khmelnitskiy": _2, "khmelnytskyi": _2, "kiev": _2, "kirovograd": _2, "km": _2, "kr": _2, "krym": _2, "ks": _2, "kv": _2, "kyiv": _2, "lg": _2, "lt": _2, "lugansk": _2, "lutsk": _2, "lv": _2, "lviv": _2, "mk": _2, "mykolaiv": _2, "nikolaev": _2, "od": _2, "odesa": _2, "odessa": _2, "pl": _2, "poltava": _2, "rivne": _2, "rovno": _2, "rv": _2, "sb": _2, "sebastopol": _2, "sevastopol": _2, "sm": _2, "sumy": _2, "te": _2, "ternopil": _2, "uz": _2, "uzhgorod": _2, "vinnica": _2, "vinnytsia": _2, "vn": _2, "volyn": _2, "yalta": _2, "zaporizhzhe": _2, "zaporizhzhia": _2, "zhitomir": _2, "zhytomyr": _2, "zp": _2, "zt": _2, "cc": _3, "inf": _3, "ltd": _3, "cx": _3, "ie": _3, "biz": _3, "co": _3, "pp": _3, "v": _3 } }, "ug": { "$": 1, "succ": { "co": _2, "or": _2, "ac": _2, "sc": _2, "go": _2, "ne": _2, "com": _2, "org": _2, "blogspot": _3 } }, "uk": { "$": 1, "succ": { "ac": _2, "co": { "$": 1, "succ": { "bytemark": { "$": 0, "succ": { "dh": _3, "vm": _3 } }, "blogspot": _3, "layershift": _26, "barsy": _3, "barsyonline": _3, "retrosnub": _31, "nh-serv": _3, "no-ip": _3, "wellbeingzone": _3, "adimo": _3, "myspreadshop": _3 } }, "gov": { "$": 1, "succ": { "campaign": _3, "service": _3, "api": _3, "homeoffice": _3 } }, "ltd": _2, "me": _2, "net": _2, "nhs": _2, "org": { "$": 1, "succ": { "glug": _3, "lug": _3, "lugs": _3, "affinitylottery": _3, "raffleentry": _3, "weeklylottery": _3 } }, "plc": _2, "police": _2, "sch": _8, "conn": _3, "copro": _3, "hosp": _3, "independent-commission": _3, "independent-inquest": _3, "independent-inquiry": _3, "independent-panel": _3, "independent-review": _3, "public-inquiry": _3, "royal-commission": _3, "pymnt": _3, "barsy": _3 } }, "us": { "$": 1, "succ": { "dni": _2, "fed": _2, "isa": _2, "kids": _2, "nsn": _2, "ak": _40, "al": _40, "ar": _40, "as": _40, "az": _40, "ca": _40, "co": _40, "ct": _40, "dc": _40, "de": { "$": 1, "succ": { "k12": _2, "cc": _2, "lib": _3 } }, "fl": _40, "ga": _40, "gu": _40, "hi": _41, "ia": _40, "id": _40, "il": _40, "in": _40, "ks": _40, "ky": _40, "la": _40, "ma": { "$": 1, "succ": { "k12": { "$": 1, "succ": { "pvt": _2, "chtr": _2, "paroch": _2 } }, "cc": _2, "lib": _2 } }, "md": _40, "me": _40, "mi": { "$": 1, "succ": { "k12": _2, "cc": _2, "lib": _2, "ann-arbor": _2, "cog": _2, "dst": _2, "eaton": _2, "gen": _2, "mus": _2, "tec": _2, "washtenaw": _2 } }, "mn": _40, "mo": _40, "ms": _40, "mt": _40, "nc": _40, "nd": _41, "ne": _40, "nh": _40, "nj": _40, "nm": _40, "nv": _40, "ny": _40, "oh": _40, "ok": _40, "or": _40, "pa": _40, "pr": _40, "ri": _41, "sc": _40, "sd": _41, "tn": _40, "tx": _40, "ut": _40, "vi": _40, "vt": _40, "va": _40, "wa": _40, "wi": _40, "wv": { "$": 1, "succ": { "cc": _2 } }, "wy": _40, "graphox": _3, "cloudns": _3, "drud": _3, "is-by": _3, "land-4-sale": _3, "stuff-4-sale": _3, "enscaled": { "$": 0, "succ": { "phx": _3 } }, "mircloud": _3, "freeddns": _3, "golffan": _3, "noip": _3, "pointto": _3, "platterp": _3 } }, "uy": { "$": 1, "succ": { "com": _6, "edu": _2, "gub": _2, "mil": _2, "net": _2, "org": _2 } }, "uz": { "$": 1, "succ": { "co": _2, "com": _2, "net": _2, "org": _2 } }, "va": _2, "vc": { "$": 1, "succ": { "com": _2, "net": _2, "org": _2, "gov": _2, "mil": _2, "edu": _2, "gv": { "$": 2, "succ": { "d": _3 } }, "0e": _3 } }, "ve": { "$": 1, "succ": { "arts": _2, "bib": _2, "co": _2, "com": _2, "e12": _2, "edu": _2, "firm": _2, "gob": _2, "gov": _2, "info": _2, "int": _2, "mil": _2, "net": _2, "nom": _2, "org": _2, "rar": _2, "rec": _2, "store": _2, "tec": _2, "web": _2 } }, "vg": { "$": 1, "succ": { "at": _3 } }, "vi": { "$": 1, "succ": { "co": _2, "com": _2, "k12": _2, "net": _2, "org": _2 } }, "vn": { "$": 1, "succ": { "com": _2, "net": _2, "org": _2, "edu": _2, "gov": _2, "int": _2, "ac": _2, "biz": _2, "info": _2, "name": _2, "pro": _2, "health": _2, "blogspot": _3 } }, "vu": { "$": 1, "succ": { "com": _2, "edu": _2, "net": _2, "org": _2, "cn": _3, "blog": _3, "dev": _3, "me": _3 } }, "wf": { "$": 1, "succ": { "biz": _3, "sch": _3 } }, "ws": { "$": 1, "succ": { "com": _2, "net": _2, "org": _2, "gov": _2, "edu": _2, "advisor": _5, "cloud66": _3, "dyndns": _3, "mypets": _3 } }, "yt": { "$": 1, "succ": { "org": _3 } }, "xn--mgbaam7a8h": _2, "امارات": _2, "xn--y9a3aq": _2, "հայ": _2, "xn--54b7fta0cc": _2, "বাংলা": _2, "xn--90ae": _2, "бг": _2, "xn--mgbcpq6gpa1a": _2, "البحرين": _2, "xn--90ais": _2, "бел": _2, "xn--fiqs8s": _2, "中国": _2, "xn--fiqz9s": _2, "中國": _2, "xn--lgbbat1ad8j": _2, "الجزائر": _2, "xn--wgbh1c": _2, "مصر": _2, "xn--e1a4c": _2, "ею": _2, "xn--qxa6a": _2, "ευ": _2, "xn--mgbah1a3hjkrd": _2, "موريتانيا": _2, "xn--node": _2, "გე": _2, "xn--qxam": _2, "ελ": _2, "xn--j6w193g": { "$": 1, "succ": { "xn--55qx5d": _2, "xn--wcvs22d": _2, "xn--mxtq1m": _2, "xn--gmqw5a": _2, "xn--od0alg": _2, "xn--uc0atv": _2 } }, "香港": { "$": 1, "succ": { "公司": _2, "教育": _2, "政府": _2, "個人": _2, "網絡": _2, "組織": _2 } }, "xn--2scrj9c": _2, "ಭಾರತ": _2, "xn--3hcrj9c": _2, "ଭାରତ": _2, "xn--45br5cyl": _2, "ভাৰত": _2, "xn--h2breg3eve": _2, "भारतम्": _2, "xn--h2brj9c8c": _2, "भारोत": _2, "xn--mgbgu82a": _2, "ڀارت": _2, "xn--rvc1e0am3e": _2, "ഭാരതം": _2, "xn--h2brj9c": _2, "भारत": _2, "xn--mgbbh1a": _2, "بارت": _2, "xn--mgbbh1a71e": _2, "بھارت": _2, "xn--fpcrj9c3d": _2, "భారత్": _2, "xn--gecrj9c": _2, "ભારત": _2, "xn--s9brj9c": _2, "ਭਾਰਤ": _2, "xn--45brj9c": _2, "ভারত": _2, "xn--xkc2dl3a5ee0h": _2, "இந்தியா": _2, "xn--mgba3a4f16a": _2, "ایران": _2, "xn--mgba3a4fra": _2, "ايران": _2, "xn--mgbtx2b": _2, "عراق": _2, "xn--mgbayh7gpa": _2, "الاردن": _2, "xn--3e0b707e": _2, "한국": _2, "xn--80ao21a": _2, "қаз": _2, "xn--q7ce6a": _2, "ລາວ": _2, "xn--fzc2c9e2c": _2, "ලංකා": _2, "xn--xkc2al3hye2a": _2, "இலங்கை": _2, "xn--mgbc0a9azcg": _2, "المغرب": _2, "xn--d1alf": _2, "мкд": _2, "xn--l1acc": _2, "мон": _2, "xn--mix891f": _2, "澳門": _2, "xn--mix082f": _2, "澳门": _2, "xn--mgbx4cd0ab": _2, "مليسيا": _2, "xn--mgb9awbf": _2, "عمان": _2, "xn--mgbai9azgqp6j": _2, "پاکستان": _2, "xn--mgbai9a5eva00b": _2, "پاكستان": _2, "xn--ygbi2ammx": _2, "فلسطين": _2, "xn--90a3ac": { "$": 1, "succ": { "xn--o1ac": _2, "xn--c1avg": _2, "xn--90azh": _2, "xn--d1at": _2, "xn--o1ach": _2, "xn--80au": _2 } }, "срб": { "$": 1, "succ": { "пр": _2, "орг": _2, "обр": _2, "од": _2, "упр": _2, "ак": _2 } }, "xn--p1ai": _2, "рф": _2, "xn--wgbl6a": _2, "قطر": _2, "xn--mgberp4a5d4ar": _2, "السعودية": _2, "xn--mgberp4a5d4a87g": _2, "السعودیة": _2, "xn--mgbqly7c0a67fbc": _2, "السعودیۃ": _2, "xn--mgbqly7cvafr": _2, "السعوديه": _2, "xn--mgbpl2fh": _2, "سودان": _2, "xn--yfro4i67o": _2, "新加坡": _2, "xn--clchc0ea0b2g2a9gcd": _2, "சிங்கப்பூர்": _2, "xn--ogbpf8fl": _2, "سورية": _2, "xn--mgbtf8fl": _2, "سوريا": _2, "xn--o3cw4h": { "$": 1, "succ": { "xn--12c1fe0br": _2, "xn--12co0c3b4eva": _2, "xn--h3cuzk1di": _2, "xn--o3cyx2a": _2, "xn--m3ch0j3a": _2, "xn--12cfi8ixb8l": _2 } }, "ไทย": { "$": 1, "succ": { "ศึกษา": _2, "ธุรกิจ": _2, "รัฐบาล": _2, "ทหาร": _2, "เน็ต": _2, "องค์กร": _2 } }, "xn--pgbs0dh": _2, "تونس": _2, "xn--kpry57d": _2, "台灣": _2, "xn--kprw13d": _2, "台湾": _2, "xn--nnx388a": _2, "臺灣": _2, "xn--j1amh": _2, "укр": _2, "xn--mgb2ddes": _2, "اليمن": _2, "xxx": _2, "ye": _32, "za": { "$": 0, "succ": { "ac": _2, "agric": _2, "alt": _2, "co": _6, "edu": _2, "gov": _2, "grondar": _2, "law": _2, "mil": _2, "net": _2, "ngo": _2, "nic": _2, "nis": _2, "nom": _2, "org": _2, "school": _2, "tm": _2, "web": _2 } }, "zm": { "$": 1, "succ": { "ac": _2, "biz": _2, "co": _2, "com": _2, "edu": _2, "gov": _2, "info": _2, "mil": _2, "net": _2, "org": _2, "sch": _2 } }, "zw": { "$": 1, "succ": { "ac": _2, "co": _2, "gov": _2, "mil": _2, "org": _2 } }, "aaa": _2, "aarp": _2, "abarth": _2, "abb": _2, "abbott": _2, "abbvie": _2, "abc": _2, "able": _2, "abogado": _2, "abudhabi": _2, "academy": { "$": 1, "succ": { "official": _3 } }, "accenture": _2, "accountant": _2, "accountants": _2, "aco": _2, "actor": _2, "ads": _2, "adult": _2, "aeg": _2, "aetna": _2, "afl": _2, "africa": _2, "agakhan": _2, "agency": _2, "aig": _2, "airbus": _2, "airforce": _2, "airtel": _2, "akdn": _2, "alfaromeo": _2, "alibaba": _2, "alipay": _2, "allfinanz": _2, "allstate": _2, "ally": _2, "alsace": _2, "alstom": _2, "amazon": _2, "americanexpress": _2, "americanfamily": _2, "amex": _2, "amfam": _2, "amica": _2, "amsterdam": _2, "analytics": _2, "android": _2, "anquan": _2, "anz": _2, "aol": _2, "apartments": _2, "app": { "$": 1, "succ": { "beget": _5, "clerk": _3, "clerkstage": _3, "wnext": _3, "platform0": _3, "deta": _3, "ondigitalocean": _3, "easypanel": _3, "encr": _3, "edgecompute": _3, "fireweb": _3, "onflashdrive": _3, "framer": _3, "run": { "$": 2, "succ": { "a": _3 } }, "web": _3, "hasura": _3, "loginline": _3, "messerli": _3, "netlify": _3, "ngrok": _3, "ngrok-free": _3, "developer": _5, "noop": _3, "northflank": _5, "snowflake": { "$": 2, "succ": { "privatelink": _3 } }, "streamlit": _3, "telebit": _3, "typedream": _3, "vercel": _3, "bookonline": _3 } }, "apple": _2, "aquarelle": _2, "arab": _2, "aramco": _2, "archi": _2, "army": _2, "art": _2, "arte": _2, "asda": _2, "associates": _2, "athleta": _2, "attorney": _2, "auction": _2, "audi": _2, "audible": _2, "audio": _2, "auspost": _2, "author": _2, "auto": _2, "autos": _2, "avianca": _2, "aws": _2, "axa": _2, "azure": _2, "baby": _2, "baidu": _2, "banamex": _2, "bananarepublic": _2, "band": _2, "bank": _2, "bar": _2, "barcelona": _2, "barclaycard": _2, "barclays": _2, "barefoot": _2, "bargains": _2, "baseball": _2, "basketball": { "$": 1, "succ": { "aus": _3, "nz": _3 } }, "bauhaus": _2, "bayern": _2, "bbc": _2, "bbt": _2, "bbva": _2, "bcg": _2, "bcn": _2, "beats": _2, "beauty": _2, "beer": _2, "bentley": _2, "berlin": _2, "best": _2, "bestbuy": _2, "bet": _2, "bharti": _2, "bible": _2, "bid": _2, "bike": _2, "bing": _2, "bingo": _2, "bio": _2, "black": _2, "blackfriday": _2, "blockbuster": _2, "blog": _2, "bloomberg": _2, "blue": _2, "bms": _2, "bmw": _2, "bnpparibas": _2, "boats": _2, "boehringer": _2, "bofa": _2, "bom": _2, "bond": _2, "boo": _2, "book": _2, "booking": _2, "bosch": _2, "bostik": _2, "boston": _2, "bot": _2, "boutique": _2, "box": _2, "bradesco": _2, "bridgestone": _2, "broadway": _2, "broker": _2, "brother": _2, "brussels": _2, "build": _2, "builders": { "$": 1, "succ": { "cloudsite": _3 } }, "business": _10, "buy": _2, "buzz": _2, "bzh": _2, "cab": _2, "cafe": _2, "cal": _2, "call": _2, "calvinklein": _2, "cam": _2, "camera": _2, "camp": _2, "canon": _2, "capetown": _2, "capital": _2, "capitalone": _2, "car": _2, "caravan": _2, "cards": _2, "care": _2, "career": _2, "careers": _2, "cars": _2, "casa": { "$": 1, "succ": { "nabu": { "$": 0, "succ": { "ui": _3 } } } }, "case": _2, "cash": _2, "casino": _2, "catering": _2, "catholic": _2, "cba": _2, "cbn": _2, "cbre": _2, "cbs": _2, "center": _2, "ceo": _2, "cern": _2, "cfa": _2, "cfd": _2, "chanel": _2, "channel": _2, "charity": _2, "chase": _2, "chat": _2, "cheap": _2, "chintai": _2, "christmas": _2, "chrome": _2, "church": _2, "cipriani": _2, "circle": _2, "cisco": _2, "citadel": _2, "citi": _2, "citic": _2, "city": _2, "cityeats": _2, "claims": _2, "cleaning": _2, "click": _2, "clinic": _2, "clinique": _2, "clothing": _2, "cloud": { "$": 1, "succ": { "banzai": _5, "elementor": _3, "encoway": { "$": 0, "succ": { "eu": _3 } }, "statics": _5, "ravendb": _3, "axarnet": { "$": 0, "succ": { "es-1": _3 } }, "diadem": _3, "jelastic": { "$": 0, "succ": { "vip": _3 } }, "jele": _3, "jenv-aruba": { "$": 0, "succ": { "aruba": { "$": 0, "succ": { "eur": { "$": 0, "succ": { "it1": _3 } } } }, "it1": _3 } }, "keliweb": { "$": 2, "succ": { "cs": _3 } }, "oxa": { "$": 2, "succ": { "tn": _3, "uk": _3 } }, "primetel": { "$": 2, "succ": { "uk": _3 } }, "reclaim": { "$": 0, "succ": { "ca": _3, "uk": _3, "us": _3 } }, "trendhosting": { "$": 0, "succ": { "ch": _3, "de": _3 } }, "jotelulu": _3, "kuleuven": _3, "linkyard": _3, "magentosite": _5, "perspecta": _3, "vapor": _3, "on-rancher": _5, "scw": { "$": 0, "succ": { "baremetal": { "$": 0, "succ": { "fr-par-1": _3, "fr-par-2": _3, "nl-ams-1": _3 } }, "fr-par": { "$": 0, "succ": { "fnc": { "$": 2, "succ": { "functions": _3 } }, "k8s": _11, "s3": _3, "s3-website": _3, "whm": _3 } }, "instances": { "$": 0, "succ": { "priv": _3, "pub": _3 } }, "k8s": _3, "nl-ams": { "$": 0, "succ": { "k8s": _11, "s3": _3, "s3-website": _3, "whm": _3 } }, "pl-waw": { "$": 0, "succ": { "k8s": _11, "s3": _3, "s3-website": _3 } }, "scalebook": _3, "smartlabeling": _3 } }, "sensiosite": _5, "trafficplex": _3, "urown": _3, "voorloper": _3 } }, "club": { "$": 1, "succ": { "cloudns": _3, "jele": _3, "barsy": _3 } }, "clubmed": _2, "coach": _2, "codes": { "$": 1, "succ": { "owo": _5 } }, "coffee": _2, "college": _2, "cologne": _2, "comcast": _2, "commbank": _2, "community": { "$": 1, "succ": { "nog": _3, "ravendb": _3, "myforum": _3 } }, "company": _2, "compare": _2, "computer": _2, "comsec": _2, "condos": _2, "construction": _2, "consulting": _2, "contact": _2, "contractors": _2, "cooking": _2, "cookingchannel": _2, "cool": { "$": 1, "succ": { "elementor": _3, "de": _3 } }, "corsica": _2, "country": _2, "coupon": _2, "coupons": _2, "courses": _2, "cpa": _2, "credit": _2, "creditcard": _2, "creditunion": _2, "cricket": _2, "crown": _2, "crs": _2, "cruise": _2, "cruises": _2, "cuisinella": _2, "cymru": _2, "cyou": _2, "dabur": _2, "dad": _2, "dance": _2, "data": _2, "date": _2, "dating": _2, "datsun": _2, "day": _2, "dclk": _2, "dds": _2, "deal": _2, "dealer": _2, "deals": _2, "degree": _2, "delivery": _2, "dell": _2, "deloitte": _2, "delta": _2, "democrat": _2, "dental": _2, "dentist": _2, "desi": _2, "design": { "$": 1, "succ": { "bss": _3 } }, "dev": { "$": 1, "succ": { "autocode": _3, "lcl": _5, "lclstage": _5, "stg": _5, "stgstage": _5, "pages": _3, "r2": _3, "workers": _3, "curv": _3, "deno": _3, "deno-staging": _3, "deta": _3, "fly": _3, "githubpreview": _3, "gateway": _5, "iserv": _3, "localcert": { "$": 0, "succ": { "user": _5 } }, "loginline": _3, "mediatech": _3, "ngrok": _3, "ngrok-free": _3, "platter-app": _3, "shiftcrypto": _3, "vercel": _3, "webhare": _5 } }, "dhl": _2, "diamonds": _2, "diet": _2, "digital": { "$": 1, "succ": { "cloudapps": { "$": 2, "succ": { "london": _3 } } } }, "direct": _2, "directory": _2, "discount": _2, "discover": _2, "dish": _2, "diy": _2, "dnp": _2, "docs": _2, "doctor": _2, "dog": _2, "domains": _2, "dot": _2, "download": _2, "drive": _2, "dtv": _2, "dubai": _2, "dunlop": _2, "dupont": _2, "durban": _2, "dvag": _2, "dvr": _2, "earth": { "$": 1, "succ": { "dapps": { "$": 0, "succ": { "*": _3, "bzz": _5 } } } }, "eat": _2, "eco": _2, "edeka": _2, "education": _10, "email": _2, "emerck": _2, "energy": _2, "engineer": _2, "engineering": _2, "enterprises": _2, "epson": _2, "equipment": _2, "ericsson": _2, "erni": _2, "esq": _2, "estate": { "$": 1, "succ": { "compute": _5 } }, "etisalat": _2, "eurovision": _2, "eus": { "$": 1, "succ": { "party": _28 } }, "events": { "$": 1, "succ": { "koobin": _3, "co": _3 } }, "exchange": _2, "expert": _2, "exposed": _2, "express": _2, "extraspace": _2, "fage": _2, "fail": _2, "fairwinds": _2, "faith": _29, "family": _2, "fan": _2, "fans": _2, "farm": { "$": 1, "succ": { "storj": _3 } }, "farmers": _2, "fashion": _2, "fast": _2, "fedex": _2, "feedback": _2, "ferrari": _2, "ferrero": _2, "fiat": _2, "fidelity": _2, "fido": _2, "film": _2, "final": _2, "finance": _2, "financial": _10, "fire": _2, "firestone": _2, "firmdale": _2, "fish": _2, "fishing": _2, "fit": _2, "fitness": _2, "flickr": _2, "flights": _2, "flir": _2, "florist": _2, "flowers": _2, "fly": _2, "foo": _2, "food": _2, "foodnetwork": _2, "football": _2, "ford": _2, "forex": _2, "forsale": _2, "forum": _2, "foundation": _2, "fox": _2, "free": _2, "fresenius": _2, "frl": _2, "frogans": _2, "frontdoor": _2, "frontier": _2, "ftr": _2, "fujitsu": _2, "fun": _2, "fund": _2, "furniture": _2, "futbol": _2, "fyi": _2, "gal": _2, "gallery": _2, "gallo": _2, "gallup": _2, "game": _2, "games": _2, "gap": _2, "garden": _2, "gay": _2, "gbiz": _2, "gdn": { "$": 1, "succ": { "cnpy": _3 } }, "gea": _2, "gent": _2, "genting": _2, "george": _2, "ggee": _2, "gift": _2, "gifts": _2, "gives": _2, "giving": _2, "glass": _2, "gle": _2, "global": _2, "globo": _2, "gmail": _2, "gmbh": _2, "gmo": _2, "gmx": _2, "godaddy": _2, "gold": _2, "goldpoint": _2, "golf": _2, "goo": _2, "goodyear": _2, "goog": { "$": 1, "succ": { "cloud": _3, "translate": _3, "usercontent": _5 } }, "google": _2, "gop": _2, "got": _2, "grainger": _2, "graphics": _2, "gratis": _2, "green": _2, "gripe": _2, "grocery": _2, "group": { "$": 1, "succ": { "discourse": _3 } }, "guardian": _2, "gucci": _2, "guge": _2, "guide": _2, "guitars": _2, "guru": _2, "hair": _2, "hamburg": _2, "hangout": _2, "haus": _2, "hbo": _2, "hdfc": _2, "hdfcbank": _2, "health": { "$": 1, "succ": { "hra": _3 } }, "healthcare": _2, "help": _2, "helsinki": _2, "here": _2, "hermes": _2, "hgtv": _2, "hiphop": _2, "hisamitsu": _2, "hitachi": _2, "hiv": _2, "hkt": _2, "hockey": _2, "holdings": _2, "holiday": _2, "homedepot": _2, "homegoods": _2, "homes": _2, "homesense": _2, "honda": _2, "horse": _2, "hospital": _2, "host": { "$": 1, "succ": { "cloudaccess": _3, "freesite": _3, "easypanel": _3, "fastvps": _3, "myfast": _3, "tempurl": _3, "wpmudev": _3, "jele": _3, "mircloud": _3, "pcloud": _3, "half": _3 } }, "hosting": { "$": 1, "succ": { "opencraft": _3 } }, "hot": _2, "hoteles": _2, "hotels": _2, "hotmail": _2, "house": _2, "how": _2, "hsbc": _2, "hughes": _2, "hyatt": _2, "hyundai": _2, "ibm": _2, "icbc": _2, "ice": _2, "icu": _2, "ieee": _2, "ifm": _2, "ikano": _2, "imamat": _2, "imdb": _2, "immo": _2, "immobilien": _2, "inc": _2, "industries": _2, "infiniti": _2, "ing": _2, "ink": _2, "institute": _2, "insurance": _2, "insure": _2, "international": _2, "intuit": _2, "investments": _2, "ipiranga": _2, "irish": _2, "ismaili": _2, "ist": _2, "istanbul": _2, "itau": _2, "itv": _2, "jaguar": _2, "java": _2, "jcb": _2, "jeep": _2, "jetzt": _2, "jewelry": _2, "jio": _2, "jll": _2, "jmp": _2, "jnj": _2, "joburg": _2, "jot": _2, "joy": _2, "jpmorgan": _2, "jprs": _2, "juegos": _2, "juniper": _2, "kaufen": _2, "kddi": _2, "kerryhotels": _2, "kerrylogistics": _2, "kerryproperties": _2, "kfh": _2, "kia": _2, "kids": _2, "kim": _2, "kinder": _2, "kindle": _2, "kitchen": _2, "kiwi": _2, "koeln": _2, "komatsu": _2, "kosher": _2, "kpmg": _2, "kpn": _2, "krd": { "$": 1, "succ": { "co": _3, "edu": _3 } }, "kred": _2, "kuokgroup": _2, "kyoto": _2, "lacaixa": _2, "lamborghini": _2, "lamer": _2, "lancaster": _2, "lancia": _2, "land": { "$": 1, "succ": { "static": { "$": 2, "succ": { "dev": _3, "sites": _3 } } } }, "landrover": _2, "lanxess": _2, "lasalle": _2, "lat": _2, "latino": _2, "latrobe": _2, "law": _2, "lawyer": _2, "lds": _2, "lease": _2, "leclerc": _2, "lefrak": _2, "legal": _2, "lego": _2, "lexus": _2, "lgbt": _2, "lidl": _2, "life": _2, "lifeinsurance": _2, "lifestyle": _2, "lighting": _2, "like": _2, "lilly": _2, "limited": _2, "limo": _2, "lincoln": _2, "link": { "$": 1, "succ": { "cyon": _3, "mypep": _3, "dweb": _5 } }, "lipsy": _2, "live": { "$": 1, "succ": { "hlx": _3 } }, "living": _2, "llc": _2, "llp": _2, "loan": _2, "loans": _2, "locker": _2, "locus": _2, "lol": { "$": 1, "succ": { "omg": _3 } }, "london": _2, "lotte": _2, "lotto": _2, "love": _2, "lpl": _2, "lplfinancial": _2, "ltd": _2, "ltda": _2, "lundbeck": _2, "luxe": _2, "luxury": _2, "madrid": _2, "maif": _2, "maison": _2, "makeup": _2, "man": _2, "management": { "$": 1, "succ": { "router": _3 } }, "mango": _2, "map": _2, "market": _2, "marketing": _2, "markets": _2, "marriott": _2, "marshalls": _2, "maserati": _2, "mattel": _2, "mba": _2, "mckinsey": _2, "med": _2, "media": _35, "meet": _2, "melbourne": _2, "meme": _2, "memorial": _2, "men": _2, "menu": _36, "merckmsd": _2, "miami": _2, "microsoft": _2, "mini": _2, "mint": _2, "mit": _2, "mitsubishi": _2, "mlb": _2, "mls": _2, "mma": _2, "mobile": _2, "moda": _2, "moe": _2, "moi": _2, "mom": _2, "monash": _2, "money": _2, "monster": _2, "mormon": _2, "mortgage": _2, "moscow": _2, "moto": _2, "motorcycles": _2, "mov": _2, "movie": _2, "msd": _2, "mtn": _2, "mtr": _2, "music": _2, "mutual": _2, "nab": _2, "nagoya": _2, "natura": _2, "navy": _2, "nba": _2, "nec": _2, "netbank": _2, "netflix": _2, "network": { "$": 1, "succ": { "alces": _5, "co": _3, "arvo": _3, "azimuth": _3, "tlon": _3 } }, "neustar": _2, "new": _2, "news": { "$": 1, "succ": { "noticeable": _3 } }, "next": _2, "nextdirect": _2, "nexus": _2, "nfl": _2, "ngo": _2, "nhk": _2, "nico": _2, "nike": _2, "nikon": _2, "ninja": _2, "nissan": _2, "nissay": _2, "nokia": _2, "northwesternmutual": _2, "norton": _2, "now": _2, "nowruz": _2, "nowtv": _2, "nra": _2, "nrw": _2, "ntt": _2, "nyc": _2, "obi": _2, "observer": _2, "office": _2, "okinawa": _2, "olayan": _2, "olayangroup": _2, "oldnavy": _2, "ollo": _2, "omega": _2, "one": { "$": 1, "succ": { "onred": { "$": 2, "succ": { "staging": _3 } }, "service": _3, "homelink": _3 } }, "ong": _2, "onl": _2, "online": { "$": 1, "succ": { "eero": _3, "eero-stage": _3, "barsy": _3 } }, "ooo": _2, "open": _2, "oracle": _2, "orange": { "$": 1, "succ": { "tech": _3 } }, "organic": _2, "origins": _2, "osaka": _2, "otsuka": _2, "ott": _2, "ovh": { "$": 1, "succ": { "nerdpol": _3 } }, "page": { "$": 1, "succ": { "hlx": _3, "hlx3": _3, "translated": _3, "codeberg": _3, "pdns": _3, "plesk": _3, "prvcy": _3, "rocky": _3, "magnet": _3 } }, "panasonic": _2, "paris": _2, "pars": _2, "partners": _2, "parts": _2, "party": _29, "passagens": _2, "pay": _2, "pccw": _2, "pet": _2, "pfizer": _2, "pharmacy": _2, "phd": _2, "philips": _2, "phone": _2, "photo": _2, "photography": _2, "photos": _35, "physio": _2, "pics": _2, "pictet": _2, "pictures": { "$": 1, "succ": { "1337": _3 } }, "pid": _2, "pin": _2, "ping": _2, "pink": _2, "pioneer": _2, "pizza": { "$": 1, "succ": { "ngrok": _3 } }, "place": _10, "play": _2, "playstation": _2, "plumbing": _2, "plus": _2, "pnc": _2, "pohl": _2, "poker": _2, "politie": _2, "porn": { "$": 1, "succ": { "indie": _3 } }, "pramerica": _2, "praxi": _2, "press": _2, "prime": _2, "prod": _2, "productions": _2, "prof": _2, "progressive": _2, "promo": _2, "properties": _2, "property": _2, "protection": _2, "pru": _2, "prudential": _2, "pub": _36, "pwc": _2, "qpon": _2, "quebec": _2, "quest": _2, "racing": _2, "radio": _2, "read": _2, "realestate": _2, "realtor": _2, "realty": _2, "recipes": _2, "red": _2, "redstone": _2, "redumbrella": _2, "rehab": _2, "reise": _2, "reisen": _2, "reit": _2, "reliance": _2, "ren": _2, "rent": _2, "rentals": _2, "repair": _2, "report": _2, "republican": _2, "rest": _2, "restaurant": _2, "review": _29, "reviews": _2, "rexroth": _2, "rich": _2, "richardli": _2, "ricoh": _2, "ril": _2, "rio": _2, "rip": { "$": 1, "succ": { "clan": _3 } }, "rocher": _2, "rocks": { "$": 1, "succ": { "myddns": _3, "lima-city": _3, "webspace": _3 } }, "rodeo": _2, "rogers": _2, "room": _2, "rsvp": _2, "rugby": _2, "ruhr": _2, "run": { "$": 1, "succ": { "hs": _3, "development": _3, "ravendb": _3, "servers": _3, "build": _5, "code": _5, "database": _5, "migration": _5, "onporter": _3, "repl": _3 } }, "rwe": _2, "ryukyu": _2, "saarland": _2, "safe": _2, "safety": _2, "sakura": _2, "sale": _2, "salon": _2, "samsclub": _2, "samsung": _2, "sandvik": _2, "sandvikcoromant": _2, "sanofi": _2, "sap": _2, "sarl": _2, "sas": _2, "save": _2, "saxo": _2, "sbi": _2, "sbs": _2, "sca": _2, "scb": _2, "schaeffler": _2, "schmidt": _2, "scholarships": _2, "school": _2, "schule": _2, "schwarz": _2, "science": _29, "scot": { "$": 1, "succ": { "edu": _3, "gov": { "$": 2, "succ": { "service": _3 } } } }, "search": _2, "seat": _2, "secure": _2, "security": _2, "seek": _2, "select": _2, "sener": _2, "services": { "$": 1, "succ": { "loginline": _3 } }, "seven": _2, "sew": _2, "sex": _2, "sexy": _2, "sfr": _2, "shangrila": _2, "sharp": _2, "shaw": _2, "shell": _2, "shia": _2, "shiksha": _2, "shoes": _2, "shop": { "$": 1, "succ": { "base": _3, "hoplix": _3, "barsy": _3 } }, "shopping": _2, "shouji": _2, "show": _2, "showtime": _2, "silk": _2, "sina": _2, "singles": _2, "site": { "$": 1, "succ": { "cloudera": _5, "cyon": _3, "fnwk": _3, "folionetwork": _3, "fastvps": _3, "jele": _3, "lelux": _3, "loginline": _3, "barsy": _3, "mintere": _3, "omniwe": _3, "opensocial": _3, "platformsh": _5, "tst": _5, "byen": _3, "srht": _3, "novecore": _3 } }, "ski": _2, "skin": _2, "sky": _2, "skype": _2, "sling": _2, "smart": _2, "smile": _2, "sncf": _2, "soccer": _2, "social": _2, "softbank": _2, "software": _2, "sohu": _2, "solar": _2, "solutions": { "$": 1, "succ": { "diher": _5 } }, "song": _2, "sony": _2, "soy": _2, "spa": _2, "space": { "$": 1, "succ": { "myfast": _3, "uber": _3, "xs4all": _3 } }, "sport": _2, "spot": _2, "srl": _2, "stada": _2, "staples": _2, "star": _2, "statebank": _2, "statefarm": _2, "stc": _2, "stcgroup": _2, "stockholm": _2, "storage": _2, "store": { "$": 1, "succ": { "sellfy": _3, "shopware": _3, "storebase": _3 } }, "stream": _2, "studio": _2, "study": _2, "style": _2, "sucks": _2, "supplies": _2, "supply": _2, "support": _36, "surf": _2, "surgery": _2, "suzuki": _2, "swatch": _2, "swiss": _2, "sydney": _2, "systems": { "$": 1, "succ": { "knightpoint": _3 } }, "tab": _2, "taipei": _2, "talk": _2, "taobao": _2, "target": _2, "tatamotors": _2, "tatar": _2, "tattoo": _2, "tax": _2, "taxi": _2, "tci": _2, "tdk": _2, "team": { "$": 1, "succ": { "discourse": _3, "jelastic": _3 } }, "tech": _2, "technology": _10, "temasek": _2, "tennis": _2, "teva": _2, "thd": _2, "theater": _2, "theatre": _2, "tiaa": _2, "tickets": _2, "tienda": _2, "tiffany": _2, "tips": _2, "tires": _2, "tirol": _2, "tjmaxx": _2, "tjx": _2, "tkmaxx": _2, "tmall": _2, "today": { "$": 1, "succ": { "prequalifyme": _3 } }, "tokyo": _2, "tools": _2, "top": { "$": 1, "succ": { "now-dns": _3, "ntdll": _3 } }, "toray": _2, "toshiba": _2, "total": _2, "tours": _2, "town": _2, "toyota": _2, "toys": _2, "trade": _29, "trading": _2, "training": _2, "travel": _2, "travelchannel": _2, "travelers": _2, "travelersinsurance": _2, "trust": _2, "trv": _2, "tube": _2, "tui": _2, "tunes": _2, "tushu": _2, "tvs": _2, "ubank": _2, "ubs": _2, "unicom": _2, "university": _2, "uno": _2, "uol": _2, "ups": _2, "vacations": _2, "vana": _2, "vanguard": _2, "vegas": _2, "ventures": _2, "verisign": _2, "versicherung": _2, "vet": _2, "viajes": _2, "video": _2, "vig": _2, "viking": _2, "villas": _2, "vin": _2, "vip": _2, "virgin": _2, "visa": _2, "vision": _2, "viva": _2, "vivo": _2, "vlaanderen": _2, "vodka": _2, "volkswagen": _2, "volvo": _2, "vote": _2, "voting": _2, "voto": _2, "voyage": _2, "vuelos": _2, "wales": _2, "walmart": _2, "walter": _2, "wang": _2, "wanggou": _2, "watch": _2, "watches": _2, "weather": _2, "weatherchannel": _2, "webcam": _2, "weber": _2, "website": _35, "wedding": _2, "weibo": _2, "weir": _2, "whoswho": _2, "wien": _2, "wiki": _35, "williamhill": _2, "win": _2, "windows": _2, "wine": _2, "winners": _2, "wme": _2, "wolterskluwer": _2, "woodside": _2, "work": _2, "works": _2, "world": _2, "wow": _2, "wtc": _2, "wtf": _2, "xbox": _2, "xerox": _2, "xfinity": _2, "xihuan": _2, "xin": _2, "xn--11b4c3d": _2, "कॉम": _2, "xn--1ck2e1b": _2, "セール": _2, "xn--1qqw23a": _2, "佛山": _2, "xn--30rr7y": _2, "慈善": _2, "xn--3bst00m": _2, "集团": _2, "xn--3ds443g": _2, "在线": _2, "xn--3pxu8k": _2, "点看": _2, "xn--42c2d9a": _2, "คอม": _2, "xn--45q11c": _2, "八卦": _2, "xn--4gbrim": _2, "موقع": _2, "xn--55qw42g": _2, "公益": _2, "xn--55qx5d": _2, "公司": _2, "xn--5su34j936bgsg": _2, "香格里拉": _2, "xn--5tzm5g": _2, "网站": _2, "xn--6frz82g": _2, "移动": _2, "xn--6qq986b3xl": _2, "我爱你": _2, "xn--80adxhks": _2, "москва": _2, "xn--80aqecdr1a": _2, "католик": _2, "xn--80asehdb": _2, "онлайн": _2, "xn--80aswg": _2, "сайт": _2, "xn--8y0a063a": _2, "联通": _2, "xn--9dbq2a": _2, "קום": _2, "xn--9et52u": _2, "时尚": _2, "xn--9krt00a": _2, "微博": _2, "xn--b4w605ferd": _2, "淡马锡": _2, "xn--bck1b9a5dre4c": _2, "ファッション": _2, "xn--c1avg": _2, "орг": _2, "xn--c2br7g": _2, "नेट": _2, "xn--cck2b3b": _2, "ストア": _2, "xn--cckwcxetd": _2, "アマゾン": _2, "xn--cg4bki": _2, "삼성": _2, "xn--czr694b": _2, "商标": _2, "xn--czrs0t": _2, "商店": _2, "xn--czru2d": _2, "商城": _2, "xn--d1acj3b": _2, "дети": _2, "xn--eckvdtc9d": _2, "ポイント": _2, "xn--efvy88h": _2, "新闻": _2, "xn--fct429k": _2, "家電": _2, "xn--fhbei": _2, "كوم": _2, "xn--fiq228c5hs": _2, "中文网": _2, "xn--fiq64b": _2, "中信": _2, "xn--fjq720a": _2, "娱乐": _2, "xn--flw351e": _2, "谷歌": _2, "xn--fzys8d69uvgm": _2, "電訊盈科": _2, "xn--g2xx48c": _2, "购物": _2, "xn--gckr3f0f": _2, "クラウド": _2, "xn--gk3at1e": _2, "通販": _2, "xn--hxt814e": _2, "网店": _2, "xn--i1b6b1a6a2e": _2, "संगठन": _2, "xn--imr513n": _2, "餐厅": _2, "xn--io0a7i": _2, "网络": _2, "xn--j1aef": _2, "ком": _2, "xn--jlq480n2rg": _2, "亚马逊": _2, "xn--jvr189m": _2, "食品": _2, "xn--kcrx77d1x4a": _2, "飞利浦": _2, "xn--kput3i": _2, "手机": _2, "xn--mgba3a3ejt": _2, "ارامكو": _2, "xn--mgba7c0bbn0a": _2, "العليان": _2, "xn--mgbaakc7dvf": _2, "اتصالات": _2, "xn--mgbab2bd": _2, "بازار": _2, "xn--mgbca7dzdo": _2, "ابوظبي": _2, "xn--mgbi4ecexp": _2, "كاثوليك": _2, "xn--mgbt3dhd": _2, "همراه": _2, "xn--mk1bu44c": _2, "닷컴": _2, "xn--mxtq1m": _2, "政府": _2, "xn--ngbc5azd": _2, "شبكة": _2, "xn--ngbe9e0a": _2, "بيتك": _2, "xn--ngbrx": _2, "عرب": _2, "xn--nqv7f": _2, "机构": _2, "xn--nqv7fs00ema": _2, "组织机构": _2, "xn--nyqy26a": _2, "健康": _2, "xn--otu796d": _2, "招聘": _2, "xn--p1acf": { "$": 1, "succ": { "xn--90amc": _3, "xn--j1aef": _3, "xn--j1ael8b": _3, "xn--h1ahn": _3, "xn--j1adp": _3, "xn--c1avg": _3, "xn--80aaa0cvac": _3, "xn--h1aliz": _3, "xn--90a1af": _3, "xn--41a": _3 } }, "рус": { "$": 1, "succ": { "биз": _3, "ком": _3, "крым": _3, "мир": _3, "мск": _3, "орг": _3, "самара": _3, "сочи": _3, "спб": _3, "я": _3 } }, "xn--pssy2u": _2, "大拿": _2, "xn--q9jyb4c": _2, "みんな": _2, "xn--qcka1pmc": _2, "グーグル": _2, "xn--rhqv96g": _2, "世界": _2, "xn--rovu88b": _2, "書籍": _2, "xn--ses554g": _2, "网址": _2, "xn--t60b56a": _2, "닷넷": _2, "xn--tckwe": _2, "コム": _2, "xn--tiq49xqyj": _2, "天主教": _2, "xn--unup4y": _2, "游戏": _2, "xn--vermgensberater-ctb": _2, "vermögensberater": _2, "xn--vermgensberatung-pwb": _2, "vermögensberatung": _2, "xn--vhquv": _2, "企业": _2, "xn--vuq861b": _2, "信息": _2, "xn--w4r85el8fhu5dnra": _2, "嘉里大酒店": _2, "xn--w4rs40l": _2, "嘉里": _2, "xn--xhq521b": _2, "广东": _2, "xn--zfr164b": _2, "政务": _2, "xyz": { "$": 1, "succ": { "blogsite": _3, "localzone": _3, "crafting": _3, "zapto": _3, "telebit": _5 } }, "yachts": _2, "yahoo": _2, "yamaxun": _2, "yandex": _2, "yodobashi": _2, "yoga": _2, "yokohama": _2, "you": _2, "youtube": _2, "yun": _2, "zappos": _2, "zara": _2, "zero": _2, "zip": _2, "zone": { "$": 1, "succ": { "cloud66": _3, "hs": _3, "triton": _5, "lima": _3 } }, "zuerich": _2 } };
    ;
    return rules;
})();

;// ./node_modules/.pnpm/tldts@5.7.112/node_modules/tldts/dist/es6/src/suffix-trie.js


/**
 * Lookup parts of domain in Trie
 */
function lookupInTrie(parts, trie, index, allowedMask) {
    let result = null;
    let node = trie;
    while (node !== undefined) {
        // We have a match!
        if ((node.$ & allowedMask) !== 0) {
            result = {
                index: index + 1,
                isIcann: node.$ === 1 /* RULE_TYPE.ICANN */,
                isPrivate: node.$ === 2 /* RULE_TYPE.PRIVATE */,
            };
        }
        // No more `parts` to look for
        if (index === -1) {
            break;
        }
        const succ = node.succ;
        node = succ && (succ[parts[index]] || succ['*']);
        index -= 1;
    }
    return result;
}
/**
 * Check if `hostname` has a valid public suffix in `trie`.
 */
function suffix_trie_suffixLookup(hostname, options, out) {
    if (fast_path(hostname, options, out) === true) {
        return;
    }
    const hostnameParts = hostname.split('.');
    const allowedMask = (options.allowPrivateDomains === true ? 2 /* RULE_TYPE.PRIVATE */ : 0) |
        (options.allowIcannDomains === true ? 1 /* RULE_TYPE.ICANN */ : 0);
    // Look for exceptions
    const exceptionMatch = lookupInTrie(hostnameParts, exceptions, hostnameParts.length - 1, allowedMask);
    if (exceptionMatch !== null) {
        out.isIcann = exceptionMatch.isIcann;
        out.isPrivate = exceptionMatch.isPrivate;
        out.publicSuffix = hostnameParts.slice(exceptionMatch.index + 1).join('.');
        return;
    }
    // Look for a match in rules
    const rulesMatch = lookupInTrie(hostnameParts, rules, hostnameParts.length - 1, allowedMask);
    if (rulesMatch !== null) {
        out.isIcann = rulesMatch.isIcann;
        out.isPrivate = rulesMatch.isPrivate;
        out.publicSuffix = hostnameParts.slice(rulesMatch.index).join('.');
        return;
    }
    // No match found...
    // Prevailing rule is '*' so we consider the top-level domain to be the
    // public suffix of `hostname` (e.g.: 'example.org' => 'org').
    out.isIcann = false;
    out.isPrivate = false;
    out.publicSuffix = hostnameParts[hostnameParts.length - 1];
}

;// ./node_modules/.pnpm/tldts@5.7.112/node_modules/tldts/dist/es6/index.js


// For all methods but 'parse', it does not make sense to allocate an object
// every single time to only return the value of a specific attribute. To avoid
// this un-necessary allocation, we use a global object which is re-used.
const RESULT = getEmptyResult();
function parse(url, options = {}) {
    return factory_parseImpl(url, 5 /* FLAG.ALL */, suffix_trie_suffixLookup, options, getEmptyResult());
}
function getHostname(url, options = {}) {
    /*@__INLINE__*/ factory_resetResult(RESULT);
    return factory_parseImpl(url, 0 /* FLAG.HOSTNAME */, suffix_trie_suffixLookup, options, RESULT).hostname;
}
function getPublicSuffix(url, options = {}) {
    /*@__INLINE__*/ factory_resetResult(RESULT);
    return factory_parseImpl(url, 2 /* FLAG.PUBLIC_SUFFIX */, suffix_trie_suffixLookup, options, RESULT)
        .publicSuffix;
}
function es6_getDomain(url, options = {}) {
    /*@__INLINE__*/ factory_resetResult(RESULT);
    return factory_parseImpl(url, 3 /* FLAG.DOMAIN */, suffix_trie_suffixLookup, options, RESULT).domain;
}
function es6_getSubdomain(url, options = {}) {
    /*@__INLINE__*/ resetResult(RESULT);
    return parseImpl(url, 4 /* FLAG.SUB_DOMAIN */, suffixLookup, options, RESULT)
        .subdomain;
}
function es6_getDomainWithoutSuffix(url, options = {}) {
    /*@__INLINE__*/ resetResult(RESULT);
    return parseImpl(url, 5 /* FLAG.ALL */, suffixLookup, options, RESULT)
        .domainWithoutSuffix;
}


/***/ }),

/***/ 92976:
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_RESULT__;/////////////////////////////////////////////////////////////////////////////////
/* UAParser.js v1.0.36
   Copyright © 2012-2021 Faisal Salman <f@faisalman.com>
   MIT License *//*
   Detect Browser, Engine, OS, CPU, and Device type/model from User-Agent data.
   Supports browser & node.js environment. 
   Demo   : https://faisalman.github.io/ua-parser-js
   Source : https://github.com/faisalman/ua-parser-js */
/////////////////////////////////////////////////////////////////////////////////

(function (window, undefined) {

    'use strict';

    //////////////
    // Constants
    /////////////


    var LIBVERSION  = '1.0.36',
        EMPTY       = '',
        UNKNOWN     = '?',
        FUNC_TYPE   = 'function',
        UNDEF_TYPE  = 'undefined',
        OBJ_TYPE    = 'object',
        STR_TYPE    = 'string',
        MAJOR       = 'major',
        MODEL       = 'model',
        NAME        = 'name',
        TYPE        = 'type',
        VENDOR      = 'vendor',
        VERSION     = 'version',
        ARCHITECTURE= 'architecture',
        CONSOLE     = 'console',
        MOBILE      = 'mobile',
        TABLET      = 'tablet',
        SMARTTV     = 'smarttv',
        WEARABLE    = 'wearable',
        EMBEDDED    = 'embedded',
        UA_MAX_LENGTH = 350;

    var AMAZON  = 'Amazon',
        APPLE   = 'Apple',
        ASUS    = 'ASUS',
        BLACKBERRY = 'BlackBerry',
        BROWSER = 'Browser',
        CHROME  = 'Chrome',
        EDGE    = 'Edge',
        FIREFOX = 'Firefox',
        GOOGLE  = 'Google',
        HUAWEI  = 'Huawei',
        LG      = 'LG',
        MICROSOFT = 'Microsoft',
        MOTOROLA  = 'Motorola',
        OPERA   = 'Opera',
        SAMSUNG = 'Samsung',
        SHARP   = 'Sharp',
        SONY    = 'Sony',
        VIERA   = 'Viera',
        XIAOMI  = 'Xiaomi',
        ZEBRA   = 'Zebra',
        FACEBOOK    = 'Facebook',
        CHROMIUM_OS = 'Chromium OS',
        MAC_OS  = 'Mac OS';

    ///////////
    // Helper
    //////////

    var extend = function (regexes, extensions) {
            var mergedRegexes = {};
            for (var i in regexes) {
                if (extensions[i] && extensions[i].length % 2 === 0) {
                    mergedRegexes[i] = extensions[i].concat(regexes[i]);
                } else {
                    mergedRegexes[i] = regexes[i];
                }
            }
            return mergedRegexes;
        },
        enumerize = function (arr) {
            var enums = {};
            for (var i=0; i<arr.length; i++) {
                enums[arr[i].toUpperCase()] = arr[i];
            }
            return enums;
        },
        has = function (str1, str2) {
            return typeof str1 === STR_TYPE ? lowerize(str2).indexOf(lowerize(str1)) !== -1 : false;
        },
        lowerize = function (str) {
            return str.toLowerCase();
        },
        majorize = function (version) {
            return typeof(version) === STR_TYPE ? version.replace(/[^\d\.]/g, EMPTY).split('.')[0] : undefined;
        },
        trim = function (str, len) {
            if (typeof(str) === STR_TYPE) {
                str = str.replace(/^\s\s*/, EMPTY);
                return typeof(len) === UNDEF_TYPE ? str : str.substring(0, UA_MAX_LENGTH);
            }
    };

    ///////////////
    // Map helper
    //////////////

    var rgxMapper = function (ua, arrays) {

            var i = 0, j, k, p, q, matches, match;

            // loop through all regexes maps
            while (i < arrays.length && !matches) {

                var regex = arrays[i],       // even sequence (0,2,4,..)
                    props = arrays[i + 1];   // odd sequence (1,3,5,..)
                j = k = 0;

                // try matching uastring with regexes
                while (j < regex.length && !matches) {

                    if (!regex[j]) { break; }
                    matches = regex[j++].exec(ua);

                    if (!!matches) {
                        for (p = 0; p < props.length; p++) {
                            match = matches[++k];
                            q = props[p];
                            // check if given property is actually array
                            if (typeof q === OBJ_TYPE && q.length > 0) {
                                if (q.length === 2) {
                                    if (typeof q[1] == FUNC_TYPE) {
                                        // assign modified match
                                        this[q[0]] = q[1].call(this, match);
                                    } else {
                                        // assign given value, ignore regex match
                                        this[q[0]] = q[1];
                                    }
                                } else if (q.length === 3) {
                                    // check whether function or regex
                                    if (typeof q[1] === FUNC_TYPE && !(q[1].exec && q[1].test)) {
                                        // call function (usually string mapper)
                                        this[q[0]] = match ? q[1].call(this, match, q[2]) : undefined;
                                    } else {
                                        // sanitize match using given regex
                                        this[q[0]] = match ? match.replace(q[1], q[2]) : undefined;
                                    }
                                } else if (q.length === 4) {
                                        this[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined;
                                }
                            } else {
                                this[q] = match ? match : undefined;
                            }
                        }
                    }
                }
                i += 2;
            }
        },

        strMapper = function (str, map) {

            for (var i in map) {
                // check if current value is array
                if (typeof map[i] === OBJ_TYPE && map[i].length > 0) {
                    for (var j = 0; j < map[i].length; j++) {
                        if (has(map[i][j], str)) {
                            return (i === UNKNOWN) ? undefined : i;
                        }
                    }
                } else if (has(map[i], str)) {
                    return (i === UNKNOWN) ? undefined : i;
                }
            }
            return str;
    };

    ///////////////
    // String map
    //////////////

    // Safari < 3.0
    var oldSafariMap = {
            '1.0'   : '/8',
            '1.2'   : '/1',
            '1.3'   : '/3',
            '2.0'   : '/412',
            '2.0.2' : '/416',
            '2.0.3' : '/417',
            '2.0.4' : '/419',
            '?'     : '/'
        },
        windowsVersionMap = {
            'ME'        : '4.90',
            'NT 3.11'   : 'NT3.51',
            'NT 4.0'    : 'NT4.0',
            '2000'      : 'NT 5.0',
            'XP'        : ['NT 5.1', 'NT 5.2'],
            'Vista'     : 'NT 6.0',
            '7'         : 'NT 6.1',
            '8'         : 'NT 6.2',
            '8.1'       : 'NT 6.3',
            '10'        : ['NT 6.4', 'NT 10.0'],
            'RT'        : 'ARM'
    };

    //////////////
    // Regex map
    /////////////

    var regexes = {

        browser : [[

            /\b(?:crmo|crios)\/([\w\.]+)/i                                      // Chrome for Android/iOS
            ], [VERSION, [NAME, 'Chrome']], [
            /edg(?:e|ios|a)?\/([\w\.]+)/i                                       // Microsoft Edge
            ], [VERSION, [NAME, 'Edge']], [

            // Presto based
            /(opera mini)\/([-\w\.]+)/i,                                        // Opera Mini
            /(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,                 // Opera Mobi/Tablet
            /(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i                           // Opera
            ], [NAME, VERSION], [
            /opios[\/ ]+([\w\.]+)/i                                             // Opera mini on iphone >= 8.0
            ], [VERSION, [NAME, OPERA+' Mini']], [
            /\bopr\/([\w\.]+)/i                                                 // Opera Webkit
            ], [VERSION, [NAME, OPERA]], [

            // Mixed
            /(kindle)\/([\w\.]+)/i,                                             // Kindle
            /(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,      // Lunascape/Maxthon/Netfront/Jasmine/Blazer
            // Trident based
            /(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,               // Avant/IEMobile/SlimBrowser
            /(ba?idubrowser)[\/ ]?([\w\.]+)/i,                                  // Baidu Browser
            /(?:ms|\()(ie) ([\w\.]+)/i,                                         // Internet Explorer

            // Webkit/KHTML based                                               // Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron/Iridium/PhantomJS/Bowser/QupZilla/Falkon
            /(flock|rockmelt|midori|epiphany|silk|skyfire|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,
                                                                                // Rekonq/Puffin/Brave/Whale/QQBrowserLite/QQ, aka ShouQ
            /(heytap|ovi)browser\/([\d\.]+)/i,                                  // Heytap/Ovi
            /(weibo)__([\d\.]+)/i                                               // Weibo
            ], [NAME, VERSION], [
            /(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i                 // UCBrowser
            ], [VERSION, [NAME, 'UC'+BROWSER]], [
            /microm.+\bqbcore\/([\w\.]+)/i,                                     // WeChat Desktop for Windows Built-in Browser
            /\bqbcore\/([\w\.]+).+microm/i
            ], [VERSION, [NAME, 'WeChat(Win) Desktop']], [
            /micromessenger\/([\w\.]+)/i                                        // WeChat
            ], [VERSION, [NAME, 'WeChat']], [
            /konqueror\/([\w\.]+)/i                                             // Konqueror
            ], [VERSION, [NAME, 'Konqueror']], [
            /trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i                       // IE11
            ], [VERSION, [NAME, 'IE']], [
            /ya(?:search)?browser\/([\w\.]+)/i                                  // Yandex
            ], [VERSION, [NAME, 'Yandex']], [
            /(avast|avg)\/([\w\.]+)/i                                           // Avast/AVG Secure Browser
            ], [[NAME, /(.+)/, '$1 Secure '+BROWSER], VERSION], [
            /\bfocus\/([\w\.]+)/i                                               // Firefox Focus
            ], [VERSION, [NAME, FIREFOX+' Focus']], [
            /\bopt\/([\w\.]+)/i                                                 // Opera Touch
            ], [VERSION, [NAME, OPERA+' Touch']], [
            /coc_coc\w+\/([\w\.]+)/i                                            // Coc Coc Browser
            ], [VERSION, [NAME, 'Coc Coc']], [
            /dolfin\/([\w\.]+)/i                                                // Dolphin
            ], [VERSION, [NAME, 'Dolphin']], [
            /coast\/([\w\.]+)/i                                                 // Opera Coast
            ], [VERSION, [NAME, OPERA+' Coast']], [
            /miuibrowser\/([\w\.]+)/i                                           // MIUI Browser
            ], [VERSION, [NAME, 'MIUI '+BROWSER]], [
            /fxios\/([-\w\.]+)/i                                                // Firefox for iOS
            ], [VERSION, [NAME, FIREFOX]], [
            /\bqihu|(qi?ho?o?|360)browser/i                                     // 360
            ], [[NAME, '360 '+BROWSER]], [
            /(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i
            ], [[NAME, /(.+)/, '$1 '+BROWSER], VERSION], [                      // Oculus/Samsung/Sailfish/Huawei Browser
            /(comodo_dragon)\/([\w\.]+)/i                                       // Comodo Dragon
            ], [[NAME, /_/g, ' '], VERSION], [
            /(electron)\/([\w\.]+) safari/i,                                    // Electron-based App
            /(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,                   // Tesla
            /m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i            // QQBrowser/Baidu App/2345 Browser
            ], [NAME, VERSION], [
            /(metasr)[\/ ]?([\w\.]+)/i,                                         // SouGouBrowser
            /(lbbrowser)/i,                                                     // LieBao Browser
            /\[(linkedin)app\]/i                                                // LinkedIn App for iOS & Android
            ], [NAME], [

            // WebView
            /((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i       // Facebook App for iOS & Android
            ], [[NAME, FACEBOOK], VERSION], [
            /(kakao(?:talk|story))[\/ ]([\w\.]+)/i,                             // Kakao App
            /(naver)\(.*?(\d+\.[\w\.]+).*\)/i,                                  // Naver InApp
            /safari (line)\/([\w\.]+)/i,                                        // Line App for iOS
            /\b(line)\/([\w\.]+)\/iab/i,                                        // Line App for Android
            /(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i                     // Chromium/Instagram/Snapchat
            ], [NAME, VERSION], [
            /\bgsa\/([\w\.]+) .*safari\//i                                      // Google Search Appliance on iOS
            ], [VERSION, [NAME, 'GSA']], [
            /musical_ly(?:.+app_?version\/|_)([\w\.]+)/i                        // TikTok
            ], [VERSION, [NAME, 'TikTok']], [

            /headlesschrome(?:\/([\w\.]+)| )/i                                  // Chrome Headless
            ], [VERSION, [NAME, CHROME+' Headless']], [

            / wv\).+(chrome)\/([\w\.]+)/i                                       // Chrome WebView
            ], [[NAME, CHROME+' WebView'], VERSION], [

            /droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i           // Android Browser
            ], [VERSION, [NAME, 'Android '+BROWSER]], [

            /(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i       // Chrome/OmniWeb/Arora/Tizen/Nokia
            ], [NAME, VERSION], [

            /version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i                      // Mobile Safari
            ], [VERSION, [NAME, 'Mobile Safari']], [
            /version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i                // Safari & Safari Mobile
            ], [VERSION, NAME], [
            /webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i                      // Safari < 3.0
            ], [NAME, [VERSION, strMapper, oldSafariMap]], [

            /(webkit|khtml)\/([\w\.]+)/i
            ], [NAME, VERSION], [

            // Gecko based
            /(navigator|netscape\d?)\/([-\w\.]+)/i                              // Netscape
            ], [[NAME, 'Netscape'], VERSION], [
            /mobile vr; rv:([\w\.]+)\).+firefox/i                               // Firefox Reality
            ], [VERSION, [NAME, FIREFOX+' Reality']], [
            /ekiohf.+(flow)\/([\w\.]+)/i,                                       // Flow
            /(swiftfox)/i,                                                      // Swiftfox
            /(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,
                                                                                // IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror/Klar
            /(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,
                                                                                // Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix
            /(firefox)\/([\w\.]+)/i,                                            // Other Firefox-based
            /(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,                         // Mozilla

            // Other
            /(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,
                                                                                // Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/Sleipnir/Obigo/Mosaic/Go/ICE/UP.Browser
            /(links) \(([\w\.]+)/i,                                             // Links
            /panasonic;(viera)/i                                                // Panasonic Viera
            ], [NAME, VERSION], [
            
            /(cobalt)\/([\w\.]+)/i                                              // Cobalt
            ], [NAME, [VERSION, /master.|lts./, ""]]
        ],

        cpu : [[

            /(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i                     // AMD64 (x64)
            ], [[ARCHITECTURE, 'amd64']], [

            /(ia32(?=;))/i                                                      // IA32 (quicktime)
            ], [[ARCHITECTURE, lowerize]], [

            /((?:i[346]|x)86)[;\)]/i                                            // IA32 (x86)
            ], [[ARCHITECTURE, 'ia32']], [

            /\b(aarch64|arm(v?8e?l?|_?64))\b/i                                 // ARM64
            ], [[ARCHITECTURE, 'arm64']], [

            /\b(arm(?:v[67])?ht?n?[fl]p?)\b/i                                   // ARMHF
            ], [[ARCHITECTURE, 'armhf']], [

            // PocketPC mistakenly identified as PowerPC
            /windows (ce|mobile); ppc;/i
            ], [[ARCHITECTURE, 'arm']], [

            /((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i                            // PowerPC
            ], [[ARCHITECTURE, /ower/, EMPTY, lowerize]], [

            /(sun4\w)[;\)]/i                                                    // SPARC
            ], [[ARCHITECTURE, 'sparc']], [

            /((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i
                                                                                // IA64, 68K, ARM/64, AVR/32, IRIX/64, MIPS/64, SPARC/64, PA-RISC
            ], [[ARCHITECTURE, lowerize]]
        ],

        device : [[

            //////////////////////////
            // MOBILES & TABLETS
            /////////////////////////

            // Samsung
            /\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i
            ], [MODEL, [VENDOR, SAMSUNG], [TYPE, TABLET]], [
            /\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,
            /samsung[- ]([-\w]+)/i,
            /sec-(sgh\w+)/i
            ], [MODEL, [VENDOR, SAMSUNG], [TYPE, MOBILE]], [

            // Apple
            /(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i                          // iPod/iPhone
            ], [MODEL, [VENDOR, APPLE], [TYPE, MOBILE]], [
            /\((ipad);[-\w\),; ]+apple/i,                                       // iPad
            /applecoremedia\/[\w\.]+ \((ipad)/i,
            /\b(ipad)\d\d?,\d\d?[;\]].+ios/i
            ], [MODEL, [VENDOR, APPLE], [TYPE, TABLET]], [
            /(macintosh);/i
            ], [MODEL, [VENDOR, APPLE]], [

            // Sharp
            /\b(sh-?[altvz]?\d\d[a-ekm]?)/i
            ], [MODEL, [VENDOR, SHARP], [TYPE, MOBILE]], [

            // Huawei
            /\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i
            ], [MODEL, [VENDOR, HUAWEI], [TYPE, TABLET]], [
            /(?:huawei|honor)([-\w ]+)[;\)]/i,
            /\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i
            ], [MODEL, [VENDOR, HUAWEI], [TYPE, MOBILE]], [

            // Xiaomi
            /\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,                  // Xiaomi POCO
            /\b; (\w+) build\/hm\1/i,                                           // Xiaomi Hongmi 'numeric' models
            /\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,                             // Xiaomi Hongmi
            /\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,                   // Xiaomi Redmi
            /\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i // Xiaomi Mi
            ], [[MODEL, /_/g, ' '], [VENDOR, XIAOMI], [TYPE, MOBILE]], [
            /\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i                        // Mi Pad tablets
            ],[[MODEL, /_/g, ' '], [VENDOR, XIAOMI], [TYPE, TABLET]], [

            // OPPO
            /; (\w+) bui.+ oppo/i,
            /\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i
            ], [MODEL, [VENDOR, 'OPPO'], [TYPE, MOBILE]], [

            // Vivo
            /vivo (\w+)(?: bui|\))/i,
            /\b(v[12]\d{3}\w?[at])(?: bui|;)/i
            ], [MODEL, [VENDOR, 'Vivo'], [TYPE, MOBILE]], [

            // Realme
            /\b(rmx[12]\d{3})(?: bui|;|\))/i
            ], [MODEL, [VENDOR, 'Realme'], [TYPE, MOBILE]], [

            // Motorola
            /\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,
            /\bmot(?:orola)?[- ](\w*)/i,
            /((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i
            ], [MODEL, [VENDOR, MOTOROLA], [TYPE, MOBILE]], [
            /\b(mz60\d|xoom[2 ]{0,2}) build\//i
            ], [MODEL, [VENDOR, MOTOROLA], [TYPE, TABLET]], [

            // LG
            /((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i
            ], [MODEL, [VENDOR, LG], [TYPE, TABLET]], [
            /(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,
            /\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,
            /\blg-?([\d\w]+) bui/i
            ], [MODEL, [VENDOR, LG], [TYPE, MOBILE]], [

            // Lenovo
            /(ideatab[-\w ]+)/i,
            /lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i
            ], [MODEL, [VENDOR, 'Lenovo'], [TYPE, TABLET]], [

            // Nokia
            /(?:maemo|nokia).*(n900|lumia \d+)/i,
            /nokia[-_ ]?([-\w\.]*)/i
            ], [[MODEL, /_/g, ' '], [VENDOR, 'Nokia'], [TYPE, MOBILE]], [

            // Google
            /(pixel c)\b/i                                                      // Google Pixel C
            ], [MODEL, [VENDOR, GOOGLE], [TYPE, TABLET]], [
            /droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i                         // Google Pixel
            ], [MODEL, [VENDOR, GOOGLE], [TYPE, MOBILE]], [

            // Sony
            /droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i
            ], [MODEL, [VENDOR, SONY], [TYPE, MOBILE]], [
            /sony tablet [ps]/i,
            /\b(?:sony)?sgp\w+(?: bui|\))/i
            ], [[MODEL, 'Xperia Tablet'], [VENDOR, SONY], [TYPE, TABLET]], [

            // OnePlus
            / (kb2005|in20[12]5|be20[12][59])\b/i,
            /(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i
            ], [MODEL, [VENDOR, 'OnePlus'], [TYPE, MOBILE]], [

            // Amazon
            /(alexa)webm/i,
            /(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i,                             // Kindle Fire without Silk / Echo Show
            /(kf[a-z]+)( bui|\)).+silk\//i                                      // Kindle Fire HD
            ], [MODEL, [VENDOR, AMAZON], [TYPE, TABLET]], [
            /((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i                     // Fire Phone
            ], [[MODEL, /(.+)/g, 'Fire Phone $1'], [VENDOR, AMAZON], [TYPE, MOBILE]], [

            // BlackBerry
            /(playbook);[-\w\),; ]+(rim)/i                                      // BlackBerry PlayBook
            ], [MODEL, VENDOR, [TYPE, TABLET]], [
            /\b((?:bb[a-f]|st[hv])100-\d)/i,
            /\(bb10; (\w+)/i                                                    // BlackBerry 10
            ], [MODEL, [VENDOR, BLACKBERRY], [TYPE, MOBILE]], [

            // Asus
            /(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i
            ], [MODEL, [VENDOR, ASUS], [TYPE, TABLET]], [
            / (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i
            ], [MODEL, [VENDOR, ASUS], [TYPE, MOBILE]], [

            // HTC
            /(nexus 9)/i                                                        // HTC Nexus 9
            ], [MODEL, [VENDOR, 'HTC'], [TYPE, TABLET]], [
            /(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,                         // HTC

            // ZTE
            /(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,
            /(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i         // Alcatel/GeeksPhone/Nexian/Panasonic/Sony
            ], [VENDOR, [MODEL, /_/g, ' '], [TYPE, MOBILE]], [

            // Acer
            /droid.+; ([ab][1-7]-?[0178a]\d\d?)/i
            ], [MODEL, [VENDOR, 'Acer'], [TYPE, TABLET]], [

            // Meizu
            /droid.+; (m[1-5] note) bui/i,
            /\bmz-([-\w]{2,})/i
            ], [MODEL, [VENDOR, 'Meizu'], [TYPE, MOBILE]], [

            // MIXED
            /(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno)[-_ ]?([-\w]*)/i,
                                                                                // BlackBerry/BenQ/Palm/Sony-Ericsson/Acer/Asus/Dell/Meizu/Motorola/Polytron
            /(hp) ([\w ]+\w)/i,                                                 // HP iPAQ
            /(asus)-?(\w+)/i,                                                   // Asus
            /(microsoft); (lumia[\w ]+)/i,                                      // Microsoft Lumia
            /(lenovo)[-_ ]?([-\w]+)/i,                                          // Lenovo
            /(jolla)/i,                                                         // Jolla
            /(oppo) ?([\w ]+) bui/i                                             // OPPO
            ], [VENDOR, MODEL, [TYPE, MOBILE]], [

            /(kobo)\s(ereader|touch)/i,                                         // Kobo
            /(archos) (gamepad2?)/i,                                            // Archos
            /(hp).+(touchpad(?!.+tablet)|tablet)/i,                             // HP TouchPad
            /(kindle)\/([\w\.]+)/i,                                             // Kindle
            /(nook)[\w ]+build\/(\w+)/i,                                        // Nook
            /(dell) (strea[kpr\d ]*[\dko])/i,                                   // Dell Streak
            /(le[- ]+pan)[- ]+(\w{1,9}) bui/i,                                  // Le Pan Tablets
            /(trinity)[- ]*(t\d{3}) bui/i,                                      // Trinity Tablets
            /(gigaset)[- ]+(q\w{1,9}) bui/i,                                    // Gigaset Tablets
            /(vodafone) ([\w ]+)(?:\)| bui)/i                                   // Vodafone
            ], [VENDOR, MODEL, [TYPE, TABLET]], [

            /(surface duo)/i                                                    // Surface Duo
            ], [MODEL, [VENDOR, MICROSOFT], [TYPE, TABLET]], [
            /droid [\d\.]+; (fp\du?)(?: b|\))/i                                 // Fairphone
            ], [MODEL, [VENDOR, 'Fairphone'], [TYPE, MOBILE]], [
            /(u304aa)/i                                                         // AT&T
            ], [MODEL, [VENDOR, 'AT&T'], [TYPE, MOBILE]], [
            /\bsie-(\w*)/i                                                      // Siemens
            ], [MODEL, [VENDOR, 'Siemens'], [TYPE, MOBILE]], [
            /\b(rct\w+) b/i                                                     // RCA Tablets
            ], [MODEL, [VENDOR, 'RCA'], [TYPE, TABLET]], [
            /\b(venue[\d ]{2,7}) b/i                                            // Dell Venue Tablets
            ], [MODEL, [VENDOR, 'Dell'], [TYPE, TABLET]], [
            /\b(q(?:mv|ta)\w+) b/i                                              // Verizon Tablet
            ], [MODEL, [VENDOR, 'Verizon'], [TYPE, TABLET]], [
            /\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i                       // Barnes & Noble Tablet
            ], [MODEL, [VENDOR, 'Barnes & Noble'], [TYPE, TABLET]], [
            /\b(tm\d{3}\w+) b/i
            ], [MODEL, [VENDOR, 'NuVision'], [TYPE, TABLET]], [
            /\b(k88) b/i                                                        // ZTE K Series Tablet
            ], [MODEL, [VENDOR, 'ZTE'], [TYPE, TABLET]], [
            /\b(nx\d{3}j) b/i                                                   // ZTE Nubia
            ], [MODEL, [VENDOR, 'ZTE'], [TYPE, MOBILE]], [
            /\b(gen\d{3}) b.+49h/i                                              // Swiss GEN Mobile
            ], [MODEL, [VENDOR, 'Swiss'], [TYPE, MOBILE]], [
            /\b(zur\d{3}) b/i                                                   // Swiss ZUR Tablet
            ], [MODEL, [VENDOR, 'Swiss'], [TYPE, TABLET]], [
            /\b((zeki)?tb.*\b) b/i                                              // Zeki Tablets
            ], [MODEL, [VENDOR, 'Zeki'], [TYPE, TABLET]], [
            /\b([yr]\d{2}) b/i,
            /\b(dragon[- ]+touch |dt)(\w{5}) b/i                                // Dragon Touch Tablet
            ], [[VENDOR, 'Dragon Touch'], MODEL, [TYPE, TABLET]], [
            /\b(ns-?\w{0,9}) b/i                                                // Insignia Tablets
            ], [MODEL, [VENDOR, 'Insignia'], [TYPE, TABLET]], [
            /\b((nxa|next)-?\w{0,9}) b/i                                        // NextBook Tablets
            ], [MODEL, [VENDOR, 'NextBook'], [TYPE, TABLET]], [
            /\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i                  // Voice Xtreme Phones
            ], [[VENDOR, 'Voice'], MODEL, [TYPE, MOBILE]], [
            /\b(lvtel\-)?(v1[12]) b/i                                           // LvTel Phones
            ], [[VENDOR, 'LvTel'], MODEL, [TYPE, MOBILE]], [
            /\b(ph-1) /i                                                        // Essential PH-1
            ], [MODEL, [VENDOR, 'Essential'], [TYPE, MOBILE]], [
            /\b(v(100md|700na|7011|917g).*\b) b/i                               // Envizen Tablets
            ], [MODEL, [VENDOR, 'Envizen'], [TYPE, TABLET]], [
            /\b(trio[-\w\. ]+) b/i                                              // MachSpeed Tablets
            ], [MODEL, [VENDOR, 'MachSpeed'], [TYPE, TABLET]], [
            /\btu_(1491) b/i                                                    // Rotor Tablets
            ], [MODEL, [VENDOR, 'Rotor'], [TYPE, TABLET]], [
            /(shield[\w ]+) b/i                                                 // Nvidia Shield Tablets
            ], [MODEL, [VENDOR, 'Nvidia'], [TYPE, TABLET]], [
            /(sprint) (\w+)/i                                                   // Sprint Phones
            ], [VENDOR, MODEL, [TYPE, MOBILE]], [
            /(kin\.[onetw]{3})/i                                                // Microsoft Kin
            ], [[MODEL, /\./g, ' '], [VENDOR, MICROSOFT], [TYPE, MOBILE]], [
            /droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i             // Zebra
            ], [MODEL, [VENDOR, ZEBRA], [TYPE, TABLET]], [
            /droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i
            ], [MODEL, [VENDOR, ZEBRA], [TYPE, MOBILE]], [

            ///////////////////
            // SMARTTVS
            ///////////////////

            /smart-tv.+(samsung)/i                                              // Samsung
            ], [VENDOR, [TYPE, SMARTTV]], [
            /hbbtv.+maple;(\d+)/i
            ], [[MODEL, /^/, 'SmartTV'], [VENDOR, SAMSUNG], [TYPE, SMARTTV]], [
            /(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i        // LG SmartTV
            ], [[VENDOR, LG], [TYPE, SMARTTV]], [
            /(apple) ?tv/i                                                      // Apple TV
            ], [VENDOR, [MODEL, APPLE+' TV'], [TYPE, SMARTTV]], [
            /crkey/i                                                            // Google Chromecast
            ], [[MODEL, CHROME+'cast'], [VENDOR, GOOGLE], [TYPE, SMARTTV]], [
            /droid.+aft(\w+)( bui|\))/i                                         // Fire TV
            ], [MODEL, [VENDOR, AMAZON], [TYPE, SMARTTV]], [
            /\(dtv[\);].+(aquos)/i,
            /(aquos-tv[\w ]+)\)/i                                               // Sharp
            ], [MODEL, [VENDOR, SHARP], [TYPE, SMARTTV]],[
            /(bravia[\w ]+)( bui|\))/i                                              // Sony
            ], [MODEL, [VENDOR, SONY], [TYPE, SMARTTV]], [
            /(mitv-\w{5}) bui/i                                                 // Xiaomi
            ], [MODEL, [VENDOR, XIAOMI], [TYPE, SMARTTV]], [
            /Hbbtv.*(technisat) (.*);/i                                         // TechniSAT
            ], [VENDOR, MODEL, [TYPE, SMARTTV]], [
            /\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,                          // Roku
            /hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i         // HbbTV devices
            ], [[VENDOR, trim], [MODEL, trim], [TYPE, SMARTTV]], [
            /\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i                   // SmartTV from Unidentified Vendors
            ], [[TYPE, SMARTTV]], [

            ///////////////////
            // CONSOLES
            ///////////////////

            /(ouya)/i,                                                          // Ouya
            /(nintendo) ([wids3utch]+)/i                                        // Nintendo
            ], [VENDOR, MODEL, [TYPE, CONSOLE]], [
            /droid.+; (shield) bui/i                                            // Nvidia
            ], [MODEL, [VENDOR, 'Nvidia'], [TYPE, CONSOLE]], [
            /(playstation [345portablevi]+)/i                                   // Playstation
            ], [MODEL, [VENDOR, SONY], [TYPE, CONSOLE]], [
            /\b(xbox(?: one)?(?!; xbox))[\); ]/i                                // Microsoft Xbox
            ], [MODEL, [VENDOR, MICROSOFT], [TYPE, CONSOLE]], [

            ///////////////////
            // WEARABLES
            ///////////////////

            /((pebble))app/i                                                    // Pebble
            ], [VENDOR, MODEL, [TYPE, WEARABLE]], [
            /(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i                              // Apple Watch
            ], [MODEL, [VENDOR, APPLE], [TYPE, WEARABLE]], [
            /droid.+; (glass) \d/i                                              // Google Glass
            ], [MODEL, [VENDOR, GOOGLE], [TYPE, WEARABLE]], [
            /droid.+; (wt63?0{2,3})\)/i
            ], [MODEL, [VENDOR, ZEBRA], [TYPE, WEARABLE]], [
            /(quest( 2| pro)?)/i                                                // Oculus Quest
            ], [MODEL, [VENDOR, FACEBOOK], [TYPE, WEARABLE]], [

            ///////////////////
            // EMBEDDED
            ///////////////////

            /(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i                              // Tesla
            ], [VENDOR, [TYPE, EMBEDDED]], [
            /(aeobc)\b/i                                                        // Echo Dot
            ], [MODEL, [VENDOR, AMAZON], [TYPE, EMBEDDED]], [

            ////////////////////
            // MIXED (GENERIC)
            ///////////////////

            /droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i           // Android Phones from Unidentified Vendors
            ], [MODEL, [TYPE, MOBILE]], [
            /droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i       // Android Tablets from Unidentified Vendors
            ], [MODEL, [TYPE, TABLET]], [
            /\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i                      // Unidentifiable Tablet
            ], [[TYPE, TABLET]], [
            /(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i    // Unidentifiable Mobile
            ], [[TYPE, MOBILE]], [
            /(android[-\w\. ]{0,9});.+buil/i                                    // Generic Android Device
            ], [MODEL, [VENDOR, 'Generic']]
        ],

        engine : [[

            /windows.+ edge\/([\w\.]+)/i                                       // EdgeHTML
            ], [VERSION, [NAME, EDGE+'HTML']], [

            /webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i                         // Blink
            ], [VERSION, [NAME, 'Blink']], [

            /(presto)\/([\w\.]+)/i,                                             // Presto
            /(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i, // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m/Goanna
            /ekioh(flow)\/([\w\.]+)/i,                                          // Flow
            /(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,                           // KHTML/Tasman/Links
            /(icab)[\/ ]([23]\.[\d\.]+)/i,                                      // iCab
            /\b(libweb)/i
            ], [NAME, VERSION], [

            /rv\:([\w\.]{1,9})\b.+(gecko)/i                                     // Gecko
            ], [VERSION, NAME]
        ],

        os : [[

            // Windows
            /microsoft (windows) (vista|xp)/i                                   // Windows (iTunes)
            ], [NAME, VERSION], [
            /(windows) nt 6\.2; (arm)/i,                                        // Windows RT
            /(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,            // Windows Phone
            /(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i
            ], [NAME, [VERSION, strMapper, windowsVersionMap]], [
            /(win(?=3|9|n)|win 9x )([nt\d\.]+)/i
            ], [[NAME, 'Windows'], [VERSION, strMapper, windowsVersionMap]], [

            // iOS/macOS
            /ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,              // iOS
            /(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,
            /cfnetwork\/.+darwin/i
            ], [[VERSION, /_/g, '.'], [NAME, 'iOS']], [
            /(mac os x) ?([\w\. ]*)/i,
            /(macintosh|mac_powerpc\b)(?!.+haiku)/i                             // Mac OS
            ], [[NAME, MAC_OS], [VERSION, /_/g, '.']], [

            // Mobile OSes
            /droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i                    // Android-x86/HarmonyOS
            ], [VERSION, NAME], [                                               // Android/WebOS/QNX/Bada/RIM/Maemo/MeeGo/Sailfish OS
            /(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,
            /(blackberry)\w*\/([\w\.]*)/i,                                      // Blackberry
            /(tizen|kaios)[\/ ]([\w\.]+)/i,                                     // Tizen/KaiOS
            /\((series40);/i                                                    // Series 40
            ], [NAME, VERSION], [
            /\(bb(10);/i                                                        // BlackBerry 10
            ], [VERSION, [NAME, BLACKBERRY]], [
            /(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i         // Symbian
            ], [VERSION, [NAME, 'Symbian']], [
            /mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i // Firefox OS
            ], [VERSION, [NAME, FIREFOX+' OS']], [
            /web0s;.+rt(tv)/i,
            /\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i                              // WebOS
            ], [VERSION, [NAME, 'webOS']], [
            /watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i                              // watchOS
            ], [VERSION, [NAME, 'watchOS']], [

            // Google Chromecast
            /crkey\/([\d\.]+)/i                                                 // Google Chromecast
            ], [VERSION, [NAME, CHROME+'cast']], [
            /(cros) [\w]+(?:\)| ([\w\.]+)\b)/i                                  // Chromium OS
            ], [[NAME, CHROMIUM_OS], VERSION],[

            // Smart TVs
            /panasonic;(viera)/i,                                               // Panasonic Viera
            /(netrange)mmh/i,                                                   // Netrange
            /(nettv)\/(\d+\.[\w\.]+)/i,                                         // NetTV

            // Console
            /(nintendo|playstation) ([wids345portablevuch]+)/i,                 // Nintendo/Playstation
            /(xbox); +xbox ([^\);]+)/i,                                         // Microsoft Xbox (360, One, X, S, Series X, Series S)

            // Other
            /\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,                            // Joli/Palm
            /(mint)[\/\(\) ]?(\w*)/i,                                           // Mint
            /(mageia|vectorlinux)[; ]/i,                                        // Mageia/VectorLinux
            /([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,
                                                                                // Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware/Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk/Linpus/Raspbian/Plan9/Minix/RISCOS/Contiki/Deepin/Manjaro/elementary/Sabayon/Linspire
            /(hurd|linux) ?([\w\.]*)/i,                                         // Hurd/Linux
            /(gnu) ?([\w\.]*)/i,                                                // GNU
            /\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i, // FreeBSD/NetBSD/OpenBSD/PC-BSD/GhostBSD/DragonFly
            /(haiku) (\w+)/i                                                    // Haiku
            ], [NAME, VERSION], [
            /(sunos) ?([\w\.\d]*)/i                                             // Solaris
            ], [[NAME, 'Solaris'], VERSION], [
            /((?:open)?solaris)[-\/ ]?([\w\.]*)/i,                              // Solaris
            /(aix) ((\d)(?=\.|\)| )[\w\.])*/i,                                  // AIX
            /\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i, // BeOS/OS2/AmigaOS/MorphOS/OpenVMS/Fuchsia/HP-UX/SerenityOS
            /(unix) ?([\w\.]*)/i                                                // UNIX
            ], [NAME, VERSION]
        ]
    };

    /////////////////
    // Constructor
    ////////////////

    var UAParser = function (ua, extensions) {

        if (typeof ua === OBJ_TYPE) {
            extensions = ua;
            ua = undefined;
        }

        if (!(this instanceof UAParser)) {
            return new UAParser(ua, extensions).getResult();
        }

        var _navigator = (typeof window !== UNDEF_TYPE && window.navigator) ? window.navigator : undefined;
        var _ua = ua || ((_navigator && _navigator.userAgent) ? _navigator.userAgent : EMPTY);
        var _uach = (_navigator && _navigator.userAgentData) ? _navigator.userAgentData : undefined;
        var _rgxmap = extensions ? extend(regexes, extensions) : regexes;
        var _isSelfNav = _navigator && _navigator.userAgent == _ua;

        this.getBrowser = function () {
            var _browser = {};
            _browser[NAME] = undefined;
            _browser[VERSION] = undefined;
            rgxMapper.call(_browser, _ua, _rgxmap.browser);
            _browser[MAJOR] = majorize(_browser[VERSION]);
            // Brave-specific detection
            if (_isSelfNav && _navigator && _navigator.brave && typeof _navigator.brave.isBrave == FUNC_TYPE) {
                _browser[NAME] = 'Brave';
            }
            return _browser;
        };
        this.getCPU = function () {
            var _cpu = {};
            _cpu[ARCHITECTURE] = undefined;
            rgxMapper.call(_cpu, _ua, _rgxmap.cpu);
            return _cpu;
        };
        this.getDevice = function () {
            var _device = {};
            _device[VENDOR] = undefined;
            _device[MODEL] = undefined;
            _device[TYPE] = undefined;
            rgxMapper.call(_device, _ua, _rgxmap.device);
            if (_isSelfNav && !_device[TYPE] && _uach && _uach.mobile) {
                _device[TYPE] = MOBILE;
            }
            // iPadOS-specific detection: identified as Mac, but has some iOS-only properties
            if (_isSelfNav && _device[MODEL] == 'Macintosh' && _navigator && typeof _navigator.standalone !== UNDEF_TYPE && _navigator.maxTouchPoints && _navigator.maxTouchPoints > 2) {
                _device[MODEL] = 'iPad';
                _device[TYPE] = TABLET;
            }
            return _device;
        };
        this.getEngine = function () {
            var _engine = {};
            _engine[NAME] = undefined;
            _engine[VERSION] = undefined;
            rgxMapper.call(_engine, _ua, _rgxmap.engine);
            return _engine;
        };
        this.getOS = function () {
            var _os = {};
            _os[NAME] = undefined;
            _os[VERSION] = undefined;
            rgxMapper.call(_os, _ua, _rgxmap.os);
            if (_isSelfNav && !_os[NAME] && _uach && _uach.platform != 'Unknown') {
                _os[NAME] = _uach.platform  
                                    .replace(/chrome os/i, CHROMIUM_OS)
                                    .replace(/macos/i, MAC_OS);           // backward compatibility
            }
            return _os;
        };
        this.getResult = function () {
            return {
                ua      : this.getUA(),
                browser : this.getBrowser(),
                engine  : this.getEngine(),
                os      : this.getOS(),
                device  : this.getDevice(),
                cpu     : this.getCPU()
            };
        };
        this.getUA = function () {
            return _ua;
        };
        this.setUA = function (ua) {
            _ua = (typeof ua === STR_TYPE && ua.length > UA_MAX_LENGTH) ? trim(ua, UA_MAX_LENGTH) : ua;
            return this;
        };
        this.setUA(_ua);
        return this;
    };

    UAParser.VERSION = LIBVERSION;
    UAParser.BROWSER =  enumerize([NAME, VERSION, MAJOR]);
    UAParser.CPU = enumerize([ARCHITECTURE]);
    UAParser.DEVICE = enumerize([MODEL, VENDOR, TYPE, CONSOLE, MOBILE, SMARTTV, TABLET, WEARABLE, EMBEDDED]);
    UAParser.ENGINE = UAParser.OS = enumerize([NAME, VERSION]);

    ///////////
    // Export
    //////////

    // check js environment
    if (typeof(exports) !== UNDEF_TYPE) {
        // nodejs env
        if ("object" !== UNDEF_TYPE && module.exports) {
            exports = module.exports = UAParser;
        }
        exports.UAParser = UAParser;
    } else {
        // requirejs env (optional)
        if ("function" === FUNC_TYPE && __webpack_require__.amdO) {
            !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
                return UAParser;
            }).call(exports, __webpack_require__, exports, module),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
        } else if (typeof window !== UNDEF_TYPE) {
            // browser env
            window.UAParser = UAParser;
        }
    }

    // jQuery/Zepto specific (optional)
    // Note:
    //   In AMD env the global scope should be kept clean, but jQuery is an exception.
    //   jQuery always exports to global scope, unless jQuery.noConflict(true) is used,
    //   and we should catch that.
    var $ = typeof window !== UNDEF_TYPE && (window.jQuery || window.Zepto);
    if ($ && !$.ua) {
        var parser = new UAParser();
        $.ua = parser.getResult();
        $.ua.get = function () {
            return parser.getUA();
        };
        $.ua.set = function (ua) {
            parser.setUA(ua);
            var result = parser.getResult();
            for (var prop in result) {
                $.ua[prop] = result[prop];
            }
        };
    }

})(typeof window === 'object' ? window : this);


/***/ }),

/***/ 88680:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {


/**
 * Module exports.
 */

module.exports = deprecate;

/**
 * Mark that a method should not be used.
 * Returns a modified function which warns once by default.
 *
 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
 *
 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
 * will throw an Error when invoked.
 *
 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
 * will invoke `console.trace()` instead of `console.error()`.
 *
 * @param {Function} fn - the function to deprecate
 * @param {String} msg - the string to print to the console when `fn` is invoked
 * @returns {Function} a new "deprecated" version of `fn`
 * @api public
 */

function deprecate (fn, msg) {
  if (config('noDeprecation')) {
    return fn;
  }

  var warned = false;
  function deprecated() {
    if (!warned) {
      if (config('throwDeprecation')) {
        throw new Error(msg);
      } else if (config('traceDeprecation')) {
        console.trace(msg);
      } else {
        console.warn(msg);
      }
      warned = true;
    }
    return fn.apply(this, arguments);
  }

  return deprecated;
}

/**
 * Checks `localStorage` for boolean values for the given `name`.
 *
 * @param {String} name
 * @returns {Boolean}
 * @api private
 */

function config (name) {
  // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  try {
    if (!__webpack_require__.g.localStorage) return false;
  } catch (_) {
    return false;
  }
  var val = __webpack_require__.g.localStorage[name];
  if (null == val) return false;
  return String(val).toLowerCase() === 'true';
}


/***/ }),

/***/ 51755:
/***/ ((__unused_webpack_module, exports) => {

var indexOf = function (xs, item) {
    if (xs.indexOf) return xs.indexOf(item);
    else for (var i = 0; i < xs.length; i++) {
        if (xs[i] === item) return i;
    }
    return -1;
};
var Object_keys = function (obj) {
    if (Object.keys) return Object.keys(obj)
    else {
        var res = [];
        for (var key in obj) res.push(key)
        return res;
    }
};

var forEach = function (xs, fn) {
    if (xs.forEach) return xs.forEach(fn)
    else for (var i = 0; i < xs.length; i++) {
        fn(xs[i], i, xs);
    }
};

var defineProp = (function() {
    try {
        Object.defineProperty({}, '_', {});
        return function(obj, name, value) {
            Object.defineProperty(obj, name, {
                writable: true,
                enumerable: false,
                configurable: true,
                value: value
            })
        };
    } catch(e) {
        return function(obj, name, value) {
            obj[name] = value;
        };
    }
}());

var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function',
'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError',
'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError',
'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape',
'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape'];

function Context() {}
Context.prototype = {};

var Script = exports.Script = function NodeScript (code) {
    if (!(this instanceof Script)) return new Script(code);
    this.code = code;
};

Script.prototype.runInContext = function (context) {
    if (!(context instanceof Context)) {
        throw new TypeError("needs a 'context' argument.");
    }
    
    var iframe = document.createElement('iframe');
    if (!iframe.style) iframe.style = {};
    iframe.style.display = 'none';
    
    document.body.appendChild(iframe);
    
    var win = iframe.contentWindow;
    var wEval = win.eval, wExecScript = win.execScript;

    if (!wEval && wExecScript) {
        // win.eval() magically appears when this is called in IE:
        wExecScript.call(win, 'null');
        wEval = win.eval;
    }
    
    forEach(Object_keys(context), function (key) {
        win[key] = context[key];
    });
    forEach(globals, function (key) {
        if (context[key]) {
            win[key] = context[key];
        }
    });
    
    var winKeys = Object_keys(win);

    var res = wEval.call(win, this.code);
    
    forEach(Object_keys(win), function (key) {
        // Avoid copying circular objects like `top` and `window` by only
        // updating existing context properties or new properties in the `win`
        // that was only introduced after the eval.
        if (key in context || indexOf(winKeys, key) === -1) {
            context[key] = win[key];
        }
    });

    forEach(globals, function (key) {
        if (!(key in context)) {
            defineProp(context, key, win[key]);
        }
    });
    
    document.body.removeChild(iframe);
    
    return res;
};

Script.prototype.runInThisContext = function () {
    return eval(this.code); // maybe...
};

Script.prototype.runInNewContext = function (context) {
    var ctx = Script.createContext(context);
    var res = this.runInContext(ctx);

    if (context) {
        forEach(Object_keys(ctx), function (key) {
            context[key] = ctx[key];
        });
    }

    return res;
};

forEach(Object_keys(Script.prototype), function (name) {
    exports[name] = Script[name] = function (code) {
        var s = Script(code);
        return s[name].apply(s, [].slice.call(arguments, 1));
    };
});

exports.isContext = function (context) {
    return context instanceof Context;
};

exports.createScript = function (code) {
    return exports.Script(code);
};

exports.createContext = Script.createContext = function (context) {
    var copy = new Context();
    if(typeof context === 'object') {
        forEach(Object_keys(context), function (key) {
            copy[key] = context[key];
        });
    }
    return copy;
};


/***/ }),

/***/ 7967:
/***/ (function(module, exports) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (global, factory) {
  if (true) {
    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [module], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
		__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
		(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  } else { var mod; }
})(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (module) {
  /* webextension-polyfill - v0.12.0 - Tue May 14 2024 18:01:29 */
  /* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
  /* vim: set sts=2 sw=2 et tw=80: */
  /* This Source Code Form is subject to the terms of the Mozilla Public
   * License, v. 2.0. If a copy of the MPL was not distributed with this
   * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  "use strict";

  if (!(globalThis.chrome && globalThis.chrome.runtime && globalThis.chrome.runtime.id)) {
    throw new Error("This script should only be loaded in a browser extension.");
  }
  if (!(globalThis.browser && globalThis.browser.runtime && globalThis.browser.runtime.id)) {
    const CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE = "The message port closed before a response was received.";

    // Wrapping the bulk of this polyfill in a one-time-use function is a minor
    // optimization for Firefox. Since Spidermonkey does not fully parse the
    // contents of a function until the first time it's called, and since it will
    // never actually need to be called, this allows the polyfill to be included
    // in Firefox nearly for free.
    const wrapAPIs = extensionAPIs => {
      // NOTE: apiMetadata is associated to the content of the api-metadata.json file
      // at build time by replacing the following "include" with the content of the
      // JSON file.
      const apiMetadata = {
        "alarms": {
          "clear": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "clearAll": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "get": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "getAll": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "bookmarks": {
          "create": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "get": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getChildren": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getRecent": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getSubTree": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getTree": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "move": {
            "minArgs": 2,
            "maxArgs": 2
          },
          "remove": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeTree": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "search": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "update": {
            "minArgs": 2,
            "maxArgs": 2
          }
        },
        "browserAction": {
          "disable": {
            "minArgs": 0,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "enable": {
            "minArgs": 0,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "getBadgeBackgroundColor": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getBadgeText": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getPopup": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getTitle": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "openPopup": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "setBadgeBackgroundColor": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "setBadgeText": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "setIcon": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "setPopup": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "setTitle": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          }
        },
        "browsingData": {
          "remove": {
            "minArgs": 2,
            "maxArgs": 2
          },
          "removeCache": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeCookies": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeDownloads": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeFormData": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeHistory": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeLocalStorage": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removePasswords": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removePluginData": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "settings": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "commands": {
          "getAll": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "contextMenus": {
          "remove": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeAll": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "update": {
            "minArgs": 2,
            "maxArgs": 2
          }
        },
        "cookies": {
          "get": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getAll": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getAllCookieStores": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "remove": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "set": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "devtools": {
          "inspectedWindow": {
            "eval": {
              "minArgs": 1,
              "maxArgs": 2,
              "singleCallbackArg": false
            }
          },
          "panels": {
            "create": {
              "minArgs": 3,
              "maxArgs": 3,
              "singleCallbackArg": true
            },
            "elements": {
              "createSidebarPane": {
                "minArgs": 1,
                "maxArgs": 1
              }
            }
          }
        },
        "downloads": {
          "cancel": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "download": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "erase": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getFileIcon": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "open": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "pause": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeFile": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "resume": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "search": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "show": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          }
        },
        "extension": {
          "isAllowedFileSchemeAccess": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "isAllowedIncognitoAccess": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "history": {
          "addUrl": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "deleteAll": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "deleteRange": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "deleteUrl": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getVisits": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "search": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "i18n": {
          "detectLanguage": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getAcceptLanguages": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "identity": {
          "launchWebAuthFlow": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "idle": {
          "queryState": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "management": {
          "get": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getAll": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "getSelf": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "setEnabled": {
            "minArgs": 2,
            "maxArgs": 2
          },
          "uninstallSelf": {
            "minArgs": 0,
            "maxArgs": 1
          }
        },
        "notifications": {
          "clear": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "create": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "getAll": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "getPermissionLevel": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "update": {
            "minArgs": 2,
            "maxArgs": 2
          }
        },
        "pageAction": {
          "getPopup": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getTitle": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "hide": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "setIcon": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "setPopup": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "setTitle": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "show": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          }
        },
        "permissions": {
          "contains": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getAll": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "remove": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "request": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "runtime": {
          "getBackgroundPage": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "getPlatformInfo": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "openOptionsPage": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "requestUpdateCheck": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "sendMessage": {
            "minArgs": 1,
            "maxArgs": 3
          },
          "sendNativeMessage": {
            "minArgs": 2,
            "maxArgs": 2
          },
          "setUninstallURL": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "sessions": {
          "getDevices": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "getRecentlyClosed": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "restore": {
            "minArgs": 0,
            "maxArgs": 1
          }
        },
        "storage": {
          "local": {
            "clear": {
              "minArgs": 0,
              "maxArgs": 0
            },
            "get": {
              "minArgs": 0,
              "maxArgs": 1
            },
            "getBytesInUse": {
              "minArgs": 0,
              "maxArgs": 1
            },
            "remove": {
              "minArgs": 1,
              "maxArgs": 1
            },
            "set": {
              "minArgs": 1,
              "maxArgs": 1
            }
          },
          "managed": {
            "get": {
              "minArgs": 0,
              "maxArgs": 1
            },
            "getBytesInUse": {
              "minArgs": 0,
              "maxArgs": 1
            }
          },
          "sync": {
            "clear": {
              "minArgs": 0,
              "maxArgs": 0
            },
            "get": {
              "minArgs": 0,
              "maxArgs": 1
            },
            "getBytesInUse": {
              "minArgs": 0,
              "maxArgs": 1
            },
            "remove": {
              "minArgs": 1,
              "maxArgs": 1
            },
            "set": {
              "minArgs": 1,
              "maxArgs": 1
            }
          }
        },
        "tabs": {
          "captureVisibleTab": {
            "minArgs": 0,
            "maxArgs": 2
          },
          "create": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "detectLanguage": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "discard": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "duplicate": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "executeScript": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "get": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getCurrent": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "getZoom": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "getZoomSettings": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "goBack": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "goForward": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "highlight": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "insertCSS": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "move": {
            "minArgs": 2,
            "maxArgs": 2
          },
          "query": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "reload": {
            "minArgs": 0,
            "maxArgs": 2
          },
          "remove": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeCSS": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "sendMessage": {
            "minArgs": 2,
            "maxArgs": 3
          },
          "setZoom": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "setZoomSettings": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "update": {
            "minArgs": 1,
            "maxArgs": 2
          }
        },
        "topSites": {
          "get": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "webNavigation": {
          "getAllFrames": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getFrame": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "webRequest": {
          "handlerBehaviorChanged": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "windows": {
          "create": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "get": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "getAll": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "getCurrent": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "getLastFocused": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "remove": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "update": {
            "minArgs": 2,
            "maxArgs": 2
          }
        }
      };
      if (Object.keys(apiMetadata).length === 0) {
        throw new Error("api-metadata.json has not been included in browser-polyfill");
      }

      /**
       * A WeakMap subclass which creates and stores a value for any key which does
       * not exist when accessed, but behaves exactly as an ordinary WeakMap
       * otherwise.
       *
       * @param {function} createItem
       *        A function which will be called in order to create the value for any
       *        key which does not exist, the first time it is accessed. The
       *        function receives, as its only argument, the key being created.
       */
      class DefaultWeakMap extends WeakMap {
        constructor(createItem, items = undefined) {
          super(items);
          this.createItem = createItem;
        }
        get(key) {
          if (!this.has(key)) {
            this.set(key, this.createItem(key));
          }
          return super.get(key);
        }
      }

      /**
       * Returns true if the given object is an object with a `then` method, and can
       * therefore be assumed to behave as a Promise.
       *
       * @param {*} value The value to test.
       * @returns {boolean} True if the value is thenable.
       */
      const isThenable = value => {
        return value && typeof value === "object" && typeof value.then === "function";
      };

      /**
       * Creates and returns a function which, when called, will resolve or reject
       * the given promise based on how it is called:
       *
       * - If, when called, `chrome.runtime.lastError` contains a non-null object,
       *   the promise is rejected with that value.
       * - If the function is called with exactly one argument, the promise is
       *   resolved to that value.
       * - Otherwise, the promise is resolved to an array containing all of the
       *   function's arguments.
       *
       * @param {object} promise
       *        An object containing the resolution and rejection functions of a
       *        promise.
       * @param {function} promise.resolve
       *        The promise's resolution function.
       * @param {function} promise.reject
       *        The promise's rejection function.
       * @param {object} metadata
       *        Metadata about the wrapped method which has created the callback.
       * @param {boolean} metadata.singleCallbackArg
       *        Whether or not the promise is resolved with only the first
       *        argument of the callback, alternatively an array of all the
       *        callback arguments is resolved. By default, if the callback
       *        function is invoked with only a single argument, that will be
       *        resolved to the promise, while all arguments will be resolved as
       *        an array if multiple are given.
       *
       * @returns {function}
       *        The generated callback function.
       */
      const makeCallback = (promise, metadata) => {
        return (...callbackArgs) => {
          if (extensionAPIs.runtime.lastError) {
            promise.reject(new Error(extensionAPIs.runtime.lastError.message));
          } else if (metadata.singleCallbackArg || callbackArgs.length <= 1 && metadata.singleCallbackArg !== false) {
            promise.resolve(callbackArgs[0]);
          } else {
            promise.resolve(callbackArgs);
          }
        };
      };
      const pluralizeArguments = numArgs => numArgs == 1 ? "argument" : "arguments";

      /**
       * Creates a wrapper function for a method with the given name and metadata.
       *
       * @param {string} name
       *        The name of the method which is being wrapped.
       * @param {object} metadata
       *        Metadata about the method being wrapped.
       * @param {integer} metadata.minArgs
       *        The minimum number of arguments which must be passed to the
       *        function. If called with fewer than this number of arguments, the
       *        wrapper will raise an exception.
       * @param {integer} metadata.maxArgs
       *        The maximum number of arguments which may be passed to the
       *        function. If called with more than this number of arguments, the
       *        wrapper will raise an exception.
       * @param {boolean} metadata.singleCallbackArg
       *        Whether or not the promise is resolved with only the first
       *        argument of the callback, alternatively an array of all the
       *        callback arguments is resolved. By default, if the callback
       *        function is invoked with only a single argument, that will be
       *        resolved to the promise, while all arguments will be resolved as
       *        an array if multiple are given.
       *
       * @returns {function(object, ...*)}
       *       The generated wrapper function.
       */
      const wrapAsyncFunction = (name, metadata) => {
        return function asyncFunctionWrapper(target, ...args) {
          if (args.length < metadata.minArgs) {
            throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`);
          }
          if (args.length > metadata.maxArgs) {
            throw new Error(`Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`);
          }
          return new Promise((resolve, reject) => {
            if (metadata.fallbackToNoCallback) {
              // This API method has currently no callback on Chrome, but it return a promise on Firefox,
              // and so the polyfill will try to call it with a callback first, and it will fallback
              // to not passing the callback if the first call fails.
              try {
                target[name](...args, makeCallback({
                  resolve,
                  reject
                }, metadata));
              } catch (cbError) {
                console.warn(`${name} API method doesn't seem to support the callback parameter, ` + "falling back to call it without a callback: ", cbError);
                target[name](...args);

                // Update the API method metadata, so that the next API calls will not try to
                // use the unsupported callback anymore.
                metadata.fallbackToNoCallback = false;
                metadata.noCallback = true;
                resolve();
              }
            } else if (metadata.noCallback) {
              target[name](...args);
              resolve();
            } else {
              target[name](...args, makeCallback({
                resolve,
                reject
              }, metadata));
            }
          });
        };
      };

      /**
       * Wraps an existing method of the target object, so that calls to it are
       * intercepted by the given wrapper function. The wrapper function receives,
       * as its first argument, the original `target` object, followed by each of
       * the arguments passed to the original method.
       *
       * @param {object} target
       *        The original target object that the wrapped method belongs to.
       * @param {function} method
       *        The method being wrapped. This is used as the target of the Proxy
       *        object which is created to wrap the method.
       * @param {function} wrapper
       *        The wrapper function which is called in place of a direct invocation
       *        of the wrapped method.
       *
       * @returns {Proxy<function>}
       *        A Proxy object for the given method, which invokes the given wrapper
       *        method in its place.
       */
      const wrapMethod = (target, method, wrapper) => {
        return new Proxy(method, {
          apply(targetMethod, thisObj, args) {
            return wrapper.call(thisObj, target, ...args);
          }
        });
      };
      let hasOwnProperty = Function.call.bind(Object.prototype.hasOwnProperty);

      /**
       * Wraps an object in a Proxy which intercepts and wraps certain methods
       * based on the given `wrappers` and `metadata` objects.
       *
       * @param {object} target
       *        The target object to wrap.
       *
       * @param {object} [wrappers = {}]
       *        An object tree containing wrapper functions for special cases. Any
       *        function present in this object tree is called in place of the
       *        method in the same location in the `target` object tree. These
       *        wrapper methods are invoked as described in {@see wrapMethod}.
       *
       * @param {object} [metadata = {}]
       *        An object tree containing metadata used to automatically generate
       *        Promise-based wrapper functions for asynchronous. Any function in
       *        the `target` object tree which has a corresponding metadata object
       *        in the same location in the `metadata` tree is replaced with an
       *        automatically-generated wrapper function, as described in
       *        {@see wrapAsyncFunction}
       *
       * @returns {Proxy<object>}
       */
      const wrapObject = (target, wrappers = {}, metadata = {}) => {
        let cache = Object.create(null);
        let handlers = {
          has(proxyTarget, prop) {
            return prop in target || prop in cache;
          },
          get(proxyTarget, prop, receiver) {
            if (prop in cache) {
              return cache[prop];
            }
            if (!(prop in target)) {
              return undefined;
            }
            let value = target[prop];
            if (typeof value === "function") {
              // This is a method on the underlying object. Check if we need to do
              // any wrapping.

              if (typeof wrappers[prop] === "function") {
                // We have a special-case wrapper for this method.
                value = wrapMethod(target, target[prop], wrappers[prop]);
              } else if (hasOwnProperty(metadata, prop)) {
                // This is an async method that we have metadata for. Create a
                // Promise wrapper for it.
                let wrapper = wrapAsyncFunction(prop, metadata[prop]);
                value = wrapMethod(target, target[prop], wrapper);
              } else {
                // This is a method that we don't know or care about. Return the
                // original method, bound to the underlying object.
                value = value.bind(target);
              }
            } else if (typeof value === "object" && value !== null && (hasOwnProperty(wrappers, prop) || hasOwnProperty(metadata, prop))) {
              // This is an object that we need to do some wrapping for the children
              // of. Create a sub-object wrapper for it with the appropriate child
              // metadata.
              value = wrapObject(value, wrappers[prop], metadata[prop]);
            } else if (hasOwnProperty(metadata, "*")) {
              // Wrap all properties in * namespace.
              value = wrapObject(value, wrappers[prop], metadata["*"]);
            } else {
              // We don't need to do any wrapping for this property,
              // so just forward all access to the underlying object.
              Object.defineProperty(cache, prop, {
                configurable: true,
                enumerable: true,
                get() {
                  return target[prop];
                },
                set(value) {
                  target[prop] = value;
                }
              });
              return value;
            }
            cache[prop] = value;
            return value;
          },
          set(proxyTarget, prop, value, receiver) {
            if (prop in cache) {
              cache[prop] = value;
            } else {
              target[prop] = value;
            }
            return true;
          },
          defineProperty(proxyTarget, prop, desc) {
            return Reflect.defineProperty(cache, prop, desc);
          },
          deleteProperty(proxyTarget, prop) {
            return Reflect.deleteProperty(cache, prop);
          }
        };

        // Per contract of the Proxy API, the "get" proxy handler must return the
        // original value of the target if that value is declared read-only and
        // non-configurable. For this reason, we create an object with the
        // prototype set to `target` instead of using `target` directly.
        // Otherwise we cannot return a custom object for APIs that
        // are declared read-only and non-configurable, such as `chrome.devtools`.
        //
        // The proxy handlers themselves will still use the original `target`
        // instead of the `proxyTarget`, so that the methods and properties are
        // dereferenced via the original targets.
        let proxyTarget = Object.create(target);
        return new Proxy(proxyTarget, handlers);
      };

      /**
       * Creates a set of wrapper functions for an event object, which handles
       * wrapping of listener functions that those messages are passed.
       *
       * A single wrapper is created for each listener function, and stored in a
       * map. Subsequent calls to `addListener`, `hasListener`, or `removeListener`
       * retrieve the original wrapper, so that  attempts to remove a
       * previously-added listener work as expected.
       *
       * @param {DefaultWeakMap<function, function>} wrapperMap
       *        A DefaultWeakMap object which will create the appropriate wrapper
       *        for a given listener function when one does not exist, and retrieve
       *        an existing one when it does.
       *
       * @returns {object}
       */
      const wrapEvent = wrapperMap => ({
        addListener(target, listener, ...args) {
          target.addListener(wrapperMap.get(listener), ...args);
        },
        hasListener(target, listener) {
          return target.hasListener(wrapperMap.get(listener));
        },
        removeListener(target, listener) {
          target.removeListener(wrapperMap.get(listener));
        }
      });
      const onRequestFinishedWrappers = new DefaultWeakMap(listener => {
        if (typeof listener !== "function") {
          return listener;
        }

        /**
         * Wraps an onRequestFinished listener function so that it will return a
         * `getContent()` property which returns a `Promise` rather than using a
         * callback API.
         *
         * @param {object} req
         *        The HAR entry object representing the network request.
         */
        return function onRequestFinished(req) {
          const wrappedReq = wrapObject(req, {} /* wrappers */, {
            getContent: {
              minArgs: 0,
              maxArgs: 0
            }
          });
          listener(wrappedReq);
        };
      });
      const onMessageWrappers = new DefaultWeakMap(listener => {
        if (typeof listener !== "function") {
          return listener;
        }

        /**
         * Wraps a message listener function so that it may send responses based on
         * its return value, rather than by returning a sentinel value and calling a
         * callback. If the listener function returns a Promise, the response is
         * sent when the promise either resolves or rejects.
         *
         * @param {*} message
         *        The message sent by the other end of the channel.
         * @param {object} sender
         *        Details about the sender of the message.
         * @param {function(*)} sendResponse
         *        A callback which, when called with an arbitrary argument, sends
         *        that value as a response.
         * @returns {boolean}
         *        True if the wrapped listener returned a Promise, which will later
         *        yield a response. False otherwise.
         */
        return function onMessage(message, sender, sendResponse) {
          let didCallSendResponse = false;
          let wrappedSendResponse;
          let sendResponsePromise = new Promise(resolve => {
            wrappedSendResponse = function (response) {
              didCallSendResponse = true;
              resolve(response);
            };
          });
          let result;
          try {
            result = listener(message, sender, wrappedSendResponse);
          } catch (err) {
            result = Promise.reject(err);
          }
          const isResultThenable = result !== true && isThenable(result);

          // If the listener didn't returned true or a Promise, or called
          // wrappedSendResponse synchronously, we can exit earlier
          // because there will be no response sent from this listener.
          if (result !== true && !isResultThenable && !didCallSendResponse) {
            return false;
          }

          // A small helper to send the message if the promise resolves
          // and an error if the promise rejects (a wrapped sendMessage has
          // to translate the message into a resolved promise or a rejected
          // promise).
          const sendPromisedResult = promise => {
            promise.then(msg => {
              // send the message value.
              sendResponse(msg);
            }, error => {
              // Send a JSON representation of the error if the rejected value
              // is an instance of error, or the object itself otherwise.
              let message;
              if (error && (error instanceof Error || typeof error.message === "string")) {
                message = error.message;
              } else {
                message = "An unexpected error occurred";
              }
              sendResponse({
                __mozWebExtensionPolyfillReject__: true,
                message
              });
            }).catch(err => {
              // Print an error on the console if unable to send the response.
              console.error("Failed to send onMessage rejected reply", err);
            });
          };

          // If the listener returned a Promise, send the resolved value as a
          // result, otherwise wait the promise related to the wrappedSendResponse
          // callback to resolve and send it as a response.
          if (isResultThenable) {
            sendPromisedResult(result);
          } else {
            sendPromisedResult(sendResponsePromise);
          }

          // Let Chrome know that the listener is replying.
          return true;
        };
      });
      const wrappedSendMessageCallback = ({
        reject,
        resolve
      }, reply) => {
        if (extensionAPIs.runtime.lastError) {
          // Detect when none of the listeners replied to the sendMessage call and resolve
          // the promise to undefined as in Firefox.
          // See https://github.com/mozilla/webextension-polyfill/issues/130
          if (extensionAPIs.runtime.lastError.message === CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE) {
            resolve();
          } else {
            reject(new Error(extensionAPIs.runtime.lastError.message));
          }
        } else if (reply && reply.__mozWebExtensionPolyfillReject__) {
          // Convert back the JSON representation of the error into
          // an Error instance.
          reject(new Error(reply.message));
        } else {
          resolve(reply);
        }
      };
      const wrappedSendMessage = (name, metadata, apiNamespaceObj, ...args) => {
        if (args.length < metadata.minArgs) {
          throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`);
        }
        if (args.length > metadata.maxArgs) {
          throw new Error(`Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`);
        }
        return new Promise((resolve, reject) => {
          const wrappedCb = wrappedSendMessageCallback.bind(null, {
            resolve,
            reject
          });
          args.push(wrappedCb);
          apiNamespaceObj.sendMessage(...args);
        });
      };
      const staticWrappers = {
        devtools: {
          network: {
            onRequestFinished: wrapEvent(onRequestFinishedWrappers)
          }
        },
        runtime: {
          onMessage: wrapEvent(onMessageWrappers),
          onMessageExternal: wrapEvent(onMessageWrappers),
          sendMessage: wrappedSendMessage.bind(null, "sendMessage", {
            minArgs: 1,
            maxArgs: 3
          })
        },
        tabs: {
          sendMessage: wrappedSendMessage.bind(null, "sendMessage", {
            minArgs: 2,
            maxArgs: 3
          })
        }
      };
      const settingMetadata = {
        clear: {
          minArgs: 1,
          maxArgs: 1
        },
        get: {
          minArgs: 1,
          maxArgs: 1
        },
        set: {
          minArgs: 1,
          maxArgs: 1
        }
      };
      apiMetadata.privacy = {
        network: {
          "*": settingMetadata
        },
        services: {
          "*": settingMetadata
        },
        websites: {
          "*": settingMetadata
        }
      };
      return wrapObject(extensionAPIs, staticWrappers, apiMetadata);
    };

    // The build process adds a UMD wrapper around this file, which makes the
    // `module` variable available.
    module.exports = wrapAPIs(chrome);
  } else {
    module.exports = globalThis.browser;
  }
});


/***/ }),

/***/ 20399:
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ 34149:
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ 89780:
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ 73936:
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ 99926:
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ 90124:
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ 71220:
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ 38854:
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ 2786:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var isCallable = __webpack_require__(33901);
var tryToString = __webpack_require__(56383);

var $TypeError = TypeError;

// `Assert: IsCallable(argument) is true`
module.exports = function (argument) {
  if (isCallable(argument)) return argument;
  throw new $TypeError(tryToString(argument) + ' is not a function');
};


/***/ }),

/***/ 55034:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var isPossiblePrototype = __webpack_require__(26493);

var $String = String;
var $TypeError = TypeError;

module.exports = function (argument) {
  if (isPossiblePrototype(argument)) return argument;
  throw new $TypeError("Can't set " + $String(argument) + ' as a prototype');
};


/***/ }),

/***/ 9693:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var wellKnownSymbol = __webpack_require__(25723);
var create = __webpack_require__(66736);
var defineProperty = (__webpack_require__(9609).f);

var UNSCOPABLES = wellKnownSymbol('unscopables');
var ArrayPrototype = Array.prototype;

// Array.prototype[@@unscopables]
// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
if (ArrayPrototype[UNSCOPABLES] === undefined) {
  defineProperty(ArrayPrototype, UNSCOPABLES, {
    configurable: true,
    value: create(null)
  });
}

// add a key to Array.prototype[@@unscopables]
module.exports = function (key) {
  ArrayPrototype[UNSCOPABLES][key] = true;
};


/***/ }),

/***/ 87759:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var isPrototypeOf = __webpack_require__(44657);

var $TypeError = TypeError;

module.exports = function (it, Prototype) {
  if (isPrototypeOf(Prototype, it)) return it;
  throw new $TypeError('Incorrect invocation');
};


/***/ }),

/***/ 93263:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var isObject = __webpack_require__(34186);

var $String = String;
var $TypeError = TypeError;

// `Assert: Type(argument) is Object`
module.exports = function (argument) {
  if (isObject(argument)) return argument;
  throw new $TypeError($String(argument) + ' is not an object');
};


/***/ }),

/***/ 84043:
/***/ ((module) => {

"use strict";

// eslint-disable-next-line es/no-typed-arrays -- safe
module.exports = typeof ArrayBuffer != 'undefined' && typeof DataView != 'undefined';


/***/ }),

/***/ 95308:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var NATIVE_ARRAY_BUFFER = __webpack_require__(84043);
var DESCRIPTORS = __webpack_require__(72468);
var globalThis = __webpack_require__(34760);
var isCallable = __webpack_require__(33901);
var isObject = __webpack_require__(34186);
var hasOwn = __webpack_require__(30217);
var classof = __webpack_require__(45123);
var tryToString = __webpack_require__(56383);
var createNonEnumerableProperty = __webpack_require__(98515);
var defineBuiltIn = __webpack_require__(44432);
var defineBuiltInAccessor = __webpack_require__(43954);
var isPrototypeOf = __webpack_require__(44657);
var getPrototypeOf = __webpack_require__(73595);
var setPrototypeOf = __webpack_require__(45407);
var wellKnownSymbol = __webpack_require__(25723);
var uid = __webpack_require__(64232);
var InternalStateModule = __webpack_require__(37813);

var enforceInternalState = InternalStateModule.enforce;
var getInternalState = InternalStateModule.get;
var Int8Array = globalThis.Int8Array;
var Int8ArrayPrototype = Int8Array && Int8Array.prototype;
var Uint8ClampedArray = globalThis.Uint8ClampedArray;
var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype;
var TypedArray = Int8Array && getPrototypeOf(Int8Array);
var TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype);
var ObjectPrototype = Object.prototype;
var TypeError = globalThis.TypeError;

var TO_STRING_TAG = wellKnownSymbol('toStringTag');
var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG');
var TYPED_ARRAY_CONSTRUCTOR = 'TypedArrayConstructor';
// Fixing native typed arrays in Opera Presto crashes the browser, see #595
var NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(globalThis.opera) !== 'Opera';
var TYPED_ARRAY_TAG_REQUIRED = false;
var NAME, Constructor, Prototype;

var TypedArrayConstructorsList = {
  Int8Array: 1,
  Uint8Array: 1,
  Uint8ClampedArray: 1,
  Int16Array: 2,
  Uint16Array: 2,
  Int32Array: 4,
  Uint32Array: 4,
  Float32Array: 4,
  Float64Array: 8
};

var BigIntArrayConstructorsList = {
  BigInt64Array: 8,
  BigUint64Array: 8
};

var isView = function isView(it) {
  if (!isObject(it)) return false;
  var klass = classof(it);
  return klass === 'DataView'
    || hasOwn(TypedArrayConstructorsList, klass)
    || hasOwn(BigIntArrayConstructorsList, klass);
};

var getTypedArrayConstructor = function (it) {
  var proto = getPrototypeOf(it);
  if (!isObject(proto)) return;
  var state = getInternalState(proto);
  return (state && hasOwn(state, TYPED_ARRAY_CONSTRUCTOR)) ? state[TYPED_ARRAY_CONSTRUCTOR] : getTypedArrayConstructor(proto);
};

var isTypedArray = function (it) {
  if (!isObject(it)) return false;
  var klass = classof(it);
  return hasOwn(TypedArrayConstructorsList, klass)
    || hasOwn(BigIntArrayConstructorsList, klass);
};

var aTypedArray = function (it) {
  if (isTypedArray(it)) return it;
  throw new TypeError('Target is not a typed array');
};

var aTypedArrayConstructor = function (C) {
  if (isCallable(C) && (!setPrototypeOf || isPrototypeOf(TypedArray, C))) return C;
  throw new TypeError(tryToString(C) + ' is not a typed array constructor');
};

var exportTypedArrayMethod = function (KEY, property, forced, options) {
  if (!DESCRIPTORS) return;
  if (forced) for (var ARRAY in TypedArrayConstructorsList) {
    var TypedArrayConstructor = globalThis[ARRAY];
    if (TypedArrayConstructor && hasOwn(TypedArrayConstructor.prototype, KEY)) try {
      delete TypedArrayConstructor.prototype[KEY];
    } catch (error) {
      // old WebKit bug - some methods are non-configurable
      try {
        TypedArrayConstructor.prototype[KEY] = property;
      } catch (error2) { /* empty */ }
    }
  }
  if (!TypedArrayPrototype[KEY] || forced) {
    defineBuiltIn(TypedArrayPrototype, KEY, forced ? property
      : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property, options);
  }
};

var exportTypedArrayStaticMethod = function (KEY, property, forced) {
  var ARRAY, TypedArrayConstructor;
  if (!DESCRIPTORS) return;
  if (setPrototypeOf) {
    if (forced) for (ARRAY in TypedArrayConstructorsList) {
      TypedArrayConstructor = globalThis[ARRAY];
      if (TypedArrayConstructor && hasOwn(TypedArrayConstructor, KEY)) try {
        delete TypedArrayConstructor[KEY];
      } catch (error) { /* empty */ }
    }
    if (!TypedArray[KEY] || forced) {
      // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable
      try {
        return defineBuiltIn(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && TypedArray[KEY] || property);
      } catch (error) { /* empty */ }
    } else return;
  }
  for (ARRAY in TypedArrayConstructorsList) {
    TypedArrayConstructor = globalThis[ARRAY];
    if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) {
      defineBuiltIn(TypedArrayConstructor, KEY, property);
    }
  }
};

for (NAME in TypedArrayConstructorsList) {
  Constructor = globalThis[NAME];
  Prototype = Constructor && Constructor.prototype;
  if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor;
  else NATIVE_ARRAY_BUFFER_VIEWS = false;
}

for (NAME in BigIntArrayConstructorsList) {
  Constructor = globalThis[NAME];
  Prototype = Constructor && Constructor.prototype;
  if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor;
}

// WebKit bug - typed arrays constructors prototype is Object.prototype
if (!NATIVE_ARRAY_BUFFER_VIEWS || !isCallable(TypedArray) || TypedArray === Function.prototype) {
  // eslint-disable-next-line no-shadow -- safe
  TypedArray = function TypedArray() {
    throw new TypeError('Incorrect invocation');
  };
  if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {
    if (globalThis[NAME]) setPrototypeOf(globalThis[NAME], TypedArray);
  }
}

if (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) {
  TypedArrayPrototype = TypedArray.prototype;
  if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {
    if (globalThis[NAME]) setPrototypeOf(globalThis[NAME].prototype, TypedArrayPrototype);
  }
}

// WebKit bug - one more object in Uint8ClampedArray prototype chain
if (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) {
  setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype);
}

if (DESCRIPTORS && !hasOwn(TypedArrayPrototype, TO_STRING_TAG)) {
  TYPED_ARRAY_TAG_REQUIRED = true;
  defineBuiltInAccessor(TypedArrayPrototype, TO_STRING_TAG, {
    configurable: true,
    get: function () {
      return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined;
    }
  });
  for (NAME in TypedArrayConstructorsList) if (globalThis[NAME]) {
    createNonEnumerableProperty(globalThis[NAME], TYPED_ARRAY_TAG, NAME);
  }
}

module.exports = {
  NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS,
  TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQUIRED && TYPED_ARRAY_TAG,
  aTypedArray: aTypedArray,
  aTypedArrayConstructor: aTypedArrayConstructor,
  exportTypedArrayMethod: exportTypedArrayMethod,
  exportTypedArrayStaticMethod: exportTypedArrayStaticMethod,
  getTypedArrayConstructor: getTypedArrayConstructor,
  isView: isView,
  isTypedArray: isTypedArray,
  TypedArray: TypedArray,
  TypedArrayPrototype: TypedArrayPrototype
};


/***/ }),

/***/ 65282:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var lengthOfArrayLike = __webpack_require__(47294);

module.exports = function (Constructor, list, $length) {
  var index = 0;
  var length = arguments.length > 2 ? $length : lengthOfArrayLike(list);
  var result = new Constructor(length);
  while (length > index) result[index] = list[index++];
  return result;
};


/***/ }),

/***/ 5865:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var toIndexedObject = __webpack_require__(42173);
var toAbsoluteIndex = __webpack_require__(63458);
var lengthOfArrayLike = __webpack_require__(47294);

// `Array.prototype.{ indexOf, includes }` methods implementation
var createMethod = function (IS_INCLUDES) {
  return function ($this, el, fromIndex) {
    var O = toIndexedObject($this);
    var length = lengthOfArrayLike(O);
    if (length === 0) return !IS_INCLUDES && -1;
    var index = toAbsoluteIndex(fromIndex, length);
    var value;
    // Array#includes uses SameValueZero equality algorithm
    // eslint-disable-next-line no-self-compare -- NaN check
    if (IS_INCLUDES && el !== el) while (length > index) {
      value = O[index++];
      // eslint-disable-next-line no-self-compare -- NaN check
      if (value !== value) return true;
    // Array#indexOf ignores holes, Array#includes - not
    } else for (;length > index; index++) {
      if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
    } return !IS_INCLUDES && -1;
  };
};

module.exports = {
  // `Array.prototype.includes` method
  // https://tc39.es/ecma262/#sec-array.prototype.includes
  includes: createMethod(true),
  // `Array.prototype.indexOf` method
  // https://tc39.es/ecma262/#sec-array.prototype.indexof
  indexOf: createMethod(false)
};


/***/ }),

/***/ 73271:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var bind = __webpack_require__(82184);
var IndexedObject = __webpack_require__(98119);
var toObject = __webpack_require__(76573);
var lengthOfArrayLike = __webpack_require__(47294);

// `Array.prototype.{ findLast, findLastIndex }` methods implementation
var createMethod = function (TYPE) {
  var IS_FIND_LAST_INDEX = TYPE === 1;
  return function ($this, callbackfn, that) {
    var O = toObject($this);
    var self = IndexedObject(O);
    var index = lengthOfArrayLike(self);
    var boundFunction = bind(callbackfn, that);
    var value, result;
    while (index-- > 0) {
      value = self[index];
      result = boundFunction(value, index, O);
      if (result) switch (TYPE) {
        case 0: return value; // findLast
        case 1: return index; // findLastIndex
      }
    }
    return IS_FIND_LAST_INDEX ? -1 : undefined;
  };
};

module.exports = {
  // `Array.prototype.findLast` method
  // https://github.com/tc39/proposal-array-find-from-last
  findLast: createMethod(0),
  // `Array.prototype.findLastIndex` method
  // https://github.com/tc39/proposal-array-find-from-last
  findLastIndex: createMethod(1)
};


/***/ }),

/***/ 11822:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var fails = __webpack_require__(2599);

module.exports = function (METHOD_NAME, argument) {
  var method = [][METHOD_NAME];
  return !!method && fails(function () {
    // eslint-disable-next-line no-useless-call -- required for testing
    method.call(null, argument || function () { return 1; }, 1);
  });
};


/***/ }),

/***/ 13302:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var aCallable = __webpack_require__(2786);
var toObject = __webpack_require__(76573);
var IndexedObject = __webpack_require__(98119);
var lengthOfArrayLike = __webpack_require__(47294);

var $TypeError = TypeError;

var REDUCE_EMPTY = 'Reduce of empty array with no initial value';

// `Array.prototype.{ reduce, reduceRight }` methods implementation
var createMethod = function (IS_RIGHT) {
  return function (that, callbackfn, argumentsLength, memo) {
    var O = toObject(that);
    var self = IndexedObject(O);
    var length = lengthOfArrayLike(O);
    aCallable(callbackfn);
    if (length === 0 && argumentsLength < 2) throw new $TypeError(REDUCE_EMPTY);
    var index = IS_RIGHT ? length - 1 : 0;
    var i = IS_RIGHT ? -1 : 1;
    if (argumentsLength < 2) while (true) {
      if (index in self) {
        memo = self[index];
        index += i;
        break;
      }
      index += i;
      if (IS_RIGHT ? index < 0 : length <= index) {
        throw new $TypeError(REDUCE_EMPTY);
      }
    }
    for (;IS_RIGHT ? index >= 0 : length > index; index += i) if (index in self) {
      memo = callbackfn(memo, self[index], index, O);
    }
    return memo;
  };
};

module.exports = {
  // `Array.prototype.reduce` method
  // https://tc39.es/ecma262/#sec-array.prototype.reduce
  left: createMethod(false),
  // `Array.prototype.reduceRight` method
  // https://tc39.es/ecma262/#sec-array.prototype.reduceright
  right: createMethod(true)
};


/***/ }),

/***/ 17303:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var DESCRIPTORS = __webpack_require__(72468);
var isArray = __webpack_require__(52176);

var $TypeError = TypeError;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;

// Safari < 13 does not throw an error in this case
var SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS && !function () {
  // makes no sense without proper strict mode support
  if (this !== undefined) return true;
  try {
    // eslint-disable-next-line es/no-object-defineproperty -- safe
    Object.defineProperty([], 'length', { writable: false }).length = 1;
  } catch (error) {
    return error instanceof TypeError;
  }
}();

module.exports = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function (O, length) {
  if (isArray(O) && !getOwnPropertyDescriptor(O, 'length').writable) {
    throw new $TypeError('Cannot set read only .length');
  } return O.length = length;
} : function (O, length) {
  return O.length = length;
};


/***/ }),

/***/ 48452:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var lengthOfArrayLike = __webpack_require__(47294);

// https://tc39.es/proposal-change-array-by-copy/#sec-array.prototype.toReversed
// https://tc39.es/proposal-change-array-by-copy/#sec-%typedarray%.prototype.toReversed
module.exports = function (O, C) {
  var len = lengthOfArrayLike(O);
  var A = new C(len);
  var k = 0;
  for (; k < len; k++) A[k] = O[len - k - 1];
  return A;
};


/***/ }),

/***/ 89392:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var lengthOfArrayLike = __webpack_require__(47294);
var toIntegerOrInfinity = __webpack_require__(71939);

var $RangeError = RangeError;

// https://tc39.es/proposal-change-array-by-copy/#sec-array.prototype.with
// https://tc39.es/proposal-change-array-by-copy/#sec-%typedarray%.prototype.with
module.exports = function (O, C, index, value) {
  var len = lengthOfArrayLike(O);
  var relativeIndex = toIntegerOrInfinity(index);
  var actualIndex = relativeIndex < 0 ? len + relativeIndex : relativeIndex;
  if (actualIndex >= len || actualIndex < 0) throw new $RangeError('Incorrect index');
  var A = new C(len);
  var k = 0;
  for (; k < len; k++) A[k] = k === actualIndex ? value : O[k];
  return A;
};


/***/ }),

/***/ 632:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var uncurryThis = __webpack_require__(54936);

var toString = uncurryThis({}.toString);
var stringSlice = uncurryThis(''.slice);

module.exports = function (it) {
  return stringSlice(toString(it), 8, -1);
};


/***/ }),

/***/ 45123:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var TO_STRING_TAG_SUPPORT = __webpack_require__(2980);
var isCallable = __webpack_require__(33901);
var classofRaw = __webpack_require__(632);
var wellKnownSymbol = __webpack_require__(25723);

var TO_STRING_TAG = wellKnownSymbol('toStringTag');
var $Object = Object;

// ES3 wrong here
var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) === 'Arguments';

// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
  try {
    return it[key];
  } catch (error) { /* empty */ }
};

// getting tag from ES6+ `Object.prototype.toString`
module.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {
  var O, tag, result;
  return it === undefined ? 'Undefined' : it === null ? 'Null'
    // @@toStringTag case
    : typeof (tag = tryGet(O = $Object(it), TO_STRING_TAG)) == 'string' ? tag
    // builtinTag case
    : CORRECT_ARGUMENTS ? classofRaw(O)
    // ES3 arguments fallback
    : (result = classofRaw(O)) === 'Object' && isCallable(O.callee) ? 'Arguments' : result;
};


/***/ }),

/***/ 81988:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var hasOwn = __webpack_require__(30217);
var ownKeys = __webpack_require__(49951);
var getOwnPropertyDescriptorModule = __webpack_require__(84987);
var definePropertyModule = __webpack_require__(9609);

module.exports = function (target, source, exceptions) {
  var keys = ownKeys(source);
  var defineProperty = definePropertyModule.f;
  var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    if (!hasOwn(target, key) && !(exceptions && hasOwn(exceptions, key))) {
      defineProperty(target, key, getOwnPropertyDescriptor(source, key));
    }
  }
};


/***/ }),

/***/ 90603:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var fails = __webpack_require__(2599);

module.exports = !fails(function () {
  function F() { /* empty */ }
  F.prototype.constructor = null;
  // eslint-disable-next-line es/no-object-getprototypeof -- required for testing
  return Object.getPrototypeOf(new F()) !== F.prototype;
});


/***/ }),

/***/ 98515:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var DESCRIPTORS = __webpack_require__(72468);
var definePropertyModule = __webpack_require__(9609);
var createPropertyDescriptor = __webpack_require__(57692);

module.exports = DESCRIPTORS ? function (object, key, value) {
  return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
} : function (object, key, value) {
  object[key] = value;
  return object;
};


/***/ }),

/***/ 57692:
/***/ ((module) => {

"use strict";

module.exports = function (bitmap, value) {
  return {
    enumerable: !(bitmap & 1),
    configurable: !(bitmap & 2),
    writable: !(bitmap & 4),
    value: value
  };
};


/***/ }),

/***/ 43954:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var makeBuiltIn = __webpack_require__(57171);
var defineProperty = __webpack_require__(9609);

module.exports = function (target, name, descriptor) {
  if (descriptor.get) makeBuiltIn(descriptor.get, name, { getter: true });
  if (descriptor.set) makeBuiltIn(descriptor.set, name, { setter: true });
  return defineProperty.f(target, name, descriptor);
};


/***/ }),

/***/ 44432:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var isCallable = __webpack_require__(33901);
var definePropertyModule = __webpack_require__(9609);
var makeBuiltIn = __webpack_require__(57171);
var defineGlobalProperty = __webpack_require__(47473);

module.exports = function (O, key, value, options) {
  if (!options) options = {};
  var simple = options.enumerable;
  var name = options.name !== undefined ? options.name : key;
  if (isCallable(value)) makeBuiltIn(value, name, options);
  if (options.global) {
    if (simple) O[key] = value;
    else defineGlobalProperty(key, value);
  } else {
    try {
      if (!options.unsafe) delete O[key];
      else if (O[key]) simple = true;
    } catch (error) { /* empty */ }
    if (simple) O[key] = value;
    else definePropertyModule.f(O, key, {
      value: value,
      enumerable: false,
      configurable: !options.nonConfigurable,
      writable: !options.nonWritable
    });
  } return O;
};


/***/ }),

/***/ 47473:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var globalThis = __webpack_require__(34760);

// eslint-disable-next-line es/no-object-defineproperty -- safe
var defineProperty = Object.defineProperty;

module.exports = function (key, value) {
  try {
    defineProperty(globalThis, key, { value: value, configurable: true, writable: true });
  } catch (error) {
    globalThis[key] = value;
  } return value;
};


/***/ }),

/***/ 72468:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var fails = __webpack_require__(2599);

// Detect IE8's incomplete defineProperty implementation
module.exports = !fails(function () {
  // eslint-disable-next-line es/no-object-defineproperty -- required for testing
  return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] !== 7;
});


/***/ }),

/***/ 55391:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var globalThis = __webpack_require__(34760);
var isObject = __webpack_require__(34186);

var document = globalThis.document;
// typeof document.createElement is 'object' in old IE
var EXISTS = isObject(document) && isObject(document.createElement);

module.exports = function (it) {
  return EXISTS ? document.createElement(it) : {};
};


/***/ }),

/***/ 56381:
/***/ ((module) => {

"use strict";

var $TypeError = TypeError;
var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; // 2 ** 53 - 1 == 9007199254740991

module.exports = function (it) {
  if (it > MAX_SAFE_INTEGER) throw $TypeError('Maximum allowed index exceeded');
  return it;
};


/***/ }),

/***/ 76146:
/***/ ((module) => {

"use strict";

module.exports = {
  IndexSizeError: { s: 'INDEX_SIZE_ERR', c: 1, m: 1 },
  DOMStringSizeError: { s: 'DOMSTRING_SIZE_ERR', c: 2, m: 0 },
  HierarchyRequestError: { s: 'HIERARCHY_REQUEST_ERR', c: 3, m: 1 },
  WrongDocumentError: { s: 'WRONG_DOCUMENT_ERR', c: 4, m: 1 },
  InvalidCharacterError: { s: 'INVALID_CHARACTER_ERR', c: 5, m: 1 },
  NoDataAllowedError: { s: 'NO_DATA_ALLOWED_ERR', c: 6, m: 0 },
  NoModificationAllowedError: { s: 'NO_MODIFICATION_ALLOWED_ERR', c: 7, m: 1 },
  NotFoundError: { s: 'NOT_FOUND_ERR', c: 8, m: 1 },
  NotSupportedError: { s: 'NOT_SUPPORTED_ERR', c: 9, m: 1 },
  InUseAttributeError: { s: 'INUSE_ATTRIBUTE_ERR', c: 10, m: 1 },
  InvalidStateError: { s: 'INVALID_STATE_ERR', c: 11, m: 1 },
  SyntaxError: { s: 'SYNTAX_ERR', c: 12, m: 1 },
  InvalidModificationError: { s: 'INVALID_MODIFICATION_ERR', c: 13, m: 1 },
  NamespaceError: { s: 'NAMESPACE_ERR', c: 14, m: 1 },
  InvalidAccessError: { s: 'INVALID_ACCESS_ERR', c: 15, m: 1 },
  ValidationError: { s: 'VALIDATION_ERR', c: 16, m: 0 },
  TypeMismatchError: { s: 'TYPE_MISMATCH_ERR', c: 17, m: 1 },
  SecurityError: { s: 'SECURITY_ERR', c: 18, m: 1 },
  NetworkError: { s: 'NETWORK_ERR', c: 19, m: 1 },
  AbortError: { s: 'ABORT_ERR', c: 20, m: 1 },
  URLMismatchError: { s: 'URL_MISMATCH_ERR', c: 21, m: 1 },
  QuotaExceededError: { s: 'QUOTA_EXCEEDED_ERR', c: 22, m: 1 },
  TimeoutError: { s: 'TIMEOUT_ERR', c: 23, m: 1 },
  InvalidNodeTypeError: { s: 'INVALID_NODE_TYPE_ERR', c: 24, m: 1 },
  DataCloneError: { s: 'DATA_CLONE_ERR', c: 25, m: 1 }
};


/***/ }),

/***/ 77343:
/***/ ((module) => {

"use strict";

// IE8- don't enum bug keys
module.exports = [
  'constructor',
  'hasOwnProperty',
  'isPrototypeOf',
  'propertyIsEnumerable',
  'toLocaleString',
  'toString',
  'valueOf'
];


/***/ }),

/***/ 9273:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var ENVIRONMENT = __webpack_require__(55327);

module.exports = ENVIRONMENT === 'NODE';


/***/ }),

/***/ 74623:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var globalThis = __webpack_require__(34760);

var navigator = globalThis.navigator;
var userAgent = navigator && navigator.userAgent;

module.exports = userAgent ? String(userAgent) : '';


/***/ }),

/***/ 6839:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var globalThis = __webpack_require__(34760);
var userAgent = __webpack_require__(74623);

var process = globalThis.process;
var Deno = globalThis.Deno;
var versions = process && process.versions || Deno && Deno.version;
var v8 = versions && versions.v8;
var match, version;

if (v8) {
  match = v8.split('.');
  // in old Chrome, versions of V8 isn't V8 = Chrome / 10
  // but their correct versions are not interesting for us
  version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]);
}

// BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`
// so check `userAgent` even if `.v8` exists, but 0
if (!version && userAgent) {
  match = userAgent.match(/Edge\/(\d+)/);
  if (!match || match[1] >= 74) {
    match = userAgent.match(/Chrome\/(\d+)/);
    if (match) version = +match[1];
  }
}

module.exports = version;


/***/ }),

/***/ 55327:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

/* global Bun, Deno -- detection */
var globalThis = __webpack_require__(34760);
var userAgent = __webpack_require__(74623);
var classof = __webpack_require__(632);

var userAgentStartsWith = function (string) {
  return userAgent.slice(0, string.length) === string;
};

module.exports = (function () {
  if (userAgentStartsWith('Bun/')) return 'BUN';
  if (userAgentStartsWith('Cloudflare-Workers')) return 'CLOUDFLARE';
  if (userAgentStartsWith('Deno/')) return 'DENO';
  if (userAgentStartsWith('Node.js/')) return 'NODE';
  if (globalThis.Bun && typeof Bun.version == 'string') return 'BUN';
  if (globalThis.Deno && typeof Deno.version == 'object') return 'DENO';
  if (classof(globalThis.process) === 'process') return 'NODE';
  if (globalThis.window && globalThis.document) return 'BROWSER';
  return 'REST';
})();


/***/ }),

/***/ 96345:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var uncurryThis = __webpack_require__(54936);

var $Error = Error;
var replace = uncurryThis(''.replace);

var TEST = (function (arg) { return String(new $Error(arg).stack); })('zxcasd');
// eslint-disable-next-line redos/no-vulnerable, sonarjs/slow-regex -- safe
var V8_OR_CHAKRA_STACK_ENTRY = /\n\s*at [^:]*:[^\n]*/;
var IS_V8_OR_CHAKRA_STACK = V8_OR_CHAKRA_STACK_ENTRY.test(TEST);

module.exports = function (stack, dropEntries) {
  if (IS_V8_OR_CHAKRA_STACK && typeof stack == 'string' && !$Error.prepareStackTrace) {
    while (dropEntries--) stack = replace(stack, V8_OR_CHAKRA_STACK_ENTRY, '');
  } return stack;
};


/***/ }),

/***/ 15827:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var createNonEnumerableProperty = __webpack_require__(98515);
var clearErrorStack = __webpack_require__(96345);
var ERROR_STACK_INSTALLABLE = __webpack_require__(11179);

// non-standard V8
var captureStackTrace = Error.captureStackTrace;

module.exports = function (error, C, stack, dropEntries) {
  if (ERROR_STACK_INSTALLABLE) {
    if (captureStackTrace) captureStackTrace(error, C);
    else createNonEnumerableProperty(error, 'stack', clearErrorStack(stack, dropEntries));
  }
};


/***/ }),

/***/ 11179:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var fails = __webpack_require__(2599);
var createPropertyDescriptor = __webpack_require__(57692);

module.exports = !fails(function () {
  var error = new Error('a');
  if (!('stack' in error)) return true;
  // eslint-disable-next-line es/no-object-defineproperty -- safe
  Object.defineProperty(error, 'stack', createPropertyDescriptor(1, 7));
  return error.stack !== 7;
});


/***/ }),

/***/ 79214:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var globalThis = __webpack_require__(34760);
var getOwnPropertyDescriptor = (__webpack_require__(84987).f);
var createNonEnumerableProperty = __webpack_require__(98515);
var defineBuiltIn = __webpack_require__(44432);
var defineGlobalProperty = __webpack_require__(47473);
var copyConstructorProperties = __webpack_require__(81988);
var isForced = __webpack_require__(46612);

/*
  options.target         - name of the target object
  options.global         - target is the global object
  options.stat           - export as static methods of target
  options.proto          - export as prototype methods of target
  options.real           - real prototype method for the `pure` version
  options.forced         - export even if the native feature is available
  options.bind           - bind methods to the target, required for the `pure` version
  options.wrap           - wrap constructors to preventing global pollution, required for the `pure` version
  options.unsafe         - use the simple assignment of property instead of delete + defineProperty
  options.sham           - add a flag to not completely full polyfills
  options.enumerable     - export as enumerable property
  options.dontCallGetSet - prevent calling a getter on target
  options.name           - the .name of the function if it does not match the key
*/
module.exports = function (options, source) {
  var TARGET = options.target;
  var GLOBAL = options.global;
  var STATIC = options.stat;
  var FORCED, target, key, targetProperty, sourceProperty, descriptor;
  if (GLOBAL) {
    target = globalThis;
  } else if (STATIC) {
    target = globalThis[TARGET] || defineGlobalProperty(TARGET, {});
  } else {
    target = globalThis[TARGET] && globalThis[TARGET].prototype;
  }
  if (target) for (key in source) {
    sourceProperty = source[key];
    if (options.dontCallGetSet) {
      descriptor = getOwnPropertyDescriptor(target, key);
      targetProperty = descriptor && descriptor.value;
    } else targetProperty = target[key];
    FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
    // contained in target
    if (!FORCED && targetProperty !== undefined) {
      if (typeof sourceProperty == typeof targetProperty) continue;
      copyConstructorProperties(sourceProperty, targetProperty);
    }
    // add a flag to not completely full polyfills
    if (options.sham || (targetProperty && targetProperty.sham)) {
      createNonEnumerableProperty(sourceProperty, 'sham', true);
    }
    defineBuiltIn(target, key, sourceProperty, options);
  }
};


/***/ }),

/***/ 2599:
/***/ ((module) => {

"use strict";

module.exports = function (exec) {
  try {
    return !!exec();
  } catch (error) {
    return true;
  }
};


/***/ }),

/***/ 78881:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var NATIVE_BIND = __webpack_require__(10592);

var FunctionPrototype = Function.prototype;
var apply = FunctionPrototype.apply;
var call = FunctionPrototype.call;

// eslint-disable-next-line es/no-function-prototype-bind, es/no-reflect -- safe
module.exports = typeof Reflect == 'object' && Reflect.apply || (NATIVE_BIND ? call.bind(apply) : function () {
  return call.apply(apply, arguments);
});


/***/ }),

/***/ 82184:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var uncurryThis = __webpack_require__(76812);
var aCallable = __webpack_require__(2786);
var NATIVE_BIND = __webpack_require__(10592);

var bind = uncurryThis(uncurryThis.bind);

// optional / simple context binding
module.exports = function (fn, that) {
  aCallable(fn);
  return that === undefined ? fn : NATIVE_BIND ? bind(fn, that) : function (/* ...args */) {
    return fn.apply(that, arguments);
  };
};


/***/ }),

/***/ 10592:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var fails = __webpack_require__(2599);

module.exports = !fails(function () {
  // eslint-disable-next-line es/no-function-prototype-bind -- safe
  var test = (function () { /* empty */ }).bind();
  // eslint-disable-next-line no-prototype-builtins -- safe
  return typeof test != 'function' || test.hasOwnProperty('prototype');
});


/***/ }),

/***/ 12341:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var NATIVE_BIND = __webpack_require__(10592);

var call = Function.prototype.call;
// eslint-disable-next-line es/no-function-prototype-bind -- safe
module.exports = NATIVE_BIND ? call.bind(call) : function () {
  return call.apply(call, arguments);
};


/***/ }),

/***/ 23942:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var DESCRIPTORS = __webpack_require__(72468);
var hasOwn = __webpack_require__(30217);

var FunctionPrototype = Function.prototype;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var getDescriptor = DESCRIPTORS && Object.getOwnPropertyDescriptor;

var EXISTS = hasOwn(FunctionPrototype, 'name');
// additional protection from minified / mangled / dropped function names
var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something';
var CONFIGURABLE = EXISTS && (!DESCRIPTORS || (DESCRIPTORS && getDescriptor(FunctionPrototype, 'name').configurable));

module.exports = {
  EXISTS: EXISTS,
  PROPER: PROPER,
  CONFIGURABLE: CONFIGURABLE
};


/***/ }),

/***/ 76298:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var uncurryThis = __webpack_require__(54936);
var aCallable = __webpack_require__(2786);

module.exports = function (object, key, method) {
  try {
    // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
    return uncurryThis(aCallable(Object.getOwnPropertyDescriptor(object, key)[method]));
  } catch (error) { /* empty */ }
};


/***/ }),

/***/ 76812:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var classofRaw = __webpack_require__(632);
var uncurryThis = __webpack_require__(54936);

module.exports = function (fn) {
  // Nashorn bug:
  //   https://github.com/zloirock/core-js/issues/1128
  //   https://github.com/zloirock/core-js/issues/1130
  if (classofRaw(fn) === 'Function') return uncurryThis(fn);
};


/***/ }),

/***/ 54936:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var NATIVE_BIND = __webpack_require__(10592);

var FunctionPrototype = Function.prototype;
var call = FunctionPrototype.call;
// eslint-disable-next-line es/no-function-prototype-bind -- safe
var uncurryThisWithBind = NATIVE_BIND && FunctionPrototype.bind.bind(call, call);

module.exports = NATIVE_BIND ? uncurryThisWithBind : function (fn) {
  return function () {
    return call.apply(fn, arguments);
  };
};


/***/ }),

/***/ 19631:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var globalThis = __webpack_require__(34760);
var isCallable = __webpack_require__(33901);

var aFunction = function (argument) {
  return isCallable(argument) ? argument : undefined;
};

module.exports = function (namespace, method) {
  return arguments.length < 2 ? aFunction(globalThis[namespace]) : globalThis[namespace] && globalThis[namespace][method];
};


/***/ }),

/***/ 67734:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var aCallable = __webpack_require__(2786);
var isNullOrUndefined = __webpack_require__(46013);

// `GetMethod` abstract operation
// https://tc39.es/ecma262/#sec-getmethod
module.exports = function (V, P) {
  var func = V[P];
  return isNullOrUndefined(func) ? undefined : aCallable(func);
};


/***/ }),

/***/ 91414:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var uncurryThis = __webpack_require__(54936);
var toObject = __webpack_require__(76573);

var floor = Math.floor;
var charAt = uncurryThis(''.charAt);
var replace = uncurryThis(''.replace);
var stringSlice = uncurryThis(''.slice);
// eslint-disable-next-line redos/no-vulnerable -- safe
var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d{1,2}|<[^>]*>)/g;
var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d{1,2})/g;

// `GetSubstitution` abstract operation
// https://tc39.es/ecma262/#sec-getsubstitution
module.exports = function (matched, str, position, captures, namedCaptures, replacement) {
  var tailPos = position + matched.length;
  var m = captures.length;
  var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED;
  if (namedCaptures !== undefined) {
    namedCaptures = toObject(namedCaptures);
    symbols = SUBSTITUTION_SYMBOLS;
  }
  return replace(replacement, symbols, function (match, ch) {
    var capture;
    switch (charAt(ch, 0)) {
      case '$': return '$';
      case '&': return matched;
      case '`': return stringSlice(str, 0, position);
      case "'": return stringSlice(str, tailPos);
      case '<':
        capture = namedCaptures[stringSlice(ch, 1, -1)];
        break;
      default: // \d\d?
        var n = +ch;
        if (n === 0) return match;
        if (n > m) {
          var f = floor(n / 10);
          if (f === 0) return match;
          if (f <= m) return captures[f - 1] === undefined ? charAt(ch, 1) : captures[f - 1] + charAt(ch, 1);
          return match;
        }
        capture = captures[n - 1];
    }
    return capture === undefined ? '' : capture;
  });
};


/***/ }),

/***/ 34760:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {

"use strict";

var check = function (it) {
  return it && it.Math === Math && it;
};

// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
module.exports =
  // eslint-disable-next-line es/no-global-this -- safe
  check(typeof globalThis == 'object' && globalThis) ||
  check(typeof window == 'object' && window) ||
  // eslint-disable-next-line no-restricted-globals -- safe
  check(typeof self == 'object' && self) ||
  check(typeof __webpack_require__.g == 'object' && __webpack_require__.g) ||
  check(typeof this == 'object' && this) ||
  // eslint-disable-next-line no-new-func -- fallback
  (function () { return this; })() || Function('return this')();


/***/ }),

/***/ 30217:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var uncurryThis = __webpack_require__(54936);
var toObject = __webpack_require__(76573);

var hasOwnProperty = uncurryThis({}.hasOwnProperty);

// `HasOwnProperty` abstract operation
// https://tc39.es/ecma262/#sec-hasownproperty
// eslint-disable-next-line es/no-object-hasown -- safe
module.exports = Object.hasOwn || function hasOwn(it, key) {
  return hasOwnProperty(toObject(it), key);
};


/***/ }),

/***/ 45149:
/***/ ((module) => {

"use strict";

module.exports = {};


/***/ }),

/***/ 3733:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var getBuiltIn = __webpack_require__(19631);

module.exports = getBuiltIn('document', 'documentElement');


/***/ }),

/***/ 65125:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var DESCRIPTORS = __webpack_require__(72468);
var fails = __webpack_require__(2599);
var createElement = __webpack_require__(55391);

// Thanks to IE8 for its funny defineProperty
module.exports = !DESCRIPTORS && !fails(function () {
  // eslint-disable-next-line es/no-object-defineproperty -- required for testing
  return Object.defineProperty(createElement('div'), 'a', {
    get: function () { return 7; }
  }).a !== 7;
});


/***/ }),

/***/ 98119:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var uncurryThis = __webpack_require__(54936);
var fails = __webpack_require__(2599);
var classof = __webpack_require__(632);

var $Object = Object;
var split = uncurryThis(''.split);

// fallback for non-array-like ES3 and non-enumerable old V8 strings
module.exports = fails(function () {
  // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
  // eslint-disable-next-line no-prototype-builtins -- safe
  return !$Object('z').propertyIsEnumerable(0);
}) ? function (it) {
  return classof(it) === 'String' ? split(it, '') : $Object(it);
} : $Object;


/***/ }),

/***/ 88359:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var isCallable = __webpack_require__(33901);
var isObject = __webpack_require__(34186);
var setPrototypeOf = __webpack_require__(45407);

// makes subclassing work correct for wrapped built-ins
module.exports = function ($this, dummy, Wrapper) {
  var NewTarget, NewTargetPrototype;
  if (
    // it can work only with native `setPrototypeOf`
    setPrototypeOf &&
    // we haven't completely correct pre-ES6 way for getting `new.target`, so use this
    isCallable(NewTarget = dummy.constructor) &&
    NewTarget !== Wrapper &&
    isObject(NewTargetPrototype = NewTarget.prototype) &&
    NewTargetPrototype !== Wrapper.prototype
  ) setPrototypeOf($this, NewTargetPrototype);
  return $this;
};


/***/ }),

/***/ 37858:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var uncurryThis = __webpack_require__(54936);
var isCallable = __webpack_require__(33901);
var store = __webpack_require__(99781);

var functionToString = uncurryThis(Function.toString);

// this helper broken in `core-js@3.4.1-3.4.4`, so we can't use `shared` helper
if (!isCallable(store.inspectSource)) {
  store.inspectSource = function (it) {
    return functionToString(it);
  };
}

module.exports = store.inspectSource;


/***/ }),

/***/ 68424:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var isObject = __webpack_require__(34186);
var createNonEnumerableProperty = __webpack_require__(98515);

// `InstallErrorCause` abstract operation
// https://tc39.es/proposal-error-cause/#sec-errorobjects-install-error-cause
module.exports = function (O, options) {
  if (isObject(options) && 'cause' in options) {
    createNonEnumerableProperty(O, 'cause', options.cause);
  }
};


/***/ }),

/***/ 37813:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var NATIVE_WEAK_MAP = __webpack_require__(51366);
var globalThis = __webpack_require__(34760);
var isObject = __webpack_require__(34186);
var createNonEnumerableProperty = __webpack_require__(98515);
var hasOwn = __webpack_require__(30217);
var shared = __webpack_require__(99781);
var sharedKey = __webpack_require__(41279);
var hiddenKeys = __webpack_require__(45149);

var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
var TypeError = globalThis.TypeError;
var WeakMap = globalThis.WeakMap;
var set, get, has;

var enforce = function (it) {
  return has(it) ? get(it) : set(it, {});
};

var getterFor = function (TYPE) {
  return function (it) {
    var state;
    if (!isObject(it) || (state = get(it)).type !== TYPE) {
      throw new TypeError('Incompatible receiver, ' + TYPE + ' required');
    } return state;
  };
};

if (NATIVE_WEAK_MAP || shared.state) {
  var store = shared.state || (shared.state = new WeakMap());
  /* eslint-disable no-self-assign -- prototype methods protection */
  store.get = store.get;
  store.has = store.has;
  store.set = store.set;
  /* eslint-enable no-self-assign -- prototype methods protection */
  set = function (it, metadata) {
    if (store.has(it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
    metadata.facade = it;
    store.set(it, metadata);
    return metadata;
  };
  get = function (it) {
    return store.get(it) || {};
  };
  has = function (it) {
    return store.has(it);
  };
} else {
  var STATE = sharedKey('state');
  hiddenKeys[STATE] = true;
  set = function (it, metadata) {
    if (hasOwn(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
    metadata.facade = it;
    createNonEnumerableProperty(it, STATE, metadata);
    return metadata;
  };
  get = function (it) {
    return hasOwn(it, STATE) ? it[STATE] : {};
  };
  has = function (it) {
    return hasOwn(it, STATE);
  };
}

module.exports = {
  set: set,
  get: get,
  has: has,
  enforce: enforce,
  getterFor: getterFor
};


/***/ }),

/***/ 52176:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var classof = __webpack_require__(632);

// `IsArray` abstract operation
// https://tc39.es/ecma262/#sec-isarray
// eslint-disable-next-line es/no-array-isarray -- safe
module.exports = Array.isArray || function isArray(argument) {
  return classof(argument) === 'Array';
};


/***/ }),

/***/ 60735:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var classof = __webpack_require__(45123);

module.exports = function (it) {
  var klass = classof(it);
  return klass === 'BigInt64Array' || klass === 'BigUint64Array';
};


/***/ }),

/***/ 33901:
/***/ ((module) => {

"use strict";

// https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot
var documentAll = typeof document == 'object' && document.all;

// `IsCallable` abstract operation
// https://tc39.es/ecma262/#sec-iscallable
// eslint-disable-next-line unicorn/no-typeof-undefined -- required for testing
module.exports = typeof documentAll == 'undefined' && documentAll !== undefined ? function (argument) {
  return typeof argument == 'function' || argument === documentAll;
} : function (argument) {
  return typeof argument == 'function';
};


/***/ }),

/***/ 46612:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var fails = __webpack_require__(2599);
var isCallable = __webpack_require__(33901);

var replacement = /#|\.prototype\./;

var isForced = function (feature, detection) {
  var value = data[normalize(feature)];
  return value === POLYFILL ? true
    : value === NATIVE ? false
    : isCallable(detection) ? fails(detection)
    : !!detection;
};

var normalize = isForced.normalize = function (string) {
  return String(string).replace(replacement, '.').toLowerCase();
};

var data = isForced.data = {};
var NATIVE = isForced.NATIVE = 'N';
var POLYFILL = isForced.POLYFILL = 'P';

module.exports = isForced;


/***/ }),

/***/ 46013:
/***/ ((module) => {

"use strict";

// we can't use just `it == null` since of `document.all` special case
// https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec
module.exports = function (it) {
  return it === null || it === undefined;
};


/***/ }),

/***/ 34186:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var isCallable = __webpack_require__(33901);

module.exports = function (it) {
  return typeof it == 'object' ? it !== null : isCallable(it);
};


/***/ }),

/***/ 26493:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var isObject = __webpack_require__(34186);

module.exports = function (argument) {
  return isObject(argument) || argument === null;
};


/***/ }),

/***/ 28595:
/***/ ((module) => {

"use strict";

module.exports = false;


/***/ }),

/***/ 25292:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var isObject = __webpack_require__(34186);
var classof = __webpack_require__(632);
var wellKnownSymbol = __webpack_require__(25723);

var MATCH = wellKnownSymbol('match');

// `IsRegExp` abstract operation
// https://tc39.es/ecma262/#sec-isregexp
module.exports = function (it) {
  var isRegExp;
  return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : classof(it) === 'RegExp');
};


/***/ }),

/***/ 32813:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var getBuiltIn = __webpack_require__(19631);
var isCallable = __webpack_require__(33901);
var isPrototypeOf = __webpack_require__(44657);
var USE_SYMBOL_AS_UID = __webpack_require__(79816);

var $Object = Object;

module.exports = USE_SYMBOL_AS_UID ? function (it) {
  return typeof it == 'symbol';
} : function (it) {
  var $Symbol = getBuiltIn('Symbol');
  return isCallable($Symbol) && isPrototypeOf($Symbol.prototype, $Object(it));
};


/***/ }),

/***/ 47294:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var toLength = __webpack_require__(72406);

// `LengthOfArrayLike` abstract operation
// https://tc39.es/ecma262/#sec-lengthofarraylike
module.exports = function (obj) {
  return toLength(obj.length);
};


/***/ }),

/***/ 57171:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var uncurryThis = __webpack_require__(54936);
var fails = __webpack_require__(2599);
var isCallable = __webpack_require__(33901);
var hasOwn = __webpack_require__(30217);
var DESCRIPTORS = __webpack_require__(72468);
var CONFIGURABLE_FUNCTION_NAME = (__webpack_require__(23942).CONFIGURABLE);
var inspectSource = __webpack_require__(37858);
var InternalStateModule = __webpack_require__(37813);

var enforceInternalState = InternalStateModule.enforce;
var getInternalState = InternalStateModule.get;
var $String = String;
// eslint-disable-next-line es/no-object-defineproperty -- safe
var defineProperty = Object.defineProperty;
var stringSlice = uncurryThis(''.slice);
var replace = uncurryThis(''.replace);
var join = uncurryThis([].join);

var CONFIGURABLE_LENGTH = DESCRIPTORS && !fails(function () {
  return defineProperty(function () { /* empty */ }, 'length', { value: 8 }).length !== 8;
});

var TEMPLATE = String(String).split('String');

var makeBuiltIn = module.exports = function (value, name, options) {
  if (stringSlice($String(name), 0, 7) === 'Symbol(') {
    name = '[' + replace($String(name), /^Symbol\(([^)]*)\).*$/, '$1') + ']';
  }
  if (options && options.getter) name = 'get ' + name;
  if (options && options.setter) name = 'set ' + name;
  if (!hasOwn(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) {
    if (DESCRIPTORS) defineProperty(value, 'name', { value: name, configurable: true });
    else value.name = name;
  }
  if (CONFIGURABLE_LENGTH && options && hasOwn(options, 'arity') && value.length !== options.arity) {
    defineProperty(value, 'length', { value: options.arity });
  }
  try {
    if (options && hasOwn(options, 'constructor') && options.constructor) {
      if (DESCRIPTORS) defineProperty(value, 'prototype', { writable: false });
    // in V8 ~ Chrome 53, prototypes of some methods, like `Array.prototype.values`, are non-writable
    } else if (value.prototype) value.prototype = undefined;
  } catch (error) { /* empty */ }
  var state = enforceInternalState(value);
  if (!hasOwn(state, 'source')) {
    state.source = join(TEMPLATE, typeof name == 'string' ? name : '');
  } return value;
};

// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
// eslint-disable-next-line no-extend-native -- required
Function.prototype.toString = makeBuiltIn(function toString() {
  return isCallable(this) && getInternalState(this).source || inspectSource(this);
}, 'toString');


/***/ }),

/***/ 93149:
/***/ ((module) => {

"use strict";

var ceil = Math.ceil;
var floor = Math.floor;

// `Math.trunc` method
// https://tc39.es/ecma262/#sec-math.trunc
// eslint-disable-next-line es/no-math-trunc -- safe
module.exports = Math.trunc || function trunc(x) {
  var n = +x;
  return (n > 0 ? floor : ceil)(n);
};


/***/ }),

/***/ 92867:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var toString = __webpack_require__(93207);

module.exports = function (argument, $default) {
  return argument === undefined ? arguments.length < 2 ? '' : $default : toString(argument);
};


/***/ }),

/***/ 66736:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

/* global ActiveXObject -- old IE, WSH */
var anObject = __webpack_require__(93263);
var definePropertiesModule = __webpack_require__(82201);
var enumBugKeys = __webpack_require__(77343);
var hiddenKeys = __webpack_require__(45149);
var html = __webpack_require__(3733);
var documentCreateElement = __webpack_require__(55391);
var sharedKey = __webpack_require__(41279);

var GT = '>';
var LT = '<';
var PROTOTYPE = 'prototype';
var SCRIPT = 'script';
var IE_PROTO = sharedKey('IE_PROTO');

var EmptyConstructor = function () { /* empty */ };

var scriptTag = function (content) {
  return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
};

// Create object with fake `null` prototype: use ActiveX Object with cleared prototype
var NullProtoObjectViaActiveX = function (activeXDocument) {
  activeXDocument.write(scriptTag(''));
  activeXDocument.close();
  var temp = activeXDocument.parentWindow.Object;
  // eslint-disable-next-line no-useless-assignment -- avoid memory leak
  activeXDocument = null;
  return temp;
};

// Create object with fake `null` prototype: use iframe Object with cleared prototype
var NullProtoObjectViaIFrame = function () {
  // Thrash, waste and sodomy: IE GC bug
  var iframe = documentCreateElement('iframe');
  var JS = 'java' + SCRIPT + ':';
  var iframeDocument;
  iframe.style.display = 'none';
  html.appendChild(iframe);
  // https://github.com/zloirock/core-js/issues/475
  iframe.src = String(JS);
  iframeDocument = iframe.contentWindow.document;
  iframeDocument.open();
  iframeDocument.write(scriptTag('document.F=Object'));
  iframeDocument.close();
  return iframeDocument.F;
};

// Check for document.domain and active x support
// No need to use active x approach when document.domain is not set
// see https://github.com/es-shims/es5-shim/issues/150
// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
// avoid IE GC bug
var activeXDocument;
var NullProtoObject = function () {
  try {
    activeXDocument = new ActiveXObject('htmlfile');
  } catch (error) { /* ignore */ }
  NullProtoObject = typeof document != 'undefined'
    ? document.domain && activeXDocument
      ? NullProtoObjectViaActiveX(activeXDocument) // old IE
      : NullProtoObjectViaIFrame()
    : NullProtoObjectViaActiveX(activeXDocument); // WSH
  var length = enumBugKeys.length;
  while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];
  return NullProtoObject();
};

hiddenKeys[IE_PROTO] = true;

// `Object.create` method
// https://tc39.es/ecma262/#sec-object.create
// eslint-disable-next-line es/no-object-create -- safe
module.exports = Object.create || function create(O, Properties) {
  var result;
  if (O !== null) {
    EmptyConstructor[PROTOTYPE] = anObject(O);
    result = new EmptyConstructor();
    EmptyConstructor[PROTOTYPE] = null;
    // add "__proto__" for Object.getPrototypeOf polyfill
    result[IE_PROTO] = O;
  } else result = NullProtoObject();
  return Properties === undefined ? result : definePropertiesModule.f(result, Properties);
};


/***/ }),

/***/ 82201:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

var DESCRIPTORS = __webpack_require__(72468);
var V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(20102);
var definePropertyModule = __webpack_require__(9609);
var anObject = __webpack_require__(93263);
var toIndexedObject = __webpack_require__(42173);
var objectKeys = __webpack_require__(20600);

// `Object.defineProperties` method
// https://tc39.es/ecma262/#sec-object.defineproperties
// eslint-disable-next-line es/no-object-defineproperties -- safe
exports.f = DESCRIPTORS && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) {
  anObject(O);
  var props = toIndexedObject(Properties);
  var keys = objectKeys(Properties);
  var length = keys.length;
  var index = 0;
  var key;
  while (length > index) definePropertyModule.f(O, key = keys[index++], props[key]);
  return O;
};


/***/ }),

/***/ 9609:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

var DESCRIPTORS = __webpack_require__(72468);
var IE8_DOM_DEFINE = __webpack_require__(65125);
var V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(20102);
var anObject = __webpack_require__(93263);
var toPropertyKey = __webpack_require__(89153);

var $TypeError = TypeError;
// eslint-disable-next-line es/no-object-defineproperty -- safe
var $defineProperty = Object.defineProperty;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var ENUMERABLE = 'enumerable';
var CONFIGURABLE = 'configurable';
var WRITABLE = 'writable';

// `Object.defineProperty` method
// https://tc39.es/ecma262/#sec-object.defineproperty
exports.f = DESCRIPTORS ? V8_PROTOTYPE_DEFINE_BUG ? function defineProperty(O, P, Attributes) {
  anObject(O);
  P = toPropertyKey(P);
  anObject(Attributes);
  if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) {
    var current = $getOwnPropertyDescriptor(O, P);
    if (current && current[WRITABLE]) {
      O[P] = Attributes.value;
      Attributes = {
        configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE],
        enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE],
        writable: false
      };
    }
  } return $defineProperty(O, P, Attributes);
} : $defineProperty : function defineProperty(O, P, Attributes) {
  anObject(O);
  P = toPropertyKey(P);
  anObject(Attributes);
  if (IE8_DOM_DEFINE) try {
    return $defineProperty(O, P, Attributes);
  } catch (error) { /* empty */ }
  if ('get' in Attributes || 'set' in Attributes) throw new $TypeError('Accessors not supported');
  if ('value' in Attributes) O[P] = Attributes.value;
  return O;
};


/***/ }),

/***/ 84987:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

var DESCRIPTORS = __webpack_require__(72468);
var call = __webpack_require__(12341);
var propertyIsEnumerableModule = __webpack_require__(72349);
var createPropertyDescriptor = __webpack_require__(57692);
var toIndexedObject = __webpack_require__(42173);
var toPropertyKey = __webpack_require__(89153);
var hasOwn = __webpack_require__(30217);
var IE8_DOM_DEFINE = __webpack_require__(65125);

// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;

// `Object.getOwnPropertyDescriptor` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
exports.f = DESCRIPTORS ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
  O = toIndexedObject(O);
  P = toPropertyKey(P);
  if (IE8_DOM_DEFINE) try {
    return $getOwnPropertyDescriptor(O, P);
  } catch (error) { /* empty */ }
  if (hasOwn(O, P)) return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]);
};


/***/ }),

/***/ 55384:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

var internalObjectKeys = __webpack_require__(29340);
var enumBugKeys = __webpack_require__(77343);

var hiddenKeys = enumBugKeys.concat('length', 'prototype');

// `Object.getOwnPropertyNames` method
// https://tc39.es/ecma262/#sec-object.getownpropertynames
// eslint-disable-next-line es/no-object-getownpropertynames -- safe
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
  return internalObjectKeys(O, hiddenKeys);
};


/***/ }),

/***/ 19965:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

// eslint-disable-next-line es/no-object-getownpropertysymbols -- safe
exports.f = Object.getOwnPropertySymbols;


/***/ }),

/***/ 73595:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var hasOwn = __webpack_require__(30217);
var isCallable = __webpack_require__(33901);
var toObject = __webpack_require__(76573);
var sharedKey = __webpack_require__(41279);
var CORRECT_PROTOTYPE_GETTER = __webpack_require__(90603);

var IE_PROTO = sharedKey('IE_PROTO');
var $Object = Object;
var ObjectPrototype = $Object.prototype;

// `Object.getPrototypeOf` method
// https://tc39.es/ecma262/#sec-object.getprototypeof
// eslint-disable-next-line es/no-object-getprototypeof -- safe
module.exports = CORRECT_PROTOTYPE_GETTER ? $Object.getPrototypeOf : function (O) {
  var object = toObject(O);
  if (hasOwn(object, IE_PROTO)) return object[IE_PROTO];
  var constructor = object.constructor;
  if (isCallable(constructor) && object instanceof constructor) {
    return constructor.prototype;
  } return object instanceof $Object ? ObjectPrototype : null;
};


/***/ }),

/***/ 44657:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var uncurryThis = __webpack_require__(54936);

module.exports = uncurryThis({}.isPrototypeOf);


/***/ }),

/***/ 29340:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var uncurryThis = __webpack_require__(54936);
var hasOwn = __webpack_require__(30217);
var toIndexedObject = __webpack_require__(42173);
var indexOf = (__webpack_require__(5865).indexOf);
var hiddenKeys = __webpack_require__(45149);

var push = uncurryThis([].push);

module.exports = function (object, names) {
  var O = toIndexedObject(object);
  var i = 0;
  var result = [];
  var key;
  for (key in O) !hasOwn(hiddenKeys, key) && hasOwn(O, key) && push(result, key);
  // Don't enum bug & hidden keys
  while (names.length > i) if (hasOwn(O, key = names[i++])) {
    ~indexOf(result, key) || push(result, key);
  }
  return result;
};


/***/ }),

/***/ 20600:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var internalObjectKeys = __webpack_require__(29340);
var enumBugKeys = __webpack_require__(77343);

// `Object.keys` method
// https://tc39.es/ecma262/#sec-object.keys
// eslint-disable-next-line es/no-object-keys -- safe
module.exports = Object.keys || function keys(O) {
  return internalObjectKeys(O, enumBugKeys);
};


/***/ }),

/***/ 72349:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

var $propertyIsEnumerable = {}.propertyIsEnumerable;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;

// Nashorn ~ JDK8 bug
var NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ 1: 2 }, 1);

// `Object.prototype.propertyIsEnumerable` method implementation
// https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
  var descriptor = getOwnPropertyDescriptor(this, V);
  return !!descriptor && descriptor.enumerable;
} : $propertyIsEnumerable;


/***/ }),

/***/ 45407:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

/* eslint-disable no-proto -- safe */
var uncurryThisAccessor = __webpack_require__(76298);
var isObject = __webpack_require__(34186);
var requireObjectCoercible = __webpack_require__(98654);
var aPossiblePrototype = __webpack_require__(55034);

// `Object.setPrototypeOf` method
// https://tc39.es/ecma262/#sec-object.setprototypeof
// Works with __proto__ only. Old v8 can't work with null proto objects.
// eslint-disable-next-line es/no-object-setprototypeof -- safe
module.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () {
  var CORRECT_SETTER = false;
  var test = {};
  var setter;
  try {
    setter = uncurryThisAccessor(Object.prototype, '__proto__', 'set');
    setter(test, []);
    CORRECT_SETTER = test instanceof Array;
  } catch (error) { /* empty */ }
  return function setPrototypeOf(O, proto) {
    requireObjectCoercible(O);
    aPossiblePrototype(proto);
    if (!isObject(O)) return O;
    if (CORRECT_SETTER) setter(O, proto);
    else O.__proto__ = proto;
    return O;
  };
}() : undefined);


/***/ }),

/***/ 67718:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var call = __webpack_require__(12341);
var isCallable = __webpack_require__(33901);
var isObject = __webpack_require__(34186);

var $TypeError = TypeError;

// `OrdinaryToPrimitive` abstract operation
// https://tc39.es/ecma262/#sec-ordinarytoprimitive
module.exports = function (input, pref) {
  var fn, val;
  if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
  if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) return val;
  if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
  throw new $TypeError("Can't convert object to primitive value");
};


/***/ }),

/***/ 49951:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var getBuiltIn = __webpack_require__(19631);
var uncurryThis = __webpack_require__(54936);
var getOwnPropertyNamesModule = __webpack_require__(55384);
var getOwnPropertySymbolsModule = __webpack_require__(19965);
var anObject = __webpack_require__(93263);

var concat = uncurryThis([].concat);

// all object keys, includes non-enumerable and symbols
module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
  var keys = getOwnPropertyNamesModule.f(anObject(it));
  var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
  return getOwnPropertySymbols ? concat(keys, getOwnPropertySymbols(it)) : keys;
};


/***/ }),

/***/ 96728:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var defineProperty = (__webpack_require__(9609).f);

module.exports = function (Target, Source, key) {
  key in Target || defineProperty(Target, key, {
    configurable: true,
    get: function () { return Source[key]; },
    set: function (it) { Source[key] = it; }
  });
};


/***/ }),

/***/ 89587:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var anObject = __webpack_require__(93263);

// `RegExp.prototype.flags` getter implementation
// https://tc39.es/ecma262/#sec-get-regexp.prototype.flags
module.exports = function () {
  var that = anObject(this);
  var result = '';
  if (that.hasIndices) result += 'd';
  if (that.global) result += 'g';
  if (that.ignoreCase) result += 'i';
  if (that.multiline) result += 'm';
  if (that.dotAll) result += 's';
  if (that.unicode) result += 'u';
  if (that.unicodeSets) result += 'v';
  if (that.sticky) result += 'y';
  return result;
};


/***/ }),

/***/ 39938:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var call = __webpack_require__(12341);
var hasOwn = __webpack_require__(30217);
var isPrototypeOf = __webpack_require__(44657);
var regExpFlags = __webpack_require__(89587);

var RegExpPrototype = RegExp.prototype;

module.exports = function (R) {
  var flags = R.flags;
  return flags === undefined && !('flags' in RegExpPrototype) && !hasOwn(R, 'flags') && isPrototypeOf(RegExpPrototype, R)
    ? call(regExpFlags, R) : flags;
};


/***/ }),

/***/ 98654:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var isNullOrUndefined = __webpack_require__(46013);

var $TypeError = TypeError;

// `RequireObjectCoercible` abstract operation
// https://tc39.es/ecma262/#sec-requireobjectcoercible
module.exports = function (it) {
  if (isNullOrUndefined(it)) throw new $TypeError("Can't call method on " + it);
  return it;
};


/***/ }),

/***/ 39943:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var defineProperty = (__webpack_require__(9609).f);
var hasOwn = __webpack_require__(30217);
var wellKnownSymbol = __webpack_require__(25723);

var TO_STRING_TAG = wellKnownSymbol('toStringTag');

module.exports = function (target, TAG, STATIC) {
  if (target && !STATIC) target = target.prototype;
  if (target && !hasOwn(target, TO_STRING_TAG)) {
    defineProperty(target, TO_STRING_TAG, { configurable: true, value: TAG });
  }
};


/***/ }),

/***/ 41279:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var shared = __webpack_require__(16889);
var uid = __webpack_require__(64232);

var keys = shared('keys');

module.exports = function (key) {
  return keys[key] || (keys[key] = uid(key));
};


/***/ }),

/***/ 99781:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var IS_PURE = __webpack_require__(28595);
var globalThis = __webpack_require__(34760);
var defineGlobalProperty = __webpack_require__(47473);

var SHARED = '__core-js_shared__';
var store = module.exports = globalThis[SHARED] || defineGlobalProperty(SHARED, {});

(store.versions || (store.versions = [])).push({
  version: '3.40.0',
  mode: IS_PURE ? 'pure' : 'global',
  copyright: '© 2014-2025 Denis Pushkarev (zloirock.ru)',
  license: 'https://github.com/zloirock/core-js/blob/v3.40.0/LICENSE',
  source: 'https://github.com/zloirock/core-js'
});


/***/ }),

/***/ 16889:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var store = __webpack_require__(99781);

module.exports = function (key, value) {
  return store[key] || (store[key] = value || {});
};


/***/ }),

/***/ 36647:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

/* eslint-disable es/no-symbol -- required for testing */
var V8_VERSION = __webpack_require__(6839);
var fails = __webpack_require__(2599);
var globalThis = __webpack_require__(34760);

var $String = globalThis.String;

// eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing
module.exports = !!Object.getOwnPropertySymbols && !fails(function () {
  var symbol = Symbol('symbol detection');
  // Chrome 38 Symbol has incorrect toString conversion
  // `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances
  // nb: Do not call `String` directly to avoid this being optimized out to `symbol+''` which will,
  // of course, fail.
  return !$String(symbol) || !(Object(symbol) instanceof Symbol) ||
    // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
    !Symbol.sham && V8_VERSION && V8_VERSION < 41;
});


/***/ }),

/***/ 63458:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var toIntegerOrInfinity = __webpack_require__(71939);

var max = Math.max;
var min = Math.min;

// Helper for a popular repeating case of the spec:
// Let integer be ? ToInteger(index).
// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
module.exports = function (index, length) {
  var integer = toIntegerOrInfinity(index);
  return integer < 0 ? max(integer + length, 0) : min(integer, length);
};


/***/ }),

/***/ 93222:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var toPrimitive = __webpack_require__(44321);

var $TypeError = TypeError;

// `ToBigInt` abstract operation
// https://tc39.es/ecma262/#sec-tobigint
module.exports = function (argument) {
  var prim = toPrimitive(argument, 'number');
  if (typeof prim == 'number') throw new $TypeError("Can't convert number to bigint");
  // eslint-disable-next-line es/no-bigint -- safe
  return BigInt(prim);
};


/***/ }),

/***/ 42173:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

// toObject with fallback for non-array-like ES3 strings
var IndexedObject = __webpack_require__(98119);
var requireObjectCoercible = __webpack_require__(98654);

module.exports = function (it) {
  return IndexedObject(requireObjectCoercible(it));
};


/***/ }),

/***/ 71939:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var trunc = __webpack_require__(93149);

// `ToIntegerOrInfinity` abstract operation
// https://tc39.es/ecma262/#sec-tointegerorinfinity
module.exports = function (argument) {
  var number = +argument;
  // eslint-disable-next-line no-self-compare -- NaN check
  return number !== number || number === 0 ? 0 : trunc(number);
};


/***/ }),

/***/ 72406:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var toIntegerOrInfinity = __webpack_require__(71939);

var min = Math.min;

// `ToLength` abstract operation
// https://tc39.es/ecma262/#sec-tolength
module.exports = function (argument) {
  var len = toIntegerOrInfinity(argument);
  return len > 0 ? min(len, 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
};


/***/ }),

/***/ 76573:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var requireObjectCoercible = __webpack_require__(98654);

var $Object = Object;

// `ToObject` abstract operation
// https://tc39.es/ecma262/#sec-toobject
module.exports = function (argument) {
  return $Object(requireObjectCoercible(argument));
};


/***/ }),

/***/ 91437:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var toPositiveInteger = __webpack_require__(14830);

var $RangeError = RangeError;

module.exports = function (it, BYTES) {
  var offset = toPositiveInteger(it);
  if (offset % BYTES) throw new $RangeError('Wrong offset');
  return offset;
};


/***/ }),

/***/ 14830:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var toIntegerOrInfinity = __webpack_require__(71939);

var $RangeError = RangeError;

module.exports = function (it) {
  var result = toIntegerOrInfinity(it);
  if (result < 0) throw new $RangeError("The argument can't be less than 0");
  return result;
};


/***/ }),

/***/ 44321:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var call = __webpack_require__(12341);
var isObject = __webpack_require__(34186);
var isSymbol = __webpack_require__(32813);
var getMethod = __webpack_require__(67734);
var ordinaryToPrimitive = __webpack_require__(67718);
var wellKnownSymbol = __webpack_require__(25723);

var $TypeError = TypeError;
var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');

// `ToPrimitive` abstract operation
// https://tc39.es/ecma262/#sec-toprimitive
module.exports = function (input, pref) {
  if (!isObject(input) || isSymbol(input)) return input;
  var exoticToPrim = getMethod(input, TO_PRIMITIVE);
  var result;
  if (exoticToPrim) {
    if (pref === undefined) pref = 'default';
    result = call(exoticToPrim, input, pref);
    if (!isObject(result) || isSymbol(result)) return result;
    throw new $TypeError("Can't convert object to primitive value");
  }
  if (pref === undefined) pref = 'number';
  return ordinaryToPrimitive(input, pref);
};


/***/ }),

/***/ 89153:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var toPrimitive = __webpack_require__(44321);
var isSymbol = __webpack_require__(32813);

// `ToPropertyKey` abstract operation
// https://tc39.es/ecma262/#sec-topropertykey
module.exports = function (argument) {
  var key = toPrimitive(argument, 'string');
  return isSymbol(key) ? key : key + '';
};


/***/ }),

/***/ 2980:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var wellKnownSymbol = __webpack_require__(25723);

var TO_STRING_TAG = wellKnownSymbol('toStringTag');
var test = {};

test[TO_STRING_TAG] = 'z';

module.exports = String(test) === '[object z]';


/***/ }),

/***/ 93207:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var classof = __webpack_require__(45123);

var $String = String;

module.exports = function (argument) {
  if (classof(argument) === 'Symbol') throw new TypeError('Cannot convert a Symbol value to a string');
  return $String(argument);
};


/***/ }),

/***/ 56383:
/***/ ((module) => {

"use strict";

var $String = String;

module.exports = function (argument) {
  try {
    return $String(argument);
  } catch (error) {
    return 'Object';
  }
};


/***/ }),

/***/ 64232:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var uncurryThis = __webpack_require__(54936);

var id = 0;
var postfix = Math.random();
var toString = uncurryThis(1.0.toString);

module.exports = function (key) {
  return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString(++id + postfix, 36);
};


/***/ }),

/***/ 79816:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

/* eslint-disable es/no-symbol -- required for testing */
var NATIVE_SYMBOL = __webpack_require__(36647);

module.exports = NATIVE_SYMBOL &&
  !Symbol.sham &&
  typeof Symbol.iterator == 'symbol';


/***/ }),

/***/ 20102:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var DESCRIPTORS = __webpack_require__(72468);
var fails = __webpack_require__(2599);

// V8 ~ Chrome 36-
// https://bugs.chromium.org/p/v8/issues/detail?id=3334
module.exports = DESCRIPTORS && fails(function () {
  // eslint-disable-next-line es/no-object-defineproperty -- required for testing
  return Object.defineProperty(function () { /* empty */ }, 'prototype', {
    value: 42,
    writable: false
  }).prototype !== 42;
});


/***/ }),

/***/ 34356:
/***/ ((module) => {

"use strict";

var $TypeError = TypeError;

module.exports = function (passed, required) {
  if (passed < required) throw new $TypeError('Not enough arguments');
  return passed;
};


/***/ }),

/***/ 51366:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var globalThis = __webpack_require__(34760);
var isCallable = __webpack_require__(33901);

var WeakMap = globalThis.WeakMap;

module.exports = isCallable(WeakMap) && /native code/.test(String(WeakMap));


/***/ }),

/***/ 25723:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var globalThis = __webpack_require__(34760);
var shared = __webpack_require__(16889);
var hasOwn = __webpack_require__(30217);
var uid = __webpack_require__(64232);
var NATIVE_SYMBOL = __webpack_require__(36647);
var USE_SYMBOL_AS_UID = __webpack_require__(79816);

var Symbol = globalThis.Symbol;
var WellKnownSymbolsStore = shared('wks');
var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol['for'] || Symbol : Symbol && Symbol.withoutSetter || uid;

module.exports = function (name) {
  if (!hasOwn(WellKnownSymbolsStore, name)) {
    WellKnownSymbolsStore[name] = NATIVE_SYMBOL && hasOwn(Symbol, name)
      ? Symbol[name]
      : createWellKnownSymbol('Symbol.' + name);
  } return WellKnownSymbolsStore[name];
};


/***/ }),

/***/ 1361:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var getBuiltIn = __webpack_require__(19631);
var hasOwn = __webpack_require__(30217);
var createNonEnumerableProperty = __webpack_require__(98515);
var isPrototypeOf = __webpack_require__(44657);
var setPrototypeOf = __webpack_require__(45407);
var copyConstructorProperties = __webpack_require__(81988);
var proxyAccessor = __webpack_require__(96728);
var inheritIfRequired = __webpack_require__(88359);
var normalizeStringArgument = __webpack_require__(92867);
var installErrorCause = __webpack_require__(68424);
var installErrorStack = __webpack_require__(15827);
var DESCRIPTORS = __webpack_require__(72468);
var IS_PURE = __webpack_require__(28595);

module.exports = function (FULL_NAME, wrapper, FORCED, IS_AGGREGATE_ERROR) {
  var STACK_TRACE_LIMIT = 'stackTraceLimit';
  var OPTIONS_POSITION = IS_AGGREGATE_ERROR ? 2 : 1;
  var path = FULL_NAME.split('.');
  var ERROR_NAME = path[path.length - 1];
  var OriginalError = getBuiltIn.apply(null, path);

  if (!OriginalError) return;

  var OriginalErrorPrototype = OriginalError.prototype;

  // V8 9.3- bug https://bugs.chromium.org/p/v8/issues/detail?id=12006
  if (!IS_PURE && hasOwn(OriginalErrorPrototype, 'cause')) delete OriginalErrorPrototype.cause;

  if (!FORCED) return OriginalError;

  var BaseError = getBuiltIn('Error');

  var WrappedError = wrapper(function (a, b) {
    var message = normalizeStringArgument(IS_AGGREGATE_ERROR ? b : a, undefined);
    var result = IS_AGGREGATE_ERROR ? new OriginalError(a) : new OriginalError();
    if (message !== undefined) createNonEnumerableProperty(result, 'message', message);
    installErrorStack(result, WrappedError, result.stack, 2);
    if (this && isPrototypeOf(OriginalErrorPrototype, this)) inheritIfRequired(result, this, WrappedError);
    if (arguments.length > OPTIONS_POSITION) installErrorCause(result, arguments[OPTIONS_POSITION]);
    return result;
  });

  WrappedError.prototype = OriginalErrorPrototype;

  if (ERROR_NAME !== 'Error') {
    if (setPrototypeOf) setPrototypeOf(WrappedError, BaseError);
    else copyConstructorProperties(WrappedError, BaseError, { name: true });
  } else if (DESCRIPTORS && STACK_TRACE_LIMIT in OriginalError) {
    proxyAccessor(WrappedError, OriginalError, STACK_TRACE_LIMIT);
    proxyAccessor(WrappedError, OriginalError, 'prepareStackTrace');
  }

  copyConstructorProperties(WrappedError, OriginalError);

  if (!IS_PURE) try {
    // Safari 13- bug: WebAssembly errors does not have a proper `.name`
    if (OriginalErrorPrototype.name !== ERROR_NAME) {
      createNonEnumerableProperty(OriginalErrorPrototype, 'name', ERROR_NAME);
    }
    OriginalErrorPrototype.constructor = WrappedError;
  } catch (error) { /* empty */ }

  return WrappedError;
};


/***/ }),

/***/ 9539:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var $ = __webpack_require__(79214);
var toObject = __webpack_require__(76573);
var lengthOfArrayLike = __webpack_require__(47294);
var toIntegerOrInfinity = __webpack_require__(71939);
var addToUnscopables = __webpack_require__(9693);

// `Array.prototype.at` method
// https://tc39.es/ecma262/#sec-array.prototype.at
$({ target: 'Array', proto: true }, {
  at: function at(index) {
    var O = toObject(this);
    var len = lengthOfArrayLike(O);
    var relativeIndex = toIntegerOrInfinity(index);
    var k = relativeIndex >= 0 ? relativeIndex : len + relativeIndex;
    return (k < 0 || k >= len) ? undefined : O[k];
  }
});

addToUnscopables('at');


/***/ }),

/***/ 90767:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var $ = __webpack_require__(79214);
var $includes = (__webpack_require__(5865).includes);
var fails = __webpack_require__(2599);
var addToUnscopables = __webpack_require__(9693);

// FF99+ bug
var BROKEN_ON_SPARSE = fails(function () {
  // eslint-disable-next-line es/no-array-prototype-includes -- detection
  return !Array(1).includes();
});

// `Array.prototype.includes` method
// https://tc39.es/ecma262/#sec-array.prototype.includes
$({ target: 'Array', proto: true, forced: BROKEN_ON_SPARSE }, {
  includes: function includes(el /* , fromIndex = 0 */) {
    return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
  }
});

// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables('includes');


/***/ }),

/***/ 10474:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var $ = __webpack_require__(79214);
var toObject = __webpack_require__(76573);
var lengthOfArrayLike = __webpack_require__(47294);
var setArrayLength = __webpack_require__(17303);
var doesNotExceedSafeInteger = __webpack_require__(56381);
var fails = __webpack_require__(2599);

var INCORRECT_TO_LENGTH = fails(function () {
  return [].push.call({ length: 0x100000000 }, 1) !== 4294967297;
});

// V8 <= 121 and Safari <= 15.4; FF < 23 throws InternalError
// https://bugs.chromium.org/p/v8/issues/detail?id=12681
var properErrorOnNonWritableLength = function () {
  try {
    // eslint-disable-next-line es/no-object-defineproperty -- safe
    Object.defineProperty([], 'length', { writable: false }).push();
  } catch (error) {
    return error instanceof TypeError;
  }
};

var FORCED = INCORRECT_TO_LENGTH || !properErrorOnNonWritableLength();

// `Array.prototype.push` method
// https://tc39.es/ecma262/#sec-array.prototype.push
$({ target: 'Array', proto: true, arity: 1, forced: FORCED }, {
  // eslint-disable-next-line no-unused-vars -- required for `.length`
  push: function push(item) {
    var O = toObject(this);
    var len = lengthOfArrayLike(O);
    var argCount = arguments.length;
    doesNotExceedSafeInteger(len + argCount);
    for (var i = 0; i < argCount; i++) {
      O[len] = arguments[i];
      len++;
    }
    setArrayLength(O, len);
    return len;
  }
});


/***/ }),

/***/ 51472:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var $ = __webpack_require__(79214);
var $reduce = (__webpack_require__(13302).left);
var arrayMethodIsStrict = __webpack_require__(11822);
var CHROME_VERSION = __webpack_require__(6839);
var IS_NODE = __webpack_require__(9273);

// Chrome 80-82 has a critical bug
// https://bugs.chromium.org/p/chromium/issues/detail?id=1049982
var CHROME_BUG = !IS_NODE && CHROME_VERSION > 79 && CHROME_VERSION < 83;
var FORCED = CHROME_BUG || !arrayMethodIsStrict('reduce');

// `Array.prototype.reduce` method
// https://tc39.es/ecma262/#sec-array.prototype.reduce
$({ target: 'Array', proto: true, forced: FORCED }, {
  reduce: function reduce(callbackfn /* , initialValue */) {
    var length = arguments.length;
    return $reduce(this, callbackfn, length, length > 1 ? arguments[1] : undefined);
  }
});


/***/ }),

/***/ 59952:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

/* eslint-disable no-unused-vars -- required for functions `.length` */
var $ = __webpack_require__(79214);
var globalThis = __webpack_require__(34760);
var apply = __webpack_require__(78881);
var wrapErrorConstructorWithCause = __webpack_require__(1361);

var WEB_ASSEMBLY = 'WebAssembly';
var WebAssembly = globalThis[WEB_ASSEMBLY];

// eslint-disable-next-line es/no-error-cause -- feature detection
var FORCED = new Error('e', { cause: 7 }).cause !== 7;

var exportGlobalErrorCauseWrapper = function (ERROR_NAME, wrapper) {
  var O = {};
  O[ERROR_NAME] = wrapErrorConstructorWithCause(ERROR_NAME, wrapper, FORCED);
  $({ global: true, constructor: true, arity: 1, forced: FORCED }, O);
};

var exportWebAssemblyErrorCauseWrapper = function (ERROR_NAME, wrapper) {
  if (WebAssembly && WebAssembly[ERROR_NAME]) {
    var O = {};
    O[ERROR_NAME] = wrapErrorConstructorWithCause(WEB_ASSEMBLY + '.' + ERROR_NAME, wrapper, FORCED);
    $({ target: WEB_ASSEMBLY, stat: true, constructor: true, arity: 1, forced: FORCED }, O);
  }
};

// https://tc39.es/ecma262/#sec-nativeerror
exportGlobalErrorCauseWrapper('Error', function (init) {
  return function Error(message) { return apply(init, this, arguments); };
});
exportGlobalErrorCauseWrapper('EvalError', function (init) {
  return function EvalError(message) { return apply(init, this, arguments); };
});
exportGlobalErrorCauseWrapper('RangeError', function (init) {
  return function RangeError(message) { return apply(init, this, arguments); };
});
exportGlobalErrorCauseWrapper('ReferenceError', function (init) {
  return function ReferenceError(message) { return apply(init, this, arguments); };
});
exportGlobalErrorCauseWrapper('SyntaxError', function (init) {
  return function SyntaxError(message) { return apply(init, this, arguments); };
});
exportGlobalErrorCauseWrapper('TypeError', function (init) {
  return function TypeError(message) { return apply(init, this, arguments); };
});
exportGlobalErrorCauseWrapper('URIError', function (init) {
  return function URIError(message) { return apply(init, this, arguments); };
});
exportWebAssemblyErrorCauseWrapper('CompileError', function (init) {
  return function CompileError(message) { return apply(init, this, arguments); };
});
exportWebAssemblyErrorCauseWrapper('LinkError', function (init) {
  return function LinkError(message) { return apply(init, this, arguments); };
});
exportWebAssemblyErrorCauseWrapper('RuntimeError', function (init) {
  return function RuntimeError(message) { return apply(init, this, arguments); };
});


/***/ }),

/***/ 24376:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var $ = __webpack_require__(79214);
var globalThis = __webpack_require__(34760);
var setToStringTag = __webpack_require__(39943);

$({ global: true }, { Reflect: {} });

// Reflect[@@toStringTag] property
// https://tc39.es/ecma262/#sec-reflect-@@tostringtag
setToStringTag(globalThis.Reflect, 'Reflect', true);


/***/ }),

/***/ 59077:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var $ = __webpack_require__(79214);
var uncurryThis = __webpack_require__(54936);
var requireObjectCoercible = __webpack_require__(98654);
var toIntegerOrInfinity = __webpack_require__(71939);
var toString = __webpack_require__(93207);
var fails = __webpack_require__(2599);

var charAt = uncurryThis(''.charAt);

var FORCED = fails(function () {
  // eslint-disable-next-line es/no-string-prototype-at -- safe
  return '𠮷'.at(-2) !== '\uD842';
});

// `String.prototype.at` method
// https://tc39.es/ecma262/#sec-string.prototype.at
$({ target: 'String', proto: true, forced: FORCED }, {
  at: function at(index) {
    var S = toString(requireObjectCoercible(this));
    var len = S.length;
    var relativeIndex = toIntegerOrInfinity(index);
    var k = relativeIndex >= 0 ? relativeIndex : len + relativeIndex;
    return (k < 0 || k >= len) ? undefined : charAt(S, k);
  }
});


/***/ }),

/***/ 22114:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var $ = __webpack_require__(79214);
var call = __webpack_require__(12341);
var uncurryThis = __webpack_require__(54936);
var requireObjectCoercible = __webpack_require__(98654);
var isCallable = __webpack_require__(33901);
var isNullOrUndefined = __webpack_require__(46013);
var isRegExp = __webpack_require__(25292);
var toString = __webpack_require__(93207);
var getMethod = __webpack_require__(67734);
var getRegExpFlags = __webpack_require__(39938);
var getSubstitution = __webpack_require__(91414);
var wellKnownSymbol = __webpack_require__(25723);
var IS_PURE = __webpack_require__(28595);

var REPLACE = wellKnownSymbol('replace');
var $TypeError = TypeError;
var indexOf = uncurryThis(''.indexOf);
var replace = uncurryThis(''.replace);
var stringSlice = uncurryThis(''.slice);
var max = Math.max;

// `String.prototype.replaceAll` method
// https://tc39.es/ecma262/#sec-string.prototype.replaceall
$({ target: 'String', proto: true }, {
  replaceAll: function replaceAll(searchValue, replaceValue) {
    var O = requireObjectCoercible(this);
    var IS_REG_EXP, flags, replacer, string, searchString, functionalReplace, searchLength, advanceBy, position, replacement;
    var endOfLastMatch = 0;
    var result = '';
    if (!isNullOrUndefined(searchValue)) {
      IS_REG_EXP = isRegExp(searchValue);
      if (IS_REG_EXP) {
        flags = toString(requireObjectCoercible(getRegExpFlags(searchValue)));
        if (!~indexOf(flags, 'g')) throw new $TypeError('`.replaceAll` does not allow non-global regexes');
      }
      replacer = getMethod(searchValue, REPLACE);
      if (replacer) return call(replacer, searchValue, O, replaceValue);
      if (IS_PURE && IS_REG_EXP) return replace(toString(O), searchValue, replaceValue);
    }
    string = toString(O);
    searchString = toString(searchValue);
    functionalReplace = isCallable(replaceValue);
    if (!functionalReplace) replaceValue = toString(replaceValue);
    searchLength = searchString.length;
    advanceBy = max(1, searchLength);
    position = indexOf(string, searchString);
    while (position !== -1) {
      replacement = functionalReplace
        ? toString(replaceValue(searchString, position, string))
        : getSubstitution(searchString, string, position, [], undefined, replaceValue);
      result += stringSlice(string, endOfLastMatch, position) + replacement;
      endOfLastMatch = position + searchLength;
      position = position + advanceBy > string.length ? -1 : indexOf(string, searchString, position + advanceBy);
    }
    if (endOfLastMatch < string.length) {
      result += stringSlice(string, endOfLastMatch);
    }
    return result;
  }
});


/***/ }),

/***/ 47348:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var ArrayBufferViewCore = __webpack_require__(95308);
var lengthOfArrayLike = __webpack_require__(47294);
var toIntegerOrInfinity = __webpack_require__(71939);

var aTypedArray = ArrayBufferViewCore.aTypedArray;
var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;

// `%TypedArray%.prototype.at` method
// https://tc39.es/ecma262/#sec-%typedarray%.prototype.at
exportTypedArrayMethod('at', function at(index) {
  var O = aTypedArray(this);
  var len = lengthOfArrayLike(O);
  var relativeIndex = toIntegerOrInfinity(index);
  var k = relativeIndex >= 0 ? relativeIndex : len + relativeIndex;
  return (k < 0 || k >= len) ? undefined : O[k];
});


/***/ }),

/***/ 16022:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var ArrayBufferViewCore = __webpack_require__(95308);
var $findLastIndex = (__webpack_require__(73271).findLastIndex);

var aTypedArray = ArrayBufferViewCore.aTypedArray;
var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;

// `%TypedArray%.prototype.findLastIndex` method
// https://tc39.es/ecma262/#sec-%typedarray%.prototype.findlastindex
exportTypedArrayMethod('findLastIndex', function findLastIndex(predicate /* , thisArg */) {
  return $findLastIndex(aTypedArray(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
});


/***/ }),

/***/ 68551:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var ArrayBufferViewCore = __webpack_require__(95308);
var $findLast = (__webpack_require__(73271).findLast);

var aTypedArray = ArrayBufferViewCore.aTypedArray;
var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;

// `%TypedArray%.prototype.findLast` method
// https://tc39.es/ecma262/#sec-%typedarray%.prototype.findlast
exportTypedArrayMethod('findLast', function findLast(predicate /* , thisArg */) {
  return $findLast(aTypedArray(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
});


/***/ }),

/***/ 56965:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var globalThis = __webpack_require__(34760);
var call = __webpack_require__(12341);
var ArrayBufferViewCore = __webpack_require__(95308);
var lengthOfArrayLike = __webpack_require__(47294);
var toOffset = __webpack_require__(91437);
var toIndexedObject = __webpack_require__(76573);
var fails = __webpack_require__(2599);

var RangeError = globalThis.RangeError;
var Int8Array = globalThis.Int8Array;
var Int8ArrayPrototype = Int8Array && Int8Array.prototype;
var $set = Int8ArrayPrototype && Int8ArrayPrototype.set;
var aTypedArray = ArrayBufferViewCore.aTypedArray;
var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;

var WORKS_WITH_OBJECTS_AND_GENERIC_ON_TYPED_ARRAYS = !fails(function () {
  // eslint-disable-next-line es/no-typed-arrays -- required for testing
  var array = new Uint8ClampedArray(2);
  call($set, array, { length: 1, 0: 3 }, 1);
  return array[1] !== 3;
});

// https://bugs.chromium.org/p/v8/issues/detail?id=11294 and other
var TO_OBJECT_BUG = WORKS_WITH_OBJECTS_AND_GENERIC_ON_TYPED_ARRAYS && ArrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS && fails(function () {
  var array = new Int8Array(2);
  array.set(1);
  array.set('2', 1);
  return array[0] !== 0 || array[1] !== 2;
});

// `%TypedArray%.prototype.set` method
// https://tc39.es/ecma262/#sec-%typedarray%.prototype.set
exportTypedArrayMethod('set', function set(arrayLike /* , offset */) {
  aTypedArray(this);
  var offset = toOffset(arguments.length > 1 ? arguments[1] : undefined, 1);
  var src = toIndexedObject(arrayLike);
  if (WORKS_WITH_OBJECTS_AND_GENERIC_ON_TYPED_ARRAYS) return call($set, this, src, offset);
  var length = this.length;
  var len = lengthOfArrayLike(src);
  var index = 0;
  if (len + offset > length) throw new RangeError('Wrong length');
  while (index < len) this[offset + index] = src[index++];
}, !WORKS_WITH_OBJECTS_AND_GENERIC_ON_TYPED_ARRAYS || TO_OBJECT_BUG);


/***/ }),

/***/ 93491:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var arrayToReversed = __webpack_require__(48452);
var ArrayBufferViewCore = __webpack_require__(95308);

var aTypedArray = ArrayBufferViewCore.aTypedArray;
var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;
var getTypedArrayConstructor = ArrayBufferViewCore.getTypedArrayConstructor;

// `%TypedArray%.prototype.toReversed` method
// https://tc39.es/ecma262/#sec-%typedarray%.prototype.toreversed
exportTypedArrayMethod('toReversed', function toReversed() {
  return arrayToReversed(aTypedArray(this), getTypedArrayConstructor(this));
});


/***/ }),

/***/ 90948:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var ArrayBufferViewCore = __webpack_require__(95308);
var uncurryThis = __webpack_require__(54936);
var aCallable = __webpack_require__(2786);
var arrayFromConstructorAndList = __webpack_require__(65282);

var aTypedArray = ArrayBufferViewCore.aTypedArray;
var getTypedArrayConstructor = ArrayBufferViewCore.getTypedArrayConstructor;
var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;
var sort = uncurryThis(ArrayBufferViewCore.TypedArrayPrototype.sort);

// `%TypedArray%.prototype.toSorted` method
// https://tc39.es/ecma262/#sec-%typedarray%.prototype.tosorted
exportTypedArrayMethod('toSorted', function toSorted(compareFn) {
  if (compareFn !== undefined) aCallable(compareFn);
  var O = aTypedArray(this);
  var A = arrayFromConstructorAndList(getTypedArrayConstructor(O), O);
  return sort(A, compareFn);
});


/***/ }),

/***/ 31873:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var arrayWith = __webpack_require__(89392);
var ArrayBufferViewCore = __webpack_require__(95308);
var isBigIntArray = __webpack_require__(60735);
var toIntegerOrInfinity = __webpack_require__(71939);
var toBigInt = __webpack_require__(93222);

var aTypedArray = ArrayBufferViewCore.aTypedArray;
var getTypedArrayConstructor = ArrayBufferViewCore.getTypedArrayConstructor;
var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;

var PROPER_ORDER = !!function () {
  try {
    // eslint-disable-next-line no-throw-literal, es/no-typed-arrays, es/no-array-prototype-with -- required for testing
    new Int8Array(1)['with'](2, { valueOf: function () { throw 8; } });
  } catch (error) {
    // some early implementations, like WebKit, does not follow the final semantic
    // https://github.com/tc39/proposal-change-array-by-copy/pull/86
    return error === 8;
  }
}();

// `%TypedArray%.prototype.with` method
// https://tc39.es/ecma262/#sec-%typedarray%.prototype.with
exportTypedArrayMethod('with', { 'with': function (index, value) {
  var O = aTypedArray(this);
  var relativeIndex = toIntegerOrInfinity(index);
  var actualValue = isBigIntArray(O) ? toBigInt(value) : +value;
  return arrayWith(O, getTypedArrayConstructor(O), relativeIndex, actualValue);
} }['with'], !PROPER_ORDER);


/***/ }),

/***/ 83659:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var $ = __webpack_require__(79214);
var globalThis = __webpack_require__(34760);
var getBuiltIn = __webpack_require__(19631);
var createPropertyDescriptor = __webpack_require__(57692);
var defineProperty = (__webpack_require__(9609).f);
var hasOwn = __webpack_require__(30217);
var anInstance = __webpack_require__(87759);
var inheritIfRequired = __webpack_require__(88359);
var normalizeStringArgument = __webpack_require__(92867);
var DOMExceptionConstants = __webpack_require__(76146);
var clearErrorStack = __webpack_require__(96345);
var DESCRIPTORS = __webpack_require__(72468);
var IS_PURE = __webpack_require__(28595);

var DOM_EXCEPTION = 'DOMException';
var Error = getBuiltIn('Error');
var NativeDOMException = getBuiltIn(DOM_EXCEPTION);

var $DOMException = function DOMException() {
  anInstance(this, DOMExceptionPrototype);
  var argumentsLength = arguments.length;
  var message = normalizeStringArgument(argumentsLength < 1 ? undefined : arguments[0]);
  var name = normalizeStringArgument(argumentsLength < 2 ? undefined : arguments[1], 'Error');
  var that = new NativeDOMException(message, name);
  var error = new Error(message);
  error.name = DOM_EXCEPTION;
  defineProperty(that, 'stack', createPropertyDescriptor(1, clearErrorStack(error.stack, 1)));
  inheritIfRequired(that, this, $DOMException);
  return that;
};

var DOMExceptionPrototype = $DOMException.prototype = NativeDOMException.prototype;

var ERROR_HAS_STACK = 'stack' in new Error(DOM_EXCEPTION);
var DOM_EXCEPTION_HAS_STACK = 'stack' in new NativeDOMException(1, 2);

// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var descriptor = NativeDOMException && DESCRIPTORS && Object.getOwnPropertyDescriptor(globalThis, DOM_EXCEPTION);

// Bun ~ 0.1.1 DOMException have incorrect descriptor and we can't redefine it
// https://github.com/Jarred-Sumner/bun/issues/399
var BUGGY_DESCRIPTOR = !!descriptor && !(descriptor.writable && descriptor.configurable);

var FORCED_CONSTRUCTOR = ERROR_HAS_STACK && !BUGGY_DESCRIPTOR && !DOM_EXCEPTION_HAS_STACK;

// `DOMException` constructor patch for `.stack` where it's required
// https://webidl.spec.whatwg.org/#es-DOMException-specialness
$({ global: true, constructor: true, forced: IS_PURE || FORCED_CONSTRUCTOR }, { // TODO: fix export logic
  DOMException: FORCED_CONSTRUCTOR ? $DOMException : NativeDOMException
});

var PolyfilledDOMException = getBuiltIn(DOM_EXCEPTION);
var PolyfilledDOMExceptionPrototype = PolyfilledDOMException.prototype;

if (PolyfilledDOMExceptionPrototype.constructor !== PolyfilledDOMException) {
  if (!IS_PURE) {
    defineProperty(PolyfilledDOMExceptionPrototype, 'constructor', createPropertyDescriptor(1, PolyfilledDOMException));
  }

  for (var key in DOMExceptionConstants) if (hasOwn(DOMExceptionConstants, key)) {
    var constant = DOMExceptionConstants[key];
    var constantName = constant.s;
    if (!hasOwn(PolyfilledDOMException, constantName)) {
      defineProperty(PolyfilledDOMException, constantName, createPropertyDescriptor(6, constant.c));
    }
  }
}


/***/ }),

/***/ 91219:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var $ = __webpack_require__(79214);
var globalThis = __webpack_require__(34760);
var defineBuiltInAccessor = __webpack_require__(43954);
var DESCRIPTORS = __webpack_require__(72468);

var $TypeError = TypeError;
// eslint-disable-next-line es/no-object-defineproperty -- safe
var defineProperty = Object.defineProperty;
var INCORRECT_VALUE = globalThis.self !== globalThis;

// `self` getter
// https://html.spec.whatwg.org/multipage/window-object.html#dom-self
try {
  if (DESCRIPTORS) {
    // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
    var descriptor = Object.getOwnPropertyDescriptor(globalThis, 'self');
    // some engines have `self`, but with incorrect descriptor
    // https://github.com/denoland/deno/issues/15765
    if (INCORRECT_VALUE || !descriptor || !descriptor.get || !descriptor.enumerable) {
      defineBuiltInAccessor(globalThis, 'self', {
        get: function self() {
          return globalThis;
        },
        set: function self(value) {
          if (this !== globalThis) throw new $TypeError('Illegal invocation');
          defineProperty(globalThis, 'self', {
            value: value,
            writable: true,
            configurable: true,
            enumerable: true
          });
        },
        configurable: true,
        enumerable: true
      });
    }
  } else $({ global: true, simple: true, forced: INCORRECT_VALUE }, {
    self: globalThis
  });
} catch (error) { /* empty */ }


/***/ }),

/***/ 4659:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var defineBuiltIn = __webpack_require__(44432);
var uncurryThis = __webpack_require__(54936);
var toString = __webpack_require__(93207);
var validateArgumentsLength = __webpack_require__(34356);

var $URLSearchParams = URLSearchParams;
var URLSearchParamsPrototype = $URLSearchParams.prototype;
var append = uncurryThis(URLSearchParamsPrototype.append);
var $delete = uncurryThis(URLSearchParamsPrototype['delete']);
var forEach = uncurryThis(URLSearchParamsPrototype.forEach);
var push = uncurryThis([].push);
var params = new $URLSearchParams('a=1&a=2&b=3');

params['delete']('a', 1);
// `undefined` case is a Chromium 117 bug
// https://bugs.chromium.org/p/v8/issues/detail?id=14222
params['delete']('b', undefined);

if (params + '' !== 'a=2') {
  defineBuiltIn(URLSearchParamsPrototype, 'delete', function (name /* , value */) {
    var length = arguments.length;
    var $value = length < 2 ? undefined : arguments[1];
    if (length && $value === undefined) return $delete(this, name);
    var entries = [];
    forEach(this, function (v, k) { // also validates `this`
      push(entries, { key: k, value: v });
    });
    validateArgumentsLength(length, 1);
    var key = toString(name);
    var value = toString($value);
    var index = 0;
    var dindex = 0;
    var found = false;
    var entriesLength = entries.length;
    var entry;
    while (index < entriesLength) {
      entry = entries[index++];
      if (found || entry.key === key) {
        found = true;
        $delete(this, entry.key);
      } else dindex++;
    }
    while (dindex < entriesLength) {
      entry = entries[dindex++];
      if (!(entry.key === key && entry.value === value)) append(this, entry.key, entry.value);
    }
  }, { enumerable: true, unsafe: true });
}


/***/ }),

/***/ 43526:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var defineBuiltIn = __webpack_require__(44432);
var uncurryThis = __webpack_require__(54936);
var toString = __webpack_require__(93207);
var validateArgumentsLength = __webpack_require__(34356);

var $URLSearchParams = URLSearchParams;
var URLSearchParamsPrototype = $URLSearchParams.prototype;
var getAll = uncurryThis(URLSearchParamsPrototype.getAll);
var $has = uncurryThis(URLSearchParamsPrototype.has);
var params = new $URLSearchParams('a=1');

// `undefined` case is a Chromium 117 bug
// https://bugs.chromium.org/p/v8/issues/detail?id=14222
if (params.has('a', 2) || !params.has('a', undefined)) {
  defineBuiltIn(URLSearchParamsPrototype, 'has', function has(name /* , value */) {
    var length = arguments.length;
    var $value = length < 2 ? undefined : arguments[1];
    if (length && $value === undefined) return $has(this, name);
    var values = getAll(this, name); // also validates `this`
    validateArgumentsLength(length, 1);
    var value = toString($value);
    var index = 0;
    while (index < values.length) {
      if (values[index++] === value) return true;
    } return false;
  }, { enumerable: true, unsafe: true });
}


/***/ }),

/***/ 9561:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var DESCRIPTORS = __webpack_require__(72468);
var uncurryThis = __webpack_require__(54936);
var defineBuiltInAccessor = __webpack_require__(43954);

var URLSearchParamsPrototype = URLSearchParams.prototype;
var forEach = uncurryThis(URLSearchParamsPrototype.forEach);

// `URLSearchParams.prototype.size` getter
// https://github.com/whatwg/url/pull/734
if (DESCRIPTORS && !('size' in URLSearchParamsPrototype)) {
  defineBuiltInAccessor(URLSearchParamsPrototype, 'size', {
    get: function size() {
      var count = 0;
      forEach(this, function () { count++; });
      return count;
    },
    configurable: true,
    enumerable: true
  });
}


/***/ }),

/***/ 25651:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   bZ: () => (/* binding */ getFormattedTokenName),
/* harmony export */   f0: () => (/* binding */ decodeIdent),
/* harmony export */   jz: () => (/* binding */ tokenizeExtended),
/* harmony export */   ks: () => (/* binding */ TokenType),
/* harmony export */   y0: () => (/* binding */ hasToken)
/* harmony export */ });
/* unused harmony exports CSS_TOKENIZER_VERSION, TokenizerContext, getBaseTokenName, tokenize */
/*
 * CSSTokenizer v1.2.0 (build date: Mon, 03 Feb 2025 15:26:11 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/css-tokenizer#readme
 */
/**
 * @file Implementation of CSS Syntax Module Level 3 tokenizer definitions (§ 4.2.)
 *
 * @see {@link https://www.w3.org/TR/css-syntax-3/#tokenizer-definitions}
 */
/**
 * Check if code point code is between two code points
 *
 * @param code Code point to check
 * @param min Minimum code point
 * @param max Maximum code point
 * @returns `true` if code point is between `min` and `max`, `false` otherwise
 * @note Boundaries are inclusive
 * @note This function is used instead of `code >= min && code <= max` because TypeScript doesn't allow to compare
 * `number | undefined` with `number` (even though it's perfectly valid in JavaScript)
 */
function isBetween(code, min, max) {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore 18048
    return code >= min && code <= max;
}
/**
 * Check if code point code is greater than other code point
 *
 * @param code Code point to check
 * @param min Minimum code point
 * @returns `true` if code point is greater than `min`, `false` otherwise
 * @note This function is used instead of `code > min` because TypeScript doesn't allow to compare
 * `number | undefined` with `number` (even though it's perfectly valid in JavaScript)
 */
function isGreaterThan(code, min) {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore 18048
    return code > min;
}
/**
 * Check if code point code is greater than or equal to other code point
 *
 * @param code Code point to check
 * @param min Minimum code point
 * @returns `true` if code point is greater than or equal to `min`, `false` otherwise
 * @note This function is used instead of `code >= min` because TypeScript doesn't allow to compare
 * `number | undefined` with `number` (even though it's perfectly valid in JavaScript)
 */
function isGreaterThanOrEqual(code, min) {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore 18048
    return code >= min;
}
/**
 * Check if character code is a digit
 *
 * @param code Character code
 * @returns `true` if character code is a digit, `false` otherwise
 * @see {@link https://www.w3.org/TR/css-syntax-3/#digit}
 */
function isDigit(code) {
    // A code point between U+0030 DIGIT ZERO (0) and U+0039 DIGIT NINE (9) inclusive.
    return isBetween(code, 48 /* CodePoint.DigitZero */, 57 /* CodePoint.DigitNine */);
}
/**
 * Check if character code is a hex digit
 *
 * @param code Character code
 * @returns `true` if character code is a hex digit, `false` otherwise
 * @see {@link https://www.w3.org/TR/css-syntax-3/#hex-digit}
 */
function isHexDigit(code) {
    // A digit, or a code point between U+0041 LATIN CAPITAL LETTER A (A) and U+0046 LATIN CAPITAL LETTER F (F)
    // inclusive, or a code point between U+0061 LATIN SMALL LETTER A (a) and U+0066 LATIN SMALL LETTER F (f) inclusive.
    return isDigit(code) // 0-9
        || isBetween(code, 65 /* CodePoint.LatinCapitalLetterA */, 70 /* CodePoint.LatinCapitalLetterF */) // A-F
        || isBetween(code, 97 /* CodePoint.LatinSmallLetterA */, 102 /* CodePoint.LatinSmallLetterF */); // a-f
}
/**
 * Check if character code is an uppercase letter
 *
 * @param code Character code
 * @returns `true` if character code is an uppercase letter, `false` otherwise
 * @see {@link https://www.w3.org/TR/css-syntax-3/#uppercase-letter}
 */
function isUppercaseLetter(code) {
    // A code point between U+0041 LATIN CAPITAL LETTER A (A) and U+005A LATIN CAPITAL LETTER Z (Z) inclusive.
    return isBetween(code, 65 /* CodePoint.LatinCapitalLetterA */, 90 /* CodePoint.LatinCapitalLetterZ */); // A-Z
}
/**
 * Check if character code is a lowercase letter
 *
 * @param code Character code
 * @returns `true` if character code is a lowercase letter, `false` otherwise
 * @see {@link https://www.w3.org/TR/css-syntax-3/#lowercase-letter}
 */
function isLowercaseLetter(code) {
    // A code point between U+0061 LATIN SMALL LETTER A (a) and U+007A LATIN SMALL LETTER Z (z) inclusive.
    return isBetween(code, 97 /* CodePoint.LatinSmallLetterA */, 122 /* CodePoint.LatinSmallLetterZ */); // a-z
}
/**
 * Check if character code is a letter
 *
 * @param code Character code
 * @returns `true` if character code is a letter, `false` otherwise
 * @see {@link https://www.w3.org/TR/css-syntax-3/#letter}
 */
function isLetter(code) {
    // An uppercase letter or a lowercase letter.
    return isUppercaseLetter(code) || isLowercaseLetter(code); // A-Z or a-z
}
/**
 * Check if character code is a non-ASCII code point
 *
 * @param code Character code
 * @returns `true` if character code is a non-ASCII code point, `false` otherwise
 * @see {@link https://www.w3.org/TR/css-syntax-3/#non-ascii-code-point}
 */
function isNonAsciiCodePoint(code) {
    // A code point with a value equal to or greater than U+0080 <control>.
    return isGreaterThanOrEqual(code, 128 /* CodePoint.ControlCharacterStart */);
}
/**
 * Check if character code is a name code point
 *
 * @param code Character code
 * @returns `true` if character code is a name start code point, `false` otherwise
 * @see {@link https://www.w3.org/TR/css-syntax-3/#ident-start-code-point}
 */
function isIdentStartCodePoint(code) {
    // A letter, a non-ASCII code point, or U+005F LOW LINE (_).
    return isLetter(code) || isNonAsciiCodePoint(code) || code === 95 /* CodePoint.LowLine */;
}
/**
 * Check if character code is a name code point
 *
 * @param code Character code
 * @returns `true` if character code is a name code point, `false` otherwise
 * @see {@link https://www.w3.org/TR/css-syntax-3/#ident-code-point}
 */
function isIdentCodePoint(code) {
    // An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
    return isIdentStartCodePoint(code) || isDigit(code) || code === 45 /* CodePoint.HyphenMinus */;
}
/**
 * Check if character code is a non-printable code point
 *
 * @param code Character code
 * @returns `true` if character code is a non-printable code point, `false` otherwise
 * @see {@link https://www.w3.org/TR/css-syntax-3/#non-printable-code-point}
 */
function isNonPrintableCodePoint(code) {
    // A code point between U+0000 NULL and U+0008 BACKSPACE inclusive, or U+000B LINE TABULATION, or a code point
    // between U+000E SHIFT OUT and U+001F INFORMATION SEPARATOR ONE inclusive, or U+007F DELETE.
    return isBetween(code, 0 /* CodePoint.Null */, 8 /* CodePoint.Backspace */)
        || code === 11 /* CodePoint.LineTabulation */
        || isBetween(code, 14 /* CodePoint.ShiftOut */, 31 /* CodePoint.InformationSeparatorOne */)
        || code === 127 /* CodePoint.Delete */;
}
/**
 * Check if character code is a newline
 *
 * @param code Character code
 * @returns `true` if character code is a newline, `false` otherwise
 * @see {@link https://www.w3.org/TR/css-syntax-3/#newline}
 */
function isNewline(code) {
    // U+000A LINE FEED. Note that U+000D CARRIAGE RETURN and U+000C FORM FEED are not included in this definition, as
    // they are converted to U+000A LINE FEED during preprocessing.
    return code === 10 /* CodePoint.LineFeed */ || code === 13 /* CodePoint.CarriageReturn */ || code === 12 /* CodePoint.FormFeed */;
}
/**
 * Check if character code is a whitespace
 *
 * @param code Character code
 * @returns `true` if character code is a whitespace, `false` otherwise
 * @see {@link https://www.w3.org/TR/css-syntax-3/#whitespace}
 */
function isWhitespace(code) {
    // A newline, U+0009 CHARACTER TABULATION, or U+0020 SPACE.
    return isNewline(code) || code === 9 /* CodePoint.CharacterTabulation */ || code === 32 /* CodePoint.Space */;
}
/**
 * Check if character code is a leading surrogate
 *
 * @param code Character code
 * @returns `true` if character code is a leading surrogate, `false` otherwise
 * @see {@link https://infra.spec.whatwg.org/#surrogate}
 */
function isLeadingSurrogate(code) {
    return isBetween(code, 55296 /* CodePoint.LeadingSurrogateStart */, 56319 /* CodePoint.LeadingSurrogateEnd */);
}
/**
 * Check if character code is a trailing surrogate
 *
 * @param code Character code
 * @returns `true` if character code is a trailing surrogate, `false` otherwise
 * @see {@link https://infra.spec.whatwg.org/#surrogate}
 */
function isTrailingSurrogate(code) {
    return isBetween(code, 56320 /* CodePoint.TrailingSurrogateStart */, 57343 /* CodePoint.TrailingSurrogateEnd */);
}
/**
 * Check if character code is a surrogate
 *
 * @param code Character code
 * @returns `true` if character code is a surrogate, `false` otherwise
 * @see {@link https://infra.spec.whatwg.org/#surrogate}
 */
function isSurrogate(code) {
    return isLeadingSurrogate(code) || isTrailingSurrogate(code);
}
/**
 * Check if character code is greater than maximum allowed code point
 *
 * @param code Character code
 * @returns `true` if character code is greater than maximum allowed code point, `false` otherwise
 * @see {@link https://www.w3.org/TR/css-syntax-3/#maximum-allowed-code-point}
 */
function isGreaterThanMaxAllowedCodePoint(code) {
    return isGreaterThan(code, 1114111 /* CodePoint.MaxCodePoint */);
}
// TODO: Uncomment when needed, maybe useful in the future
// /**
//  * Check if character code is a valid identifier sequence code point
//  *
//  * @param code Character code
//  * @returns `true` if character code is a valid identifier sequence code point, `false` otherwise
//  * @see {@link https://www.w3.org/TR/css-syntax-3/#ident-sequence}
//  * @note The part of an <at-keyword-token> after the "@", the part of a <hash-token> (with the "id" type flag) after
//  * the "#", the part of a <function-token> before the "(", and the unit of a <dimension-token> are all ident
//  * sequences.
//  */
// export function isIdentSequence(code: number): boolean {
//     // A sequence of code points that has the same syntax as an <ident-token>.
// eslint-disable-next-line max-len
//     return isIdentStartCodePoint(code) || isDigit(code) || code === CodePoint.HyphenMinus || code === CodePoint.LowLine;
// }
/**
 * Check if character code is a BOM (Byte Order Mark)
 *
 * @param code Character code to check
 * @returns `true` if character code is a BOM, `false` otherwise
 */
function isBOM(code) {
    return code === 65279 /* CodePoint.Utf16BeBom */ || code === 65534 /* CodePoint.Utf16LeBom */;
}
/**
 * § 4.3.8. Check if two code points are a valid escape
 *
 * @param a First code point
 * @param b Second code point
 * @returns `true` if the code points are a valid escape, `false` otherwise
 * @see {@link https://www.w3.org/TR/css-syntax-3/#starts-with-a-valid-escape}
 * @note This algorithm will not consume any additional code point.
 */
const checkForValidEscape = (a, b) => {
    // If the first code point is not U+005C REVERSE SOLIDUS (\), return false.
    if (a !== 92 /* CodePoint.ReverseSolidus */) {
        return false;
    }
    // Otherwise, if the second code point is a newline, return false.
    // Otherwise, return true.
    return !isNewline(b);
};
/**
 * § 4.3.9. Check if three code points would start an ident sequence
 *
 * @param a First code point
 * @param b Second code point
 * @param c Third code point
 * @returns `true` if the next code points would start an identifier, `false` otherwise
 * @see {@link https://www.w3.org/TR/css-syntax-3/#would-start-an-identifier}
 * @note This algorithm will not consume any additional code points.
 */
const checkForIdentStart = (a, b, c) => {
    // Look at the first code point:
    // U+002D HYPHEN-MINUS
    if (a === 45 /* CodePoint.HyphenMinus */) {
        // If the second code point is an ident-start code point or a U+002D HYPHEN-MINUS,
        // or the second and third code points are a valid escape, return true. Otherwise, return false.
        return isIdentStartCodePoint(b) || b === 45 /* CodePoint.HyphenMinus */ || checkForValidEscape(b, c);
    }
    // ident-start code point
    if (isIdentStartCodePoint(a)) {
        // Return true.
        return true;
    }
    // U+005C REVERSE SOLIDUS (\)
    if (a === 92 /* CodePoint.ReverseSolidus */) {
        // If the first and second code points are a valid escape, return true. Otherwise, return false.
        return checkForValidEscape(a, b);
    }
    // anything else
    // Return false.
    return false;
};
/**
 * § 4.3.10. Check if three code points would start a number
 *
 * @param a First code point
 * @param b Second code point
 * @param c Third code point
 * @returns `true` if the next code points would start a number, `false` otherwise
 * @see {@link https://www.w3.org/TR/css-syntax-3/#starts-with-a-number}
 * @note This algorithm will not consume any additional code points.
 */
const checkForNumberStart = (a, b, c) => {
    // Look at the first code point:
    // U+002B PLUS SIGN (+)
    // U+002D HYPHEN-MINUS (-)
    if (a === 43 /* CodePoint.PlusSign */ || a === 45 /* CodePoint.HyphenMinus */) {
        // If the second code point is a digit, return true.
        if (isDigit(b)) {
            return true;
        }
        // Otherwise, if the second code point is a U+002E FULL STOP (.) and the third code point is a digit, return
        // true.
        // Otherwise, return false.
        return b === 46 /* CodePoint.FullStop */ && isDigit(c);
    }
    // U+002E FULL STOP (.)
    if (a === 46 /* CodePoint.FullStop */) {
        // If the second code point is a digit, return true. Otherwise, return false.
        return isDigit(b);
    }
    // digit
    // Return true.
    // anything else
    // Return false.
    return isDigit(a);
};

/* eslint-disable no-bitwise */
/**
 * @file Hashing functions based on the djb2 algorithm
 *
 * @see {@link http://www.cse.yorku.ca/~oz/hash.html}
 * @see {@link https://gist.github.com/eplawless/52813b1d8ad9af510d85?permalink_comment_id=3367765#gistcomment-3367765}
 * @todo If we need it, we can create case-sensitive versions of these functions
 */
/**
 * Make a unique hash from the given array of code points
 *
 * @param arr Reference to the array of code points
 * @param start Start index
 * @param end End index
 * @returns Hash of the given array of code points
 * @note Case-insensitive (we use it just for function names which are case-insensitive)
 */
function getCodePointsArrayHash(arr, start, end) {
    let hash = 5381;
    for (let i = start; i < end; i += 1) {
        hash = hash * 33 ^ (arr[i] | 0x20);
    }
    return hash >>> 0;
}

/**
 * @file Tokenizer context
 */
/**
 * Context of the tokenizer which is shared between all the functions
 */
class TokenizerContext {
    /**
     * Cached source length
     */
    length;
    /**
     * Reference to the `onToken` callback function
     */
    onToken;
    /**
     * Reference to the `onError` callback function
     */
    onError;
    /**
     * Unicode code points of the source string
     *
     * @note The last code point is always EOF ("imaginary" code point)
     * @note Using `!` is safe here because the `preprocess` function always sets the codes in the constructor
     * @note We need a signed 32-bit integer array, because the code points are 21-bit integers + imaginary code points
     * are negative numbers
     */
    codes;
    /**
     * Actual position in the source string
     */
    cursor;
    /**
     * Custom function handlers to handle special functions, like Extended CSS's pseudo selectors
     */
    customFunctionHandlers;
    /**
     * Constructs a new tokenizer context instance
     *
     * @param source Source string
     * @param onToken Callback function to call when a token is found
     * @param onError Callback function to call when a parsing error occurs
     * @param functionHandlers Custom function handlers to handle special functions, like Extended CSS's pseudo
     * selectors
     */
    constructor(source, onToken, onError, functionHandlers) {
        // Set the source and offset
        // this.source = source;
        this.length = source.length;
        this.preprocess(source);
        // Ignore BOM character if present
        this.cursor = isBOM(this.codes[0]) ? 1 : 0;
        // Set the callback functions
        this.onToken = onToken;
        this.onError = onError;
        // Register custom function handlers, if any
        if (functionHandlers) {
            this.customFunctionHandlers = new Map();
            for (const [hash, handler] of functionHandlers) {
                this.customFunctionHandlers.set(hash, handler);
            }
        }
    }
    /**
     * § 3.3. Preprocessing the input stream
     *
     * @param source Source string to preprocess
     * @see {@link https://www.w3.org/TR/css-syntax-3/#input-preprocessing}
     */
    preprocess(source) {
        const len = source.length;
        this.codes = new Int32Array(len + 1); // add +1 slot for the EOF "code point"
        // TODO: Uncomment when needed - actually, we don't convert the CRLF to LF to keep the original source positions
        // // The input stream consists of the filtered code points pushed into it as the input byte stream is decoded.
        // for (let i = 0; i < len; i += 1) {
        //     const code = source.charCodeAt(i);
        //     // To filter code points from a stream of (unfiltered) code points input:
        //     switch (code) {
        //         // Replace any U+000D CARRIAGE RETURN (CR) code points, U+000C FORM FEED (FF) code points, or pairs
        //         // of U+000D CARRIAGE RETURN (CR) followed by U+000A LINE FEED (LF) in input by a single
        //         // U+000A LINE FEED (LF) code point.
        //         case CodePoint.CarriageReturn:
        //             if (source.charCodeAt(i + 1) === CodePoint.LineFeed) {
        //                 this.codes[i] = CodePoint.LineFeed;
        //                 // Skip the next code point
        //                 i += 1;
        //                 break;
        //             }
        //             this.codes[i] = CodePoint.LineFeed;
        //             break;
        //         case CodePoint.FormFeed:
        //             this.codes[i] = CodePoint.LineFeed;
        //             break;
        //         // Replace any U+0000 NULL or surrogate code points in input with U+FFFD REPLACEMENT CHARACTER (�).
        //         case CodePoint.Null:
        //             this.codes[i] = CodePoint.ReplacementCharacter;
        //             break;
        //         default:
        //             this.codes[i] = code;
        //             break;
        //     }
        // }
        // Everything what we need here is to transform the ASCII source to Unicode code points as fast as possible
        for (let i = 0; i < len; i += 1) {
            this.codes[i] = source.charCodeAt(i);
        }
        // Set last code point to EOF (this way we can use it in switch-case statements, which are faster than if-else
        // or classic lookup tables)
        // See https://stackoverflow.com/a/37955539
        this.codes[len] = -1 /* ImaginaryCodePoint.Eof */;
    }
    /**
     * Gets the corresponding custom function handler for the given function name hash
     *
     * @param hash Function name hash
     * @returns Corresponding custom function handler or `undefined` if not found
     */
    getFunctionHandler(hash) {
        return this.customFunctionHandlers?.get(hash);
    }
    /**
     * Checks if the custom function handler is registered for the given function name hash
     *
     * @param hash Custom function name hash
     * @returns `true` if the custom function handler is registered, `false` otherwise
     */
    hasFunctionHandler(hash) {
        return this.customFunctionHandlers?.has(hash) ?? false;
    }
    /**
     * Returns the current offset
     *
     * @returns Current offset
     */
    get offset() {
        return this.cursor;
    }
    /**
     * Returns the code point at the current offset
     *
     * @returns Code point at the current offset
     */
    get code() {
        return this.codes[this.offset];
    }
    /**
     * Returns the code point at the previous offset
     *
     * @returns Code point at the previous offset or `undefined` if the offset is out of bounds
     */
    get prevCode() {
        return this.codes[this.offset - 1];
    }
    /**
     * Returns the code point at the next offset
     *
     * @returns Code point at the next offset or `undefined` if the offset is out of bounds
     */
    get nextCode() {
        return this.codes[this.offset + 1];
    }
    /**
     * Returns the code point at the given relative offset
     *
     * @param relativeOffset Relative offset
     * @returns Code point at the relative offset or `undefined` if the offset is out of bounds
     * @note Relative offset compared to the current offset. 1 means the next code point, -1 means the previous code
     * point, 2 means the code point after the next code point, etc.
     */
    getRelativeCode(relativeOffset) {
        return this.codes[this.offset + relativeOffset];
    }
    /**
     * Check if the current offset is at the end of the source (or past it)
     *
     * @returns `true` if the current offset is at the end of the source, `false` otherwise
     */
    isEof() {
        return this.offset >= this.length;
    }
    /**
     * Stops the tokenizer by moving the cursor to the end of the input.
     *
     * @note This method is defined as an arrow function to ensure it retains the correct `this` context.
     * Since `stop` is always passed to the `onToken` callback, which is invoked frequently during tokenization,
     * avoiding unnecessary overhead is crucial.
     * Using an arrow function provides better performance compared to binding the method in the constructor
     * or at the call site.
     */
    stop = () => {
        this.cursor = this.length;
    };
    /**
     * Check if the next code point is EOF
     *
     * @returns `true` if the next code point is EOF, `false` otherwise
     */
    isNextEof() {
        return this.cursor + 1 === this.length;
    }
    /**
     * Check if the current offset is less than or equal to the end of the source
     *
     * @returns `true` if the current offset is less than or equal to the end of the source, `false` otherwise
     */
    isLessThanEqualToEof() {
        return this.offset <= this.length;
    }
    /**
     * Consumes the given number of code points
     *
     * @param n Number of code points to consume (default: 1)
     * @note Negative numbers are allowed (they will move the cursor backwards)
     * @note No protection against out of bounds for performance reasons
     */
    consumeCodePoint(n = 1) {
        this.cursor += n;
    }
    /**
     * Finds the next non-whitespace code point and returns it
     *
     * @returns Next non-whitespace code point or EOF imaginary code point if the rest of the source is whitespace
     */
    getNextNonWsCode() {
        let i = this.cursor;
        while (i < this.length && isWhitespace(this.codes[i])) {
            i += 1;
        }
        return this.codes[i];
    }
    /**
     * Consumes the whitespace code points
     */
    consumeWhitespace() {
        while (this.code && isWhitespace(this.code)) {
            this.consumeCodePoint();
        }
    }
    /**
     * Consumes a single whitespace code point, if the current code point is a whitespace
     */
    consumeSingleWhitespace() {
        if (isWhitespace(this.code)) {
            // special case: consume CRLF as a single whitespace
            this.cursor += this.code === 13 /* CodePoint.CarriageReturn */ && this.nextCode === 10 /* CodePoint.LineFeed */ ? 2 : 1;
        }
    }
    /**
     * Consumes everything until the end of the comment (or the end of the source)
     */
    consumeUntilCommentEnd() {
        // search for the end of the comment or reach the end of the source
        while (this.cursor < this.length) {
            // check if the current code point is a *
            if (this.code === 42 /* CodePoint.Asterisk */ && this.nextCode === 47 /* CodePoint.Solidus */) {
                // consume '*/' and exit the loop
                this.cursor += 2;
                break;
            }
            // consume the current code point, it seems it's a part of the comment
            this.cursor += 1;
        }
    }
    /**
     * Consumes a single-character token (trivial token) and reports it via the `onToken` callback
     *
     * @param tokenType Token type to report
     */
    consumeTrivialToken(tokenType) {
        // eslint-disable-next-line no-plusplus
        this.onToken(tokenType, this.cursor, ++this.cursor, undefined, this.stop);
    }
    /**
     * Calculates the hash of the fragment from the given start offset to the current offset. This is useful to
     * fast-check function names.
     *
     * @param start Start offset
     * @returns Calculated hash
     */
    getHashFrom(start) {
        return getCodePointsArrayHash(this.codes, start, this.cursor);
    }
}

/**
 * @file Possible CSS token types, as defined in the CSS Syntax Module Level 3.
 *
 * ! Strictly follows the spec.
 *
 * @see {@link https://www.w3.org/TR/css-syntax-3/#tokenization}
 */
var TokenType;
(function (TokenType) {
    TokenType[TokenType["Eof"] = 0] = "Eof";
    TokenType[TokenType["Ident"] = 1] = "Ident";
    TokenType[TokenType["Function"] = 2] = "Function";
    TokenType[TokenType["AtKeyword"] = 3] = "AtKeyword";
    TokenType[TokenType["Hash"] = 4] = "Hash";
    TokenType[TokenType["String"] = 5] = "String";
    TokenType[TokenType["BadString"] = 6] = "BadString";
    TokenType[TokenType["Url"] = 7] = "Url";
    TokenType[TokenType["BadUrl"] = 8] = "BadUrl";
    TokenType[TokenType["Delim"] = 9] = "Delim";
    TokenType[TokenType["Number"] = 10] = "Number";
    TokenType[TokenType["Percentage"] = 11] = "Percentage";
    TokenType[TokenType["Dimension"] = 12] = "Dimension";
    TokenType[TokenType["Whitespace"] = 13] = "Whitespace";
    TokenType[TokenType["Cdo"] = 14] = "Cdo";
    TokenType[TokenType["Cdc"] = 15] = "Cdc";
    TokenType[TokenType["Colon"] = 16] = "Colon";
    TokenType[TokenType["Semicolon"] = 17] = "Semicolon";
    TokenType[TokenType["Comma"] = 18] = "Comma";
    TokenType[TokenType["OpenSquareBracket"] = 19] = "OpenSquareBracket";
    TokenType[TokenType["CloseSquareBracket"] = 20] = "CloseSquareBracket";
    TokenType[TokenType["OpenParenthesis"] = 21] = "OpenParenthesis";
    TokenType[TokenType["CloseParenthesis"] = 22] = "CloseParenthesis";
    TokenType[TokenType["OpenCurlyBracket"] = 23] = "OpenCurlyBracket";
    TokenType[TokenType["CloseCurlyBracket"] = 24] = "CloseCurlyBracket";
    TokenType[TokenType["Comment"] = 25] = "Comment";
})(TokenType || (TokenType = {}));

/**
 * @file CSS token names
 */
const UNKNOWN_TOKEN_NAME = 'unknown';
/**
 * Pairs of token types and their base names
 */
const TOKEN_NAMES = Object.freeze({
    [TokenType.Eof]: 'eof',
    [TokenType.Ident]: 'ident',
    [TokenType.Function]: 'function',
    [TokenType.AtKeyword]: 'at-keyword',
    [TokenType.Hash]: 'hash',
    [TokenType.String]: 'string',
    [TokenType.BadString]: 'bad-string',
    [TokenType.Url]: 'url',
    [TokenType.BadUrl]: 'bad-url',
    [TokenType.Delim]: 'delim',
    [TokenType.Number]: 'number',
    [TokenType.Percentage]: 'percentage',
    [TokenType.Dimension]: 'dimension',
    [TokenType.Whitespace]: 'whitespace',
    [TokenType.Cdo]: 'CDO',
    [TokenType.Cdc]: 'CDC',
    [TokenType.Colon]: 'colon',
    [TokenType.Semicolon]: 'semicolon',
    [TokenType.Comma]: 'comma',
    [TokenType.OpenSquareBracket]: '[',
    [TokenType.CloseSquareBracket]: ']',
    [TokenType.OpenParenthesis]: '(',
    [TokenType.CloseParenthesis]: ')',
    [TokenType.OpenCurlyBracket]: '{',
    [TokenType.CloseCurlyBracket]: '}',
    [TokenType.Comment]: 'comment',
});
/**
 * Get base token name by token type
 *
 * @param type Token type
 *
 * @example
 * ```ts
 * getBaseTokenName(TokenType.Ident); // 'ident'
 * getBaseTokenName(-1); // 'unknown'
 * ```
 *
 * @returns Base token name or 'unknown' if token type is unknown
 */
const getBaseTokenName = (type) => {
    return TOKEN_NAMES[type] ?? UNKNOWN_TOKEN_NAME;
};
/**
 * Get formatted token name by token type
 *
 * @param type Token type
 *
 * @example
 * ```ts
 * getFormattedTokenName(TokenType.Ident); // '<ident-token>'
 * getFormattedTokenName(-1); // '<unknown-token>'
 * ```
 *
 * @returns Formatted token name or `'<unknown-token>'` if token type is unknown
 */
const getFormattedTokenName = (type) => {
    return `<${getBaseTokenName(type)}-token>`;
};

/**
 * @file Tokenizing logic for escaped code points
 */
const MAX_HEX_DIGITS = 6;
/**
 * § 4.3.7. Consume an escaped code point
 *
 * @param context Reference to the tokenizer context instance
 * @see {@link https://www.w3.org/TR/css-syntax-3/#consume-escaped-code-point}
 */
const consumeEscapedCodePoint = (context) => {
    // It assumes that the U+005C REVERSE SOLIDUS (\) has already been consumed and that the next input code point has
    // already been verified to be part of a valid escape.
    // Consume the next input code point.
    context.consumeCodePoint();
    // hex digit
    if (isHexDigit(context.code)) {
        // Consume as many hex digits as possible, but no more than 5. Note that this means 1-6 hex digits have been
        // consumed in total. If the next input code point is whitespace, consume it as well. Interpret the hex digits
        // as a hexadecimal number.
        let consumedHexDigits = 0;
        while (isHexDigit(context.code) && consumedHexDigits <= MAX_HEX_DIGITS) {
            context.consumeCodePoint();
            consumedHexDigits += 1;
        }
        // If the next input code point is whitespace, consume it as well.
        context.consumeSingleWhitespace();
        // If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point,
        // return U+FFFD REPLACEMENT CHARACTER (�).
        // Otherwise, return the code point with that value.
        // TODO: Implement surrogate check
    }
    // EOF
    // This is a parse error. Return U+FFFD REPLACEMENT CHARACTER (�).
    if (context.isEof()) {
        context.onError("Unexpected end of file while parsing escaped code point." /* ErrorMessage.UnexpectedEofInEscaped */, context.offset, context.offset);
    }
    // anything else
    // Return the current input code point.
};

/**
 * @file Tokenizing logic for ident sequences
 */
/**
 * § 4.3.11. Consume an ident sequence
 *
 * Consume an ident sequence from a stream of code points. It returns a string containing the largest name that can be
 * formed from adjacent code points in the stream, starting from the first.
 *
 * @param context Reference to the tokenizer context instance
 * @see {@link https://www.w3.org/TR/css-syntax-3/#consume-name}
 * @note This algorithm does not do the verification of the first few code points that are necessary to ensure the
 * returned code points would constitute an <ident-token>. If that is the intended use, ensure that the stream
 * starts with an ident sequence before calling this algorithm.
 */
const consumeIndentSequence = (context) => {
    // Let result initially be an empty string.
    // Repeatedly consume the next input code point from the stream:
    while (!context.isEof()) {
        // ident code point
        if (isIdentCodePoint(context.code)) {
            // Append the code point to result.
            context.consumeCodePoint();
            continue;
        }
        // the stream starts with a valid escape
        if (checkForValidEscape(context.code, context.nextCode)) {
            // Consume an escaped code point. Append the returned code point to result.
            context.consumeCodePoint();
            consumeEscapedCodePoint(context);
            continue;
        }
        // anything else
        // Reconsume the current input code point. Return result.
        return;
    }
};

/**
 * @file Tokenizing logic for URLs
 */
/**
 * § 4.3.14. Consume the remnants of a bad url
 *
 * Consume the remnants of a bad url from a stream of code points, "cleaning up" after the tokenizer realizes that it’s
 * in the middle of a <bad-url-token> rather than a <url-token>. It returns nothing; its sole use is to consume enough
 * of the input stream to reach a recovery point where normal tokenizing can resume.
 *
 * @param context Tokenizer context
 * @see {@link https://www.w3.org/TR/css-syntax-3/#consume-remnants-of-bad-url}
 */
function consumeBadUrlRemnants(context) {
    // Repeatedly consume the next input code point from the stream:
    // eslint-disable-next-line no-constant-condition
    for (; !context.isEof(); context.consumeCodePoint()) {
        // U+0029 RIGHT PARENTHESIS ())
        if (context.code === 41 /* CodePoint.RightParenthesis */) {
            // Don’t forget to consume it.
            context.consumeCodePoint();
            return;
        }
        // the input stream starts with a valid escape
        if (checkForValidEscape(context.getRelativeCode(1), context.getRelativeCode(2))) {
            // Consume an escaped code point. This allows an escaped right parenthesis ("\)") to be encountered
            // without ending the <bad-url-token>. This is otherwise identical to the "anything else" clause.
            context.consumeCodePoint();
            consumeEscapedCodePoint(context);
            continue;
        }
        // anything else
        // Do nothing.
    }
}
/**
 * Helper function for consuming a bad url token.
 *
 * @param context Tokenizer context
 * @param start Token start offset
 * @see {@link https://www.w3.org/TR/css-syntax-3/#consume-remnants-of-bad-url}
 */
function consumeBadUrlToken(context, start) {
    consumeBadUrlRemnants(context);
    context.onToken(TokenType.BadUrl, start, context.offset, undefined, context.stop);
}
/**
 * § 4.3.6. Consume a url token
 *
 * Consume a url token from a stream of code points. It returns either a <url-token> or a <bad-url-token>.
 *
 * @param context Reference to the tokenizer context instance
 * @param start Token start offset
 * @see {@link https://www.w3.org/TR/css-syntax-3/#consume-url-token}
 * @note This algorithm assumes that the initial "url(" has already been consumed. This algorithm also assumes that
 * it’s being called to consume an "unquoted" value, like url(foo). A quoted value, like url("foo"), is parsed as a
 * <function-token>. Consume an ident-like token automatically handles this distinction; this algorithm shouldn’t be
 * called directly otherwise.
 */
const consumeUrlToken = (context, start) => {
    // Initially create a <url-token> with its value set to the empty string.
    // Consume as much whitespace as possible.
    while (isWhitespace(context.code)) {
        context.consumeCodePoint();
    }
    // Repeatedly consume the next input code point from the stream:
    // eslint-disable-next-line no-constant-condition
    while (context.offset <= context.length) {
        // TODO: Use switch-case here, but need to resolve non-printable code points first
        // U+0029 RIGHT PARENTHESIS ())
        if (context.code === 41 /* CodePoint.RightParenthesis */) {
            // Consume it.
            context.consumeCodePoint();
            // Return the <url-token>.
            context.onToken(TokenType.Url, start, context.offset, undefined, context.stop);
            return;
        }
        // EOF
        if (context.isEof()) {
            // This is a parse error. Return the <url-token>.
            context.onToken(TokenType.Url, start, context.offset, undefined, context.stop);
            context.onError("Unexpected end of file while parsing URL." /* ErrorMessage.UnexpectedEofInUrl */, start, context.offset);
            return;
        }
        // whitespace
        if (isWhitespace(context.code)) {
            // Consume as much whitespace as possible. If the next input code point is U+0029 RIGHT PARENTHESIS ())
            // or EOF, consume it and return the <url-token> (if EOF was encountered, this is a parse error);
            // otherwise, consume the remnants of a bad url, create a <bad-url-token>, and return it.
            while (isWhitespace(context.code)) {
                context.consumeCodePoint();
            }
            if (context.code === 41 /* CodePoint.RightParenthesis */ || context.isEof()) {
                context.consumeCodePoint();
                context.onToken(TokenType.Url, start, context.offset, undefined, context.stop);
                context.onError("Unexpected end of file while parsing URL." /* ErrorMessage.UnexpectedEofInUrl */, start, context.offset);
                return;
            }
            context.onError("Unexpected character in URL." /* ErrorMessage.UnexpectedCharInUrl */, start, context.offset);
            consumeBadUrlToken(context, start);
            return;
        }
        // U+0022 QUOTATION MARK (")
        // U+0027 APOSTROPHE (')
        // U+0028 LEFT PARENTHESIS (()
        // non-printable code point
        if (context.code === 34 /* CodePoint.QuotationMark */
            || context.code === 39 /* CodePoint.Apostrophe */
            || context.code === 40 /* CodePoint.LeftParenthesis */
            || isNonPrintableCodePoint(context.code)) {
            // This is a parse error. Consume the remnants of a bad url, create a <bad-url-token>, and return it.
            context.onError("Unexpected character in URL." /* ErrorMessage.UnexpectedCharInUrl */, start, context.offset);
            consumeBadUrlToken(context, start);
            return;
        }
        // U+005C REVERSE SOLIDUS (\)
        if (context.code === 92 /* CodePoint.ReverseSolidus */) {
            // If the stream starts with a valid escape, consume an escaped code point and append the returned code
            // point to the <url-token>’s value.
            if (checkForValidEscape(context.code, context.nextCode)) {
                // Consume reversed solidus, then consume escaped code point
                context.consumeCodePoint();
                consumeEscapedCodePoint(context);
                continue;
            }
            // Otherwise, this is a parse error. Consume the remnants of a bad url, create a <bad-url-token>, and
            // return it.
            context.onError("Unexpected character in URL." /* ErrorMessage.UnexpectedCharInUrl */, start, context.offset);
            consumeBadUrlToken(context, start);
            return;
        }
        // anything else
        // Append the current input code point to the <url-token>’s value.
        context.consumeCodePoint();
    }
};

/**
 * @file Tokenizing logic for ident-like tokens
 */
const URL_FUNCTION_HASH = 193422222; // getStringHash('url')
/**
 * § 4.3.4. Consume an ident-like token
 *
 * Consume an ident-like token from a stream of code points. It returns an <ident-token>, <function-token>, <url-token>,
 * or <bad-url-token>.
 *
 * @param context Reference to the tokenizer context instance
 * @see {@link https://www.w3.org/TR/css-syntax-3/#consume-an-ident-like-token}
 * @note We extended the algorithm to allow custom function handlers, but the tokenizer still strictly follows the spec.
 */
const consumeIdentLikeToken = (context) => {
    // Consume an ident sequence, and let string be the result.
    const start = context.offset;
    consumeIndentSequence(context);
    // If the ident sequence is followed by U+0028 LEFT PARENTHESIS ((), consume it as a function:
    if (context.code === 40 /* CodePoint.LeftParenthesis */) {
        // First, store the function’s name hash
        const fnHash = context.getHashFrom(start);
        // Consume the opening parenthesis.
        context.consumeCodePoint();
        // URL
        if (fnHash === URL_FUNCTION_HASH) {
            // While the next two input code points are whitespace, consume the next input code point
            // If the next one or two input code points are U+0022 QUOTATION MARK ("), U+0027 APOSTROPHE ('), or
            // whitespace followed by U+0022 QUOTATION MARK (") or U+0027 APOSTROPHE ('), then create a <function-token>
            // with its value set to string and return it.
            // ! Different from the spec, but technically it is enough to check the next non-whitespace code point
            const nextNonWsCode = context.getNextNonWsCode();
            if (nextNonWsCode === 34 /* CodePoint.QuotationMark */ || nextNonWsCode === 39 /* CodePoint.Apostrophe */) {
                context.onToken(TokenType.Function, start, context.offset, undefined, context.stop);
                return;
            }
            // Otherwise, consume a url token, and return it.
            consumeUrlToken(context, start);
            return;
        }
        // This is a good time to call custom function handlers, if any.
        // ! This is not part of the spec, but it's a good way to extend the tokenizer and if you didn't added any
        // ! custom function handler, it will not affect the tokenizer in any way, it still strictly follows the spec.
        // For performance reasons, we use `has` and `get` separately to avoid declaring a new variable every time here
        if (context.hasFunctionHandler(fnHash)) {
            // Return the <function-token>.
            context.onToken(TokenType.Function, start, context.offset, undefined, context.stop);
            // Consume the function body
            // It's safe to call the handler directly because we already checked if it exists
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            context.getFunctionHandler(fnHash)(context);
            return;
        }
        // Otherwise, if the next input code point is U+0028 LEFT PARENTHESIS ((), consume it. Create a <function-token>
        // with its value set to string and return it.
        context.onToken(TokenType.Function, start, context.offset, undefined, context.stop);
        return;
    }
    // Otherwise, create an <ident-token> with its value set to string and return it.
    context.onToken(TokenType.Ident, start, context.offset, undefined, context.stop);
};

/**
 * @file Tokenizing logic for numbers
 */
/**
 * § 4.3.12. Consume a number
 *
 * Consume a number from a stream of code points. It returns a numeric value, and a type which is either "integer" or
 * "number".
 *
 * @param context Reference to the tokenizer context instance
 * @note This algorithm does not do the verification of the first few code points that are necessary to ensure a number
 * can be obtained from the stream. Ensure that the stream starts with a number before calling this algorithm.
 * @see {@link https://www.w3.org/TR/css-syntax-3/#consume-number}
 * @todo Uncomment type/repr handling if needed - currently we don't need them, and they're not used for performance
 * reasons
 */
const consumeNumber = (context) => {
    // Execute the following steps in order:
    // 1. Initially set type to "integer". Let repr be the empty string.
    // TODO: Uncomment type/repr handling if needed
    // let type = NumberType.Integer;
    // const repr: string[] = [];
    // 2. If the next input code point is U+002B PLUS SIGN (+) or U+002D HYPHEN-MINUS (-), consume it and append it
    // to repr.
    if (context.code === 43 /* CodePoint.PlusSign */ || context.code === 45 /* CodePoint.HyphenMinus */) {
        context.consumeCodePoint();
        // TODO: Append to repr
    }
    // 3. While the next input code point is a digit, consume it and append it to repr.
    while (isDigit(context.code)) {
        context.consumeCodePoint();
        // TODO: Append to repr
    }
    // 4. If the next 2 input code points are U+002E FULL STOP (.) followed by a digit, then:
    if (context.code === 46 /* CodePoint.FullStop */ && isDigit(context.nextCode)) {
        // 1. Consume them.
        context.consumeCodePoint(2);
        // 2.Append them to repr
        // TODO: Append to repr
        // 3. Set type to "number".
        // type = NumberType.Number;
        // 4. While the next input code point is a digit, consume it and append it to repr.
        while (isDigit(context.code)) {
            context.consumeCodePoint();
            // TODO: Append to repr
        }
    }
    // 5. If the next 2 or 3 input code points are U+0045 LATIN CAPITAL LETTER E (E) or U+0065 LATIN SMALL LETTER E
    // (e) ...
    if ((context.code === 69 /* CodePoint.LatinCapitalLetterE */ || context.code === 101 /* CodePoint.LatinSmallLetterE */)) {
        // ... optionally followed by U+002D HYPHEN-MINUS (-) or U+002B PLUS SIGN (+)
        // Note: we split this into two if statements to avoid declaring a shift variable for the sign
        if ((context.nextCode === 45 /* CodePoint.HyphenMinus */ || context.nextCode === 43 /* CodePoint.PlusSign */)
            && isDigit(context.getRelativeCode(2))) {
            // 1. Consume them.
            context.consumeCodePoint(3); // e, sign, digit
            // 2. Append them to repr.
            // TODO: Append to repr
            // 3. Set type to "number".
            // TODO: Set type
            // 4. While the next input code point is a digit, consume it and append it to repr.
            while (isDigit(context.code)) {
                context.consumeCodePoint();
                // TODO: Append to repr
            }
        }
        else if (isDigit(context.nextCode)) {
            // ... followed by a digit, then:
            // 1. Consume them.
            context.consumeCodePoint(2); // e, digit
            // 2. Append them to repr.
            // TODO: Append to repr
            // 3. Set type to "number".
            // TODO: Set type
            // 4. While the next input code point is a digit, consume it and append it to repr.
            while (isDigit(context.code)) {
                context.consumeCodePoint();
                // TODO: Append to repr
            }
        }
    }
    // 6. Convert repr to a number, and set the value to the returned value.
    // TODO: Convert repr to a number
    // const value = Number(repr.join(''));
    // 7. Return value and type.
    // TODO: Uncomment type handling if needed
    // return [value, type];
};

/**
 * @file Tokenizing logic for numeric tokens
 */
/**
 * § 4.3.3. Consume a numeric token
 *
 * Consume a numeric token from a stream of code points. It returns either a <number-token>, <percentage-token>, or
 * <dimension-token>.
 *
 * @param context Reference to the tokenizer context instance
 * @see {@link https://www.w3.org/TR/css-syntax-3/#consume-numeric-token}
 */
const consumeNumericToken = (context) => {
    const start = context.offset;
    // Consume a number and let number be the result.
    consumeNumber(context);
    // If the next 3 input code points would start an ident sequence, then:
    if (checkForIdentStart(context.code, context.nextCode, context.getRelativeCode(2))) {
        // 1. Create a <dimension-token> with the same value and type flag as number, and a unit set initially to
        // the empty string.
        // 2. Consume an ident sequence. Set the <dimension-token>’s unit to the returned value.
        consumeIndentSequence(context);
        // 3. Return the <dimension-token>.
        context.onToken(TokenType.Dimension, start, context.offset, undefined, context.stop);
        return;
    }
    // Otherwise, if the next input code point is U+0025 PERCENTAGE SIGN (%), consume it. Create a
    // <percentage-token> with the same value as number, and return it.
    if (context.code === 37 /* CodePoint.PercentageSign */) {
        context.consumeCodePoint();
        context.onToken(TokenType.Percentage, start, context.offset, undefined, context.stop);
        return;
    }
    // Otherwise, create a <number-token> with the same value and type flag as number, and return it.
    context.onToken(TokenType.Number, start, context.offset, undefined, context.stop);
};

/**
 * @file Tokenizing logic for strings
 */
/**
 * § 4.3.5. Consume a string token
 *
 * Consume a string token from a stream of code points. It returns either a <string-token> or <bad-string-token>.
 *
 * @param context Reference to the tokenizer context instance
 * @see {@link https://www.w3.org/TR/css-syntax-3/#consume-string-token}
 */
const consumeStringToken = (context) => {
    // This algorithm may be called with an ending code point, which denotes the code point that ends the string.
    // If an ending code point is not specified, the current input code point is used.
    const endingCodePoint = context.code;
    // Initially create a <string-token> with its value set to the empty string.
    const start = context.offset;
    // Consume opening character
    context.consumeCodePoint();
    // Repeatedly consume the next input code point from the stream:
    // eslint-disable-next-line no-constant-condition
    while (context.isLessThanEqualToEof()) {
        switch (context.code) {
            // ending code point
            case endingCodePoint:
                // Consume it
                context.consumeCodePoint();
                // Return the <string-token>.
                context.onToken(TokenType.String, start, context.offset, undefined, context.stop);
                return;
            // EOF
            case -1 /* ImaginaryCodePoint.Eof */:
                // This is a parse error. Return the <string-token>.
                context.onToken(TokenType.String, start, context.offset, undefined, context.stop);
                context.onError("Unexpected end of file while parsing string token." /* ErrorMessage.UnexpectedEofInString */, start, context.offset);
                return;
            // newline
            case 13 /* CodePoint.CarriageReturn */:
            case 10 /* CodePoint.LineFeed */:
            case 12 /* CodePoint.FormFeed */:
                // Special case: CRLF is 2 code points
                if (context.code === 13 /* CodePoint.CarriageReturn */ && context.nextCode === 10 /* CodePoint.LineFeed */) {
                    // Do an extra consume
                    context.consumeCodePoint(1);
                }
                context.consumeCodePoint(1);
                // This is a parse error. Reconsume the current input code point, create a <bad-string-token>, and
                // return it.
                context.onToken(TokenType.BadString, start, context.offset, undefined, context.stop);
                context.onError("Unexpected newline while parsing string token." /* ErrorMessage.UnexpectedNewlineInString */, start, context.offset);
                return;
            // U+005C REVERSE SOLIDUS (\)
            case 92 /* CodePoint.ReverseSolidus */:
                // If the next input code point is EOF, do nothing.
                if (context.isNextEof()) {
                    context.consumeCodePoint();
                    context.onToken(TokenType.String, start, context.offset, undefined, context.stop);
                    context.onError("Unexpected end of file while parsing string token." /* ErrorMessage.UnexpectedEofInString */, start, context.offset);
                    return;
                }
                // Otherwise, if the next input code point is a newline, consume it.
                if (isNewline(context.nextCode)) {
                    context.consumeCodePoint(2);
                    break;
                }
                // Otherwise, (the stream starts with a valid escape) consume an escaped code point and append the
                // returned code point to the <string-token>’s value.
                if (checkForValidEscape(context.code, context.nextCode)) {
                    context.consumeCodePoint();
                    consumeEscapedCodePoint(context);
                }
                break;
            // anything else
            default:
                // Append the current input code point to the <string-token>’s value.
                context.consumeCodePoint();
        }
    }
};

/**
 * @file Tokenizing logic for whitespace
 */
/**
 * § 4.3.1. Consume a token (whitespace)
 *
 * @see {@link https://www.w3.org/TR/css-syntax-3/#consume-token}
 * @param context Reference to the tokenizer context instance
 */
const consumeWhitespaceToken = (context) => {
    // Consume as much whitespace as possible. Return a <whitespace-token>.
    const start = context.offset;
    context.consumeWhitespace();
    context.onToken(TokenType.Whitespace, start, context.offset, undefined, context.stop);
};

/**
 * @file CSS tokenizer that strictly follows the CSS Syntax Module Level 3 specification
 *
 * @see {@link https://www.w3.org/TR/css-syntax-3/#tokenization}
 */
/**
 * CSS tokenizer function
 *
 * @param source Source code to tokenize
 * @param onToken Tokenizer callback which is called for each token found in source code
 * @param onError Error callback which is called when a parsing error is found (optional)
 * @param functionHandlers Custom function handlers (optional)
 */
const tokenize = (source, onToken, onError = () => { }, functionHandlers) => {
    // Create tokenizer context
    const context = new TokenizerContext(source, onToken, onError, functionHandlers);
    // Repeatedly consume the next input code point from the stream:
    while (!context.isEof()) {
        switch (context.code) {
            // According to the spec, these are all whitespace code points:
            case 9 /* CodePoint.CharacterTabulation */:
            case 32 /* CodePoint.Space */:
            case 10 /* CodePoint.LineFeed */:
            case 12 /* CodePoint.FormFeed */:
            case 13 /* CodePoint.CarriageReturn */:
                // Consume as much whitespace as possible. Return a <whitespace-token>.
                consumeWhitespaceToken(context);
                break;
            // Digit
            case 48 /* CodePoint.DigitZero */:
            case 49 /* CodePoint.DigitOne */:
            case 50 /* CodePoint.DigitTwo */:
            case 51 /* CodePoint.DigitThree */:
            case 52 /* CodePoint.DigitFour */:
            case 53 /* CodePoint.DigitFive */:
            case 54 /* CodePoint.DigitSix */:
            case 55 /* CodePoint.DigitSeven */:
            case 56 /* CodePoint.DigitEight */:
            case 57 /* CodePoint.DigitNine */:
                consumeNumericToken(context);
                break;
            case 40 /* CodePoint.LeftParenthesis */:
                context.consumeTrivialToken(TokenType.OpenParenthesis);
                break;
            case 41 /* CodePoint.RightParenthesis */:
                context.consumeTrivialToken(TokenType.CloseParenthesis);
                break;
            case 44 /* CodePoint.Comma */:
                context.consumeTrivialToken(TokenType.Comma);
                break;
            case 58 /* CodePoint.Colon */:
                context.consumeTrivialToken(TokenType.Colon);
                break;
            case 59 /* CodePoint.SemiColon */:
                context.consumeTrivialToken(TokenType.Semicolon);
                break;
            case 91 /* CodePoint.LeftSquareBracket */:
                context.consumeTrivialToken(TokenType.OpenSquareBracket);
                break;
            case 93 /* CodePoint.RightSquareBracket */:
                context.consumeTrivialToken(TokenType.CloseSquareBracket);
                break;
            case 123 /* CodePoint.LeftCurlyBracket */:
                context.consumeTrivialToken(TokenType.OpenCurlyBracket);
                break;
            case 125 /* CodePoint.RightCurlyBracket */:
                context.consumeTrivialToken(TokenType.CloseCurlyBracket);
                break;
            case 39 /* CodePoint.Apostrophe */:
            case 34 /* CodePoint.QuotationMark */:
                // Consume a string token and return it.
                consumeStringToken(context);
                break;
            case 35 /* CodePoint.NumberSign */:
                // If the next input code point is an ident code point or the next two input code points are a
                // valid escape, then:
                if (isIdentCodePoint(context.getRelativeCode(1))
                    || checkForValidEscape(context.getRelativeCode(1), context.getRelativeCode(2))) {
                    const start = context.offset;
                    // 1. Create a <hash-token>.
                    // 2. If the next 3 input code points would start an ident sequence, set the <hash-token>’s
                    // type flag to "id".
                    // TODO: Uncomment when needed
                    // const props = {
                    //     typeFlag: checkForIdentStart(
                    //         context.getRelativeCode(1),
                    //         context.getRelativeCode(2),
                    //         context.getRelativeCode(3),
                    //     ) ? 'id' : 'unrestricted',
                    // };
                    // Consume an ident sequence, and set the <hash-token>’s value to the returned string.
                    context.consumeCodePoint();
                    consumeIndentSequence(context);
                    // 4. Return the <hash-token>.
                    // TODO: Uncomment when needed
                    // context.onToken(TokenType.Hash, start, context.offset, props);
                    context.onToken(TokenType.Hash, start, context.offset, undefined, context.stop);
                    break;
                }
                // Otherwise, return a <delim-token> with its value set to the current input code point.
                context.consumeTrivialToken(TokenType.Delim);
                break;
            case 43 /* CodePoint.PlusSign */:
                // If the input stream starts with a number, reconsume the current input code point, consume a
                // numeric token, and return it.
                if (checkForNumberStart(context.code, context.getRelativeCode(1), context.getRelativeCode(2))) {
                    consumeNumericToken(context);
                    break;
                }
                // Otherwise, return a <delim-token> with its value set to the current input code point.
                context.consumeTrivialToken(TokenType.Delim);
                break;
            case 45 /* CodePoint.HyphenMinus */:
                // If the input stream starts with a number, reconsume the current input code point, consume a
                // numeric token, and return it.
                if (checkForNumberStart(context.code, context.getRelativeCode(1), context.getRelativeCode(2))) {
                    consumeNumericToken(context);
                    break;
                }
                // Otherwise, if the next 2 input code points are U+002D HYPHEN-MINUS U+003E GREATER-THAN SIGN
                // (>), consume them and return a <CDC-token>.
                if (context.getRelativeCode(1) === 45 /* CodePoint.HyphenMinus */
                    && context.getRelativeCode(2) === 62 /* CodePoint.GreaterThanSign */) {
                    context.consumeCodePoint(3);
                    context.onToken(TokenType.Cdc, context.offset - 3, context.offset, undefined, context.stop);
                    break;
                }
                // Otherwise, if the input stream starts with an ident sequence, reconsume the current input
                // code point, consume an ident-like token, and return it.
                if (checkForIdentStart(context.code, context.getRelativeCode(1), context.getRelativeCode(2))) {
                    consumeIdentLikeToken(context);
                    break;
                }
                // Otherwise, return a <delim-token> with its value set to the current input code point.
                context.consumeTrivialToken(TokenType.Delim);
                break;
            case 46 /* CodePoint.FullStop */:
                // If the input stream starts with a number, reconsume the current input code point, consume a
                // numeric token, and return it.
                if (checkForNumberStart(context.code, context.getRelativeCode(1), context.getRelativeCode(2))) {
                    consumeNumericToken(context);
                    break;
                }
                // Otherwise, return a <delim-token> with its value set to the current input code point.
                context.consumeTrivialToken(TokenType.Delim);
                break;
            case 60 /* CodePoint.LessThanSign */:
                // If the next 3 input code points are U+0021 EXCLAMATION MARK U+002D HYPHEN-MINUS U+002D
                // HYPHEN-MINUS (!--), consume them and return a <CDO-token>.
                if (context.getRelativeCode(1) === 33 /* CodePoint.ExclamationMark */
                    && context.getRelativeCode(2) === 45 /* CodePoint.HyphenMinus */
                    && context.getRelativeCode(3) === 45 /* CodePoint.HyphenMinus */) {
                    context.consumeCodePoint(4);
                    context.onToken(TokenType.Cdo, context.offset - 4, context.offset, undefined, context.stop);
                    break;
                }
                // Otherwise, return a <delim-token> with its value set to the current input code point.
                context.consumeTrivialToken(TokenType.Delim);
                break;
            case 64 /* CodePoint.CommercialAt */:
                // If the next 3 input code points would start an ident sequence, consume an ident sequence,
                // create an <at-keyword-token> with its value set to the returned value, and return it.
                if (checkForIdentStart(context.getRelativeCode(1), context.getRelativeCode(2), context.getRelativeCode(3))) {
                    const start = context.offset;
                    // Consume commercial at character
                    context.consumeCodePoint();
                    // Consume ident sequence after commercial at character
                    consumeIndentSequence(context);
                    context.onToken(TokenType.AtKeyword, start, context.offset, undefined, context.stop);
                    break;
                }
                // Otherwise, return a <delim-token> with its value set to the current input code point.
                context.consumeTrivialToken(TokenType.Delim);
                break;
            case 92 /* CodePoint.ReverseSolidus */:
                // If the input stream starts with a valid escape, reconsume the current input code point,
                // consume an ident-like token, and return it.
                if (checkForValidEscape(context.code, context.getRelativeCode(1))) {
                    consumeIdentLikeToken(context);
                    break;
                }
                // Otherwise, this is a parse error. Return a <delim-token> with its value set to the current
                // input code point.
                context.consumeTrivialToken(TokenType.Delim);
                context.onError("Invalid escape sequence." /* ErrorMessage.InvalidEscapeSequence */, context.offset - 1, context.offset);
                break;
            case 47 /* CodePoint.Solidus */:
                // If the next two input code point are U+002F SOLIDUS (/) followed by a U+002A ASTERISK (*),
                // If the preceding paragraph ended by consuming an EOF code point, this is a parse error.
                if (context.getRelativeCode(1) === 42 /* CodePoint.Asterisk */) {
                    const start = context.offset;
                    // Consume U+002F SOLIDUS (/) and U+002A ASTERISK (*)
                    context.consumeCodePoint(2);
                    // consume them and all following code points up to and including the first U+002A ASTERISK
                    // (*) followed by a U+002F SOLIDUS (/), or up to an EOF code point. Return to the start of
                    // this step.
                    context.consumeUntilCommentEnd();
                    if (context.isEof()) {
                        context.onError("Unterminated comment." /* ErrorMessage.UnterminatedComment */, start, context.length - 2);
                    }
                    context.onToken(TokenType.Comment, start, context.offset, undefined, context.stop);
                    break;
                }
                // Otherwise, return a <delim-token> with its value set to the current input code point.
                context.consumeTrivialToken(TokenType.Delim);
                break;
            // anything else
            default:
                // Can't be optimized because of the control threshold
                if (isIdentStartCodePoint(context.code)) {
                    // Reconsume the current input code point, consume an ident-like token, and return it.
                    consumeIdentLikeToken(context);
                    break;
                }
                // Return a <delim-token> with its value set to the current input code point.
                context.consumeTrivialToken(TokenType.Delim);
        }
    }
};

/**
 * @file Custom tokenizing logic for Extended CSS's pseudo-classes
 */
/**
 * Generic handler for the Extended CSS's pseudo-classes
 *
 * @param context Reference to the tokenizer context instance
 */
const handleRegularExtendedCssPseudo = (context) => {
    // Save the current offset, because we will need it later
    const start = context.offset;
    // Consume as much whitespace as possible
    context.consumeWhitespace();
    // If the first non-whitespace code point is an apostrophe or a quotation mark, it means that we are dealing
    // with a string parameter.
    // In this case, we simply abort the custom handler here, and let the standard tokenizer handle the string and
    // everything that comes after it as specified in the spec.
    // This behavior is similar to the standard CSS's url() function, it is also handled differently if its parameter
    // is a string.
    if (context.code === 39 /* CodePoint.Apostrophe */ || context.code === 34 /* CodePoint.QuotationMark */) {
        // Report whitespace tokens (if any)
        // It is important to report them, because we already consumed them - and the report is faster here than
        // a re-consume
        if (context.offset > start) {
            context.onToken(TokenType.Whitespace, start, context.offset, undefined, context.stop);
        }
        // We simply abort the custom handler
        return;
    }
    // Otherwise, we need to find the closing parenthesis based on the parenthesis balance
    // Parenthesis balance: 1, because we start after the opening parenthesis:
    // :contains(param)
    //           ^ we starts from here, so we already have 1 open parenthesis
    let balance = 1;
    // Don't forget to report already consumed whitespace chars as delim-tokens (if any)
    // Note: we handle the parameter characters as delim-tokens, this is why we don't need to report them here
    // as whitespace-tokens
    for (let i = start; i < context.offset; i += 1) {
        context.onToken(TokenType.Delim, i, i + 1, undefined, context.stop);
    }
    // Consume until we find the closing parenthesis or we reach the end of the source
    while (!context.isEof()) {
        if (context.code === 40 /* CodePoint.LeftParenthesis */ && context.prevCode !== 92 /* CodePoint.ReverseSolidus */) {
            // If we find an unescaped opening parenthesis, we increase the balance
            balance += 1;
        }
        else if (context.code === 41 /* CodePoint.RightParenthesis */ && context.prevCode !== 92 /* CodePoint.ReverseSolidus */) {
            // If we find an unescaped closing parenthesis, we decrease the balance
            balance -= 1;
            // If the balance is 0, it means that we found the closing parenthesis
            if (balance === 0) {
                break;
            }
        }
        // Consume the current character as a delim-token
        context.consumeTrivialToken(TokenType.Delim);
    }
};

/**
 * @file Custom tokenizing logic for Extended CSS's `:xpath()` pseudo-class
 * @note `:xpath()` is a bit tricky, because it can contain unescaped parentheses inside strings in the XPath
 * expression.
 */
/**
 * Handler for the Extended CSS's `:xpath()` pseudo-class
 *
 * @param context Reference to the tokenizer context instance
 */
const handleXpathExtendedCssPseudo = (context) => {
    // Save the current offset, because we will need it later
    const start = context.offset;
    // Consume as much whitespace as possible
    context.consumeWhitespace();
    // If the first non-whitespace code point is an apostrophe or a quotation mark, it means that we are dealing
    // with a string parameter.
    // In this case, we simply abort the custom handler here, and let the standard tokenizer handle the string and
    // everything that comes after it as specified in the spec.
    // This behavior is similar to the standard CSS's url() function, it is also handled differently if its parameter
    // is a string.
    if (context.code === 39 /* CodePoint.Apostrophe */ || context.code === 34 /* CodePoint.QuotationMark */) {
        // Report whitespace tokens (if any)
        // It is important to report them, because we already consumed them - and the report is faster here than
        // a re-consume
        if (context.offset > start) {
            context.onToken(TokenType.Whitespace, start, context.offset, undefined, context.stop);
        }
        // We simply abort the custom handler
        return;
    }
    // Otherwise, we need to find the closing parenthesis based on the parenthesis balance
    // Parenthesis balance: 1, because we start after the opening parenthesis:
    // :xpath(param)
    //        ^ we starts from here, so we already have 1 open parenthesis
    let balance = 1;
    // Don't forget to report already consumed whitespace chars as delim-tokens (if any)
    // Note: we handle the parameter characters as delim-tokens, this is why we don't need to report them here
    // as whitespace-tokens
    for (let i = start; i < context.offset; i += 1) {
        context.onToken(TokenType.Delim, i, i + 1, undefined, context.stop);
    }
    // :xpath() is a bit tricky, because it can contain unescaped parentheses inside strings in the XPath expression,
    // like this:
    // :xpath(//div[@class="foo(bar)"])
    // but in this case, not required the whole XPath expression to be a string
    let inString = false;
    // Consume until we find the closing parenthesis or we reach the end of the source
    while (!context.isEof()) {
        // If we find an unescaped quote mark, we toggle the "inString" flag
        // It is important, because we should omit parentheses inside strings.
        if (context.code === 34 /* CodePoint.QuotationMark */ && context.prevCode !== 92 /* CodePoint.ReverseSolidus */) {
            inString = !inString;
        }
        // If we are not inside a string, we should check parentheses balance
        if (!inString) {
            if (context.code === 40 /* CodePoint.LeftParenthesis */ && context.prevCode !== 92 /* CodePoint.ReverseSolidus */) {
                // If we find an unescaped opening parenthesis, we increase the balance
                balance += 1;
            }
            else if (context.code === 41 /* CodePoint.RightParenthesis */ && context.prevCode !== 92 /* CodePoint.ReverseSolidus */) {
                // If we find an unescaped closing parenthesis, we decrease the balance
                balance -= 1;
                // If the balance is 0, it means that we found the closing parenthesis of the
                // pseudo-class
                if (balance === 0) {
                    break;
                }
            }
        }
        // Consume the current character as a delim-token
        context.consumeTrivialToken(TokenType.Delim);
    }
};

/**
 * @file Map utility functions
 */
/**
 * Simple utility function to merge two maps.
 *
 * @param map1 First map
 * @param map2 Second map
 * @returns Merged map
 * @note If a key is present in both maps, the value from the second map will be used
 * @note This function does not modify the original maps, it returns a new map
 */
function mergeMaps(map1, map2) {
    const result = new Map();
    for (const [key, value] of map1) {
        result.set(key, value);
    }
    for (const [key, value] of map2) {
        result.set(key, value);
    }
    return result;
}

/**
 * @file Extended CSS tokenizer that extends the core CSS tokenizer
 *
 * This library supports various Extended CSS language elements from
 * - AdGuard,
 * - uBlock Origin and
 * - Adblock Plus.
 *
 * @see {@link https://github.com/AdguardTeam/ExtendedCss}
 * @see {@link https://github.com/gorhill/uBlock/wiki/Procedural-cosmetic-filters}
 * @see {@link https://help.adblockplus.org/hc/en-us/articles/360062733293#elemhide-emulation}
 */
const ABP_CONTAINS_HASH = 1989084725; // getStringHash('-abp-contains')
const CONTAINS_HASH = 2399470598; // getStringHash('contains')
const HAS_TEXT_HASH = 1221663855; // getStringHash('has-text')
const MATCHES_CSS_HASH = 102304302; // getStringHash('matches-css')
const MATCHES_CSS_AFTER_HASH = 2923888231; // getStringHash('matches-css-after')
const MATCHES_CSS_BEFORE_HASH = 1739713050; // getStringHash('matches-css-before')
const MATCHES_PROPERTY_HASH = 1860790666; // getStringHash('matches-property')
const MATCHES_ATTR_HASH = 3376104318; // getStringHash('matches-attr')
const XPATH_HASH = 196571984; // getStringHash('xpath')
/**
 * Map of Extended CSS's pseudo-classes and their respective handler functions
 */
const EXT_CSS_PSEUDO_HANDLERS = new Map([
    // Note: alternatively, you can use `getStringHash` to get the hash of the pseudo-class name, but we use
    // pre-calculated hashes here for performance reasons
    [ABP_CONTAINS_HASH, handleRegularExtendedCssPseudo],
    [CONTAINS_HASH, handleRegularExtendedCssPseudo],
    [HAS_TEXT_HASH, handleRegularExtendedCssPseudo],
    [MATCHES_CSS_HASH, handleRegularExtendedCssPseudo],
    [MATCHES_CSS_AFTER_HASH, handleRegularExtendedCssPseudo],
    [MATCHES_CSS_BEFORE_HASH, handleRegularExtendedCssPseudo],
    [MATCHES_PROPERTY_HASH, handleRegularExtendedCssPseudo],
    [MATCHES_ATTR_HASH, handleRegularExtendedCssPseudo],
    [XPATH_HASH, handleXpathExtendedCssPseudo],
]);
/**
 * Extended CSS tokenizer function
 *
 * @param source Source code to tokenize
 * @param onToken Tokenizer callback which is called for each token found in source code
 * @param onError Error callback which is called when a parsing error is found (optional)
 * @param functionHandlers Custom function handlers (optional)
 * @note If you specify custom function handlers, they will be merged with the default function handlers. If you
 * duplicate a function handler, the custom one will be used instead of the default one, so you can override the default
 * function handlers this way, if you want to.
 */
const tokenizeExtended = (source, onToken, onError = () => { }, functionHandlers = new Map()) => {
    tokenize(source, onToken, onError, 
    // Register custom function handlers for Extended CSS's pseudo-classes, but do not call mergeMaps if there are
    // no custom function handlers are provided
    functionHandlers.size > 0
        ? mergeMaps(EXT_CSS_PSEUDO_HANDLERS, functionHandlers)
        : EXT_CSS_PSEUDO_HANDLERS);
};

/**
 * @file CSS identifier decoder.
 */
const EMPTY_STRING = '';
/**
 * Decodes a CSS identifier according to the CSS Syntax Module Level 3 specification.
 *
 * @param ident CSS identifier to decode.
 *
 * @example
 * ```ts
 * decodeIdent(String.raw`\00075\00072\0006C`); // 'url'
 * decodeIdent('url'); // 'url'
 * ```
 *
 * @returns Decoded CSS identifier.
 */
const decodeIdent = (ident) => {
    const decodedIdent = [];
    for (let i = 0; i < ident.length; i += 1) {
        const codePoint = ident.charCodeAt(i);
        // 4.3.7. Consume an escaped code point
        // https://www.w3.org/TR/css-syntax-3/#consume-an-escaped-code-point
        if (codePoint === 92 /* CodePoint.ReverseSolidus */) {
            // hex digit
            if (isHexDigit(ident.charCodeAt(i + 1))) {
                // Consume as many hex digits as possible, but no more than 5.
                // Note that this means 1-6 hex digits have been consumed in total.
                let n = 0;
                let j = 0; // consumed hex digits
                while (j < MAX_HEX_DIGITS && isHexDigit(ident.charCodeAt(i + j + 1))) {
                    // Interpret the hex digits as a hexadecimal number.
                    n = n * 16 + parseInt(ident[i + j + 1], 16);
                    j += 1;
                }
                decodedIdent.push(
                // If this number is zero, or is for a surrogate, or is greater than the maximum allowed code
                // point, return U+FFFD REPLACEMENT CHARACTER (�).
                // Otherwise, return the code point with that value.
                String.fromCodePoint(n === 0 || isSurrogate(n) || isGreaterThanMaxAllowedCodePoint(n)
                    ? 65533 /* CodePoint.ReplacementCharacter */
                    : n));
                i += j;
                // If the next input code point is whitespace, consume it as well.
                const nextCodePoint = ident.charCodeAt(i + 1);
                if (isWhitespace(nextCodePoint)) {
                    // Consume whitespace character
                    i += 1;
                    // Special case: consume +1 character if the sequence is CR LF
                    if (nextCodePoint === 13 /* CodePoint.CarriageReturn */ && ident.charCodeAt(i + 1) === 10 /* CodePoint.LineFeed */) {
                        i += 1;
                    }
                }
            }
            // do nothing for EOF
        }
        else {
            // anything else
            // Return the current input code point.
            decodedIdent.push(ident[i]);
        }
    }
    return decodedIdent.join(EMPTY_STRING);
};

const version = "1.2.0";

/**
 * @file Package version
 */
// ! Notice:
// Don't export version from package.json directly, because if you run `tsc` in the root directory, it will generate
// `dist/types/src/version.d.ts` with wrong relative path to `package.json`. So we need this little "hack"
const CSS_TOKENIZER_VERSION = (/* unused pure expression or super */ null && (version));

/**
 * Checks if the given raw string contains any of the specified tokens.
 *
 * @param raw - The raw string to be tokenized and checked.
 * @param tokens - A set of token types to check for in the raw string.
 * @param tokenizer - The tokenizer function to use. Defaults to `tokenizeExtended`.
 * @returns `true` if any of the specified tokens are found in the raw string, otherwise `false`.
 */
const hasToken = (raw, tokens, tokenizer = tokenizeExtended) => {
    let found = false;
    tokenizer(raw, (type, start, end, props, stop) => {
        if (tokens.has(type)) {
            found = true;
            stop();
        }
    });
    return found;
};




/***/ }),

/***/ 89814:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   H: () => (/* binding */ AbpSnippetInjectionBodyCommon)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Common class for the ABP snippet injection body.
 * This class contains shared constants and utilities for handling ABP snippet injection bodies.
 */
class AbpSnippetInjectionBodyCommon {
    /**
     * Error messages used by the parser and generator.
     */
    static ERROR_MESSAGES = {
        /**
         * Error message indicating that an ABP snippet call is empty.
         */
        EMPTY_SCRIPTLET_CALL: 'Empty ABP snippet call',
    };
}




/***/ }),

/***/ 64163:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   w: () => (/* binding */ getAdblockSyntax)
/* harmony export */ });
/* harmony import */ var _utils_adblockers_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(88226);
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * Possible AdGuard agent markers.
 */
const ADG_NAME_MARKERS = new Set([
    'adguard',
    'adg',
]);
/**
 * Possible uBlock Origin agent markers.
 */
const UBO_NAME_MARKERS = new Set([
    'ublock',
    'ublock origin',
    'ubo',
]);
/**
 * Possible Adblock Plus agent markers.
 */
const ABP_NAME_MARKERS = new Set([
    'adblock',
    'adblock plus',
    'adblockplus',
    'abp',
]);
/**
 * Returns the adblock syntax based on the adblock name parsed from the agent type comment.
 * Needed for modifiers validation of network rules by AGLint.
 *
 * @param name Adblock name.
 *
 * @returns Adblock syntax.
 */
const getAdblockSyntax = (name) => {
    let syntax = _utils_adblockers_js__WEBPACK_IMPORTED_MODULE_0__/* .AdblockSyntax */ .Y.Common;
    const lowerCaseName = name.toLowerCase();
    if (ADG_NAME_MARKERS.has(lowerCaseName)) {
        syntax = _utils_adblockers_js__WEBPACK_IMPORTED_MODULE_0__/* .AdblockSyntax */ .Y.Adg;
    }
    else if (UBO_NAME_MARKERS.has(lowerCaseName)) {
        syntax = _utils_adblockers_js__WEBPACK_IMPORTED_MODULE_0__/* .AdblockSyntax */ .Y.Ubo;
    }
    else if (ABP_NAME_MARKERS.has(lowerCaseName)) {
        syntax = _utils_adblockers_js__WEBPACK_IMPORTED_MODULE_0__/* .AdblockSyntax */ .Y.Abp;
    }
    return syntax;
};




/***/ }),

/***/ 31784:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   S: () => (/* binding */ UboPseudoName)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Known uBO-specific pseudo-class names.
 */
const UboPseudoName = {
    MatchesMedia: 'matches-media',
    MatchesPath: 'matches-path',
    Remove: 'remove',
    Style: 'style',
};




/***/ }),

/***/ 9119:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   PY: () => (/* binding */ ABP_EXT_CSS_PREFIX),
/* harmony export */   Ss: () => (/* binding */ EXT_CSS_PSEUDO_CLASSES),
/* harmony export */   at: () => (/* binding */ LEGACY_EXT_CSS_ATTRIBUTE_PREFIX),
/* harmony export */   ig: () => (/* binding */ EXT_CSS_PSEUDO_CLASSES_STRICT)
/* harmony export */ });
/* unused harmony exports EXT_CSS_LEGACY_ATTRIBUTES, FORBIDDEN_CSS_FUNCTIONS */
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * @file Known CSS elements and attributes.
 * TODO: Implement a compatibility table for Extended CSS
 */
/**
 * Legacy Extended CSS attribute prefix.
 *
 * @example
 * ```css
 * [-ext-<name>=...]
 * ```
 */
const LEGACY_EXT_CSS_ATTRIBUTE_PREFIX = '-ext-';
/**
 * ABP Extended CSS prefix.
 *
 * @example
 * ```css
 * [-abp-<name>=...]
 * -abp-<name>(...)
 * ```
 */
const ABP_EXT_CSS_PREFIX = '-abp';
/**
 * Known _strict_ Extended CSS pseudo-classes. Please, keep this list sorted.
 * Strict means that these pseudo-classes are not supported by any browser natively,
 * and they always require Extended CSS libraries to work.
 */
const EXT_CSS_PSEUDO_CLASSES_STRICT = new Set([
    // AdGuard
    // https://github.com/AdguardTeam/ExtendedCss
    'contains',
    'if-not',
    'matches-attr',
    'matches-css',
    'matches-property',
    'nth-ancestor',
    'remove',
    'upward',
    'xpath',
    // uBlock Origin
    // https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#procedural-cosmetic-filters
    'has-text',
    'matches-css-after',
    'matches-css-before',
    'matches-path',
    'min-text-length',
    'watch-attr',
    // Adblock Plus
    // https://help.eyeo.com/adblockplus/how-to-write-filters#elemhide-emulation
    '-abp-contains',
    '-abp-has',
    '-abp-properties',
]);
/**
 * _ALL_ known Extended CSS pseudo-classes. Please, keep this list sorted.
 * It includes strict pseudo-classes and additional pseudo-classes that may be
 * supported by some browsers natively.
 */
const EXT_CSS_PSEUDO_CLASSES = new Set([
    ...EXT_CSS_PSEUDO_CLASSES_STRICT,
    /**
     * https://developer.mozilla.org/en-US/docs/Web/CSS/:has
     */
    'has',
    /**
     * https://developer.mozilla.org/en-US/docs/Web/CSS/:is
     */
    'is',
]);
/**
 * Known legacy Extended CSS attributes. These attributes are deprecated and
 * should be replaced with the corresponding pseudo-classes. In a long term,
 * these attributes will be COMPLETELY removed from the Extended CSS syntax.
 *
 * Please, keep this list sorted.
 */
const EXT_CSS_LEGACY_ATTRIBUTES = new Set([
    // AdGuard
    '-ext-contains',
    '-ext-has',
    '-ext-if-not',
    '-ext-is',
    '-ext-matches-attr',
    '-ext-matches-css',
    '-ext-matches-property',
    '-ext-nth-ancestor',
    '-ext-remove',
    '-ext-upward',
    '-ext-xpath',
    // uBlock Origin
    '-ext-has-text',
    '-ext-matches-css-after',
    '-ext-matches-css-before',
    '-ext-matches-path',
    '-ext-min-text-length',
    '-ext-watch-attr',
    // Adblock Plus
    '-ext-abp-contains',
    '-ext-abp-has',
    '-ext-abp-properties',
]);
/**
 * Known CSS functions that aren't allowed in CSS injection rules, because they
 * able to load external resources. Please, keep this list sorted.
 */
const FORBIDDEN_CSS_FUNCTIONS = new Set([
    // https://developer.mozilla.org/en-US/docs/Web/CSS/cross-fade
    '-webkit-cross-fade',
    'cross-fade',
    // https://developer.mozilla.org/en-US/docs/Web/CSS/image
    'image',
    // https://developer.mozilla.org/en-US/docs/Web/CSS/image-set
    '-webkit-image-set',
    'image-set',
    // https://developer.mozilla.org/en-US/docs/Web/CSS/url
    'url',
]);




/***/ }),

/***/ 87363:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  b: () => (/* binding */ RuleConverter)
});

// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/nodes/index.js
var nodes = __webpack_require__(64638);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/constants.js
var constants = __webpack_require__(65523);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/errors/not-implemented-error.js
var not_implemented_error = __webpack_require__(65489);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/converter/base-interfaces/base-converter.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * @file Base class for converters
 *
 * TS doesn't support abstract static methods, so we should use
 * a workaround and extend this class instead of implementing it
 */
/* eslint-disable jsdoc/require-returns-check */
/* eslint-disable @typescript-eslint/no-unused-vars */
/**
 * Basic class for rule converters
 */
class BaseConverter {
    /**
     * Converts some data to AdGuard format
     *
     * @param data Data to convert
     * @returns An object which follows the {@link ConversionResult} interface. Its `result` property contains
     * the converted node, and its `isConverted` flag indicates whether the original node was converted.
     * If the node was not converted, the result will contain the original node with the same object reference
     * @throws If the data is invalid or incompatible
     */
    static convertToAdg(data) {
        throw new not_implemented_error/* NotImplementedError */.E();
    }
    /**
     * Converts some data to Adblock Plus format
     *
     * @param data Data to convert
     * @returns An object which follows the {@link ConversionResult} interface. Its `result` property contains
     * the converted node, and its `isConverted` flag indicates whether the original node was converted.
     * If the node was not converted, the result will contain the original node with the same object reference
     * @throws If the data is invalid or incompatible
     */
    static convertToAbp(data) {
        throw new not_implemented_error/* NotImplementedError */.E();
    }
    /**
     * Converts some data to uBlock Origin format
     *
     * @param data Data to convert
     * @returns An object which follows the {@link ConversionResult} interface. Its `result` property contains
     * the converted node, and its `isConverted` flag indicates whether the original node was converted.
     * If the node was not converted, the result will contain the original node with the same object reference
     * @throws If the data is invalid or incompatible
     */
    static convertToUbo(data) {
        throw new not_implemented_error/* NotImplementedError */.E();
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/converter/base-interfaces/rule-converter-base.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */



/**
 * @file Base class for rule converters
 *
 * TS doesn't support abstract static methods, so we should use
 * a workaround and extend this class instead of implementing it
 */
/* eslint-disable jsdoc/require-returns-check */
/* eslint-disable @typescript-eslint/no-unused-vars */
/**
 * Basic class for rule converters
 */
class RuleConverterBase extends BaseConverter {
    /**
     * Converts an adblock filtering rule to AdGuard format, if possible.
     *
     * @param rule Rule node to convert
     * @returns An object which follows the {@link NodeConversionResult} interface. Its `result` property contains
     * the array of converted rule nodes, and its `isConverted` flag indicates whether the original rule was converted.
     * If the rule was not converted, the result array will contain the original node with the same object reference
     * @throws If the rule is invalid or cannot be converted
     */
    static convertToAdg(rule) {
        throw new not_implemented_error/* NotImplementedError */.E();
    }
    /**
     * Converts an adblock filtering rule to Adblock Plus format, if possible.
     *
     * @param rule Rule node to convert
     * @returns An object which follows the {@link NodeConversionResult} interface. Its `result` property contains
     * the array of converted rule nodes, and its `isConverted` flag indicates whether the original rule was converted.
     * If the rule was not converted, the result array will contain the original node with the same object reference
     * @throws If the rule is invalid or cannot be converted
     */
    static convertToAbp(rule) {
        throw new not_implemented_error/* NotImplementedError */.E();
    }
    /**
     * Converts an adblock filtering rule to uBlock Origin format, if possible.
     *
     * @param rule Rule node to convert
     * @returns An object which follows the {@link NodeConversionResult} interface. Its `result` property contains
     * the array of converted rule nodes, and its `isConverted` flag indicates whether the original rule was converted.
     * If the rule was not converted, the result array will contain the original node with the same object reference
     * @throws If the rule is invalid or cannot be converted
     */
    static convertToUbo(rule) {
        throw new not_implemented_error/* NotImplementedError */.E();
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/clone-deep@4.0.1/node_modules/clone-deep/index.js
var clone_deep = __webpack_require__(51258);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/clone.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * @file Clone related utilities
 *
 * We should keep clone related functions in this file. Thus, we just provide
 * a simple interface for cloning values, we use it across the AGTree project,
 * and the implementation "under the hood" can be improved later, if needed.
 */
/**
 * Clones an input value to avoid side effects. Use it only in justified cases,
 * because it can impact performance negatively.
 *
 * @param value Value to clone
 * @returns Cloned value
 */
function clone(value) {
    // TODO: Replace cloneDeep with a more efficient implementation
    return clone_deep(value);
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/converter/base-interfaces/conversion-result.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * @file Conversion result interface and helper functions
 */
/**
 * Helper function to create a generic conversion result.
 *
 * @param result Conversion result
 * @param isConverted Indicates whether the input item was converted
 * @template T Type of the item to convert
 * @template U Type of the conversion result (defaults to `T`, but can be `T[]` as well)
 * @returns Generic conversion result
 */
// eslint-disable-next-line max-len
function createConversionResult(result, isConverted) {
    return {
        result,
        isConverted,
    };
}
/**
 * Helper function to create a node conversion result.
 *
 * @param nodes Array of nodes
 * @param isConverted Indicates whether the input item was converted
 * @template T Type of the node (extends `Node`)
 * @returns Node conversion result
 */
function createNodeConversionResult(nodes, isConverted) {
    return createConversionResult(nodes, isConverted);
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/converter/comment/index.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */






/**
 * @file Comment rule converter
 */
/**
 * Comment rule converter class
 *
 * @todo Implement `convertToUbo` and `convertToAbp`
 */
class CommentRuleConverter extends RuleConverterBase {
    /**
     * Converts a comment rule to AdGuard format, if possible.
     *
     * @param rule Rule node to convert
     * @returns An object which follows the {@link NodeConversionResult} interface. Its `result` property contains
     * the array of converted rule nodes, and its `isConverted` flag indicates whether the original rule was converted.
     * If the rule was not converted, the result array will contain the original node with the same object reference
     * @throws If the rule is invalid or cannot be converted
     */
    static convertToAdg(rule) {
        // TODO: Add support for other comment types, if needed
        // Main task is # -> ! conversion
        switch (rule.type) {
            case nodes/* CommentRuleType */.gV.CommentRule:
                // Check if the rule needs to be converted
                if (rule.type === nodes/* CommentRuleType */.gV.CommentRule && rule.marker.value === nodes/* CommentMarker */.yg.Hashmark) {
                    // Add a ! to the beginning of the comment
                    // TODO: Replace with custom clone method
                    const ruleClone = clone(rule);
                    ruleClone.marker.value = nodes/* CommentMarker */.yg.Regular;
                    // Add the hashmark to the beginning of the comment text
                    ruleClone.text.value = `${constants/* SPACE */.t6}${nodes/* CommentMarker */.yg.Hashmark}${ruleClone.text.value}`;
                    return createNodeConversionResult([ruleClone], true);
                }
                return createNodeConversionResult([rule], false);
            // Leave any other comment rule as is
            default:
                return createNodeConversionResult([rule], false);
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/adblockers.js
var adblockers = __webpack_require__(88226);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+css-tokenizer@1.2.0/node_modules/@adguard/css-tokenizer/dist/csstokenizer.mjs
var csstokenizer = __webpack_require__(25651);
// EXTERNAL MODULE: ./node_modules/.pnpm/sprintf-js@1.1.3/node_modules/sprintf-js/src/sprintf.js
var sprintf = __webpack_require__(63607);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/errors/rule-conversion-error.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * @file Customized error class for conversion errors.
 */
const ERROR_NAME = 'RuleConversionError';
/**
 * Customized error class for conversion errors.
 */
class RuleConversionError extends Error {
    /**
     * Constructs a new `RuleConversionError` instance.
     *
     * @param message Error message
     */
    constructor(message) {
        super(message);
        this.name = ERROR_NAME;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/regexp.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * @file Regular expression utilities
 */
// Special RegExp constants
const REGEX_START = constants/* CARET */.cP; // '^'
const REGEX_END = constants/* DOLLAR_SIGN */.nj; // '$'
const REGEX_ANY_CHARACTERS = constants/* DOT */.y0 + constants/* ASTERISK */.Ln; // '.*'
// Special adblock pattern symbols and their RegExp equivalents
const ADBLOCK_URL_START = constants/* PIPE */.L5 + constants/* PIPE */.L5; // '||'
const ADBLOCK_URL_START_REGEX = '^(http|https|ws|wss)://([a-z0-9-_.]+\\.)?';
const ADBLOCK_URL_SEPARATOR = constants/* CARET */.cP; // '^'
const ADBLOCK_URL_SEPARATOR_REGEX = '([^ a-zA-Z0-9.%_-]|$)';
const ADBLOCK_WILDCARD = constants/* ASTERISK */.Ln; // '*'
const ADBLOCK_WILDCARD_REGEX = REGEX_ANY_CHARACTERS;
// Negation wrapper for RegExp patterns
const REGEX_NEGATION_PREFIX = '^((?!';
const REGEX_NEGATION_SUFFIX = ').)*$';
/**
 * Special RegExp symbols
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#special-escape
 */
const SPECIAL_REGEX_SYMBOLS = new Set([
    constants/* ASTERISK */.Ln,
    constants/* CARET */.cP,
    constants/* CLOSE_CURLY_BRACKET */.wU,
    constants/* CLOSE_PARENTHESIS */.s1,
    constants/* CLOSE_SQUARE_BRACKET */.A1,
    constants/* DOLLAR_SIGN */.nj,
    constants/* DOT */.y0,
    constants/* ESCAPE_CHARACTER */.Kx,
    constants/* OPEN_CURLY_BRACKET */.sV,
    constants/* OPEN_PARENTHESIS */.Cx,
    constants/* OPEN_SQUARE_BRACKET */.cU,
    constants/* PIPE */.L5,
    constants/* PLUS */.uu,
    constants/* QUESTION_MARK */.Nb,
    constants/* SLASH */.o,
]);
/**
 * Utility functions for working with RegExp patterns
 */
class RegExpUtils {
    /**
     * Checks whether a string possibly is a RegExp pattern.
     * Flags are not supported.
     *
     * Note: it does not perform a full validation of the pattern,
     * it just checks if the string starts and ends with a slash.
     *
     * @param pattern - Pattern to check
     * @returns `true` if the string is a RegExp pattern, `false` otherwise
     */
    static isRegexPattern(pattern) {
        const trimmedPattern = pattern.trim();
        // Avoid false positives
        return trimmedPattern.length > constants/* REGEX_MARKER */.Vb.length * 2
            && trimmedPattern.startsWith(constants/* REGEX_MARKER */.Vb)
            && trimmedPattern.endsWith(constants/* REGEX_MARKER */.Vb)
            && trimmedPattern[constants/* REGEX_MARKER */.Vb.length - 2] !== constants/* ESCAPE_CHARACTER */.Kx;
    }
    /**
     * Checks whether a string is a negated RegExp pattern.
     *
     * @param pattern - Pattern to check
     * @returns `true` if the string is a negated RegExp pattern, `false` otherwise
     */
    static isNegatedRegexPattern(pattern) {
        if (pattern.startsWith(constants/* REGEX_MARKER */.Vb) && pattern.endsWith(constants/* REGEX_MARKER */.Vb)) {
            const innerPattern = pattern.slice(constants/* REGEX_MARKER */.Vb.length, pattern.length - constants/* REGEX_MARKER */.Vb.length);
            return innerPattern.startsWith(REGEX_NEGATION_PREFIX) && innerPattern.endsWith(REGEX_NEGATION_SUFFIX);
        }
        return pattern.startsWith(REGEX_NEGATION_PREFIX) && pattern.endsWith(REGEX_NEGATION_SUFFIX);
    }
    /**
     * Removes negation from a RegExp pattern.
     *
     * @param pattern - RegExp pattern to remove negation from
     * @returns RegExp pattern without negation
     */
    static removeNegationFromRegexPattern(pattern) {
        let result = pattern.trim();
        const slashes = RegExpUtils.isRegexPattern(result);
        if (slashes) {
            result = result.substring(constants/* REGEX_MARKER */.Vb.length, result.length - constants/* REGEX_MARKER */.Vb.length);
        }
        if (result.startsWith(REGEX_NEGATION_PREFIX) && result.endsWith(REGEX_NEGATION_SUFFIX)) {
            result = result.substring(REGEX_NEGATION_PREFIX.length, result.length - REGEX_NEGATION_SUFFIX.length);
        }
        return slashes ? `${constants/* REGEX_MARKER */.Vb}${result}${constants/* REGEX_MARKER */.Vb}` : result;
    }
    /**
     * Negates a RegExp pattern. Technically, this method wraps the pattern in `^((?!` and `).)*$`.
     *
     * RegExp modifiers are not supported.
     *
     * @param pattern Pattern to negate (can be wrapped in slashes or not)
     * @returns Negated RegExp pattern
     */
    static negateRegexPattern(pattern) {
        let result = pattern.trim();
        let slashes = false;
        // Remove the leading and trailing slashes (/)
        if (RegExpUtils.isRegexPattern(result)) {
            result = result.substring(constants/* REGEX_MARKER */.Vb.length, result.length - constants/* REGEX_MARKER */.Vb.length);
            slashes = true;
        }
        // Only negate the pattern if it's not already negated
        if (!(result.startsWith(REGEX_NEGATION_PREFIX) && result.endsWith(REGEX_NEGATION_SUFFIX))) {
            // Remove leading caret (^)
            if (result.startsWith(REGEX_START)) {
                result = result.substring(REGEX_START.length);
            }
            // Remove trailing dollar sign ($)
            if (result.endsWith(REGEX_END)) {
                result = result.substring(0, result.length - REGEX_END.length);
            }
            // Wrap the pattern in the negation
            result = `${REGEX_NEGATION_PREFIX}${result}${REGEX_NEGATION_SUFFIX}`;
        }
        // Add the leading and trailing slashes back if they were there
        if (slashes) {
            result = `${constants/* REGEX_MARKER */.Vb}${result}${constants/* REGEX_MARKER */.Vb}`;
        }
        return result;
    }
    /**
     * Ensures that a pattern is wrapped in slashes.
     *
     * @param pattern Pattern to ensure slashes for
     * @returns Pattern with slashes
     */
    static ensureSlashes(pattern) {
        let result = pattern;
        if (!result.startsWith(constants/* REGEX_MARKER */.Vb)) {
            result = `${constants/* REGEX_MARKER */.Vb}${result}`;
        }
        if (!result.endsWith(constants/* REGEX_MARKER */.Vb)) {
            result += constants/* REGEX_MARKER */.Vb;
        }
        return result;
    }
    /**
     * Converts a basic adblock rule pattern to a RegExp pattern. Based on
     * https://github.com/AdguardTeam/tsurlfilter/blob/9b26e0b4a0e30b87690bc60f7cf377d112c3085c/packages/tsurlfilter/src/rules/simple-regex.ts#L219
     *
     * @param pattern Pattern to convert
     * @returns RegExp equivalent of the pattern
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#basic-rules}
     */
    static patternToRegexp(pattern) {
        const trimmed = pattern.trim();
        // Return regex for any character sequence if the pattern is just |, ||, * or empty
        if (trimmed === ADBLOCK_URL_START
            || trimmed === constants/* PIPE */.L5
            || trimmed === ADBLOCK_WILDCARD
            || trimmed === constants/* EMPTY */.wg) {
            return REGEX_ANY_CHARACTERS;
        }
        // If the pattern is already a RegExp, just return it, but remove the leading and trailing slashes
        if (RegExpUtils.isRegexPattern(pattern)) {
            return pattern.substring(constants/* REGEX_MARKER */.Vb.length, pattern.length - constants/* REGEX_MARKER */.Vb.length);
        }
        let result = constants/* EMPTY */.wg;
        let offset = 0;
        let len = trimmed.length;
        // Handle leading pipes
        if (trimmed[0] === constants/* PIPE */.L5) {
            if (trimmed[1] === constants/* PIPE */.L5) {
                // Replace adblock url start (||) with its RegExp equivalent
                result += ADBLOCK_URL_START_REGEX;
                offset = ADBLOCK_URL_START.length;
            }
            else {
                // Replace single pipe (|) with the RegExp start symbol (^)
                result += REGEX_START;
                offset = REGEX_START.length;
            }
        }
        // Handle trailing pipes
        let trailingPipe = false;
        if (trimmed.endsWith(constants/* PIPE */.L5)) {
            trailingPipe = true;
            len -= constants/* PIPE */.L5.length;
        }
        // Handle the rest of the pattern, if any
        for (; offset < len; offset += 1) {
            if (trimmed[offset] === ADBLOCK_WILDCARD) {
                // Replace adblock wildcard (*) with its RegExp equivalent
                result += ADBLOCK_WILDCARD_REGEX;
            }
            else if (trimmed[offset] === ADBLOCK_URL_SEPARATOR) {
                // Replace adblock url separator (^) with its RegExp equivalent
                result += ADBLOCK_URL_SEPARATOR_REGEX;
            }
            else if (SPECIAL_REGEX_SYMBOLS.has(trimmed[offset])) {
                // Escape special RegExp symbols (we handled pipe (|) and asterisk (*) already)
                result += constants/* ESCAPE_CHARACTER */.Kx + trimmed[offset];
            }
            else {
                // Just add any other character
                result += trimmed[offset];
            }
        }
        // Handle trailing pipes
        if (trailingPipe) {
            // Replace trailing pipe (|) with the RegExp end symbol ($)
            result += REGEX_END;
        }
        return result;
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/type-guards.js
var type_guards = __webpack_require__(30239);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/ast-utils/clone.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * @file Custom clone functions for AST nodes, this is probably the most efficient way to clone AST nodes.
 * @todo Maybe move them to parser classes as 'clone' methods
 */
/**
 * Clones a scriptlet rule node.
 *
 * @param node Node to clone
 * @returns Cloned node
 */
function cloneScriptletRuleNode(node) {
    return {
        type: node.type,
        children: node.children.map((child) => ((0,type_guards/* isNull */.kZ)(child) ? null : { ...child })),
    };
}
/**
 * Clones a domain list node.
 *
 * @param node Node to clone
 * @returns Cloned node
 */
function cloneDomainListNode(node) {
    return {
        type: node.type,
        separator: node.separator,
        children: node.children.map((domain) => ({ ...domain })),
    };
}
/**
 * Clones a modifier list node.
 *
 * @param node Node to clone
 * @returns Cloned node
 */
function cloneModifierListNode(node) {
    return {
        type: node.type,
        children: node.children.map((modifier) => {
            const res = {
                type: modifier.type,
                exception: modifier.exception,
                name: { ...modifier.name },
            };
            if (modifier.value) {
                res.value = { ...modifier.value };
            }
            return res;
        }),
    };
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/css/css-token-stream.js
var css_token_stream = __webpack_require__(31478);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/string.js
var string = __webpack_require__(54857);
// EXTERNAL MODULE: ./node_modules/.pnpm/tldts@5.7.112/node_modules/tldts/dist/es6/index.js + 12 modules
var es6 = __webpack_require__(13548);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/quotes.js
var quotes = __webpack_require__(8725);
// EXTERNAL MODULE: ./node_modules/.pnpm/json5@2.2.3/node_modules/json5/dist/index.js
var dist = __webpack_require__(91801);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/converter/cosmetic/html.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */

















/**
 * @file HTML filtering rule converter
 */
/**
 * From the AdGuard docs:
 * Specifies the maximum length for content of HTML element. If this parameter is
 * set and the content length exceeds the value, a rule does not apply to the element.
 * If this parameter is not specified, the max-length is considered to be 8192 (8 KB).
 * When converting from other formats, we set the max-length to 262144 (256 KB).
 *
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#html-filtering-rules}
 */
const ADG_HTML_DEFAULT_MAX_LENGTH = 8192;
const ADG_HTML_CONVERSION_MAX_LENGTH = ADG_HTML_DEFAULT_MAX_LENGTH * 32;
const NOT_SPECIFIED = -1;
const PseudoClasses = {
    Contains: 'contains',
    HasText: 'has-text',
    MinTextLength: 'min-text-length',
};
/**
 * Constructs a pseudo-class string with a specified value for use in CSS selectors.
 *
 * @param pseudo - The pseudo-class name.
 * @param value - The value of the pseudo-class.
 * @returns pseudo-class string, including pseudo-class name, value and delimiters.
 */
const addPseudoClassWithValue = (pseudo, value) => {
    return `${constants/* CSS_PSEUDO_MARKER */.U4}${pseudo}${constants/* CSS_PSEUDO_OPEN */.e2}${value}${constants/* CSS_PSEUDO_CLOSE */.CG}`;
};
const AttributeSelectors = {
    MaxLength: 'max-length',
    MinLength: 'min-length',
    TagContent: 'tag-content'};
const SUPPORTED_UBO_PSEUDO_CLASSES = new Set([
    PseudoClasses.Contains,
    PseudoClasses.HasText,
    PseudoClasses.MinTextLength,
]);
const ERROR_MESSAGES = {
    ABP_NOT_SUPPORTED: 'Invalid rule, ABP does not support HTML filtering rules',
    TAG_SHOULD_BE_FIRST_CHILD: "Unexpected token '%s' with value '%s', tag selector should be the first child",
    INVALID_ATTRIBUTE_NAME: "Attribute name should be an identifier, but got '%s' with value '%s'",
    // eslint-disable-next-line max-len
    INVALID_ATTRIBUTE_VALUE: `Expected '${(0,csstokenizer/* getFormattedTokenName */.bZ)(csstokenizer/* TokenType */.ks.Ident)}' or '${(0,csstokenizer/* getFormattedTokenName */.bZ)(csstokenizer/* TokenType */.ks.String)}' as attribute value, but got '%s' with value '%s`,
    VALUE_FOR_ATTR_SHOULD_BE_INT: "Value for '%s' attribute should be an integer, but got '%s'",
    INVALID_PSEUDO_CLASS: "Unsupported pseudo class '%s'",
    VALUE_FOR_PSEUDO_CLASS_SHOULD_BE_INT: "Value for '%s' pseudo class should be an integer, but got '%s'",
    // eslint-disable-next-line max-len
    REGEXP_NOT_SUPPORTED: "Cannot convert RegExp parameter '%s' from '%s' pseudo class, because converting RegExp patterns are not supported yet",
    ATTRIBUTE_SELECTOR_REQUIRES_VALUE: "Attribute selector '%s' requires a value",
    VALUE_SHOULD_BE_SPECIFIED: 'Value should be specified if operator is specified',
    VALUE_SHOULD_BE_POSITIVE: 'Value should be positive',
    UNEXPECTED_TOKEN_WITH_VALUE: "Unexpected token '%s' with value '%s'",
    FLAGS_NOT_SUPPORTED: 'Flags are not supported for attribute selectors',
};
/**
 * Convert `""` to `\"` within strings, because it does not compatible with the standard CSS syntax.
 *
 * @param selector CSS selector string
 * @returns Escaped CSS selector
 * @note In the legacy syntax, `""` is used to escape double quotes, but it cannot be used in the standard CSS syntax,
 * so we use conversion functions to handle this.
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#tag-content}
 */
function escapeDoubleQuotes(selector) {
    let withinString = false;
    const buffer = [];
    for (let i = 0; i < selector.length; i += 1) {
        if (!withinString && selector[i] === string/* DOUBLE_QUOTE_MARKER */.E0) {
            withinString = true;
            buffer.push(selector[i]);
        }
        else if (withinString && selector[i] === string/* DOUBLE_QUOTE_MARKER */.E0 && selector[i + 1] === string/* DOUBLE_QUOTE_MARKER */.E0) {
            buffer.push(constants/* ESCAPE_CHARACTER */.Kx);
            buffer.push(string/* DOUBLE_QUOTE_MARKER */.E0);
            i += 1;
        }
        else if (withinString && selector[i] === string/* DOUBLE_QUOTE_MARKER */.E0 && selector[i + 1] !== string/* DOUBLE_QUOTE_MARKER */.E0) {
            buffer.push(string/* DOUBLE_QUOTE_MARKER */.E0);
            withinString = false;
        }
        else {
            buffer.push(selector[i]);
        }
    }
    return buffer.join(constants/* EMPTY */.wg);
}
/**
 * Safely parses length values from attribute selectors, like `"262144"` from `[max-length="262144"]`
 *
 * @param value The string value to parse
 * @param attrName The attribute name for error messages
 * @returns Parsed number
 * @throws A {@link RuleConversionError} if parsing fails
 */
function parseLengthValue(value, attrName) {
    const cleanValue = quotes/* QuoteUtils */.Qj.removeQuotes(value);
    const parsed = Number(cleanValue);
    if (Number.isNaN(parsed)) {
        throw new RuleConversionError((0,sprintf.sprintf)(ERROR_MESSAGES.VALUE_FOR_ATTR_SHOULD_BE_INT, attrName, value));
    }
    if (parsed < 0) {
        throw new RuleConversionError((0,sprintf.sprintf)(ERROR_MESSAGES.VALUE_SHOULD_BE_POSITIVE, attrName, value));
    }
    return parsed;
}
/**
 * Convert escaped double quotes `\"` to `""` within strings.
 *
 * @param selector CSS selector string
 * @returns Unescaped CSS selector
 * @note In the legacy syntax, `""` is used to escape double quotes, but it cannot be used in the standard CSS syntax,
 * so we use conversion functions to handle this.
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#tag-content}
 */
function unescapeDoubleQuotes(selector) {
    let withinString = false;
    const buffer = [];
    for (let i = 0; i < selector.length; i += 1) {
        if (selector[i] === string/* DOUBLE_QUOTE_MARKER */.E0 && selector[i - 1] !== constants/* ESCAPE_CHARACTER */.Kx) {
            withinString = !withinString;
            buffer.push(selector[i]);
        }
        else if (withinString && selector[i] === constants/* ESCAPE_CHARACTER */.Kx && selector[i + 1] === string/* DOUBLE_QUOTE_MARKER */.E0) {
            buffer.push(string/* DOUBLE_QUOTE_MARKER */.E0);
        }
        else {
            buffer.push(selector[i]);
        }
    }
    return buffer.join(constants/* EMPTY */.wg);
}
/**
 * Helper function to render an attribute selector
 *
 * @param attr Attribute name
 * @param op Operator (optional)
 * @param value Attribute value (optional)
 * @param flags Attribute flags (optional)
 * @returns Rendered attribute selector string
 */
function renderAttrSelector(attr, op, value, flags) {
    const result = [];
    result.push(constants/* OPEN_SQUARE_BRACKET */.cU);
    result.push(attr);
    {
        if (value === undefined) {
            throw new Error(ERROR_MESSAGES.VALUE_SHOULD_BE_SPECIFIED);
        }
        result.push(op);
    }
    if (value !== undefined) {
        result.push(string/* DOUBLE_QUOTE_MARKER */.E0);
        result.push(value);
        result.push(string/* DOUBLE_QUOTE_MARKER */.E0);
    }
    result.push(constants/* CLOSE_SQUARE_BRACKET */.A1);
    return result.join(constants/* EMPTY */.wg);
}
/**
 * HTML filtering rule converter class
 *
 * @todo Implement `convertToUbo` (ABP currently doesn't support HTML filtering rules)
 */
class HtmlRuleConverter extends RuleConverterBase {
    /**
     * Converts a HTML rule to AdGuard syntax, if possible. Also can be used to convert
     * AdGuard rules to AdGuard syntax to validate them.
     *
     * _Note:_ uBlock Origin supports multiple selectors within a single rule, but AdGuard doesn't,
     * so the following rule
     * ```
     * example.com##^div[attr1="value1"][attr2="value2"], script:has-text(value)
     * ```
     * will be converted to multiple AdGuard rules:
     * ```
     * example.com$$div[attr1="value1"][attr2="value2"][max-length="262144"]
     * example.com$$script[tag-content="value"][max-length="262144"]
     * ```
     *
     * @param rule Rule node to convert
     * @returns An object which follows the {@link NodeConversionResult} interface. Its `result` property contains
     * the array of converted rule nodes, and its `isConverted` flag indicates whether the original rule was converted.
     * If the rule was not converted, the result array will contain the original node with the same object reference
     * @throws If the rule is invalid or cannot be converted
     */
    static convertToAdg(rule) {
        // Ignore AdGuard rules
        if (rule.syntax === adblockers/* AdblockSyntax */.Y.Adg) {
            return createNodeConversionResult([rule], false);
        }
        if (rule.syntax === adblockers/* AdblockSyntax */.Y.Abp) {
            throw new RuleConversionError(ERROR_MESSAGES.ABP_NOT_SUPPORTED);
        }
        const source = escapeDoubleQuotes(rule.body.value);
        const stream = new css_token_stream/* CssTokenStream */.d(source);
        const convertedSelector = [];
        const convertedSelectorList = [];
        let minLen = NOT_SPECIFIED;
        let maxLen = NOT_SPECIFIED;
        // Skip leading whitespace
        stream.skipWhitespace();
        // Skip ^
        stream.expect(csstokenizer/* TokenType */.ks.Delim, { value: constants/* UBO_HTML_MASK */._h });
        stream.advance();
        while (!stream.isEof()) {
            const token = stream.getOrFail();
            if (token.type === csstokenizer/* TokenType */.ks.Ident) {
                // Tag selector should be the first child, if present, but whitespace is allowed before it
                if (convertedSelector.length !== 0 && stream.lookbehindForNonWs() !== undefined) {
                    throw new RuleConversionError((0,sprintf.sprintf)(ERROR_MESSAGES.TAG_SHOULD_BE_FIRST_CHILD, (0,csstokenizer/* getFormattedTokenName */.bZ)(token.type), source.slice(token.start, token.end)));
                }
                convertedSelector.push(source.slice(token.start, token.end));
                stream.advance();
            }
            else if (token.type === csstokenizer/* TokenType */.ks.OpenSquareBracket) {
                // Attribute selectors: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors#syntax
                const { start } = token;
                let tempToken;
                // Advance opening square bracket
                stream.advance();
                // Skip optional whitespace after the opening square bracket
                stream.skipWhitespace();
                // Parse attribute name
                tempToken = stream.getOrFail();
                if (tempToken.type !== csstokenizer/* TokenType */.ks.Ident) {
                    throw new RuleConversionError((0,sprintf.sprintf)(ERROR_MESSAGES.INVALID_ATTRIBUTE_NAME, (0,csstokenizer/* getFormattedTokenName */.bZ)(tempToken.type), source.slice(tempToken.start, tempToken.end)));
                }
                const attr = source.slice(tempToken.start, tempToken.end);
                stream.advance();
                // Skip optional whitespace after the attribute name
                stream.skipWhitespace();
                // Maybe attribute selector ends here, because value is not required, like in '[disabled]'
                tempToken = stream.getOrFail();
                // So check if the next non whitespace token is a closing square bracket
                if (tempToken.type === csstokenizer/* TokenType */.ks.CloseSquareBracket) {
                    const { end } = tempToken;
                    stream.advance();
                    // Special case for min-length and max-length attributes
                    if (attr === AttributeSelectors.MinLength || attr === AttributeSelectors.MaxLength) {
                        throw new RuleConversionError((0,sprintf.sprintf)(ERROR_MESSAGES.ATTRIBUTE_SELECTOR_REQUIRES_VALUE, attr));
                    }
                    convertedSelector.push(source.slice(start, end));
                    continue;
                }
                // Next token should be a valid attribute selector operator
                // Only '=' operator is supported
                stream.expect(csstokenizer/* TokenType */.ks.Delim, { value: constants/* EQUALS */.UT });
                // Advance the operator
                stream.advance();
                // Skip optional whitespace after the operator
                stream.skipWhitespace();
                // Parse attribute value
                tempToken = stream.getOrFail();
                // According to the spec, attribute value should be an identifier or a string
                if (tempToken.type !== csstokenizer/* TokenType */.ks.Ident && tempToken.type !== csstokenizer/* TokenType */.ks.String) {
                    throw new RuleConversionError((0,sprintf.sprintf)(ERROR_MESSAGES.INVALID_ATTRIBUTE_VALUE, (0,csstokenizer/* getFormattedTokenName */.bZ)(tempToken.type), source.slice(tempToken.start, tempToken.end)));
                }
                const value = source.slice(tempToken.start, tempToken.end);
                // Advance the attribute value
                stream.advance();
                // Skip optional whitespace after the attribute value
                stream.skipWhitespace();
                // Attribute selector may have flags - but AdGuard HTML filtering does not support them
                tempToken = stream.getOrFail();
                if (tempToken.type === csstokenizer/* TokenType */.ks.Ident) {
                    throw new RuleConversionError((0,sprintf.sprintf)(ERROR_MESSAGES.FLAGS_NOT_SUPPORTED));
                }
                // Next token should be a closing square bracket
                stream.expect(csstokenizer/* TokenType */.ks.CloseSquareBracket);
                const { end } = stream.getOrFail();
                stream.advance();
                if (attr === AttributeSelectors.MinLength) {
                    // Min length attribute
                    const parsed = parseInt(value, 10);
                    if (Number.isNaN(parsed)) {
                        throw new RuleConversionError((0,sprintf.sprintf)(ERROR_MESSAGES.VALUE_FOR_ATTR_SHOULD_BE_INT, attr, value));
                    }
                    minLen = parsed;
                }
                else if (attr === AttributeSelectors.MaxLength) {
                    // Max length attribute
                    const parsed = parseInt(value, 10);
                    if (Number.isNaN(parsed)) {
                        throw new RuleConversionError((0,sprintf.sprintf)(ERROR_MESSAGES.VALUE_FOR_ATTR_SHOULD_BE_INT, attr, value));
                    }
                    maxLen = parsed;
                }
                else {
                    convertedSelector.push(source.slice(start, end));
                }
            }
            else if (token.type === csstokenizer/* TokenType */.ks.Colon) {
                let tempToken;
                // Pseudo classes: https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes#syntax
                stream.advance();
                // Next token should be a pseudo class name
                stream.expect(csstokenizer/* TokenType */.ks.Function);
                tempToken = stream.getOrFail();
                const fn = source.slice(tempToken.start, tempToken.end - 1); // do not include '('
                // Pseudo class should be supported
                if (!SUPPORTED_UBO_PSEUDO_CLASSES.has(fn)) {
                    throw new RuleConversionError((0,sprintf.sprintf)(ERROR_MESSAGES.INVALID_PSEUDO_CLASS, fn));
                }
                const paramStart = tempToken.end;
                // Find the closing paren
                stream.skipUntilBalanced();
                tempToken = stream.getOrFail();
                const paramEnd = tempToken.end;
                // Get the parameter
                const param = source.slice(paramStart, paramEnd - 1);
                if (fn === PseudoClasses.MinTextLength) {
                    // Min text length pseudo class
                    // Parameter should be parsed as an integer
                    const parsed = parseInt(param, 10);
                    if (Number.isNaN(parsed)) {
                        throw new RuleConversionError((0,sprintf.sprintf)(ERROR_MESSAGES.VALUE_FOR_PSEUDO_CLASS_SHOULD_BE_INT, fn, param));
                    }
                    minLen = parsed;
                }
                else if (fn === PseudoClasses.Contains || fn === PseudoClasses.HasText) {
                    // Contains and has-text pseudo classes
                    // Check if the argument is a RegExp
                    if (RegExpUtils.isRegexPattern(param)) {
                        // TODO: Add some support for RegExp patterns later
                        // Need to find a way to convert some RegExp patterns to glob patterns
                        throw new RuleConversionError((0,sprintf.sprintf)(ERROR_MESSAGES.REGEXP_NOT_SUPPORTED, param, fn));
                    }
                    // Escape unescaped double quotes in the parameter
                    const paramEscaped = string/* StringUtils */.$x.escapeCharacter(param, string/* DOUBLE_QUOTE_MARKER */.E0);
                    convertedSelector.push(renderAttrSelector(AttributeSelectors.TagContent, constants/* EQUALS */.UT, paramEscaped));
                }
                stream.advance();
            }
            else if (token.type === csstokenizer/* TokenType */.ks.Comma && token.balance === 0) {
                if (minLen !== NOT_SPECIFIED) {
                    convertedSelector.push(renderAttrSelector(AttributeSelectors.MinLength, constants/* EQUALS */.UT, minLen.toString()));
                }
                convertedSelector.push(renderAttrSelector(AttributeSelectors.MaxLength, constants/* EQUALS */.UT, maxLen !== NOT_SPECIFIED ? maxLen.toString() : ADG_HTML_CONVERSION_MAX_LENGTH.toString()));
                convertedSelectorList.push(convertedSelector.join(constants/* EMPTY */.wg));
                convertedSelector.length = 0;
                stream.advance();
            }
            else if (token.type === csstokenizer/* TokenType */.ks.Whitespace) {
                stream.advance();
            }
            else {
                throw new RuleConversionError((0,sprintf.sprintf)(ERROR_MESSAGES.UNEXPECTED_TOKEN_WITH_VALUE, (0,csstokenizer/* getFormattedTokenName */.bZ)(token.type), source.slice(token.start, token.end)));
            }
        }
        if (convertedSelector.length !== 0) {
            if (minLen !== NOT_SPECIFIED) {
                convertedSelector.push(renderAttrSelector(AttributeSelectors.MinLength, constants/* EQUALS */.UT, minLen.toString()));
            }
            convertedSelector.push(renderAttrSelector(AttributeSelectors.MaxLength, constants/* EQUALS */.UT, maxLen !== NOT_SPECIFIED ? maxLen.toString() : ADG_HTML_CONVERSION_MAX_LENGTH.toString()));
            convertedSelectorList.push(convertedSelector.join(constants/* EMPTY */.wg));
        }
        return createNodeConversionResult(
        // Since AdGuard HTML filtering rules do not support multiple selectors, we need to split each selector
        // into a separate rule node.
        convertedSelectorList.map((selector) => ({
            category: nodes/* RuleCategory */.$O.Cosmetic,
            type: nodes/* CosmeticRuleType */.k9.HtmlFilteringRule,
            syntax: adblockers/* AdblockSyntax */.Y.Adg,
            exception: rule.exception,
            domains: cloneDomainListNode(rule.domains),
            // Convert the separator based on the exception status
            separator: {
                type: 'Value',
                value: rule.exception
                    ? nodes/* CosmeticRuleSeparator */.p5.AdgHtmlFilteringException
                    : nodes/* CosmeticRuleSeparator */.p5.AdgHtmlFiltering,
            },
            body: {
                type: 'Value',
                value: unescapeDoubleQuotes(selector),
            },
        })), true);
    }
    /**
     * Converts a HTML rule to uBlock Origin syntax, if possible.
     *
     * @note AdGuard rules are often more specific than uBlock Origin rules, so some information
     * may be lost in conversion. AdGuard's `[max-length]` and `[tag-content]` attributes will be converted to
     * uBlock's `:min-text-length()` and `:has-text()` pseudo-classes when possible.
     *
     * @param rule Rule node to convert
     * @returns An object which follows the {@link NodeConversionResult} interface. Its `result` property contains
     * the array of converted rule nodes, and its `isConverted` flag indicates whether the original rule was converted.
     * If the rule was not converted, the result array will contain the original node with the same object reference
     * @throws Error if the rule is invalid or cannot be converted
     */
    static convertToUbo(rule) {
        // Ignore uBlock Origin rules
        if (rule.syntax === adblockers/* AdblockSyntax */.Y.Ubo) {
            return createNodeConversionResult([rule], false);
        }
        if (rule.syntax === adblockers/* AdblockSyntax */.Y.Abp) {
            throw new RuleConversionError(ERROR_MESSAGES.ABP_NOT_SUPPORTED);
        }
        const source = escapeDoubleQuotes(rule.body.value);
        const stream = new css_token_stream/* CssTokenStream */.d(source);
        const convertedSelector = [];
        let minTextLength;
        // Skip leading whitespace
        stream.skipWhitespace();
        while (!stream.isEof()) {
            const token = stream.getOrFail();
            if (token.type === csstokenizer/* TokenType */.ks.Ident) {
                convertedSelector.push(source.slice(token.start, token.end));
                stream.advance();
            }
            else if (token.type === csstokenizer/* TokenType */.ks.OpenSquareBracket) {
                // Attribute selectors
                const { start } = token;
                let tempToken;
                // Advance opening square bracket
                stream.advance();
                // Skip optional whitespace
                stream.skipWhitespace();
                // Parse attribute name
                tempToken = stream.getOrFail();
                if (tempToken.type !== csstokenizer/* TokenType */.ks.Ident) {
                    throw new RuleConversionError((0,sprintf.sprintf)(ERROR_MESSAGES.INVALID_ATTRIBUTE_NAME, (0,csstokenizer/* getFormattedTokenName */.bZ)(tempToken.type), source.slice(tempToken.start, tempToken.end)));
                }
                const attr = source.slice(tempToken.start, tempToken.end);
                stream.advance();
                // Skip optional whitespace
                stream.skipWhitespace();
                // Check if this is a standalone attribute (like [disabled])
                tempToken = stream.getOrFail();
                if (tempToken.type === csstokenizer/* TokenType */.ks.CloseSquareBracket) {
                    const { end } = tempToken;
                    stream.advance();
                    convertedSelector.push(source.slice(start, end));
                    continue;
                }
                // Expect equals operator
                stream.expect(csstokenizer/* TokenType */.ks.Delim, { value: constants/* EQUALS */.UT });
                stream.advance();
                // Skip optional whitespace
                stream.skipWhitespace();
                // Parse attribute value
                tempToken = stream.getOrFail();
                if (tempToken.type !== csstokenizer/* TokenType */.ks.Ident && tempToken.type !== csstokenizer/* TokenType */.ks.String) {
                    throw new RuleConversionError((0,sprintf.sprintf)(ERROR_MESSAGES.INVALID_ATTRIBUTE_VALUE, (0,csstokenizer/* getFormattedTokenName */.bZ)(tempToken.type), source.slice(tempToken.start, tempToken.end)));
                }
                const value = source.slice(tempToken.start, tempToken.end);
                stream.advance();
                // Skip optional whitespace
                stream.skipWhitespace();
                // Check for closing bracket
                tempToken = stream.getOrFail();
                if (tempToken.type !== csstokenizer/* TokenType */.ks.CloseSquareBracket) {
                    throw new RuleConversionError((0,sprintf.sprintf)(ERROR_MESSAGES.FLAGS_NOT_SUPPORTED));
                }
                const { end } = stream.getOrFail();
                stream.advance();
                // Handle special attributes with improved number parsing
                if (attr === AttributeSelectors.MinLength || attr === AttributeSelectors.MaxLength) {
                    const parsedValue = parseLengthValue(value, attr);
                    if (attr === AttributeSelectors.MinLength) {
                        minTextLength = parsedValue;
                    }
                }
                else if (attr === AttributeSelectors.TagContent) {
                    const unescapedValue = unescapeDoubleQuotes(value);
                    const valueWithoutQuotes = quotes/* QuoteUtils */.Qj.removeQuotes(unescapedValue);
                    convertedSelector.push(addPseudoClassWithValue(PseudoClasses.HasText, valueWithoutQuotes));
                }
                else {
                    convertedSelector.push(source.slice(start, end));
                }
            }
            else if (token.type === csstokenizer/* TokenType */.ks.Whitespace) {
                stream.advance();
            }
            else {
                throw new RuleConversionError((0,sprintf.sprintf)(ERROR_MESSAGES.UNEXPECTED_TOKEN_WITH_VALUE, (0,csstokenizer/* getFormattedTokenName */.bZ)(token.type), source.slice(token.start, token.end)));
            }
        }
        // Handle min length conversions
        if (minTextLength !== undefined) {
            convertedSelector.push(addPseudoClassWithValue(PseudoClasses.MinTextLength, minTextLength));
        }
        // Combine all selectors
        const uboSelector = `${convertedSelector.join(constants/* EMPTY */.wg)}`;
        return createNodeConversionResult([{
                category: nodes/* RuleCategory */.$O.Cosmetic,
                type: nodes/* CosmeticRuleType */.k9.HtmlFilteringRule,
                syntax: adblockers/* AdblockSyntax */.Y.Ubo,
                exception: rule.exception,
                domains: cloneDomainListNode(rule.domains),
                separator: {
                    type: 'Value',
                    value: rule.exception
                        ? `${nodes/* CosmeticRuleSeparator */.p5.ElementHidingException}${constants/* UBO_HTML_MASK */._h}`
                        : `${nodes/* CosmeticRuleSeparator */.p5.ElementHiding}${constants/* UBO_HTML_MASK */._h}`,
                },
                body: {
                    type: 'Value',
                    value: unescapeDoubleQuotes(uboSelector),
                },
            }], true);
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/ast-utils/scriptlets.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * @file Utility functions for working with scriptlet nodes
 */
/**
 * Get name of the scriptlet from the scriptlet node
 *
 * @param scriptletNode Scriptlet node to get name of
 * @returns Name of the scriptlet
 * @throws If the scriptlet is empty
 */
function getScriptletName(scriptletNode) {
    if (scriptletNode.children.length === 0) {
        throw new Error('Empty scriptlet');
    }
    return scriptletNode.children[0]?.value ?? constants/* EMPTY */.wg;
}
/**
 * Transform the nth argument of the scriptlet node
 *
 * @param scriptletNode Scriptlet node to transform argument of
 * @param index Index of the argument to transform (index 0 is the scriptlet name)
 * @param transform Function to transform the argument
 */
function transformNthScriptletArgument(scriptletNode, index, transform) {
    const child = scriptletNode.children[index];
    if (!(0,type_guards/* isUndefined */.b0)(child)) {
        const transformed = transform(child?.value ?? null);
        if ((0,type_guards/* isNull */.kZ)(transformed)) {
            // eslint-disable-next-line no-param-reassign
            scriptletNode.children[index] = null;
            return;
        }
        if ((0,type_guards/* isNull */.kZ)(child)) {
            // eslint-disable-next-line no-param-reassign
            scriptletNode.children[index] = {
                type: 'Value',
                value: transformed,
            };
            return;
        }
        child.value = transformed;
    }
}
/**
 * Transform all arguments of the scriptlet node
 *
 * @param scriptletNode Scriptlet node to transform arguments of
 * @param transform Function to transform the arguments
 */
function transformAllScriptletArguments(scriptletNode, transform) {
    for (let i = 0; i < scriptletNode.children.length; i += 1) {
        transformNthScriptletArgument(scriptletNode, i, transform);
    }
}
/**
 * Set name of the scriptlet.
 * Modifies input `scriptletNode` if needed.
 *
 * @param scriptletNode Scriptlet node to set name of
 * @param name Name to set
 */
function setScriptletName(scriptletNode, name) {
    transformNthScriptletArgument(scriptletNode, 0, () => name);
}
/**
 * Set quote type of the scriptlet parameters
 *
 * @param scriptletNode Scriptlet node to set quote type of
 * @param quoteType Preferred quote type
 */
function setScriptletQuoteType(scriptletNode, quoteType) {
    // null is a special value that means "no value", but we can't change its quote type,
    // so we need to convert it to empty string
    transformAllScriptletArguments(scriptletNode, (value) => quotes/* QuoteUtils */.Qj.setStringQuoteType(value ?? constants/* EMPTY */.wg, quoteType));
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/compatibility-tables/platforms.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/* eslint-disable no-bitwise */
/**
 * @file Provides platform enums.
 * The difference between specific and generic platforms is that specific platforms are individual platforms
 * (e.g. AdGuard for Windows, AdGuard for Android, etc.),
 * while generic platforms are groups of specific platforms
 * (e.g. AdGuard for any OS, AdGuard for any Chromium-based extension, etc.).
 */
/**
 * List of specific platforms.
 */
const SpecificPlatform = {
    AdgOsWindows: 1,
    AdgOsMac: 1 << 1,
    AdgOsAndroid: 1 << 2,
    AdgExtChrome: 1 << 3,
    AdgExtOpera: 1 << 4,
    AdgExtEdge: 1 << 5,
    AdgExtFirefox: 1 << 6,
    AdgCbAndroid: 1 << 7,
    AdgCbIos: 1 << 8,
    AdgCbSafari: 1 << 9,
    UboExtChrome: 1 << 10,
    UboExtOpera: 1 << 11,
    UboExtEdge: 1 << 12,
    UboExtFirefox: 1 << 13,
    AbpExtChrome: 1 << 14,
    AbpExtOpera: 1 << 15,
    AbpExtEdge: 1 << 16,
    AbpExtFirefox: 1 << 17,
};
const AdgOsAny = SpecificPlatform.AdgOsWindows
    | SpecificPlatform.AdgOsMac
    | SpecificPlatform.AdgOsAndroid;
const AdgSafariAny = SpecificPlatform.AdgCbSafari | SpecificPlatform.AdgCbIos;
const AdgExtChromium = SpecificPlatform.AdgExtChrome
    | SpecificPlatform.AdgExtOpera
    | SpecificPlatform.AdgExtEdge;
const AdgExtAny = AdgExtChromium | SpecificPlatform.AdgExtFirefox;
const AdgAny = AdgExtAny | AdgOsAny | AdgSafariAny | SpecificPlatform.AdgCbAndroid;
const UboExtChromium = SpecificPlatform.UboExtChrome
    | SpecificPlatform.UboExtOpera
    | SpecificPlatform.UboExtEdge;
const UboExtAny = UboExtChromium | SpecificPlatform.UboExtFirefox;
const UboAny = UboExtAny;
const AbpExtChromium = SpecificPlatform.AbpExtChrome
    | SpecificPlatform.AbpExtOpera
    | SpecificPlatform.AbpExtEdge;
const AbpExtAny = AbpExtChromium | SpecificPlatform.AbpExtFirefox;
const AbpAny = AbpExtAny;
const Any = AdgAny | UboAny | AbpAny;
/**
 * List of generic platforms (combinations of specific platforms).
 */
const GenericPlatform = {
    AdgOsAny,
    AdgSafariAny,
    AdgExtChromium,
    AdgExtAny,
    AdgAny,
    UboExtChromium,
    UboExtAny,
    UboAny,
    AbpExtChromium,
    AbpExtAny,
    AbpAny,
    Any,
};



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/compatibility-tables/utils/platform-helpers.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/* eslint-disable no-bitwise */
/**
 * @file Provides platform mapping and helper functions.
 */
/**
 * Map of specific platforms string names to their corresponding enum values.
 */
const SPECIFIC_PLATFORM_MAP = new Map([
    ['adg_os_windows', SpecificPlatform.AdgOsWindows],
    ['adg_os_mac', SpecificPlatform.AdgOsMac],
    ['adg_os_android', SpecificPlatform.AdgOsAndroid],
    ['adg_ext_chrome', SpecificPlatform.AdgExtChrome],
    ['adg_ext_opera', SpecificPlatform.AdgExtOpera],
    ['adg_ext_edge', SpecificPlatform.AdgExtEdge],
    ['adg_ext_firefox', SpecificPlatform.AdgExtFirefox],
    ['adg_cb_android', SpecificPlatform.AdgCbAndroid],
    ['adg_cb_ios', SpecificPlatform.AdgCbIos],
    ['adg_cb_safari', SpecificPlatform.AdgCbSafari],
    ['ubo_ext_chrome', SpecificPlatform.UboExtChrome],
    ['ubo_ext_opera', SpecificPlatform.UboExtOpera],
    ['ubo_ext_edge', SpecificPlatform.UboExtEdge],
    ['ubo_ext_firefox', SpecificPlatform.UboExtFirefox],
    ['abp_ext_chrome', SpecificPlatform.AbpExtChrome],
    ['abp_ext_opera', SpecificPlatform.AbpExtOpera],
    ['abp_ext_edge', SpecificPlatform.AbpExtEdge],
    ['abp_ext_firefox', SpecificPlatform.AbpExtFirefox],
]);
/**
 * Map of specific platforms enum values to their corresponding string names.
 *
 * @note Reverse of {@link SPECIFIC_PLATFORM_MAP}.
 */
const SPECIFIC_PLATFORM_MAP_REVERSE = new Map([...SPECIFIC_PLATFORM_MAP].map(([key, value]) => [value, key]));
/**
 * Map of generic platforms string names to their corresponding enum values.
 */
const GENERIC_PLATFORM_MAP = new Map([
    ['adg_os_any', GenericPlatform.AdgOsAny],
    ['adg_safari_any', GenericPlatform.AdgSafariAny],
    ['adg_ext_chromium', GenericPlatform.AdgExtChromium],
    ['adg_ext_any', GenericPlatform.AdgExtAny],
    ['adg_any', GenericPlatform.AdgAny],
    ['ubo_ext_chromium', GenericPlatform.UboExtChromium],
    ['ubo_ext_any', GenericPlatform.UboExtAny],
    ['ubo_any', GenericPlatform.UboAny],
    ['abp_ext_chromium', GenericPlatform.AbpExtChromium],
    ['abp_ext_any', GenericPlatform.AbpExtAny],
    ['abp_any', GenericPlatform.AbpAny],
    ['any', GenericPlatform.Any],
]);
/**
 * Check if the platform is a generic platform.
 *
 * @param platform Platform to check.
 *
 * @returns True if the platform is a generic platform, false otherwise.
 */
const isGenericPlatform = (platform) => {
    // if more than one bit is set, it's a generic platform
    return !!(platform & (platform - 1));
};
/**
 * Returns the platform enum value for the given platform string name.
 *
 * @param platform Platform string name, e.g., 'adg_os_windows'.
 *
 * @returns Specific or generic platform enum value.
 * @throws Error if the platform is unknown.
 */
const getPlatformId = (platform) => {
    const specificPlatform = SPECIFIC_PLATFORM_MAP.get(platform);
    if (specificPlatform) {
        return specificPlatform;
    }
    const genericPlatform = GENERIC_PLATFORM_MAP.get(platform);
    if (genericPlatform) {
        return genericPlatform;
    }
    throw new Error(`Unknown platform: ${platform}`);
};
/**
 * Returns the specific platform string name for the given platform enum value.
 *
 * @param platform Specific platform enum value.
 *
 * @returns Specific platform string name, e.g., 'adg_os_windows'.
 * @throws Error if the platform is unknown.
 */
const getSpecificPlatformName = (platform) => {
    const specificPlatform = SPECIFIC_PLATFORM_MAP_REVERSE.get(platform);
    if (!specificPlatform) {
        throw new Error(`Unknown platform: ${platform}`);
    }
    return specificPlatform;
};



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/compatibility-tables/base.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */





/* eslint-disable no-bitwise */
/**
 * @file Provides common compatibility table methods.
 */
/**
 * Base compatibility table class which provides common methods to work with compatibility data.
 *
 * @template T Compatibility data schema.
 */
class CompatibilityTableBase {
    /**
     * Compatibility table data.
     */
    data;
    /**
     * Optional name transformer function. If provided,
     * it will be called in all methods before processing compatibility data names.
     */
    nameTransformer;
    /**
     * Creates a new instance of the common compatibility table.
     *
     * @param data Compatibility table data.
     * @param nameTransformer Optional name transformer function.
     */
    constructor(data, nameTransformer = null) {
        this.data = data;
        this.nameTransformer = nameTransformer;
    }
    /**
     * Helper method to get a 'row' from the compatibility table data by name.
     *
     * @param name Compatibility data name.
     * @returns Compatibility table row storage or `null` if not found.
     */
    getRowStorage(name) {
        const idx = this.data.map[name];
        if ((0,type_guards/* isUndefined */.b0)(idx)) {
            return null;
        }
        return this.data.shared[idx];
    }
    /**
     * Checks whether a compatibility data `name` exists for any platform.
     *
     * @note Technically, do the same as `exists()` method with generic platform _any_
     * but it is faster because it does not apply complex logic.
     *
     * @param name Compatibility data name.
     *
     * @returns True if the compatibility data exists, false otherwise.
     */
    existsAny(name) {
        const normalizedName = this.nameTransformer ? this.nameTransformer(name) : name;
        return !(0,type_guards/* isUndefined */.b0)(this.data.map[normalizedName]);
    }
    /**
     * Checks whether a compatibility data `name` exists for a specified platform.
     *
     * @param name Compatibility data name.
     * @param platform Specific or generic platform.
     *
     * @returns True if the compatibility data exists, false otherwise.
     */
    exists(name, platform) {
        const normalizedName = this.nameTransformer ? this.nameTransformer(name) : name;
        const data = this.getRowStorage(normalizedName);
        if (!data) {
            return false;
        }
        const isMatch = (idx) => {
            const el = data.shared[idx];
            return !(0,type_guards/* isUndefined */.b0)(el) && (el.name === normalizedName || !!el.aliases?.includes(normalizedName));
        };
        if (isGenericPlatform(platform)) {
            // Since indexes are specific platforms in the compatibility table data,
            // we can't index them directly if the platform is generic (union of specific platforms).
            // In this case, we need to iterate over the keys and return true on the first match.
            const keys = Object.keys(data.map);
            for (let i = 0; i < keys.length; i += 1) {
                const key = Number(keys[i]);
                if (platform & key) {
                    const idx = data.map[key];
                    if (isMatch(idx)) {
                        return true;
                    }
                }
            }
            return false;
        }
        const idx = data.map[platform];
        return isMatch(idx);
    }
    /**
     * Returns a compatibility data by name and specific platform.
     *
     * @param name The name of the compatibility data.
     * @param platform The specific platform.
     *
     * @returns A single compatibility data or `null` if not found.
     */
    getSingle(name, platform) {
        const normalizedName = this.nameTransformer ? this.nameTransformer(name) : name;
        const data = this.getRowStorage(normalizedName);
        if (!data) {
            return null;
        }
        const idx = data.map[platform];
        return (0,type_guards/* isUndefined */.b0)(idx) ? null : data.shared[idx];
    }
    /**
     * Returns all compatibility data records for name and specified platform.
     *
     * @param name Compatibility data name.
     * @param platform Specific or generic platform.
     *
     * @returns Multiple records grouped by platforms.
     * Technically, it is an object where keys are platform enums values and values are compatibility data records.
     *
     * @note Platform enum values can be converted to string names using {@link getSpecificPlatformName} on demand.
     */
    getMultiple(name, platform) {
        const normalizedName = this.nameTransformer ? this.nameTransformer(name) : name;
        const data = this.getRowStorage(normalizedName);
        if (!data) {
            return null;
        }
        if (isGenericPlatform(platform)) {
            const result = {};
            const keys = Object.keys(data.map);
            for (let i = 0; i < keys.length; i += 1) {
                const key = Number(keys[i]);
                if (platform & key) {
                    const idx = data.map[key];
                    if (!(0,type_guards/* isUndefined */.b0)(idx)) {
                        result[key] = data.shared[idx];
                    }
                }
            }
            return result;
        }
        const idx = data.map[platform];
        if ((0,type_guards/* isUndefined */.b0)(idx)) {
            return null;
        }
        return { key: data.shared[idx] };
    }
    /**
     * Returns all compatibility data records for the specified platform.
     *
     * @param platform Specific or generic platform.
     *
     * @returns Array of multiple records grouped by platforms.
     */
    getAllMultiple(platform) {
        const result = [];
        for (let i = 0; i < this.data.shared.length; i += 1) {
            const data = this.data.shared[i];
            const names = new Set(data.shared.map(({ name }) => name));
            names.forEach((name) => {
                const multipleRecords = this.getMultiple(name, platform);
                if (multipleRecords) {
                    result.push(multipleRecords);
                }
            });
        }
        return result;
    }
    /**
     * Returns the first compatibility data record for name and specified platform.
     *
     * @param name Compatibility data name.
     * @param platform Specific or generic platform.
     *
     * @returns First found compatibility data record or `null` if not found.
     */
    getFirst(name, platform) {
        const normalizedName = this.nameTransformer ? this.nameTransformer(name) : name;
        const data = this.getRowStorage(normalizedName);
        if (!data) {
            return null;
        }
        if (isGenericPlatform(platform)) {
            const keys = Object.keys(data.map);
            for (let i = 0; i < keys.length; i += 1) {
                const key = Number(keys[i]);
                if (platform & key) {
                    const idx = data.map[key];
                    if (!(0,type_guards/* isUndefined */.b0)(idx)) {
                        // return the first found record
                        return data.shared[idx];
                    }
                }
            }
            return null;
        }
        const idx = data.map[platform];
        if ((0,type_guards/* isUndefined */.b0)(idx)) {
            return null;
        }
        return data.shared[idx];
    }
    /**
     * Returns all compatibility data records for the specified name.
     *
     * @param name Compatibility data name.
     *
     * @returns Array of multiple records grouped by platforms.
     */
    getRow(name) {
        const normalizedName = this.nameTransformer ? this.nameTransformer(name) : name;
        const data = this.getRowStorage(normalizedName);
        if (!data) {
            return [];
        }
        return data.shared;
    }
    /**
     * Returns all compatibility data grouped by products.
     *
     * @returns Array of multiple records grouped by products.
     */
    getRowsByProduct() {
        const result = [];
        for (let i = 0; i < this.data.shared.length; i += 1) {
            const data = this.data.shared[i];
            const keys = Object.keys(data.map);
            const row = {
                [adblockers/* AdblockSyntax */.Y.Adg]: {},
                [adblockers/* AdblockSyntax */.Y.Ubo]: {},
                [adblockers/* AdblockSyntax */.Y.Abp]: {},
            };
            for (let j = 0; j < keys.length; j += 1) {
                const key = Number(keys[j]);
                if (key & GenericPlatform.AdgAny) {
                    row[adblockers/* AdblockSyntax */.Y.Adg][key] = data.shared[data.map[key]];
                }
                else if (key & GenericPlatform.UboAny) {
                    row[adblockers/* AdblockSyntax */.Y.Ubo][key] = data.shared[data.map[key]];
                }
                else if (key & GenericPlatform.AbpAny) {
                    row[adblockers/* AdblockSyntax */.Y.Abp][key] = data.shared[data.map[key]];
                }
            }
            result.push(row);
        }
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/compatibility-tables/compatibility-table-data.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
const modifiersCompatibilityTableData = {shared:[{shared:[{name:'all',aliases:null,description:'$all modifier is made of $document, $popup, and all content-type modifiers combined.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#all-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:true,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'all',aliases:null,description:'The `all` option is equivalent to specifying all network-based types\n+ `popup`, `document`, `inline-font` and `inline-script`.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#all',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'app',aliases:null,description:'The `$app` modifier lets you narrow the rule coverage down to a specific application or a list of applications.\nThe modifier\'s behavior and syntax perfectly match the corresponding basic rules `$app` modifier.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#app-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_apps',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0}},{shared:[{name:'badfilter',aliases:null,description:'The rules with the `$badfilter` modifier disable other basic rules to which they refer. It means that\nthe text of the disabled rule should match the text of the `$badfilter` rule (without the `$badfilter` modifier).',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#badfilter-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'badfilter',aliases:null,description:'The rules with the `$badfilter` modifier disable other basic rules to which they refer. It means that\nthe text of the disabled rule should match the text of the `$badfilter` rule (without the `$badfilter` modifier).',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#badfilter',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'cname',aliases:null,description:'When used in an exception filter,\nit will bypass blocking CNAME uncloaked requests for the current (specified) document.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#cname',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'content',aliases:null,description:'Disables HTML filtering and `$replace` rules on the pages that match the rule.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#content-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0}},{shared:[{name:'cookie',aliases:null,description:'The `$cookie` modifier completely changes rule behavior.\nInstead of blocking a request, this modifier makes us suppress or modify the Cookie and Set-Cookie headers.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#cookie-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'^([^;=\\s]*?)((?:;(maxAge=\\d+;?)?|(sameSite=(lax|none|strict);?)?){1,3})(?<!;)$',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'csp',aliases:null,description:'This modifier completely changes the rule behavior.\nIf it is applied to a rule, it will not block the matching request.\nThe response headers are going to be modified instead.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#csp-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','important','subdocument','badfilter'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'csp_value',valueFormatFlags:null},{name:'csp',aliases:null,description:'This modifier completely changes the rule behavior.\nIf it is applied to a rule, it will not block the matching request.\nThe response headers are going to be modified instead.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#csp',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['1p','3p','domain','badfilter'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'csp_value',valueFormatFlags:null},{name:'csp',aliases:null,description:'This modifier completely changes the rule behavior.\nIf it is applied to a rule, it will not block the matching request.\nThe response headers are going to be modified instead.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#content-security-policies',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','subdocument'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'csp_value',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'denyallow',aliases:null,description:'The `$denyallow` modifier allows to avoid creating additional rules\nwhen it is needed to disable a certain rule for specific domains.\n`$denyallow` matches only target domains and not referrer domains.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#denyallow-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['to'],inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_denyallow_domains',valueFormatFlags:null},{name:'denyallow',aliases:null,description:'The `$denyallow` modifier allows to avoid creating additional rules\nwhen it is needed to disable a certain rule for specific domains.\n`$denyallow` matches only target domains and not referrer domains.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#denyallow',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['to'],inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_denyallow_domains',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'document',aliases:null,description:'The rule corresponds to the main frame document requests,\ni.e. HTML documents that are loaded in the browser tab.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#document-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'document',aliases:null,description:'The rule corresponds to the main frame document requests,\ni.e. HTML documents that are loaded in the browser tab.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#document-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'document',aliases:null,description:'The rule corresponds to the main frame document requests,\ni.e. HTML documents that are loaded in the browser tab.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#document-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'document',aliases:null,description:'The rule corresponds to the main frame document requests,\ni.e. HTML documents that are loaded in the browser tab.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#document-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'document',aliases:['doc'],description:'The rule corresponds to the main frame document requests,\ni.e. HTML documents that are loaded in the browser tab.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#document',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'document',aliases:null,description:'The rule corresponds to the main frame document requests,\ni.e. HTML documents that are loaded in the browser tab.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#allowlist',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'256':2,'512':3,'1024':4,'2048':4,'4096':4,'8192':4,'16384':5,'32768':5,'65536':5,'131072':5}},{shared:[{name:'domain',aliases:['from'],description:'The `$domain` modifier limits the rule application area to a list of domains and their subdomains.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#domain-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_domains',valueFormatFlags:null},{name:'domain',aliases:['from'],description:'The `$domain` modifier limits the rule application area to a list of domains and their subdomains.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#from',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_domains',valueFormatFlags:null},{name:'domain',aliases:null,description:'The `$domain` modifier limits the rule application area to a list of domains and their subdomains.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#domain-restrictions',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_domains',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'elemhide',aliases:['ehide'],description:'Disables any cosmetic rules on the pages matching the rule.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#elemhide-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'elemhide',aliases:['ehide'],description:'Disables any cosmetic rules on the pages matching the rule.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#elemhide-1',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'elemhide',aliases:['ehide'],description:'Disables any cosmetic rules on the pages matching the rule.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'empty',aliases:null,description:'This modifier is deprecated in favor of the $redirect modifier.\nRules with `$empty` are still supported and being converted into `$redirect=nooptext` now\nbut the support shall be removed in the future.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#empty-modifier',versionAdded:null,versionRemoved:null,deprecated:true,deprecationMessage:'Rules with `$empty` are still supported and being converted into `$redirect=nooptext` now\nbut the support shall be removed in the future.',removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'empty',aliases:null,description:'This modifier is deprecated in favor of the $redirect modifier.\nRules with `$empty` are still supported and being converted into `$redirect=nooptext` now\nbut the support shall be removed in the future.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#empty-modifier',versionAdded:null,versionRemoved:null,deprecated:true,deprecationMessage:'Rules with `$empty` are still supported and being converted into `$redirect=nooptext` now\nbut the support shall be removed in the future.',removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'empty',aliases:null,description:'This modifier is deprecated in favor of the $redirect modifier.\nRules with `$empty` are supported and being converted into `$redirect=nooptext`.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#empty',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'1024':2,'2048':2,'4096':2,'8192':2}},{shared:[{name:'extension',aliases:null,description:'Disables all userscripts on the pages matching this rule.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#extension-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','specifichide','generichide','elemhide','genericblock','urlblock','jsinject','content','xmlhttprequest','badfilter'],inverseConflicts:true,assignable:false,negatable:true,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0}},{shared:[{name:'first-party',aliases:['1p','~third-party'],description:'A restriction of first-party requests. Equal to `~third-party`.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#third-party-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'first-party',aliases:['1p','~third-party'],description:'A restriction of first-party requests. Equal to `~third-party`.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#1p',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'font',aliases:null,description:'The rule corresponds to requests for fonts, e.g. `.woff` filename extension.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#font-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'font',aliases:null,description:'The rule corresponds to requests for fonts, e.g. `.woff` filename extension.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'font',aliases:null,description:'The rule corresponds to requests for fonts, e.g. `.woff` filename extension.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'genericblock',aliases:null,description:'Disables generic basic rules on pages that correspond to exception rule.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#genericblock-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','specifichide','generichide','elemhide','extension','jsinject','content','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'genericblock',aliases:null,description:'Disables generic basic rules on pages that correspond to exception rule.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#genericblock-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','specifichide','generichide','elemhide','jsinject','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'genericblock',aliases:null,description:'Disables generic basic rules on pages that correspond to exception rule.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#genericblock-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','specifichide','generichide','elemhide','jsinject','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'genericblock',aliases:null,description:'Disables generic basic rules on pages that correspond to exception rule.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#genericblock-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','specifichide','generichide','elemhide','jsinject','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'genericblock',aliases:null,description:'Disables generic basic rules on pages that correspond to exception rule.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'256':2,'512':3,'16384':4,'32768':4,'65536':4,'131072':4}},{shared:[{name:'generichide',aliases:['ghide'],description:'Disables all generic cosmetic rules.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#generichide-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','genericblock','urlblock','extension','jsinject','content','xmlhttprequest','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'generichide',aliases:['ghide'],description:'Disables all generic cosmetic rules.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#generichide',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'generichide',aliases:null,description:'Disables all generic cosmetic rules.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'header',aliases:null,description:'The `$header` modifier allows matching the HTTP response\nhaving a specific header with (optionally) a specific value.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#header-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'^(?:)[\\w-]+(:(?:)(\\w+|\\/.+\\/))?',valueFormatFlags:'i'},{name:'header',aliases:null,description:'The `$header` modifier allows matching the HTTP response\nhaving a specific header with (optionally) a specific value.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#header-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'^(?:)[\\w-]+(:(?:)(\\w+|\\/.+\\/))?',valueFormatFlags:'i'},{name:'header',aliases:null,description:'The `$header` modifier allows matching the HTTP response\nhaving a specific header with (optionally) a specific value.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#header',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'^(?:)[\\w-]+(:(?:)(\\w+|\\/.+\\/))?',valueFormatFlags:'i'}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'1024':2,'2048':2,'4096':2,'8192':2}},{shared:[{name:'hls',aliases:null,description:'The `$hls` rules modify the response of a matching request.\nThey are intended as a convenient way to remove segments from HLS playlists (RFC 8216).',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#hls-modifier',versionAdded:'CoreLibs 1.10',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','third-party','app','important','match-case','xmlhttprequest'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'((?:)\\w+(?:)|(?:)\\/.+\\/(?:)([ti]*)?)',valueFormatFlags:'i'}],map:{'1':0,'2':0,'4':0}},{shared:[{name:'image',aliases:null,description:'The rule corresponds to images requests.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#image-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'image',aliases:null,description:'The rule corresponds to images requests.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'image',aliases:null,description:'The rule corresponds to images requests.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'important',aliases:null,description:'The `$important` modifier applied to a rule increases its priority\nover any other rule without `$important` modifier. Even over basic exception rules.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#important-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'important',aliases:null,description:'The `$important` modifier applied to a rule increases its priority\nover any other rule without `$important` modifier. Even over basic exception rules.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#important',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'inline-font',aliases:null,description:'The `$inline-font` modifier is a sort of a shortcut for $csp modifier with specific value.\nE.g. `||example.org^$inline-font` is converting into:\n```adblock\n||example.org^$csp=font-src \'self\' \'unsafe-eval\' http: https: data: blob: mediastream: filesystem:\n```',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#inline-font-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'inline-font',aliases:null,description:'The `$inline-font` modifier is a sort of a shortcut for $csp modifier with specific value.\nE.g. `||example.org^$inline-font` is converting into:\n```adblock\n||example.org^$csp=font-src \'self\' \'unsafe-eval\' http: https: data: blob: mediastream: filesystem:\n```',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#inline-font-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'inline-font',aliases:null,description:'The `$inline-font` modifier is a sort of a shortcut for $csp modifier with specific value.\nE.g. `||example.org^$inline-font` is converting into:\n```adblock\n||example.org^$csp=font-src \'self\' \'unsafe-eval\' http: https: data: blob: mediastream: filesystem:\n```',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#inline-font',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'1024':2,'2048':2,'4096':2,'8192':2}},{shared:[{name:'inline-script',aliases:null,description:'The `$inline-script` modifier is a sort of a shortcut for $csp modifier with specific value.\nE.g. `||example.org^$inline-script` is converting into:\n```adblock\n||example.org^$csp=script-src \'self\' \'unsafe-eval\' http: https: data: blob: mediastream: filesystem:\n```',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#inline-script-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'inline-script',aliases:null,description:'The `$inline-script` modifier is a sort of a shortcut for $csp modifier with specific value.\nE.g. `||example.org^$inline-script` is converting into:\n```adblock\n||example.org^$csp=script-src \'self\' \'unsafe-eval\' http: https: data: blob: mediastream: filesystem:\n```',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#inline-script-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'inline-script',aliases:null,description:'The `$inline-script` modifier is a sort of a shortcut for $csp modifier with specific value.\nE.g. `||example.org^$inline-script` is converting into:\n```adblock\n||example.org^$csp=script-src \'self\' \'unsafe-eval\' http: https: data: blob: mediastream: filesystem:\n```',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#inline-script',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'1024':2,'2048':2,'4096':2,'8192':2}},{shared:[{name:'jsinject',aliases:null,description:'Forbids adding of javascript code to the page.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#jsinject-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','specifichide','generichide','elemhide','genericblock','urlblock','extension','content','xmlhttprequest','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'jsinject',aliases:null,description:'Forbids adding of javascript code to the page.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#jsinject-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','specifichide','generichide','elemhide','genericblock','urlblock','xmlhttprequest','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'jsinject',aliases:null,description:'Forbids adding of javascript code to the page.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#jsinject-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','specifichide','generichide','elemhide','genericblock','urlblock','xmlhttprequest','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'jsinject',aliases:null,description:'Forbids adding of javascript code to the page.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#jsinject-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','specifichide','generichide','elemhide','genericblock','urlblock','xmlhttprequest','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'256':2,'512':3}},{shared:[{name:'jsonprune',aliases:null,description:'The `$jsonprune` rules modify the response to a matching request\nby removing JSON items that match a modified JSONPath expression.\nThey do not modify responses which are not valid JSON documents.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#jsonprune-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'^(?:)\\\\(?:)\\$(?:)\\.?(?:).+(?:)$',valueFormatFlags:'i'}],map:{'1':0,'2':0,'4':0}},{shared:[{name:'match-case',aliases:null,description:'This modifier defines a rule which applies only to addresses that match the case.\nDefault rules are case-insensitive.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#match-case-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'match-case',aliases:null,description:'This modifier defines a rule which applies only to addresses that match the case.\nDefault rules are case-insensitive.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#match-case',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'match-case',aliases:null,description:'This modifier defines a rule which applies only to addresses that match the case.\nDefault rules are case-insensitive.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'media',aliases:null,description:'A restriction of third-party and own requests.\nA third-party request is a request from a different domain.\nFor example, a request to `example.org` from `domain.com` is a third-party request.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#media-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'media',aliases:null,description:'A restriction of third-party and own requests.\nA third-party request is a request from a different domain.\nFor example, a request to `example.org` from `domain.com` is a third-party request.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'media',aliases:null,description:'A restriction of third-party and own requests.\nA third-party request is a request from a different domain.\nFor example, a request to `example.org` from `domain.com` is a third-party request.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'method',aliases:null,description:'This modifier limits the rule scope to requests that use the specified set of HTTP methods.\nNegated methods are allowed.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#method-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_methods',valueFormatFlags:null},{name:'method',aliases:null,description:'This modifier limits the rule scope to requests that use the specified set of HTTP methods.\nNegated methods are allowed.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#method-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_methods',valueFormatFlags:null},{name:'method',aliases:null,description:'This modifier limits the rule scope to requests that use the specified set of HTTP methods.\nNegated methods are allowed.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#method',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_methods',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'1024':2,'2048':2,'4096':2,'8192':2}},{shared:[{name:'mp4',aliases:null,description:'As a response to blocked request AdGuard returns a short video placeholder.\nRules with `$mp4` are still supported and being converted into `$redirect=noopmp4-1s` now\nbut the support shall be removed in the future.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#mp4-modifier',versionAdded:null,versionRemoved:null,deprecated:true,deprecationMessage:'Rules with `$mp4` are still supported and being converted into `$redirect=noopmp4-1s` now\nbut the support shall be removed in the future.',removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'mp4',aliases:null,description:'As a response to blocked request AdGuard returns a short video placeholder.\nRules with `$mp4` are still supported and being converted into `$redirect=noopmp4-1s` now\nbut the support shall be removed in the future.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#mp4-modifier',versionAdded:null,versionRemoved:null,deprecated:true,deprecationMessage:'Rules with `$mp4` are still supported and being converted into `$redirect=noopmp4-1s` now\nbut the support shall be removed in the future.',removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'mp4',aliases:null,description:'As a response to blocked request a short video placeholder is returned.\nRules with `$mp4` are supported and being converted into `$redirect=noopmp4-1s`.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#mp4',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'1024':2,'2048':2,'4096':2,'8192':2}},{shared:[{name:'network',aliases:null,description:'This is basically a Firewall-kind of rules allowing to fully block\nor unblock access to a specified remote address.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#network-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['app','important'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0}},{shared:[{name:'_',aliases:null,description:'The noop modifier does nothing and can be used solely to increase rules\' readability.\nIt consists of a sequence of underscore characters (_) of any length\nand can appear in a rule as many times as needed.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#noop-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'_',aliases:null,description:'The noop modifier does nothing and can be used solely to increase rules\' readability.\nIt consists of a sequence of underscore characters (_) of any length\nand can appear in a rule as many times as needed.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#noop-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'_',aliases:null,description:'The noop modifier does nothing and can be used solely to increase rules\' readability.\nIt consists of a sequence of underscore characters (_) of any length\nand can appear in a rule as many times as needed.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#noop-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'_',aliases:null,description:'The noop modifier does nothing and can be used solely to increase rules\' readability.\nIt consists of a sequence of underscore characters (_) of any length\nand can appear in a rule as many times as needed.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#noop-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'_',aliases:null,description:'The noop modifier does nothing and can be used solely to increase rules\' readability.\nIt consists of a sequence of underscore characters (_) of any length\nand can appear in a rule as many times as needed.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#_-aka-noop',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'256':2,'512':3,'1024':4,'2048':4,'4096':4,'8192':4}},{shared:[{name:'object-subrequest',aliases:null,description:'The `$object-subrequest` modifier is removed and is no longer supported.\nRules with it are considered as invalid.\nThe rule corresponds to requests by browser plugins (it is usually Flash).',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#object-subrequest-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:true,removalMessage:'The `$object-subrequest` modifier is removed and is no longer supported.\nRules with it are considered as invalid.',conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0}},{shared:[{name:'object',aliases:null,description:'The rule corresponds to browser plugins resources, e.g. Java or Flash',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#object-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'object',aliases:null,description:'The rule corresponds to browser plugins resources, e.g. Java or Flash.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'object',aliases:null,description:'The rule corresponds to browser plugins resources, e.g. Java or Flash.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'other',aliases:null,description:'The rule applies to requests for which the type has not been determined\nor does not match the types listed above.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#other-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'other',aliases:null,description:'The rule applies to requests for which the type has not been determined\nor does not match the types listed above.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'other',aliases:null,description:'The rule applies to requests for which the type has not been determined\nor does not match the types listed above.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'permissions',aliases:null,description:'For the requests matching a `$permissions` rule, ad blocker strengthens response\'s feature policy\nby adding additional feature policy equal to the `$permissions` modifier contents.\n`$permissions` rules are applied independently from any other rule type.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#permissions-modifier',versionAdded:'CoreLibs 1.11',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','important','subdocument'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'permissions_value',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0}},{shared:[{name:'ping',aliases:null,description:'The rule corresponds to requests caused by either navigator.sendBeacon() or the ping attribute on links.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#ping-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'ping',aliases:null,description:'The rule corresponds to requests caused by either navigator.sendBeacon() or the ping attribute on links.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'ping',aliases:null,description:'The rule corresponds to requests caused by either navigator.sendBeacon() or the ping attribute on links.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'popunder',aliases:null,description:'To block "popunders" windows/tabs where the original page redirects to an advertisement\nand the desired content loads in the newly created one.\nTo be used in the same manner as the popup filter option, except that it will block popunders.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#popunder',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:true,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'popup',aliases:null,description:'Pages opened in a new tab or window.\nNote: Filters will not block pop-ups by default, only if the `$popup`  type option is specified.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#popup-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'popup',aliases:null,description:'Pages opened in a new tab or window.\nNote: Filters will not block pop-ups by default, only if the `$popup`  type option is specified.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'popup',aliases:null,description:'Pages opened in a new tab or window.\nNote: Filters will not block pop-ups by default, only if the `$popup`  type option is specified.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'redirect-rule',aliases:null,description:'This is basically an alias to `$redirect`\nsince it has the same "redirection" values and the logic is almost similar.\nThe difference is that `$redirect-rule` is applied only in the case\nwhen the target request is blocked by a different basic rule.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#redirect-rule-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','to','third-party','popup','match-case','header','first-party','document','image','stylesheet','script','object','font','media','subdocument','ping','xmlhttprequest','websocket','other','webrtc','important','badfilter','app'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'^(1x1-transparent\\.gif|2x2-transparent\\.png|3x2-transparent\\.png|32x32-transparent\\.png|noopframe|noopcss|noopjs|noopjson|nooptext|empty|noopvmap-1\\.0|noopvast-2\\.0|noopvast-3\\.0|noopvast-4\\.0|noopmp3-0\\.1s|noopmp4-1s|amazon-apstag|ati-smarttag|didomi-loader|fingerprintjs2|fingerprintjs3|gemius|google-analytics-ga|google-analytics|google-ima3|googlesyndication-adsbygoogle|googletagservices-gpt|matomo|metrika-yandex-tag|metrika-yandex-watch|naver-wcslog|noeval|pardot-1\\.0|prebid-ads|prebid|prevent-bab|prevent-bab2|prevent-fab-3\\.2\\.0|prevent-popads-net|scorecardresearch-beacon|set-popads-dummy|click2load\\.html|)?$',valueFormatFlags:null},{name:'redirect-rule',aliases:null,description:'This is basically an alias to `$redirect`\nsince it has the same "redirection" values and the logic is almost similar.\nThe difference is that `$redirect-rule` is applied only in the case\nwhen the target request is blocked by a different basic rule.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#redirect-rule-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','to','third-party','popup','match-case','header','first-party','document','image','stylesheet','script','object','font','media','subdocument','ping','xmlhttprequest','websocket','other','webrtc','important','badfilter'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'^(1x1-transparent\\.gif|2x2-transparent\\.png|3x2-transparent\\.png|32x32-transparent\\.png|noopframe|noopcss|noopjs|noopjson|nooptext|empty|noopvmap-1\\.0|noopvast-2\\.0|noopvast-3\\.0|noopvast-4\\.0|noopmp3-0\\.1s|noopmp4-1s|amazon-apstag|ati-smarttag|didomi-loader|fingerprintjs2|fingerprintjs3|gemius|google-analytics-ga|google-analytics|google-ima3|googlesyndication-adsbygoogle|googletagservices-gpt|matomo|metrika-yandex-tag|metrika-yandex-watch|naver-wcslog|noeval|pardot-1\\.0|prebid-ads|prebid|prevent-bab|prevent-bab2|prevent-fab-3\\.2\\.0|prevent-popads-net|scorecardresearch-beacon|set-popads-dummy|click2load\\.html|)?$',valueFormatFlags:null},{name:'redirect-rule',aliases:null,description:'This is basically an alias to `$redirect`\nsince it has the same "redirection" values and the logic is almost similar.\nThe difference is that `$redirect-rule` is applied only in the case\nwhen the target request is blocked by a different basic rule.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#redirect-rule',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','to','third-party','popup','match-case','header','first-party','document','image','stylesheet','script','object','font','media','subdocument','ping','xmlhttprequest','websocket','other','webrtc','important','badfilter'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'^(1x1\\.gif|2x2\\.png|3x2\\.png|32x32\\.png|noop\\.css|noop\\.html|noopframe|noop\\.js|noop\\.txt|noop-0\\.1s\\.mp3|noop-0\\.5s\\.mp3|noop-1s\\.mp4|none|click2load\\.html|addthis_widget\\.js|amazon_ads\\.js|amazon_apstag\\.js|monkeybroker\\.js|doubleclick_instream_ad_status|google-analytics_ga\\.js|google-analytics_analytics\\.js|google-analytics_inpage_linkid\\.js|google-analytics_cx_api\\.js|google-ima\\.js|googletagservices_gpt\\.js|googletagmanager_gtm\\.js|googlesyndication_adsbygoogle\\.js|scorecardresearch_beacon\\.js|outbrain-widget\\.js|hd-main\\.js)(:[0-9]+)?$',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'1024':2,'2048':2,'4096':2,'8192':2}},{shared:[{name:'redirect',aliases:null,description:'Used to redirect web requests to a local "resource".',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#redirect-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'^(1x1-transparent\\.gif|2x2-transparent\\.png|3x2-transparent\\.png|32x32-transparent\\.png|noopframe|noopcss|noopjs|noopjson|nooptext|empty|noopvmap-1\\.0|noopvast-2\\.0|noopvast-3\\.0|noopvast-4\\.0|noopmp3-0\\.1s|noopmp4-1s|amazon-apstag|ati-smarttag|didomi-loader|fingerprintjs2|fingerprintjs3|gemius|google-analytics-ga|google-analytics|googletagmanager-gtm|google-ima3|googlesyndication-adsbygoogle|googletagservices-gpt|matomo|metrika-yandex-tag|metrika-yandex-watch|naver-wcslog|noeval|pardot-1\\.0|prebid-ads|prebid|prevent-bab|prevent-bab2|prevent-fab-3\\.2\\.0|prevent-popads-net|scorecardresearch-beacon|set-popads-dummy|click2load\\.html)?$',valueFormatFlags:null},{name:'redirect',aliases:null,description:'Used to redirect web requests to a local "resource".',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#redirect-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'^(1x1-transparent\\.gif|2x2-transparent\\.png|3x2-transparent\\.png|32x32-transparent\\.png|noopframe|noopcss|noopjs|noopjson|nooptext|empty|noopvmap-1\\.0|noopvast-2\\.0|noopvast-3\\.0|noopvast-4\\.0|noopmp3-0\\.1s|noopmp4-1s|amazon-apstag|ati-smarttag|didomi-loader|fingerprintjs2|fingerprintjs3|gemius|google-analytics-ga|google-analytics|googletagmanager-gtm|google-ima3|googlesyndication-adsbygoogle|googletagservices-gpt|matomo|metrika-yandex-tag|metrika-yandex-watch|naver-wcslog|noeval|pardot-1\\.0|prebid-ads|prebid|prevent-bab|prevent-bab2|prevent-fab-3\\.2\\.0|prevent-popads-net|scorecardresearch-beacon|set-popads-dummy|click2load\\.html)?$',valueFormatFlags:null},{name:'redirect',aliases:null,description:'Used to redirect web requests to a local "resource".',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#redirect',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'^(1x1\\.gif|2x2\\.png|3x2\\.png|32x32\\.png|noop\\.css|noop\\.html|noopframe|noop\\.js|noop\\.txt|noop-0\\.1s\\.mp3|noop-0\\.5s\\.mp3|noop-1s\\.mp4|none|click2load\\.html|addthis_widget\\.js|amazon_ads\\.js|amazon_apstag\\.js|monkeybroker\\.js|doubleclick_instream_ad_status|google-analytics_ga\\.js|google-analytics_analytics\\.js|google-analytics_inpage_linkid\\.js|google-analytics_cx_api\\.js|google-ima\\.js|googletagservices_gpt\\.js|googletagmanager_gtm\\.js|googlesyndication_adsbygoogle\\.js|scorecardresearch_beacon\\.js|outbrain-widget\\.js|hd-main\\.js)(:[0-9]+)?$',valueFormatFlags:null},{name:'rewrite',aliases:null,description:'The `rewrite=` option allows the rewriting of URLs (or redirecting requests) to an internal\nresource in order to deactivate it without causing an error. Indicate the internal resource\nby name and prefix `abp-resource:` in order to be recognized. For example\n`$rewrite=abp-resource:blank-js` sends an empty JavaScript.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#rewrite',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'(?:)^abp-resource:(?:)(blank-text|blank-css|blank-js|blank-html|blank-mp3|1x1-transparent-gif|2x2-transparent-png|3x2-transparent-png|32x32-transparent-png)$',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'1024':2,'2048':2,'4096':2,'8192':2,'16384':3,'32768':3,'65536':3,'131072':3}},{shared:[{name:'referrerpolicy',aliases:null,description:'This modifier allows overriding of a page\'s referrer policy.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#referrerpolicy-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['document','subdocument'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'referrerpolicy_value',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0}},{shared:[{name:'removeheader',aliases:null,description:'Rules with the `$removeheader` modifier are intended to remove headers from HTTP requests and responses.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#removeheader-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','third-party','first-party','app','important','match-case','document','image','stylesheet','script','object','font','media','subdocument','ping','xmlhttpreqeust','websocket','other','webrtc'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'^(?:)(request:)?(?:)(?!(access-control-allow-origin|access-control-allow-credentials|access-control-allow-headers|access-control-allow-methods|access-control-expose-headers|access-control-max-age|access-control-request-headers|access-control-request-method|origin|timing-allow-origin|allow|cross-origin-embedder-policy|cross-origin-opener-policy|cross-origin-resource-policy|content-security-policy|content-security-policy-report-only|expect-ct|feature-policy|origin-isolation|strict-transport-security|upgrade-insecure-requests|x-content-type-options|x-download-options|x-frame-options|x-permitted-cross-domain-policies|x-powered-by|x-xss-protection|public-key-pins|public-key-pins-report-only|sec-websocket-key|sec-websocket-extensions|sec-websocket-accept|sec-websocket-protocol|sec-websocket-version|p3p|sec-fetch-mode|sec-fetch-dest|sec-fetch-site|sec-fetch-user|referrer-policy|content-type|content-length|accept|accept-encoding|host|connection|transfer-encoding|upgrade)$)(?:)[A-z0-9-]+(?:)$',valueFormatFlags:'i'},{name:'removeheader',aliases:null,description:'Rules with the `$removeheader` modifier are intended to remove headers from HTTP requests and responses.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#removeheader-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','third-party','first-party','app','important','match-case','document','image','stylesheet','script','object','font','media','subdocument','ping','xmlhttpreqeust','websocket','other','webrtc'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'^(?:)(request:)?(?:)(?!(access-control-allow-origin|access-control-allow-credentials|access-control-allow-headers|access-control-allow-methods|access-control-expose-headers|access-control-max-age|access-control-request-headers|access-control-request-method|origin|timing-allow-origin|allow|cross-origin-embedder-policy|cross-origin-opener-policy|cross-origin-resource-policy|content-security-policy|content-security-policy-report-only|expect-ct|feature-policy|origin-isolation|strict-transport-security|upgrade-insecure-requests|x-content-type-options|x-download-options|x-frame-options|x-permitted-cross-domain-policies|x-powered-by|x-xss-protection|public-key-pins|public-key-pins-report-only|sec-websocket-key|sec-websocket-extensions|sec-websocket-accept|sec-websocket-protocol|sec-websocket-version|p3p|sec-fetch-mode|sec-fetch-dest|sec-fetch-site|sec-fetch-user|referrer-policy|content-type|content-length|accept|accept-encoding|host|connection|transfer-encoding|upgrade)$)(?:)[A-z0-9-]+(?:)$',valueFormatFlags:'i'}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1}},{shared:[{name:'removeparam',aliases:null,description:'Rules with the `$removeparam` modifier are intended to strip query parameters from requests\' URLs.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#removeparam-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'((?:)\\w+(?:)|\\/.+\\/(?:)([gimuy]+)?)',valueFormatFlags:'i'},{name:'removeparam',aliases:null,description:'Rules with the `$removeparam` modifier are intended to strip query parameters from requests\' URLs.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#removeparam-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'((?:)\\w+(?:)|\\/.+\\/(?:)([gimuy]+)?)',valueFormatFlags:'i'},{name:'removeparam',aliases:null,description:'Rules with the `$removeparam` modifier are intended to strip query parameters from requests\' URLs.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#removeparam',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'((?:)\\w+(?:)|\\/.+\\/(?:)([gimuy]+)?)',valueFormatFlags:'i'}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'1024':2,'2048':2,'4096':2,'8192':2}},{shared:[{name:'replace',aliases:null,description:'This modifier completely changes the rule behavior.\nIf it is applied, the rule will not block the request. The response is going to be modified instead.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#replace-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['app','domain','document','subdocument','script','stylesheet','other','xmlhttprequest','first-party','third-party','important','badfilter'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'^(?:)\\/(?:)(.+)(?:)\\/(?:)(.+)?(?:)\\/(?:)([gimuy]*)?(?:)$',valueFormatFlags:'i'},{name:'replace',aliases:null,description:'This modifier completely changes the rule behavior.\nIf it is applied, the rule will not block the request. The response is going to be modified instead.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#replace-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['app','domain','document','subdocument','script','stylesheet','other','xmlhttprequest','first-party','third-party','important','badfilter'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'^(?:)\\/(?:)(.+)(?:)\\/(?:)(.+)?(?:)\\/(?:)([gimuy]*)?(?:)$',valueFormatFlags:'i'},{name:'replace',aliases:null,description:'This modifier completely changes the rule behavior.\nIf it is applied, the rule will not block the request. The response is going to be modified instead.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#replace',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['app','domain','document','subdocument','script','stylesheet','other','xmlhttprequest','first-party','third-party','important','badfilter'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'^(?:)\\/(?:)(.+)(?:)\\/(?:)(.+)?(?:)\\/(?:)([gimuy]*)?(?:)$',valueFormatFlags:'i'}],map:{'1':0,'2':0,'4':0,'64':1,'8192':2}},{shared:[{name:'script',aliases:null,description:'The rule corresponds to script requests, e.g. javascript, vbscript.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#script-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'script',aliases:null,description:'The rule corresponds to script requests, e.g. javascript, vbscript.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'script',aliases:null,description:'The rule corresponds to script requests, e.g. javascript, vbscript.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'specifichide',aliases:['shide'],description:'Disables all specific element hiding and CSS rules, but not general ones.\nHas an opposite effect to `$generichide`.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#specifichide-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','genericblock','urlblock','extension','jsinject','content','xmlhttprequest','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'specifichide',aliases:['shide'],description:'Disables all specific element hiding and CSS rules, but not general ones.\nHas an opposite effect to `$generichide`.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#specifichide',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'stealth',aliases:null,description:'Disables the Stealth Mode module for all corresponding pages and requests.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#stealth-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:true,valueFormat:'pipe_separated_stealth_options',valueFormatFlags:null},{name:'stealth',aliases:null,description:'Disables the Stealth Mode module for all corresponding pages and requests.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#stealth-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:true,valueFormat:'pipe_separated_stealth_options',valueFormatFlags:null},{name:'stealth',aliases:null,description:'Disables the Stealth Mode module for all corresponding pages and requests.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#stealth-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:true,valueFormat:'pipe_separated_stealth_options',valueFormatFlags:null},{name:'stealth',aliases:null,description:'Disables the Stealth Mode module for all corresponding pages and requests.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#stealth-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:true,valueFormat:'pipe_separated_stealth_options',valueFormatFlags:null},{name:'stealth',aliases:null,description:'Disables the Stealth Mode module for all corresponding pages and requests.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#stealth-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:true,valueFormat:'pipe_separated_stealth_options',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':2,'32':3,'64':4}},{shared:[{name:'strict1p',aliases:null,description:'This new `strict1p` option can check for strict partyness.\nFor example, a network request qualifies as 1st-party if both the context and the request share the same hostname.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#strict1p',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'strict3p',aliases:null,description:'This new `strict3p` option can check for strict partyness.\nFor example, a network request qualifies as 3rd-party if the context and the request hostnames are different.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#strict3p',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'stylesheet',aliases:null,description:'The rule corresponds to CSS files requests.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#stylesheet-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'stylesheet',aliases:['css'],description:'The rule corresponds to CSS files requests.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#css',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'stylesheet',aliases:null,description:'The rule corresponds to CSS files requests.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'subdocument',aliases:null,description:'The rule corresponds to requests for built-in pages — HTML tags frame and iframe.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#subdocument-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'subdocument',aliases:['frame'],description:'The rule corresponds to requests for built-in pages — HTML tags frame and iframe.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#frame',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'subdocument',aliases:null,description:'The rule corresponds to requests for built-in pages — HTML tags frame and iframe.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'third-party',aliases:['3p'],description:'A restriction of third-party and own requests.\nA third-party request is a request from a different domain.\nFor example, a request to `example.org` from `domain.com` is a third-party request.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#third-party-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'3p',aliases:['third-party'],description:'A restriction of third-party and own requests.\nA third-party request is a request from a different domain.\nFor example, a request to `example.org` from `domain.com` is a third-party request.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#3p',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'third-party',aliases:null,description:'A restriction of third-party and own requests.\nA third-party request is a request from a different domain.\nFor example, a request to `example.org` from `domain.com` is a third-party request.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#party-requests',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'to',aliases:null,description:'`$to` limits the rule scope to requests made to the specified domains and their subdomains.\nTo add multiple domains to one rule, use the `|` character as a separator.',docs:'https://adguard.com/kb/general/ad-filtering/create-own-filters/#to-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['denyallow'],inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_domains',valueFormatFlags:null},{name:'to',aliases:null,description:'`$to` limits the rule scope to requests made to the specified domains and their subdomains.\nTo add multiple domains to one rule, use the `|` character as a separator.',docs:'https://adguard.com/kb/general/ad-filtering/create-own-filters/#to-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['denyallow'],inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_domains',valueFormatFlags:null},{name:'to',aliases:null,description:'The main motivation of this option is\nto give static network filtering engine an equivalent of DNR\'s `requestDomains` and `excludedRequestDomains`.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#to',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['denyallow'],inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_domains',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'1024':2,'2048':2,'4096':2,'8192':2}},{shared:[{name:'urlblock',aliases:null,description:'Disables blocking of all requests sent from the pages matching the rule.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#urlblock-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','specifichide','generichide','elemhide','extension','jsinject','content','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0}},{shared:[{name:'webrtc',aliases:null,description:'The rule applies only to WebRTC connections.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#webrtc-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:true,removalMessage:'This modifier is removed and is no longer supported.\nRules with it are considered as invalid. If you need to suppress WebRTC, consider using\nthe [nowebrtc scriptlet](https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#nowebrtc).',conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'webrtc',aliases:null,description:'The rule applies only to WebRTC connections.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:true,removalMessage:'This modifier is removed and is no longer supported.\nIf you need to suppress WebRTC, consider using\nthe [nowebrtc scriptlet](https://github.com/gorhill/uBlock/wiki/Resources-Library#nowebrtcjs-).',conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'webrtc',aliases:null,description:'The rule applies only to WebRTC connections.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:'1.13.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'websocket',aliases:null,description:'The rule applies only to WebSocket connections.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#websocket-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'websocket',aliases:null,description:'The rule applies only to WebSocket connections.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#websocket-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'websocket',aliases:null,description:'The rule applies only to WebSocket connections.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#websocket-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'websocket',aliases:null,description:'The rule applies only to WebSocket connections.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#websocket-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'websocket',aliases:null,description:'The rule applies only to WebSocket connections.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'websocket',aliases:null,description:'The rule applies only to WebSocket connections.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'256':2,'512':3,'1024':4,'2048':4,'4096':4,'8192':4,'16384':5,'32768':5,'65536':5,'131072':5}},{shared:[{name:'xmlhttprequest',aliases:['xhr'],description:'The rule applies only to ajax requests (requests sent via javascript object XMLHttpRequest).',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#xmlhttprequest-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'xhr',aliases:['xmlhttprequest'],description:'The rule applies only to ajax requests (requests sent via javascript object XMLHttpRequest).',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#xhr',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'xmlhttprequest',aliases:null,description:'The rule applies only to ajax requests (requests sent via javascript object XMLHttpRequest).',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}}],map:{all:0,app:1,badfilter:2,cname:3,content:4,cookie:5,csp:6,denyallow:7,document:8,doc:8,domain:9,from:9,elemhide:10,ehide:10,empty:11,extension:12,'first-party':13,'1p':13,'~third-party':13,font:14,genericblock:15,generichide:16,ghide:16,header:17,hls:18,image:19,important:20,'inline-font':21,'inline-script':22,jsinject:23,jsonprune:24,'match-case':25,media:26,method:27,mp4:28,network:29,_:30,'object-subrequest':31,object:32,other:33,permissions:34,ping:35,popunder:36,popup:37,'redirect-rule':38,redirect:39,rewrite:39,referrerpolicy:40,removeheader:41,removeparam:42,replace:43,script:44,specifichide:45,shide:45,stealth:46,strict1p:47,strict3p:48,stylesheet:49,css:49,subdocument:50,frame:50,'third-party':51,'3p':51,to:52,urlblock:53,webrtc:54,websocket:55,xmlhttprequest:56,xhr:56}};
const redirectsCompatibilityTableData = {shared:[{shared:[{name:'1x1-transparent.gif',aliases:['1x1.gif','1x1-transparent-gif'],description:'Redirects to a 1x1 transparent GIF.',docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-redirects.md#1x1-transparent.gif',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'1x1.gif',aliases:null,description:'Redirects to a 1x1 transparent GIF.',docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#available-empty-redirect-resources',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['image']},{name:'1x1-transparent-gif',aliases:null,description:'Redirects to a 1x1 transparent GIF.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#rewrite',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'2x2-transparent.png',aliases:['2x2.png','2x2-transparent-png'],description:'Redirects to a 2x2 transparent PNG.',docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-redirects.md#2x2-transparent.png',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'2x2.png',aliases:null,description:'Redirects to a 2x2 transparent PNG.',docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#available-empty-redirect-resources',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['image']},{name:'2x2-transparent-png',aliases:null,description:'Redirects to a 2x2 transparent PNG.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#rewrite',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'32x32-transparent.png',aliases:['32x32.png','32x32-transparent-png'],description:'Redirects to a 32x32 transparent PNG.',docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-redirects.md#32x32-transparent.png',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'32x32.png',aliases:null,description:'Redirects to a 32x32 transparent PNG.',docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#available-empty-redirect-resources',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['image']},{name:'32x32-transparent-png',aliases:null,description:'Redirects to a 32x32 transparent PNG.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#rewrite',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'3x2-transparent.png',aliases:['3x2.png','3x2-transparent-png'],description:'Redirects to a 3x2 transparent PNG.',docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-redirects.md#3x2-transparent.png',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'3x2.png',aliases:null,description:'Redirects to a 3x2 transparent PNG.',docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#available-empty-redirect-resources',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['image']},{name:'3x2-transparent-png',aliases:null,description:'Redirects to a 3x2 transparent PNG.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#rewrite',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'amazon-apstag',aliases:['ubo-amazon_apstag.js','amazon_apstag.js'],description:'Mocks Amazon\'s apstag.js',docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-redirects.md#amazon-apstag',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'amazon_apstag.js',aliases:null,description:'Mocks Amazon\'s apstag.js',docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#amazon_apstagjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'amazon_ads.js',aliases:null,description:null,docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'ampproject_v0.js',aliases:null,description:null,docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'ati-smarttag',aliases:null,description:null,docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'chartbeat.js',aliases:null,description:null,docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'click2load.html',aliases:['click2load.html','ubo-click2load.html'],description:'Redirects resource and replaces supposed content by decoy frame with button for original content recovering.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:true,resourceTypes:[]},{name:'click2load.html',aliases:null,description:'Redirects resource and replaces supposed content by decoy frame with button for original content recovering.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:true,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'didomi-loader',aliases:null,description:'Mocks Didomi\'s CMP loader script.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'empty',aliases:null,description:'Redirects to an empty file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'empty',aliases:null,description:'Redirects to an empty file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'fingerprintjs2',aliases:['fingerprint2.js'],description:'Mocks FingerprintJS2 script.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'fingerprint2.js',aliases:null,description:'Mocks FingerprintJS2 script.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'fingerprintjs3',aliases:['fingerprint3.js'],description:'Mocks FingerprintJS v3.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'fingerprint3.js',aliases:null,description:'Mocks FingerprintJS v3.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'gemius',aliases:null,description:'Mocks Gemius Analytics.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'google-analytics-ga',aliases:['ubo-google-analytics_ga.js','google-analytics_ga.js'],description:'Mocks old Google Analytics API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'google-analytics_ga.js',aliases:null,description:'Mocks old Google Analytics API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'google-analytics',aliases:['ubo-google-analytics_analytics.js','google-analytics_analytics.js','googletagmanager-gtm','ubo-googletagmanager_gtm.js','googletagmanager_gtm.js'],description:'Mocks Google\'s Analytics and Tag Manager APIs.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'google-analytics_analytics.js',aliases:null,description:'Mocks Google\'s Analytics and Tag Manager APIs.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'google-analytics_cx_api.js',aliases:null,description:null,docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'google-analytics_inpage_linkid.js',aliases:null,description:null,docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'google-ima3',aliases:['ubo-google-ima.js','google-ima.js'],description:'Mocks the IMA SDK of Google.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'google-ima.js',aliases:null,description:'Mocks the IMA SDK of Google.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'googlesyndication-adsbygoogle',aliases:['ubo-googlesyndication_adsbygoogle.js','ubo-googlesyndication.com/adsbygoogle.js','googlesyndication_adsbygoogle.js'],description:'Mocks Google AdSense API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'googlesyndication_adsbygoogle.js',aliases:['googlesyndication.com/adsbygoogle.js'],description:'Mocks Google AdSense API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'googletagservices-gpt',aliases:['ubo-googletagservices_gpt.js','googletagservices_gpt.js'],description:'Mocks Google Publisher Tag API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'googletagservices_gpt.js',aliases:null,description:'Mocks Google Publisher Tag API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'hd-main.js',aliases:null,description:null,docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'matomo',aliases:null,description:'Mocks the piwik.js file of Matomo (formerly Piwik).',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'metrika-yandex-tag',aliases:null,description:'Mocks Yandex Metrika API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'metrika-yandex-watch',aliases:null,description:'Mocks the old Yandex Metrika API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'naver-wcslog',aliases:null,description:'Mocks wcslog.js of Naver Analytics.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'no-protected-audience',aliases:null,description:'Prevents using the Protected Audience API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'no-topics',aliases:null,description:'Prevents using the Topics API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'noeval',aliases:['noeval.js','silent-noeval.js','ubo-noeval.js','ubo-silent-noeval.js','ubo-noeval','ubo-silent-noeval'],description:'Prevents page to use eval.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'noeval.js',aliases:null,description:'Prevents page to use eval.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'noop-0.5s.mp3',aliases:null,description:'Redirects to an empty MP3 file with a duration of 0.5 seconds.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['media']}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'noopcss',aliases:['noop.css','blank-css'],description:'Redirects to an empty CSS file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'noop.css',aliases:null,description:'Redirects to an empty CSS file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['stylesheet']},{name:'blank-css',aliases:null,description:'Redirects to an empty CSS file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'noopframe',aliases:['noop.html','blank-html'],description:'Redirects to an empty HTML file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'noop.html',aliases:null,description:'Redirects to an empty HTML file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['sub_frame']},{name:'blank-html',aliases:null,description:'Redirects to an empty HTML file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'noopjs',aliases:['noop.js','blank-js'],description:'Redirects to an empty JavaScript file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'noop.js',aliases:null,description:'Redirects to an empty JavaScript file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']},{name:'blank-js',aliases:null,description:'Redirects to an empty JavaScript file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'noopjson',aliases:['noop.json'],description:'Redirects to an empty JSON file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'noop.json',aliases:null,description:'Redirects to an empty JSON file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'noopmp3-0.1s',aliases:['noop-0.1s.mp3','blank-mp3'],description:'Redirects to an empty MP3 file with a duration of 0.1 seconds.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'noop-0.1s.mp3',aliases:null,description:'Redirects to an empty MP3 file with a duration of 0.1 seconds.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['media']},{name:'blank-mp3',aliases:null,description:'Redirects to an empty MP3 file with a duration of 0.1 seconds.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'noopmp4-1s',aliases:['noop-1s.mp4','blank-mp4'],description:'Redirects to an empty MP4 file with a duration of 1 second.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'noop-1s.mp4',aliases:null,description:'Redirects to an empty MP4 file with a duration of 1 second.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['media']},{name:'blank-mp4',aliases:null,description:'Redirects to an empty MP4 file with a duration of 1 second.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'nooptext',aliases:['noop.txt','blank-text'],description:'Redirects to an empty text file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'noop.txt',aliases:null,description:'Redirects to an empty text file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['image','media','sub_frame','stylesheet','script','xmlhttprequest','other']},{name:'blank-text',aliases:null,description:'Redirects to an empty text file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'noopvast-2.0',aliases:null,description:'Redirects to an empty VAST 2.0 XML file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'noopvast-3.0',aliases:null,description:'Redirects to an empty VAST 3.0 XML file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'noopvast-4.0',aliases:null,description:'Redirects to an empty VAST 4.0 XML file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'noopvmap-1.0',aliases:['noop-vmap1.0.xml'],description:'Redirects to an empty VMAP 1.0 XML file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'noop-vmap1.0.xml',aliases:null,description:'Redirects to an empty VMAP 1.0 XML file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['media']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'nowebrtc',aliases:['nowebrtc.js','ubo-nowebrtc.js','ubo-nowebrtc'],description:'Disables WebRTC by overriding `RTCPeerConnection`.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'nowebrtc.js',aliases:null,description:'Disables WebRTC by overriding `RTCPeerConnection`.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['other']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'outbrain-widget.js',aliases:null,description:null,docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'pardot-1.0',aliases:null,description:'Mocks the pd.js file of Salesforce.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'prebid-ads',aliases:['prebid-ads.js'],description:'Mocks prebid-ads.js script.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'prebid-ads.js',aliases:null,description:'Mocks prebid-ads.js script.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prebid',aliases:null,description:'Mocks the prebid.js header bidding suit.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'prevent-bab',aliases:['nobab.js'],description:'Prevents BlockAdblock script from detecting an ad blocker.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'nobab.js',aliases:null,description:'Prevents BlockAdblock script from detecting an ad blocker.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-bab2',aliases:['nobab2.js'],description:'Prevents BlockAdblock script from detecting an ad blocker.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'nobab2.js',aliases:null,description:'Prevents BlockAdblock script from detecting an ad blocker.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-fab-3.2.0',aliases:['nofab.js'],description:'Mocks FAB script v3.2.0.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'nofab.js',aliases:['fuckadblock.js-3.2.0','fuckadblock.js-3.2.0.js'],description:'Mocks FAB script v3.2.0.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-popads-net',aliases:['popads.js'],description:'Aborts on property write (PopAds, popns), throws reference error with random id.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'popads.js',aliases:null,description:'Aborts on property write (PopAds, popns), throws reference error with random id.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'scorecardresearch-beacon',aliases:['scorecardresearch_beacon.js'],description:'Mocks Scorecard Research API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'scorecardresearch_beacon.js',aliases:null,description:'Mocks Scorecard Research API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'set-popads-dummy',aliases:['popads-dummy.js'],description:'Sets static properties PopAds and popns.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'popads-dummy.js',aliases:null,description:'Sets static properties PopAds and popns.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}}],map:{'1x1-transparent.gif':0,'1x1.gif':0,'1x1-transparent-gif':0,'2x2-transparent.png':1,'2x2.png':1,'2x2-transparent-png':1,'32x32-transparent.png':2,'32x32.png':2,'32x32-transparent-png':2,'3x2-transparent.png':3,'3x2.png':3,'3x2-transparent-png':3,'amazon-apstag':4,'ubo-amazon_apstag.js':4,'amazon_apstag.js':4,'amazon_ads.js':5,'ampproject_v0.js':6,'ati-smarttag':7,'chartbeat.js':8,'click2load.html':9,'ubo-click2load.html':9,'didomi-loader':10,empty:11,fingerprintjs2:12,'fingerprint2.js':12,fingerprintjs3:13,'fingerprint3.js':13,gemius:14,'google-analytics-ga':15,'ubo-google-analytics_ga.js':15,'google-analytics_ga.js':15,'google-analytics':16,'ubo-google-analytics_analytics.js':16,'google-analytics_analytics.js':16,'googletagmanager-gtm':16,'ubo-googletagmanager_gtm.js':16,'googletagmanager_gtm.js':16,'google-analytics_cx_api.js':17,'google-analytics_inpage_linkid.js':18,'google-ima3':19,'ubo-google-ima.js':19,'google-ima.js':19,'googlesyndication-adsbygoogle':20,'ubo-googlesyndication_adsbygoogle.js':20,'ubo-googlesyndication.com/adsbygoogle.js':20,'googlesyndication_adsbygoogle.js':20,'googlesyndication.com/adsbygoogle.js':20,'googletagservices-gpt':21,'ubo-googletagservices_gpt.js':21,'googletagservices_gpt.js':21,'hd-main.js':22,matomo:23,'metrika-yandex-tag':24,'metrika-yandex-watch':25,'naver-wcslog':26,'no-protected-audience':27,'no-topics':28,noeval:29,'noeval.js':29,'silent-noeval.js':29,'ubo-noeval.js':29,'ubo-silent-noeval.js':29,'ubo-noeval':29,'ubo-silent-noeval':29,'noop-0.5s.mp3':30,noopcss:31,'noop.css':31,'blank-css':31,noopframe:32,'noop.html':32,'blank-html':32,noopjs:33,'noop.js':33,'blank-js':33,noopjson:34,'noop.json':34,'noopmp3-0.1s':35,'noop-0.1s.mp3':35,'blank-mp3':35,'noopmp4-1s':36,'noop-1s.mp4':36,'blank-mp4':36,nooptext:37,'noop.txt':37,'blank-text':37,'noopvast-2.0':38,'noopvast-3.0':39,'noopvast-4.0':40,'noopvmap-1.0':41,'noop-vmap1.0.xml':41,nowebrtc:42,'nowebrtc.js':42,'ubo-nowebrtc.js':42,'ubo-nowebrtc':42,'outbrain-widget.js':43,'pardot-1.0':44,'prebid-ads':45,'prebid-ads.js':45,prebid:46,'prevent-bab':47,'nobab.js':47,'prevent-bab2':48,'nobab2.js':48,'prevent-fab-3.2.0':49,'nofab.js':49,'fuckadblock.js-3.2.0':49,'fuckadblock.js-3.2.0.js':49,'prevent-popads-net':50,'popads.js':50,'scorecardresearch-beacon':51,'scorecardresearch_beacon.js':51,'set-popads-dummy':52,'popads-dummy.js':52}};
const scriptletsCompatibilityTableData = {shared:[{shared:[{name:'abort-current-inline-script',aliases:['abort-current-script.js','ubo-abort-current-script.js','acs.js','ubo-acs.js','ubo-abort-current-script','ubo-acs','abort-current-inline-script.js','ubo-abort-current-inline-script.js','acis.js','ubo-acis.js','ubo-abort-current-inline-script','ubo-acis','abp-abort-current-inline-script'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#abort-current-inline-script',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false},{name:'search',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'abort-current-script.js',aliases:['acs.js','abort-current-inline-script.js','acis.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#abort-current-scriptjs-',versionAdded:'1.37.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false},{name:'search',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'abort-current-inline-script',aliases:null,description:null,docs:'https://help.adblockplus.org/hc/en-us/articles/1500002338501-Snippet-filters-tutorial#snippets-ref',versionAdded:'3.4.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'api',required:true,description:null,pattern:null,'default':null,debug:false},{name:'search',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'abort-on-property-read',aliases:['abort-on-property-read.js','ubo-abort-on-property-read.js','aopr.js','ubo-aopr.js','ubo-abort-on-property-read','ubo-aopr','abp-abort-on-property-read'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#abort-on-property-read',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false}]},{name:'abort-on-property-read.js',aliases:['aopr.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#abort-on-property-readjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false}]},{name:'abort-on-property-read',aliases:null,description:null,docs:'https://help.adblockplus.org/hc/en-us/articles/1500002338501-Snippet-filters-tutorial#snippets-ref',versionAdded:'3.4.1',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false},{name:'setConfigurable',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'abort-on-property-write',aliases:['abort-on-property-write.js','ubo-abort-on-property-write.js','aopw.js','ubo-aopw.js','ubo-abort-on-property-write','ubo-aopw','abp-abort-on-property-write'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#abort-on-property-write',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false}]},{name:'abort-on-property-write.js',aliases:['aopw.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#abort-on-property-writejs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false}]},{name:'abort-on-property-write',aliases:null,description:null,docs:'https://help.adblockplus.org/hc/en-us/articles/1500002338501-Snippet-filters-tutorial#snippets-ref',versionAdded:'3.4.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false},{name:'setConfigurable',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'abort-on-stack-trace',aliases:['abort-on-stack-trace.js','ubo-abort-on-stack-trace.js','aost.js','ubo-aost.js','ubo-abort-on-stack-trace','ubo-aost','abp-abort-on-stack-trace'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#abort-on-stack-trace',versionAdded:'1.5.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:true,description:null,pattern:null,'default':null,debug:false}]},{name:'abort-on-stack-trace.js',aliases:['aost.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#abort-on-stack-tracejs-',versionAdded:'1.29.3rc9',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'adjust-setInterval',aliases:['nano-setInterval-booster.js','ubo-nano-setInterval-booster.js','nano-sib.js','ubo-nano-sib.js','adjust-setInterval.js','ubo-adjust-setInterval.js','ubo-nano-setInterval-booster','ubo-nano-sib','ubo-adjust-setInterval'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#adjust-setInterval',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'matchCallback',required:false,description:null,pattern:null,'default':null,debug:false},{name:'matchDelay',required:false,description:null,pattern:null,'default':null,debug:false},{name:'boost',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'adjust-setInterval.js',aliases:['nano-setInterval-booster.js','nano-sib.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#adjust-setIntervaljs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'matchCallback',required:false,description:null,pattern:null,'default':null,debug:false},{name:'matchDelay',required:false,description:null,pattern:null,'default':null,debug:false},{name:'boost',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'adjust-setTimeout',aliases:['adjust-setTimeout.js','ubo-adjust-setTimeout.js','nano-setTimeout-booster.js','ubo-nano-setTimeout-booster.js','nano-stb.js','ubo-nano-stb.js','ubo-adjust-setTimeout','ubo-nano-setTimeout-booster','ubo-nano-stb'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#adjust-setTimeout',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'matchCallback',required:false,description:null,pattern:null,'default':null,debug:false},{name:'matchDelay',required:false,description:null,pattern:null,'default':null,debug:false},{name:'boost',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'adjust-setTimeout.js',aliases:['nano-setTimeout-booster.js','nano-stb.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#adjust-setTimeoutjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'matchCallback',required:false,description:null,pattern:null,'default':null,debug:false},{name:'matchDelay',required:false,description:null,pattern:null,'default':null,debug:false},{name:'boost',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'amazon-apstag',aliases:['ubo-amazon_apstag.js','amazon_apstag.js'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#amazon-apstag',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'call-nothrow',aliases:['call-nothrow.js','ubo-call-nothrow.js','ubo-call-nothrow'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#call-nothrow',versionAdded:'1.10.1',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'functionName',required:true,description:null,pattern:null,'default':null,debug:false}]},{name:'call-nothrow.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#call-nothrowjs-',versionAdded:'1.48.1b0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'functionName',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'close-window',aliases:['window-close-if.js','ubo-window-close-if.js','ubo-window-close-if','close-window.js','ubo-close-window.js','ubo-close-window'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#close-window',versionAdded:'1.5.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'path',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'close-window.js',aliases:['window-close-if.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#close-windowjs-',versionAdded:'1.39.3b10',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'path',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'debug-current-inline-script',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#debug-current-inline-script',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false},{name:'search',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'debug-on-property-read',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#debug-on-property-read',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'debug-on-property-write',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#debug-on-property-write',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'didomi-loader',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#didomi-loader',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'dir-string',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#dir-string',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'times',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'disable-newtab-links',aliases:['disable-newtab-links.js','ubo-disable-newtab-links.js','ubo-disable-newtab-links'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#disable-newtab-links',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null},{name:'disable-newtab-links.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#disable-newtab-linksjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'evaldata-prune',aliases:['evaldata-prune.js','ubo-evaldata-prune.js','ubo-evaldata-prune'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#evaldata-prune',versionAdded:'1.9.37',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'obligatoryProps',required:false,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'evaldata-prune.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#evaldata-prunejs-',versionAdded:'1.49.3rc15',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'obligatoryProps',required:false,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'fingerprintjs2',aliases:['ubo-fingerprint2.js','fingerprint2.js'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#fingerprintjs2',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'fingerprintjs3',aliases:['ubo-fingerprint3.js','fingerprint3.js'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#fingerprintjs3',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'gemius',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#gemius',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'google-analytics-ga',aliases:['ubo-google-analytics_ga.js','google-analytics_ga.js'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#google-analytics-ga',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'google-analytics',aliases:['ubo-google-analytics_analytics.js','google-analytics_analytics.js','googletagmanager-gtm','ubo-googletagmanager_gtm.js','googletagmanager_gtm.js'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#google-analytics',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'google-ima3',aliases:['ubo-google-ima.js','google-ima.js'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#google-ima3',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'googlesyndication-adsbygoogle',aliases:['ubo-googlesyndication_adsbygoogle.js','googlesyndication_adsbygoogle.js'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#googlesyndication-adsbygoogle',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'googletagservices-gpt',aliases:['ubo-googletagservices_gpt.js','googletagservices_gpt.js'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#googletagservices-gpt',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'hide-in-shadow-dom',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#hide-in-shadow-dom',versionAdded:'1.3.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'selector',required:true,description:null,pattern:null,'default':null,debug:false},{name:'baseSelector',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'href-sanitizer',aliases:['href-sanitizer.js','ubo-href-sanitizer.js','ubo-href-sanitizer'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#href-sanitizer',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'selector',required:true,description:null,pattern:null,'default':null,debug:false},{name:'attribute',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'href-sanitizer.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#href-sanitizerjs-',versionAdded:'1.47.5b4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'selector',required:true,description:null,pattern:null,'default':null,debug:false},{name:'attribute',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'inject-css-in-shadow-dom',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#inject-css-in-shadow-dom',versionAdded:'1.8.2',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'cssRule',required:true,description:null,pattern:null,'default':null,debug:false},{name:'hostSelector',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'json-prune-fetch-response',aliases:['json-prune-fetch-response.js','ubo-json-prune-fetch-response.js','ubo-json-prune-fetch-response'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#json-prune-fetch-response',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'obligatoryProps',required:false,description:null,pattern:null,'default':null,debug:false},{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'json-prune-fetch-response.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#json-prune-fetch-responsejs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'obligatoryProps',required:false,description:null,pattern:null,'default':null,debug:false},{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'json-prune-xhr-response',aliases:['json-prune-xhr-response.js','ubo-json-prune-xhr-response.js','ubo-json-prune-xhr-response'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#json-prune-xhr-response',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'obligatoryProps',required:false,description:null,pattern:null,'default':null,debug:false},{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'json-prune-xhr-response.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#json-prune-xhr-responsejs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'obligatoryProps',required:false,description:null,pattern:null,'default':null,debug:false},{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'json-prune',aliases:['json-prune.js','ubo-json-prune.js','ubo-json-prune','abp-json-prune'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#json-prune',versionAdded:'1.1.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'obligatoryProps',required:false,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'json-prune.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#json-prunejs-',versionAdded:'1.23.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'obligatoryProps',required:false,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'json-prune',aliases:null,description:null,docs:'https://help.adblockplus.org/hc/en-us/articles/1500002338501-Snippet-filters-tutorial#snippets-ref',versionAdded:'3.9.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'rawPrunePaths',required:true,description:null,pattern:null,'default':null,debug:false},{name:'rawNeedlePaths',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'log-addEventListener',aliases:['addEventListener-logger.js','ubo-addEventListener-logger.js','aell.js','ubo-aell.js','ubo-addEventListener-logger','ubo-aell'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#log-addEventListener',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'log-eval',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#log-eval',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'log-on-stack-trace',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#log-on-stack-trace',versionAdded:'1.5.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'log',aliases:['abp-log'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#log',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'arguments',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'m3u-prune',aliases:['m3u-prune.js','ubo-m3u-prune.js','ubo-m3u-prune'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#m3u-prune',versionAdded:'1.9.1',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'urlToMatch',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'m3u-prune.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#m3u-prunejs-',versionAdded:'1.44.5b6',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'urlToMatch',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'matomo',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#matomo',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'metrika-yandex-tag',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#metrika-yandex-tag',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'metrika-yandex-watch',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#metrika-yandex-watch',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'naver-wcslog',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#naver-wcslog',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'no-protected-audience',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#no-protected-audience',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'no-topics',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#no-topics',versionAdded:'1.6.18',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'noeval',aliases:['noeval.js','silent-noeval.js','ubo-noeval.js','ubo-silent-noeval.js','ubo-noeval','ubo-silent-noeval'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#noeval',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'nowebrtc',aliases:['nowebrtc.js','ubo-nowebrtc.js','ubo-nowebrtc'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#nowebrtc',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null},{name:'nowebrtc.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#nowebrtcjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'pardot-1.0',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#pardot-1.0',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'prebid',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prebid',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'prevent-addEventListener',aliases:['addEventListener-defuser.js','ubo-addEventListener-defuser.js','aeld.js','ubo-aeld.js','ubo-addEventListener-defuser','ubo-aeld','abp-prevent-listener'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-addEventListener',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'typeSearch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'listenerSearch',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'addEventListener-defuser.js',aliases:['aeld.js','prevent-addEventListener.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#addEventListener-defuserjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'typeSearch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'listenerSearch',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'prevent-listener',aliases:null,description:null,docs:'https://help.adblockplus.org/hc/en-us/articles/1500002338501-Snippet-filters-tutorial#snippets-ref',versionAdded:'3.11.2',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'type',required:true,description:null,pattern:null,'default':null,debug:false},{name:'handler',required:false,description:null,pattern:null,'default':null,debug:false},{name:'selector',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'prevent-adfly',aliases:['adfly-defuser.js','ubo-adfly-defuser.js','ubo-adfly-defuser'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-adfly',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'prevent-bab',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-bab',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'prevent-element-src-loading',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-element-src-loading',versionAdded:'1.6.2',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'tagName',required:true,description:null,pattern:null,'default':null,debug:false},{name:'match',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'prevent-eval-if',aliases:['noeval-if.js','ubo-noeval-if.js','ubo-noeval-if'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-eval-if',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'search',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'noeval-if.js',aliases:['prevent-eval-if.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#noeval-ifjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'search',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-fab-3.2.0',aliases:['nofab.js','ubo-nofab.js','fuckadblock.js-3.2.0','ubo-fuckadblock.js-3.2.0','ubo-nofab'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-fab-3.2.0',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null},{name:'nofab.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#nofabjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-fetch',aliases:['prevent-fetch.js','no-fetch-if.js','ubo-no-fetch-if.js','ubo-no-fetch-if'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-fetch',versionAdded:'1.3.18',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'responseBody',required:false,description:null,pattern:null,'default':null,debug:false},{name:'responseType',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'prevent-fetch.js',aliases:['no-fetch-if.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#prevent-fetchjs-',versionAdded:'1.31.3b9',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'responseBody',required:false,description:null,pattern:null,'default':null,debug:false},{name:'responseType',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-popads-net',aliases:['popads.net.js','ubo-popads.net.js','ubo-popads.net'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-popads-net',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'prevent-refresh',aliases:['prevent-refresh.js','refresh-defuser.js','refresh-defuser','ubo-prevent-refresh.js','ubo-prevent-refresh','ubo-refresh-defuser.js','ubo-refresh-defuser'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-refresh',versionAdded:'1.6.2',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'delay',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'prevent-refresh.js',aliases:['refresh-defuser.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#prevent-refreshjs-',versionAdded:'1.38.7b3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'delay',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-requestAnimationFrame',aliases:['no-requestAnimationFrame-if.js','ubo-no-requestAnimationFrame-if.js','norafif.js','ubo-norafif.js','ubo-no-requestAnimationFrame-if','ubo-norafif'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-requestAnimationFrame',versionAdded:'1.1.15',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'search',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'no-requestAnimationFrame-if.js',aliases:['norafif.js','prevent-requestAnimationFrame.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#no-requestAnimationFrame-ifjs-',versionAdded:'1.27.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'search',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-setInterval',aliases:['no-setInterval-if.js','ubo-no-setInterval-if.js','setInterval-defuser.js','ubo-setInterval-defuser.js','nosiif.js','ubo-nosiif.js','sid.js','ubo-sid.js','ubo-no-setInterval-if','ubo-setInterval-defuser','ubo-nosiif','ubo-sid'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-setInterval',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'matchCallback',required:false,description:null,pattern:null,'default':null,debug:false},{name:'matchDelay',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'no-setInterval-if.js',aliases:['nosiif.js','prevent-setInterval.js','setInterval-defuser.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#no-setInterval-ifjs-',versionAdded:'1.23.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'matchCallback',required:false,description:null,pattern:null,'default':null,debug:false},{name:'matchDelay',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-setTimeout',aliases:['no-setTimeout-if.js','ubo-no-setTimeout-if.js','nostif.js','ubo-nostif.js','ubo-no-setTimeout-if','ubo-nostif','setTimeout-defuser.js','ubo-setTimeout-defuser.js','ubo-setTimeout-defuser','std.js','ubo-std.js','ubo-std'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-setTimeout',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'matchCallback',required:false,description:null,pattern:null,'default':null,debug:false},{name:'matchDelay',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'no-setTimeout-if.js',aliases:['nostif.js','prevent-setTimeout.js','setTimeout-defuser.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#no-setTimeout-ifjs-',versionAdded:'1.23.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'matchCallback',required:false,description:null,pattern:null,'default':null,debug:false},{name:'matchDelay',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-window-open',aliases:['window.open-defuser.js','ubo-window.open-defuser.js','ubo-window.open-defuser','nowoif.js','ubo-nowoif.js','ubo-nowoif','no-window-open-if.js','ubo-no-window-open-if.js','ubo-no-window-open-if'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-window-open',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'match',required:false,description:null,pattern:null,'default':null,debug:false},{name:'delay',required:false,description:null,pattern:null,'default':null,debug:false},{name:'replacement',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'no-window-open-if.js',aliases:['nowoif.js','prevent-window-open.js','window.open-defuser.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#no-window-open-ifjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'match',required:false,description:null,pattern:null,'default':null,debug:false},{name:'delay',required:false,description:null,pattern:null,'default':null,debug:false},{name:'replacement',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-xhr',aliases:['no-xhr-if.js','ubo-no-xhr-if.js','ubo-no-xhr-if'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-xhr',versionAdded:'1.5.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'randomize',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'no-xhr-if.js',aliases:['prevent-xhr.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#no-xhr-ifjs-',versionAdded:'1.38.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'randomize',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'remove-attr',aliases:['remove-attr.js','ubo-remove-attr.js','ra.js','ubo-ra.js','ubo-remove-attr','ubo-ra'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#remove-attr',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'attrs',required:true,description:null,pattern:null,'default':null,debug:false},{name:'selector',required:false,description:null,pattern:null,'default':null,debug:false},{name:'applying',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'remove-attr.js',aliases:['ra.js','ra','remove-attr'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#remove-attrjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'attrs',required:true,description:null,pattern:null,'default':null,debug:false},{name:'selector',required:false,description:null,pattern:null,'default':null,debug:false},{name:'applying',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'remove-class',aliases:['remove-class.js','ubo-remove-class.js','rc.js','ubo-rc.js','ubo-remove-class','ubo-rc'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#remove-class',versionAdded:'1.1.1',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'classes',required:true,description:null,pattern:null,'default':null,debug:false},{name:'selector',required:false,description:null,pattern:null,'default':null,debug:false},{name:'applying',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'remove-class.js',aliases:['rc.js','rc','remove-class'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#remove-classjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'classes',required:true,description:null,pattern:null,'default':null,debug:false},{name:'selector',required:false,description:null,pattern:null,'default':null,debug:false},{name:'applying',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'remove-cookie',aliases:['cookie-remover.js','ubo-cookie-remover.js','ubo-cookie-remover','remove-cookie.js','ubo-remove-cookie.js','ubo-remove-cookie','abp-cookie-remover'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#remove-cookie',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'match',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'remove-cookie.js',aliases:['cookie-remover.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#remove-cookiejs-',versionAdded:'1.28.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'match',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'cookie-remover',aliases:null,description:null,docs:'https://help.adblockplus.org/hc/en-us/articles/1500002338501-Snippet-filters-tutorial#snippets-ref',versionAdded:'3.11.2',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'cookie',required:true,description:null,pattern:null,'default':null,debug:false},{name:'autoRemoveCookie',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'remove-in-shadow-dom',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#remove-in-shadow-dom',versionAdded:'1.3.14',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'selector',required:true,description:null,pattern:null,'default':null,debug:false},{name:'baseSelector',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'remove-node-text',aliases:['remove-node-text.js','ubo-remove-node-text.js','rmnt.js','ubo-rmnt.js','ubo-remove-node-text','ubo-rmnt'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#remove-node-text',versionAdded:'1.9.37',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'nodeName',required:true,description:null,pattern:null,'default':null,debug:false},{name:'textMatch',required:true,description:null,pattern:null,'default':null,debug:false}]},{name:'remove-node-text.js',aliases:['rmnt.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#remove-node-textjs-',versionAdded:'1.49.3rc15',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'nodeName',required:true,description:null,pattern:null,'default':null,debug:false},{name:'textMatch',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'scorecardresearch-beacon',aliases:['ubo-scorecardresearch_beacon.js','scorecardresearch_beacon.js'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#scorecardresearch-beacon',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'set-attr',aliases:['set-attr.js','ubo-set-attr.js','ubo-set-attr'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#set-attr',versionAdded:'1.5.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'selector',required:true,description:null,pattern:null,'default':null,debug:false},{name:'attr',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'set-attr.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#set-attrjs-',versionAdded:'1.50.1b16',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'selector',required:true,description:null,pattern:null,'default':null,debug:false},{name:'attr',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'set-constant',aliases:['set-constant.js','ubo-set-constant.js','set.js','ubo-set.js','ubo-set-constant','ubo-set'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#set-constant',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false},{name:'valueWrapper',required:false,description:null,pattern:null,'default':null,debug:false},{name:'setProxyTrap',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'set-constant.js',aliases:['set.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#set-constantjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'chain',required:true,description:null,pattern:null,'default':null,debug:false},{name:'rawValue',required:true,description:null,pattern:null,'default':null,debug:false},{name:'runAt',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'override-property-read',aliases:null,description:null,docs:'https://help.adblockplus.org/hc/en-us/articles/1500002338501-Snippet-filters-tutorial#snippets-ref',versionAdded:'3.9.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false},{name:'setConfigurable',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'set-cookie-reload',aliases:['set-cookie-reload.js','ubo-set-cookie-reload.js','ubo-set-cookie-reload'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#set-cookie-reload',versionAdded:'1.3.14',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'name',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false},{name:'path',required:false,description:null,pattern:null,'default':null,debug:false},{name:'domain',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'set-cookie-reload.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#set-cookie-reloadjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'name',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false},{name:'path',required:false,description:null,pattern:null,'default':null,debug:false},{name:'domain',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'set-cookie',aliases:['set-cookie.js','ubo-set-cookie.js','ubo-set-cookie'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#set-cookie',versionAdded:'1.2.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'name',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false},{name:'path',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'set-cookie.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#set-cookiejs-',versionAdded:'1.50.1b0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'name',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false},{name:'path',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'set-local-storage-item',aliases:['set-local-storage-item.js','ubo-set-local-storage-item.js','ubo-set-local-storage-item'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#set-local-storage-item',versionAdded:'1.4.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'key',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false}]},{name:'set-local-storage-item.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#set-local-storage-itemjs-',versionAdded:'1.50.1b4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'key',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'set-popads-dummy',aliases:['popads-dummy.js','ubo-popads-dummy.js','ubo-popads-dummy'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#set-popads-dummy',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'set-session-storage-item',aliases:['set-session-storage-item.js','ubo-set-session-storage-item.js','ubo-set-session-storage-item'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#set-session-storage-item',versionAdded:'1.4.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'key',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false}]},{name:'set-session-storage-item.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#set-session-storage-itemjs-',versionAdded:'1.50.1b4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'key',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'spoof-css',aliases:['spoof-css.js','ubo-spoof-css.js','ubo-spoof-css'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#spoof-css',versionAdded:'1.10.1',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'selectors',required:true,description:null,pattern:null,'default':null,debug:false},{name:'cssPropertyName',required:true,description:null,pattern:null,'default':null,debug:false},{name:'cssPropertyValue',required:true,description:null,pattern:null,'default':null,debug:false}]},{name:'spoof-css.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#spoof-cssjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'selectors',required:true,description:null,pattern:null,'default':null,debug:false},{name:'cssPropertyName',required:true,description:null,pattern:null,'default':null,debug:false},{name:'cssPropertyValue',required:true,description:null,pattern:null,'default':null,debug:false},{name:'arguments',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'trusted-click-element',aliases:null,description:null,docs:null,versionAdded:'1.7.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'selectors',required:true,description:null,pattern:null,'default':null,debug:false},{name:'extraMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'delay',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-create-element',aliases:null,description:null,docs:null,versionAdded:'1.10.1',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'parentSelector',required:true,description:null,pattern:null,'default':null,debug:false},{name:'tagName',required:true,description:null,pattern:null,'default':null,debug:false},{name:'attributePairs',required:false,description:null,pattern:null,'default':null,debug:false},{name:'textContent',required:false,description:null,pattern:null,'default':null,debug:false},{name:'cleanupDelayMs',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-dispatch-event',aliases:null,description:null,docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'event',required:true,description:null,pattern:null,'default':null,debug:false},{name:'target',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-prune-inbound-object',aliases:null,description:null,docs:null,versionAdded:'1.9.91',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'functionName',required:true,description:null,pattern:null,'default':null,debug:false},{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'obligatoryProps',required:false,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-replace-fetch-response',aliases:null,description:null,docs:null,versionAdded:'1.7.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'pattern',required:false,description:null,pattern:null,'default':null,debug:false},{name:'replacement',required:false,description:null,pattern:null,'default':null,debug:false},{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-replace-node-text',aliases:null,description:null,docs:null,versionAdded:'1.9.37',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'nodeName',required:true,description:null,pattern:null,'default':null,debug:false},{name:'textMatch',required:true,description:null,pattern:null,'default':null,debug:false},{name:'pattern',required:true,description:null,pattern:null,'default':null,debug:false},{name:'replacement',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-replace-xhr-response',aliases:null,description:null,docs:null,versionAdded:'1.7.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'pattern',required:false,description:null,pattern:null,'default':null,debug:false},{name:'replacement',required:false,description:null,pattern:null,'default':null,debug:false},{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-set-attr',aliases:null,description:null,docs:null,versionAdded:'1.10.1',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'selector',required:true,description:null,pattern:null,'default':null,debug:false},{name:'attr',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-set-constant',aliases:null,description:null,docs:null,versionAdded:'1.8.2',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-set-cookie-reload',aliases:null,description:null,docs:null,versionAdded:'1.7.10',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'name',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false},{name:'offsetExpiresSec',required:false,description:null,pattern:null,'default':null,debug:false},{name:'path',required:false,description:null,pattern:null,'default':null,debug:false},{name:'domain',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-set-cookie',aliases:null,description:null,docs:null,versionAdded:'1.7.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'name',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false},{name:'offsetExpiresSec',required:false,description:null,pattern:null,'default':null,debug:false},{name:'path',required:false,description:null,pattern:null,'default':null,debug:false},{name:'domain',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-set-local-storage-item',aliases:null,description:null,docs:null,versionAdded:'1.7.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'key',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-suppress-native-method',aliases:null,description:null,docs:null,versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'methodPath',required:true,description:null,pattern:null,'default':null,debug:false},{name:'signatureStr',required:true,description:null,pattern:null,'default':null,debug:false},{name:'how',required:false,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'xml-prune',aliases:['xml-prune.js','ubo-xml-prune.js','ubo-xml-prune'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#xml-prune',versionAdded:'1.7.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'optionalProp',required:false,description:null,pattern:null,'default':null,debug:false},{name:'urlToMatch',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'xml-prune.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#xml-prunejs-',versionAdded:'1.49.3rc6',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'optionalProp',required:false,description:null,pattern:null,'default':null,debug:false},{name:'urlToMatch',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}}],map:{'abort-current-inline-script':0,'abort-current-script.js':0,'ubo-abort-current-script.js':0,'acs.js':0,'ubo-acs.js':0,'ubo-abort-current-script':0,'ubo-acs':0,'abort-current-inline-script.js':0,'ubo-abort-current-inline-script.js':0,'acis.js':0,'ubo-acis.js':0,'ubo-abort-current-inline-script':0,'ubo-acis':0,'abp-abort-current-inline-script':0,'abort-on-property-read':1,'abort-on-property-read.js':1,'ubo-abort-on-property-read.js':1,'aopr.js':1,'ubo-aopr.js':1,'ubo-abort-on-property-read':1,'ubo-aopr':1,'abp-abort-on-property-read':1,'abort-on-property-write':2,'abort-on-property-write.js':2,'ubo-abort-on-property-write.js':2,'aopw.js':2,'ubo-aopw.js':2,'ubo-abort-on-property-write':2,'ubo-aopw':2,'abp-abort-on-property-write':2,'abort-on-stack-trace':3,'abort-on-stack-trace.js':3,'ubo-abort-on-stack-trace.js':3,'aost.js':3,'ubo-aost.js':3,'ubo-abort-on-stack-trace':3,'ubo-aost':3,'abp-abort-on-stack-trace':3,'adjust-setInterval':4,'nano-setInterval-booster.js':4,'ubo-nano-setInterval-booster.js':4,'nano-sib.js':4,'ubo-nano-sib.js':4,'adjust-setInterval.js':4,'ubo-adjust-setInterval.js':4,'ubo-nano-setInterval-booster':4,'ubo-nano-sib':4,'ubo-adjust-setInterval':4,'adjust-setTimeout':5,'adjust-setTimeout.js':5,'ubo-adjust-setTimeout.js':5,'nano-setTimeout-booster.js':5,'ubo-nano-setTimeout-booster.js':5,'nano-stb.js':5,'ubo-nano-stb.js':5,'ubo-adjust-setTimeout':5,'ubo-nano-setTimeout-booster':5,'ubo-nano-stb':5,'amazon-apstag':6,'ubo-amazon_apstag.js':6,'amazon_apstag.js':6,'call-nothrow':7,'call-nothrow.js':7,'ubo-call-nothrow.js':7,'ubo-call-nothrow':7,'close-window':8,'window-close-if.js':8,'ubo-window-close-if.js':8,'ubo-window-close-if':8,'close-window.js':8,'ubo-close-window.js':8,'ubo-close-window':8,'debug-current-inline-script':9,'debug-on-property-read':10,'debug-on-property-write':11,'didomi-loader':12,'dir-string':13,'disable-newtab-links':14,'disable-newtab-links.js':14,'ubo-disable-newtab-links.js':14,'ubo-disable-newtab-links':14,'evaldata-prune':15,'evaldata-prune.js':15,'ubo-evaldata-prune.js':15,'ubo-evaldata-prune':15,fingerprintjs2:16,'ubo-fingerprint2.js':16,'fingerprint2.js':16,fingerprintjs3:17,'ubo-fingerprint3.js':17,'fingerprint3.js':17,gemius:18,'google-analytics-ga':19,'ubo-google-analytics_ga.js':19,'google-analytics_ga.js':19,'google-analytics':20,'ubo-google-analytics_analytics.js':20,'google-analytics_analytics.js':20,'googletagmanager-gtm':20,'ubo-googletagmanager_gtm.js':20,'googletagmanager_gtm.js':20,'google-ima3':21,'ubo-google-ima.js':21,'google-ima.js':21,'googlesyndication-adsbygoogle':22,'ubo-googlesyndication_adsbygoogle.js':22,'googlesyndication_adsbygoogle.js':22,'googletagservices-gpt':23,'ubo-googletagservices_gpt.js':23,'googletagservices_gpt.js':23,'hide-in-shadow-dom':24,'href-sanitizer':25,'href-sanitizer.js':25,'ubo-href-sanitizer.js':25,'ubo-href-sanitizer':25,'inject-css-in-shadow-dom':26,'json-prune-fetch-response':27,'json-prune-fetch-response.js':27,'ubo-json-prune-fetch-response.js':27,'ubo-json-prune-fetch-response':27,'json-prune-xhr-response':28,'json-prune-xhr-response.js':28,'ubo-json-prune-xhr-response.js':28,'ubo-json-prune-xhr-response':28,'json-prune':29,'json-prune.js':29,'ubo-json-prune.js':29,'ubo-json-prune':29,'abp-json-prune':29,'log-addEventListener':30,'addEventListener-logger.js':30,'ubo-addEventListener-logger.js':30,'aell.js':30,'ubo-aell.js':30,'ubo-addEventListener-logger':30,'ubo-aell':30,'log-eval':31,'log-on-stack-trace':32,log:33,'abp-log':33,'m3u-prune':34,'m3u-prune.js':34,'ubo-m3u-prune.js':34,'ubo-m3u-prune':34,matomo:35,'metrika-yandex-tag':36,'metrika-yandex-watch':37,'naver-wcslog':38,'no-protected-audience':39,'no-topics':40,noeval:41,'noeval.js':41,'silent-noeval.js':41,'ubo-noeval.js':41,'ubo-silent-noeval.js':41,'ubo-noeval':41,'ubo-silent-noeval':41,nowebrtc:42,'nowebrtc.js':42,'ubo-nowebrtc.js':42,'ubo-nowebrtc':42,'pardot-1.0':43,prebid:44,'prevent-addEventListener':45,'addEventListener-defuser.js':45,'ubo-addEventListener-defuser.js':45,'aeld.js':45,'ubo-aeld.js':45,'ubo-addEventListener-defuser':45,'ubo-aeld':45,'abp-prevent-listener':45,'prevent-addEventListener.js':45,'prevent-listener':45,'prevent-adfly':46,'adfly-defuser.js':46,'ubo-adfly-defuser.js':46,'ubo-adfly-defuser':46,'prevent-bab':47,'prevent-element-src-loading':48,'prevent-eval-if':49,'noeval-if.js':49,'ubo-noeval-if.js':49,'ubo-noeval-if':49,'prevent-eval-if.js':49,'prevent-fab-3.2.0':50,'nofab.js':50,'ubo-nofab.js':50,'fuckadblock.js-3.2.0':50,'ubo-fuckadblock.js-3.2.0':50,'ubo-nofab':50,'prevent-fetch':51,'prevent-fetch.js':51,'no-fetch-if.js':51,'ubo-no-fetch-if.js':51,'ubo-no-fetch-if':51,'prevent-popads-net':52,'popads.net.js':52,'ubo-popads.net.js':52,'ubo-popads.net':52,'prevent-refresh':53,'prevent-refresh.js':53,'refresh-defuser.js':53,'refresh-defuser':53,'ubo-prevent-refresh.js':53,'ubo-prevent-refresh':53,'ubo-refresh-defuser.js':53,'ubo-refresh-defuser':53,'prevent-requestAnimationFrame':54,'no-requestAnimationFrame-if.js':54,'ubo-no-requestAnimationFrame-if.js':54,'norafif.js':54,'ubo-norafif.js':54,'ubo-no-requestAnimationFrame-if':54,'ubo-norafif':54,'prevent-requestAnimationFrame.js':54,'prevent-setInterval':55,'no-setInterval-if.js':55,'ubo-no-setInterval-if.js':55,'setInterval-defuser.js':55,'ubo-setInterval-defuser.js':55,'nosiif.js':55,'ubo-nosiif.js':55,'sid.js':55,'ubo-sid.js':55,'ubo-no-setInterval-if':55,'ubo-setInterval-defuser':55,'ubo-nosiif':55,'ubo-sid':55,'prevent-setInterval.js':55,'prevent-setTimeout':56,'no-setTimeout-if.js':56,'ubo-no-setTimeout-if.js':56,'nostif.js':56,'ubo-nostif.js':56,'ubo-no-setTimeout-if':56,'ubo-nostif':56,'setTimeout-defuser.js':56,'ubo-setTimeout-defuser.js':56,'ubo-setTimeout-defuser':56,'std.js':56,'ubo-std.js':56,'ubo-std':56,'prevent-setTimeout.js':56,'prevent-window-open':57,'window.open-defuser.js':57,'ubo-window.open-defuser.js':57,'ubo-window.open-defuser':57,'nowoif.js':57,'ubo-nowoif.js':57,'ubo-nowoif':57,'no-window-open-if.js':57,'ubo-no-window-open-if.js':57,'ubo-no-window-open-if':57,'prevent-window-open.js':57,'prevent-xhr':58,'no-xhr-if.js':58,'ubo-no-xhr-if.js':58,'ubo-no-xhr-if':58,'prevent-xhr.js':58,'remove-attr':59,'remove-attr.js':59,'ubo-remove-attr.js':59,'ra.js':59,'ubo-ra.js':59,'ubo-remove-attr':59,'ubo-ra':59,ra:59,'remove-class':60,'remove-class.js':60,'ubo-remove-class.js':60,'rc.js':60,'ubo-rc.js':60,'ubo-remove-class':60,'ubo-rc':60,rc:60,'remove-cookie':61,'cookie-remover.js':61,'ubo-cookie-remover.js':61,'ubo-cookie-remover':61,'remove-cookie.js':61,'ubo-remove-cookie.js':61,'ubo-remove-cookie':61,'abp-cookie-remover':61,'cookie-remover':61,'remove-in-shadow-dom':62,'remove-node-text':63,'remove-node-text.js':63,'ubo-remove-node-text.js':63,'rmnt.js':63,'ubo-rmnt.js':63,'ubo-remove-node-text':63,'ubo-rmnt':63,'scorecardresearch-beacon':64,'ubo-scorecardresearch_beacon.js':64,'scorecardresearch_beacon.js':64,'set-attr':65,'set-attr.js':65,'ubo-set-attr.js':65,'ubo-set-attr':65,'set-constant':66,'set-constant.js':66,'ubo-set-constant.js':66,'set.js':66,'ubo-set.js':66,'ubo-set-constant':66,'ubo-set':66,'override-property-read':66,'set-cookie-reload':67,'set-cookie-reload.js':67,'ubo-set-cookie-reload.js':67,'ubo-set-cookie-reload':67,'set-cookie':68,'set-cookie.js':68,'ubo-set-cookie.js':68,'ubo-set-cookie':68,'set-local-storage-item':69,'set-local-storage-item.js':69,'ubo-set-local-storage-item.js':69,'ubo-set-local-storage-item':69,'set-popads-dummy':70,'popads-dummy.js':70,'ubo-popads-dummy.js':70,'ubo-popads-dummy':70,'set-session-storage-item':71,'set-session-storage-item.js':71,'ubo-set-session-storage-item.js':71,'ubo-set-session-storage-item':71,'spoof-css':72,'spoof-css.js':72,'ubo-spoof-css.js':72,'ubo-spoof-css':72,'trusted-click-element':73,'trusted-create-element':74,'trusted-dispatch-event':75,'trusted-prune-inbound-object':76,'trusted-replace-fetch-response':77,'trusted-replace-node-text':78,'trusted-replace-xhr-response':79,'trusted-set-attr':80,'trusted-set-constant':81,'trusted-set-cookie-reload':82,'trusted-set-cookie':83,'trusted-set-local-storage-item':84,'trusted-suppress-native-method':85,'xml-prune':86,'xml-prune.js':86,'ubo-xml-prune.js':86,'ubo-xml-prune':86}};



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/deep-freeze.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Simple deep freeze implementation.
 * It freezes the object and all its properties recursively.
 *
 * @param object Object to freeze.
 *
 * @returns Frozen object.
 *
 * @template T Type of the object to freeze.
 *
 * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze#deep_freezing}
 */
const deepFreeze = (object) => {
    // Retrieve the property names defined on object
    const propNames = Reflect.ownKeys(object);
    // Freeze properties before freezing self
    for (const name of propNames) {
        const value = object[name];
        if ((value && typeof value === 'object') || typeof value === 'function') {
            deepFreeze(value);
        }
    }
    return Object.freeze(object);
};



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/compatibility-tables/scriptlets.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * @file Compatibility tables for scriptlets.
 */
/**
 * Compatibility table for scriptlets.
 */
class ScriptletsCompatibilityTable extends CompatibilityTableBase {
}
/**
 * Deep freeze the compatibility table data to avoid accidental modifications.
 */
deepFreeze(scriptletsCompatibilityTableData);
/**
 * Compatibility table instance for scriptlets.
 */
const scriptletsCompatibilityTable = new ScriptletsCompatibilityTable(scriptletsCompatibilityTableData);



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/converter/cosmetic/scriptlet.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */























/**
 * @file Scriptlet injection rule converter
 */
const ABP_SCRIPTLET_PREFIX = 'abp-';
const UBO_SCRIPTLET_PREFIX = 'ubo-';
const UBO_SCRIPTLET_PREFIX_LENGTH = UBO_SCRIPTLET_PREFIX.length;
const UBO_SCRIPTLET_JS_SUFFIX = '.js';
const UBO_SCRIPTLET_JS_SUFFIX_LENGTH = UBO_SCRIPTLET_JS_SUFFIX.length;
const COMMA_SEPARATOR = ',';
const ADG_SET_CONSTANT_NAME = 'set-constant';
const ADG_SET_CONSTANT_EMPTY_STRING = '';
const ADG_SET_CONSTANT_EMPTY_ARRAY = 'emptyArr';
const ADG_SET_CONSTANT_EMPTY_OBJECT = 'emptyObj';
const UBO_SET_CONSTANT_EMPTY_STRING = '\'\'';
const UBO_SET_CONSTANT_EMPTY_ARRAY = '[]';
const UBO_SET_CONSTANT_EMPTY_OBJECT = '{}';
const ADG_PREVENT_FETCH_NAME = 'prevent-fetch';
const ADG_PREVENT_FETCH_EMPTY_STRING = '';
const ADG_PREVENT_FETCH_WILDCARD = '*';
const UBO_NO_FETCH_IF_WILDCARD = '/^/';
const UBO_REMOVE_CLASS_NAME = 'remove-class.js';
const UBO_REMOVE_ATTR_NAME = 'remove-attr.js';
const setConstantAdgToUboMap = {
    [ADG_SET_CONSTANT_EMPTY_STRING]: UBO_SET_CONSTANT_EMPTY_STRING,
    [ADG_SET_CONSTANT_EMPTY_ARRAY]: UBO_SET_CONSTANT_EMPTY_ARRAY,
    [ADG_SET_CONSTANT_EMPTY_OBJECT]: UBO_SET_CONSTANT_EMPTY_OBJECT,
};
const REMOVE_ATTR_CLASS_APPLYING = new Set([
    'asap',
    'stay',
    'complete',
]);
/**
 * Scriptlet injection rule converter class
 *
 * @todo Implement `convertToUbo` and `convertToAbp`
 */
class ScriptletRuleConverter extends RuleConverterBase {
    /**
     * Converts a scriptlet injection rule to AdGuard format, if possible.
     *
     * @param rule Rule node to convert
     * @returns An object which follows the {@link NodeConversionResult} interface. Its `result` property contains
     * the array of converted rule nodes, and its `isConverted` flag indicates whether the original rule was converted.
     * If the rule was not converted, the result array will contain the original node with the same object reference
     * @throws If the rule is invalid or cannot be converted
     */
    static convertToAdg(rule) {
        // Ignore AdGuard rules
        if (rule.syntax === adblockers/* AdblockSyntax */.Y.Adg) {
            return createNodeConversionResult([rule], false);
        }
        const separator = rule.separator.value;
        let convertedSeparator = separator;
        convertedSeparator = rule.exception
            ? nodes/* CosmeticRuleSeparator */.p5.AdgJsInjectionException
            : nodes/* CosmeticRuleSeparator */.p5.AdgJsInjection;
        const convertedScriptlets = [];
        for (const scriptlet of rule.body.children) {
            // Clone the node to avoid any side effects
            const scriptletClone = cloneScriptletRuleNode(scriptlet);
            // Remove possible quotes just to make it easier to work with the scriptlet name
            const scriptletName = quotes/* QuoteUtils */.Qj.setStringQuoteType(getScriptletName(scriptletClone), quotes/* QuoteType */.XA.None);
            // Add prefix if it's not already there
            let prefix;
            // In uBO / ABP syntax, if a parameter contains the separator character, it should be escaped,
            // but during the conversion, we need to unescape them, because AdGuard syntax uses quotes to
            // distinguish between parameters.
            let charToUnescape;
            switch (rule.syntax) {
                case adblockers/* AdblockSyntax */.Y.Abp:
                    prefix = ABP_SCRIPTLET_PREFIX;
                    charToUnescape = constants/* SPACE */.t6;
                    break;
                case adblockers/* AdblockSyntax */.Y.Ubo:
                    prefix = UBO_SCRIPTLET_PREFIX;
                    charToUnescape = COMMA_SEPARATOR;
                    break;
                default:
                    prefix = constants/* EMPTY */.wg;
            }
            if (!scriptletName.startsWith(prefix)) {
                setScriptletName(scriptletClone, `${prefix}${scriptletName}`);
            }
            if (!(0,type_guards/* isUndefined */.b0)(charToUnescape)) {
                transformAllScriptletArguments(scriptletClone, (value) => {
                    if (!(0,type_guards/* isNull */.kZ)(value)) {
                        return quotes/* QuoteUtils */.Qj.unescapeSingleEscapedOccurrences(value, charToUnescape);
                    }
                    return value;
                });
            }
            if (rule.syntax === adblockers/* AdblockSyntax */.Y.Ubo) {
                const scriptletData = scriptletsCompatibilityTable.getFirst(scriptletName, GenericPlatform.UboAny);
                // Some scriptlets have special values that need to be converted
                if (scriptletData
                    && (scriptletData.name === UBO_REMOVE_CLASS_NAME
                        || scriptletData.name === UBO_REMOVE_ATTR_NAME)
                    && scriptletClone.children.length > 2) {
                    const selectors = [];
                    let applying = null;
                    let lastArg = scriptletClone.children.pop();
                    // The very last argument might be the 'applying' parameter
                    if (lastArg) {
                        if (REMOVE_ATTR_CLASS_APPLYING.has(lastArg.value)) {
                            applying = lastArg.value;
                        }
                        else {
                            selectors.push(lastArg.value);
                        }
                    }
                    while (scriptletClone.children.length > 2) {
                        lastArg = scriptletClone.children.pop();
                        if (lastArg) {
                            selectors.push(lastArg.value.trim());
                        }
                    }
                    // Set last arg to be the combined selectors (in reverse order, because we popped them)
                    if (selectors.length > 0) {
                        scriptletClone.children.push({
                            type: 'Value',
                            value: selectors.reverse().join(', '),
                        });
                    }
                    // Push back the 'applying' parameter if it was found previously
                    if (!(0,type_guards/* isNull */.kZ)(applying)) {
                        // If we don't have any selectors,
                        // we need to add an empty parameter before the 'applying' one
                        if (selectors.length === 0) {
                            scriptletClone.children.push({
                                type: 'Value',
                                value: constants/* EMPTY */.wg,
                            });
                        }
                        scriptletClone.children.push({
                            type: 'Value',
                            value: applying,
                        });
                    }
                }
            }
            // ADG scriptlet parameters should be quoted, and single quoted are preferred
            setScriptletQuoteType(scriptletClone, quotes/* QuoteType */.XA.Single);
            convertedScriptlets.push(scriptletClone);
        }
        if (rule.body.children.length === 0) {
            const convertedScriptletNode = {
                category: rule.category,
                type: rule.type,
                syntax: adblockers/* AdblockSyntax */.Y.Adg,
                exception: rule.exception,
                domains: cloneDomainListNode(rule.domains),
                separator: {
                    type: 'Value',
                    value: convertedSeparator,
                },
                body: {
                    type: rule.body.type,
                    children: [],
                },
            };
            if (rule.modifiers) {
                convertedScriptletNode.modifiers = cloneModifierListNode(rule.modifiers);
            }
            return createNodeConversionResult([convertedScriptletNode], true);
        }
        return createNodeConversionResult(convertedScriptlets.map((scriptlet) => {
            const res = {
                category: rule.category,
                type: rule.type,
                syntax: adblockers/* AdblockSyntax */.Y.Adg,
                exception: rule.exception,
                domains: cloneDomainListNode(rule.domains),
                separator: {
                    type: 'Value',
                    value: convertedSeparator,
                },
                body: {
                    type: rule.body.type,
                    children: [scriptlet],
                },
            };
            if (rule.modifiers) {
                res.modifiers = cloneModifierListNode(rule.modifiers);
            }
            return res;
        }), true);
    }
    /**
     * Converts a scriptlet injection rule to uBlock format, if possible.
     *
     * @param rule Rule node to convert
     * @returns An object which follows the {@link NodeConversionResult} interface. Its `result` property contains
     * the array of converted rule nodes, and its `isConverted` flag indicates whether the original rule was converted.
     * If the rule was not converted, the result array will contain the original node with the same object reference
     * @throws If the rule is invalid or cannot be converted
     */
    static convertToUbo(rule) {
        // Ignore uBlock rules
        if (rule.syntax === adblockers/* AdblockSyntax */.Y.Ubo) {
            return createNodeConversionResult([rule], false);
        }
        const separator = rule.separator.value;
        let convertedSeparator = separator;
        convertedSeparator = rule.exception
            ? nodes/* CosmeticRuleSeparator */.p5.ElementHidingException
            : nodes/* CosmeticRuleSeparator */.p5.ElementHiding;
        const convertedScriptlets = [];
        for (const scriptlet of rule.body.children) {
            // Clone the node to avoid any side effects
            const scriptletClone = cloneScriptletRuleNode(scriptlet);
            // Remove possible quotes just to make it easier to work with the scriptlet name
            const scriptletName = quotes/* QuoteUtils */.Qj.setStringQuoteType(getScriptletName(scriptletClone), quotes/* QuoteType */.XA.None);
            let uboScriptletName;
            if (rule.syntax === adblockers/* AdblockSyntax */.Y.Adg && scriptletName.startsWith(UBO_SCRIPTLET_PREFIX)) {
                // Special case: AdGuard syntax 'preserves' the original scriptlet name,
                // so we need to convert it back by removing the uBO prefix
                uboScriptletName = scriptletName.slice(UBO_SCRIPTLET_PREFIX_LENGTH);
            }
            else {
                // Otherwise, try to find the corresponding uBO scriptlet name, or use the original one if not found
                const uboScriptlet = scriptletsCompatibilityTable.getFirst(scriptletName, GenericPlatform.UboAny);
                if (!uboScriptlet) {
                    throw new RuleConversionError(`Scriptlet "${scriptletName}" is not supported in uBlock Origin.`);
                }
                uboScriptletName = uboScriptlet.name;
            }
            // Remove the '.js' suffix if it's there - its presence is not mandatory
            if (uboScriptletName.endsWith(UBO_SCRIPTLET_JS_SUFFIX)) {
                uboScriptletName = uboScriptletName.slice(0, -UBO_SCRIPTLET_JS_SUFFIX_LENGTH);
            }
            setScriptletName(scriptletClone, uboScriptletName);
            setScriptletQuoteType(scriptletClone, quotes/* QuoteType */.XA.None);
            // Escape unescaped commas in parameters, because uBlock Origin uses them as separators.
            // For example, the following AdGuard rule:
            //
            // example.com#%#//scriptlet('spoof-css', '.adsbygoogle, #ads', 'visibility', 'visible')
            //
            //      ↓↓ should be converted to ↓↓
            //
            // example.com##+js(spoof-css.js, .adsbygoogle\, #ads, visibility, visible)
            //                  ------------  -------------------  ----------  -------
            //                    arg 0              arg 1           arg 2      arg 3
            //
            // and we need to escape the comma in the second argument to prevent it from being treated
            // as two separate arguments.
            transformAllScriptletArguments(scriptletClone, (value) => {
                if (!(0,type_guards/* isNull */.kZ)(value)) {
                    return quotes/* QuoteUtils */.Qj.escapeUnescapedOccurrences(value, COMMA_SEPARATOR);
                }
                return value;
            });
            // Unescape spaces in parameters, because uBlock Origin doesn't treat them as separators.
            if (rule.syntax === adblockers/* AdblockSyntax */.Y.Abp) {
                transformAllScriptletArguments(scriptletClone, (value) => {
                    if (!(0,type_guards/* isNull */.kZ)(value)) {
                        return quotes/* QuoteUtils */.Qj.unescapeSingleEscapedOccurrences(value, constants/* SPACE */.t6);
                    }
                    return value;
                });
            }
            // Some scriptlets have special values that need to be converted
            switch (scriptletName) {
                case ADG_SET_CONSTANT_NAME:
                    transformNthScriptletArgument(scriptletClone, 2, (value) => {
                        if (!(0,type_guards/* isNull */.kZ)(value)) {
                            return setConstantAdgToUboMap[value] ?? value;
                        }
                        return value;
                    });
                    break;
                case ADG_PREVENT_FETCH_NAME:
                    transformNthScriptletArgument(scriptletClone, 1, (value) => {
                        if (value === ADG_PREVENT_FETCH_EMPTY_STRING || value === ADG_PREVENT_FETCH_WILDCARD) {
                            return UBO_NO_FETCH_IF_WILDCARD;
                        }
                        return value;
                    });
                    break;
            }
            convertedScriptlets.push(scriptletClone);
        }
        // TODO: Refactor redundant code
        if (rule.body.children.length === 0) {
            const convertedScriptletNode = {
                category: rule.category,
                type: rule.type,
                syntax: adblockers/* AdblockSyntax */.Y.Ubo,
                exception: rule.exception,
                domains: cloneDomainListNode(rule.domains),
                separator: {
                    type: 'Value',
                    value: convertedSeparator,
                },
                body: {
                    type: rule.body.type,
                    children: [],
                },
            };
            if (rule.modifiers) {
                convertedScriptletNode.modifiers = cloneModifierListNode(rule.modifiers);
            }
            return createNodeConversionResult([convertedScriptletNode], true);
        }
        return createNodeConversionResult(convertedScriptlets.map((scriptlet) => {
            const res = {
                category: rule.category,
                type: rule.type,
                syntax: adblockers/* AdblockSyntax */.Y.Ubo,
                exception: rule.exception,
                domains: cloneDomainListNode(rule.domains),
                separator: {
                    type: 'Value',
                    value: convertedSeparator,
                },
                body: {
                    type: rule.body.type,
                    children: [scriptlet],
                },
            };
            if (rule.modifiers) {
                res.modifiers = cloneModifierListNode(rule.modifiers);
            }
            return res;
        }), true);
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/ast-utils/modifiers.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */



/**
 * @file Utility functions for working with modifier nodes
 */
/**
 * Creates a modifier node
 *
 * @param name Name of the modifier
 * @param value Value of the modifier
 * @param exception Whether the modifier is an exception
 * @returns Modifier node
 */
function createModifierNode(name, value = undefined, exception = false) {
    const result = {
        type: 'Modifier',
        exception,
        name: {
            type: 'Value',
            value: name,
        },
    };
    if (!(0,type_guards/* isUndefined */.b0)(value)) {
        result.value = {
            type: 'Value',
            value,
        };
    }
    return result;
}
/**
 * Creates a modifier list node
 *
 * @param modifiers Modifiers to put in the list (optional, defaults to an empty list)
 * @returns Modifier list node
 */
function createModifierListNode(modifiers = []) {
    const result = {
        type: 'ModifierList',
        // We need to clone the modifiers to avoid side effects
        children: modifiers.length ? clone(modifiers) : [],
    };
    return result;
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/multi-value-map.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * A very simple map extension that allows to store multiple values for the same key
 * by storing them in an array.
 *
 * @todo Add more methods if needed
 */
class MultiValueMap extends Map {
    /**
     * Adds a value to the map. If the key already exists, the value will be appended to the existing array,
     * otherwise a new array will be created for the key.
     *
     * @param key Key to add
     * @param values Value(s) to add
     */
    add(key, ...values) {
        let currentValues = super.get(key);
        if ((0,type_guards/* isUndefined */.b0)(currentValues)) {
            currentValues = [];
            super.set(key, values);
        }
        currentValues.push(...values);
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/converter/cosmetic/rule-modifiers/adg.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */









/**
 * @file Cosmetic rule modifier converter from uBO to ADG
 */
const UBO_MATCHES_PATH_OPERATOR = 'matches-path';
const ADG_PATH_MODIFIER = 'path';
/**
 * Special characters in modifier regexps that should be escaped
 */
const SPECIAL_MODIFIER_REGEX_CHARS = new Set([
    constants/* OPEN_SQUARE_BRACKET */.cU,
    constants/* CLOSE_SQUARE_BRACKET */.A1,
    constants/* COMMA */.KE,
    constants/* ESCAPE_CHARACTER */.Kx,
]);
/**
 * Helper class for converting cosmetic rule modifiers from uBO to ADG
 */
class AdgCosmeticRuleModifierConverter {
    /**
     * Converts a uBO cosmetic rule modifier list to ADG, if possible.
     *
     * @param modifierList Cosmetic rule modifier list node to convert
     * @returns An object which follows the {@link ConversionResult} interface. Its `result` property contains
     * the converted node, and its `isConverted` flag indicates whether the original node was converted.
     * If the node was not converted, the result will contain the original node with the same object reference
     * @throws If the modifier list cannot be converted
     * @see {@link https://github.com/gorhill/uBlock/wiki/Procedural-cosmetic-filters#cosmetic-filter-operators}
     */
    static convertFromUbo(modifierList) {
        const conversionMap = new MultiValueMap();
        modifierList.children.forEach((modifier, index) => {
            // :matches-path
            if (modifier.name.value === UBO_MATCHES_PATH_OPERATOR) {
                if (!modifier.value) {
                    throw new RuleConversionError(`'${UBO_MATCHES_PATH_OPERATOR}' operator requires a value`);
                }
                const value = RegExpUtils.isRegexPattern(modifier.value.value)
                    ? string/* StringUtils */.$x.escapeCharacters(modifier.value.value, SPECIAL_MODIFIER_REGEX_CHARS)
                    : modifier.value.value;
                // Convert uBO's `:matches-path(...)` operator to ADG's `$path=...` modifier
                conversionMap.add(index, createModifierNode(ADG_PATH_MODIFIER, 
                // We should negate the regexp if the modifier is an exception
                modifier.exception
                    // eslint-disable-next-line max-len
                    ? `${constants/* REGEX_MARKER */.Vb}${RegExpUtils.negateRegexPattern(RegExpUtils.patternToRegexp(value))}${constants/* REGEX_MARKER */.Vb}`
                    : value));
            }
        });
        // Check if we have any converted modifiers
        if (conversionMap.size) {
            const modifierListClone = clone(modifierList);
            // Replace the original modifiers with the converted ones
            modifierListClone.children = modifierListClone.children.map((modifier, index) => {
                const convertedModifier = conversionMap.get(index);
                return convertedModifier ?? modifier;
            }).flat();
            return createConversionResult(modifierListClone, true);
        }
        // Otherwise, just return the original modifier list
        return createConversionResult(modifierList, false);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/converter/data/css.js
var css = __webpack_require__(9119);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/converter/css/index.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */








const css_ERROR_MESSAGES = {
    // eslint-disable-next-line max-len
    INVALID_ATTRIBUTE_VALUE: `Expected '${(0,csstokenizer/* getFormattedTokenName */.bZ)(csstokenizer/* TokenType */.ks.Ident)}' or '${(0,csstokenizer/* getFormattedTokenName */.bZ)(csstokenizer/* TokenType */.ks.String)}' as attribute value, but got '%s' with value '%s`,
};
const css_PseudoClasses = {
    AbpContains: '-abp-contains',
    AbpHas: '-abp-has',
    Contains: 'contains',
    Has: 'has',
    HasText: 'has-text',
    MatchesCss: 'matches-css',
    MatchesCssAfter: 'matches-css-after',
    MatchesCssBefore: 'matches-css-before'};
const PseudoElements = {
    After: 'after',
    Before: 'before',
};
const PSEUDO_ELEMENT_NAMES = new Set([
    PseudoElements.After,
    PseudoElements.Before,
]);
/**
 * CSS selector converter
 *
 * @todo Implement `convertToUbo` and `convertToAbp`
 */
class CssSelectorConverter extends BaseConverter {
    /**
     * Converts Extended CSS elements to AdGuard-compatible ones
     *
     * @param selectorList Selector list to convert
     * @returns An object which follows the {@link ConversionResult} interface. Its `result` property contains
     * the converted node, and its `isConverted` flag indicates whether the original node was converted.
     * If the node was not converted, the result will contain the original node with the same object reference
     * @throws If the rule is invalid or incompatible
     */
    static convertToAdg(selectorList) {
        const stream = selectorList instanceof css_token_stream/* CssTokenStream */.d
            ? selectorList
            : new css_token_stream/* CssTokenStream */.d(selectorList);
        const converted = [];
        const convertAndPushPseudo = (pseudo) => {
            switch (pseudo) {
                case css_PseudoClasses.AbpContains:
                case css_PseudoClasses.HasText:
                    converted.push(css_PseudoClasses.Contains);
                    converted.push(constants/* OPEN_PARENTHESIS */.Cx);
                    break;
                case css_PseudoClasses.AbpHas:
                    converted.push(css_PseudoClasses.Has);
                    converted.push(constants/* OPEN_PARENTHESIS */.Cx);
                    break;
                // a bit special case:
                // - `:matches-css-before(...)` → `:matches-css(before, ...)`
                // - `:matches-css-after(...)`  → `:matches-css(after, ...)`
                case css_PseudoClasses.MatchesCssBefore:
                case css_PseudoClasses.MatchesCssAfter:
                    converted.push(css_PseudoClasses.MatchesCss);
                    converted.push(constants/* OPEN_PARENTHESIS */.Cx);
                    converted.push(pseudo.substring(css_PseudoClasses.MatchesCss.length + 1));
                    converted.push(constants/* COMMA */.KE);
                    break;
                default:
                    converted.push(pseudo);
                    converted.push(constants/* OPEN_PARENTHESIS */.Cx);
                    break;
            }
        };
        while (!stream.isEof()) {
            const token = stream.getOrFail();
            if (token.type === csstokenizer/* TokenType */.ks.Colon) {
                // Advance colon
                stream.advance();
                converted.push(constants/* COLON */.oH);
                const tempToken = stream.getOrFail();
                // Double colon is a pseudo-element
                if (tempToken.type === csstokenizer/* TokenType */.ks.Colon) {
                    stream.advance();
                    converted.push(constants/* COLON */.oH);
                    continue;
                }
                if (tempToken.type === csstokenizer/* TokenType */.ks.Ident) {
                    const name = stream.source.slice(tempToken.start, tempToken.end);
                    if (PSEUDO_ELEMENT_NAMES.has(name)) {
                        // Add an extra colon to the name
                        converted.push(constants/* COLON */.oH);
                        converted.push(name);
                    }
                    else {
                        // Add the name as is
                        converted.push(name);
                    }
                    // Advance the names
                    stream.advance();
                }
                else if (tempToken.type === csstokenizer/* TokenType */.ks.Function) {
                    const name = stream.source.slice(tempToken.start, tempToken.end - 1); // omit the last parenthesis
                    // :-abp-contains(...) → :contains(...)
                    // :has-text(...)      → :contains(...)
                    // :-abp-has(...)      → :has(...)
                    convertAndPushPseudo(name);
                    // Advance the function name
                    stream.advance();
                }
            }
            else if (token.type === csstokenizer/* TokenType */.ks.OpenSquareBracket) {
                let tempToken;
                const { start } = token;
                stream.advance();
                // Converts legacy Extended CSS selectors to the modern Extended CSS syntax.
                // For example:
                // - `[-ext-has=...]`                  → `:has(...)`
                // - `[-ext-contains=...]`             → `:contains(...)`
                // - `[-ext-matches-css-before=...]`   → `:matches-css(before, ...)`
                stream.skipWhitespace();
                stream.expect(csstokenizer/* TokenType */.ks.Ident);
                tempToken = stream.getOrFail();
                let attr = stream.source.slice(tempToken.start, tempToken.end);
                // Skip if the attribute name is not a legacy Extended CSS one
                if (!(attr.startsWith(css/* LEGACY_EXT_CSS_ATTRIBUTE_PREFIX */.at) || attr.startsWith(css/* ABP_EXT_CSS_PREFIX */.PY))) {
                    converted.push(stream.source.slice(start, tempToken.end));
                    stream.advance();
                    continue;
                }
                if (attr.startsWith(css/* LEGACY_EXT_CSS_ATTRIBUTE_PREFIX */.at)) {
                    attr = attr.slice(css/* LEGACY_EXT_CSS_ATTRIBUTE_PREFIX */.at.length);
                }
                stream.advance();
                stream.skipWhitespace();
                // Next token should be an equality operator (=), because Extended CSS attribute selectors
                // do not support other operators
                stream.expect(csstokenizer/* TokenType */.ks.Delim, { value: constants/* EQUALS */.UT });
                stream.advance();
                // Skip optional whitespace after the operator
                stream.skipWhitespace();
                // Parse attribute value
                tempToken = stream.getOrFail();
                // According to the spec, attribute value should be an identifier or a string
                if (tempToken.type !== csstokenizer/* TokenType */.ks.Ident && tempToken.type !== csstokenizer/* TokenType */.ks.String) {
                    throw new Error((0,sprintf.sprintf)(css_ERROR_MESSAGES.INVALID_ATTRIBUTE_VALUE, (0,csstokenizer/* getFormattedTokenName */.bZ)(tempToken.type), stream.source.slice(tempToken.start, tempToken.end)));
                }
                const value = stream.source.slice(tempToken.start, tempToken.end);
                // Advance the attribute value
                stream.advance();
                // Skip optional whitespace after the attribute value
                stream.skipWhitespace();
                // Next character should be a closing square bracket
                // We don't allow flags for Extended CSS attribute selectors
                stream.expect(csstokenizer/* TokenType */.ks.CloseSquareBracket);
                stream.advance();
                converted.push(constants/* COLON */.oH);
                convertAndPushPseudo(attr);
                let processedValue = value.slice(1, -1); // omit the quotes
                if (attr === css_PseudoClasses.Has) {
                    // TODO: Optimize this to avoid double tokenization
                    processedValue = CssSelectorConverter.convertToAdg(processedValue).result;
                }
                converted.push(processedValue);
                converted.push(constants/* CLOSE_PARENTHESIS */.s1);
            }
            else {
                converted.push(stream.source.slice(token.start, token.end));
                // Advance the token
                stream.advance();
            }
        }
        const convertedSelectorList = converted.join(constants/* EMPTY */.wg);
        return createConversionResult(convertedSelectorList, stream.source !== convertedSelectorList);
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/converter/cosmetic/css.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */








/**
 * @file CSS injection rule converter
 */
/**
 * CSS injection rule converter class
 *
 * @todo Implement `convertToUbo` and `convertToAbp`
 */
class CssInjectionRuleConverter extends RuleConverterBase {
    /**
     * Converts a CSS injection rule to AdGuard format, if possible.
     *
     * @param rule Rule node to convert
     * @returns An object which follows the {@link NodeConversionResult} interface. Its `result` property contains
     * the array of converted rule nodes, and its `isConverted` flag indicates whether the original rule was converted.
     * If the rule was not converted, the result array will contain the original node with the same object reference
     * @throws If the rule is invalid or cannot be converted
     */
    static convertToAdg(rule) {
        const separator = rule.separator.value;
        let convertedSeparator = separator;
        const stream = new css_token_stream/* CssTokenStream */.d(rule.body.selectorList.value);
        const convertedSelectorList = CssSelectorConverter.convertToAdg(stream);
        // Change the separator if the rule contains ExtendedCSS elements,
        // but do not force non-extended CSS separator if the rule does not contain any ExtendedCSS selectors,
        // because sometimes we use it to force executing ExtendedCSS library.
        if (stream.hasAnySelectorExtendedCssNodeStrict() || rule.body.remove) {
            convertedSeparator = rule.exception
                ? nodes/* CosmeticRuleSeparator */.p5.AdgExtendedCssInjectionException
                : nodes/* CosmeticRuleSeparator */.p5.AdgExtendedCssInjection;
        }
        else if (rule.syntax !== adblockers/* AdblockSyntax */.Y.Adg) {
            // If the original rule syntax is not AdGuard, use the default separator
            // e.g. if the input rule is from uBO, we need to convert ## to #$#.
            convertedSeparator = rule.exception
                ? nodes/* CosmeticRuleSeparator */.p5.AdgCssInjectionException
                : nodes/* CosmeticRuleSeparator */.p5.AdgCssInjection;
        }
        // Check if the rule needs to be converted
        if (!(rule.syntax === adblockers/* AdblockSyntax */.Y.Common || rule.syntax === adblockers/* AdblockSyntax */.Y.Adg)
            || separator !== convertedSeparator
            || convertedSelectorList.isConverted) {
            // TODO: Replace with custom clone method
            const ruleClone = clone(rule);
            ruleClone.syntax = adblockers/* AdblockSyntax */.Y.Adg;
            ruleClone.separator.value = convertedSeparator;
            ruleClone.body.selectorList.value = convertedSelectorList.result;
            return createNodeConversionResult([ruleClone], true);
        }
        // Otherwise, return the original rule
        return createNodeConversionResult([rule], false);
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/converter/cosmetic/element-hiding.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */








/**
 * @file Element hiding rule converter
 */
/**
 * Element hiding rule converter class
 *
 * @todo Implement `convertToUbo` and `convertToAbp`
 */
class ElementHidingRuleConverter extends RuleConverterBase {
    /**
     * Converts an element hiding rule to AdGuard format, if possible.
     *
     * @param rule Rule node to convert
     * @returns An object which follows the {@link NodeConversionResult} interface. Its `result` property contains
     * the array of converted rule nodes, and its `isConverted` flag indicates whether the original rule was converted.
     * If the rule was not converted, the result array will contain the original node with the same object reference
     * @throws If the rule is invalid or cannot be converted
     */
    static convertToAdg(rule) {
        const separator = rule.separator.value;
        let convertedSeparator = separator;
        const stream = new css_token_stream/* CssTokenStream */.d(rule.body.selectorList.value);
        const convertedSelectorList = CssSelectorConverter.convertToAdg(stream);
        // Change the separator if the rule contains ExtendedCSS elements,
        // but do not force non-extended CSS separator if the rule does not contain any ExtendedCSS selectors,
        // because sometimes we use it to force executing ExtendedCSS library.
        if (stream.hasAnySelectorExtendedCssNodeStrict()) {
            convertedSeparator = rule.exception
                ? nodes/* CosmeticRuleSeparator */.p5.ExtendedElementHidingException
                : nodes/* CosmeticRuleSeparator */.p5.ExtendedElementHiding;
        }
        // Check if the rule needs to be converted
        if (!(rule.syntax === adblockers/* AdblockSyntax */.Y.Common || rule.syntax === adblockers/* AdblockSyntax */.Y.Adg)
            || separator !== convertedSeparator
            || convertedSelectorList.isConverted) {
            // TODO: Replace with custom clone method
            const ruleClone = clone(rule);
            ruleClone.syntax = adblockers/* AdblockSyntax */.Y.Adg;
            ruleClone.separator.value = convertedSeparator;
            ruleClone.body.selectorList.value = convertedSelectorList.result;
            return createNodeConversionResult([ruleClone], true);
        }
        // Otherwise, return the original rule
        return createNodeConversionResult([rule], false);
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/ast-utils/network-rules.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */





/**
 * @file Utility functions for working with network rule nodes
 */
/**
 * Creates a network rule node
 *
 * @param pattern Rule pattern
 * @param modifiers Rule modifiers (optional, default: undefined)
 * @param exception Exception rule flag (optional, default: false)
 * @param syntax Adblock syntax (optional, default: Common)
 * @returns Network rule node
 */
function createNetworkRuleNode(pattern, modifiers = undefined, exception = false, syntax = adblockers/* AdblockSyntax */.Y.Common) {
    const result = {
        category: nodes/* RuleCategory */.$O.Network,
        type: nodes/* NetworkRuleType */.vY.NetworkRule,
        syntax,
        exception,
        pattern: {
            type: 'Value',
            value: pattern,
        },
    };
    if (!(0,type_guards/* isUndefined */.b0)(modifiers)) {
        result.modifiers = clone(modifiers);
    }
    return result;
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/converter/cosmetic/header-removal.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */













/**
 * @file Converter for request header removal rules
 */
const UBO_RESPONSEHEADER_FN = 'responseheader';
const ADG_REMOVEHEADER_MODIFIER = 'removeheader';
const header_removal_ERROR_MESSAGES = {
    EMPTY_PARAMETER: `Empty parameter for '${UBO_RESPONSEHEADER_FN}' function`,
    EXPECTED_END_OF_RULE: "Expected end of rule, but got '%s'",
    MULTIPLE_DOMAINS_NOT_SUPPORTED: 'Multiple domains are not supported yet',
};
/**
 * Converter for request header removal rules
 *
 * @todo Implement `convertToUbo` (ABP currently doesn't support header removal rules)
 */
class HeaderRemovalRuleConverter extends RuleConverterBase {
    /**
     * Converts a header removal rule to AdGuard syntax, if possible.
     *
     * @param rule Rule node to convert
     * @returns An object which follows the {@link NodeConversionResult} interface. Its `result` property contains
     * the array of converted rule nodes, and its `isConverted` flag indicates whether the original rule was converted.
     * If the rule was not converted, the result array will contain the original node with the same object reference
     * @throws If the rule is invalid or cannot be converted
     * @example
     * If the input rule is:
     * ```adblock
     * example.com##^responseheader(header-name)
     * ```
     * The output will be:
     * ```adblock
     * ||example.com^$removeheader=header-name
     * ```
     */
    static convertToAdg(rule) {
        // TODO: Add support for ABP syntax once it starts supporting header removal rules
        // Leave the rule as is if it's not a header removal rule
        if (rule.category !== nodes/* RuleCategory */.$O.Cosmetic || rule.type !== nodes/* CosmeticRuleType */.k9.HtmlFilteringRule) {
            return createNodeConversionResult([rule], false);
        }
        const stream = new css_token_stream/* CssTokenStream */.d(rule.body.value);
        let token;
        // Skip leading whitespace
        stream.skipWhitespace();
        // Next token should be the `^` followed by a `responseheader` function
        token = stream.get();
        if (!token || token.type !== csstokenizer/* TokenType */.ks.Delim || rule.body.value[token.start] !== constants/* UBO_HTML_MASK */._h) {
            return createNodeConversionResult([rule], false);
        }
        stream.advance();
        token = stream.get();
        if (!token) {
            return createNodeConversionResult([rule], false);
        }
        const functionName = rule.body.value.slice(token.start, token.end - 1);
        if (functionName !== UBO_RESPONSEHEADER_FN) {
            return createNodeConversionResult([rule], false);
        }
        // Parse the parameter
        const paramStart = token.end;
        stream.skipUntilBalanced();
        const paramEnd = stream.getOrFail().end;
        const param = rule.body.value.slice(paramStart, paramEnd - 1).trim();
        // Do not allow empty parameter
        if (param.length === 0) {
            throw new RuleConversionError(header_removal_ERROR_MESSAGES.EMPTY_PARAMETER);
        }
        stream.expect(csstokenizer/* TokenType */.ks.CloseParenthesis);
        stream.advance();
        // Skip trailing whitespace after the function call
        stream.skipWhitespace();
        // Expect the end of the rule - so nothing should be left in the stream
        if (!stream.isEof()) {
            token = stream.getOrFail();
            throw new RuleConversionError((0,sprintf.sprintf)(header_removal_ERROR_MESSAGES.EXPECTED_END_OF_RULE, (0,csstokenizer/* getFormattedTokenName */.bZ)(token.type)));
        }
        // Prepare network rule pattern
        const pattern = [];
        if (rule.domains.children.length === 1) {
            // If the rule has only one domain, we can use a simple network rule pattern:
            // ||single-domain-from-the-rule^
            pattern.push(ADBLOCK_URL_START, rule.domains.children[0].value, ADBLOCK_URL_SEPARATOR);
        }
        else if (rule.domains.children.length > 1) {
            // TODO: Add support for multiple domains, for example:
            // example.com,example.org,example.net##^responseheader(header-name)
            // We should consider allowing $domain with $removeheader modifier,
            // for example:
            // $removeheader=header-name,domain=example.com|example.org|example.net
            throw new RuleConversionError(header_removal_ERROR_MESSAGES.MULTIPLE_DOMAINS_NOT_SUPPORTED);
        }
        // Prepare network rule modifiers
        const modifiers = createModifierListNode();
        modifiers.children.push(createModifierNode(ADG_REMOVEHEADER_MODIFIER, param));
        // Construct the network rule
        return createNodeConversionResult([
            createNetworkRuleNode(pattern.join(constants/* EMPTY */.wg), modifiers, 
            // Copy the exception flag
            rule.exception, adblockers/* AdblockSyntax */.Y.Adg),
        ], true);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/misc/domain-list-parser.js + 1 modules
var domain_list_parser = __webpack_require__(26571);
// EXTERNAL MODULE: ./node_modules/.pnpm/is-ip@3.1.0/node_modules/is-ip/index.js
var is_ip = __webpack_require__(85183);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/converter/cosmetic/rule-modifiers/ubo.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */

















/**
 * @file Cosmetic rule modifier converter from ADG to uBO
 */
/**
 * Regular expression pattern for matching the main page
 * https://github.com/gorhill/uBlock/wiki/Procedural-cosmetic-filters#subjectmatches-patharg
 */
const UBO_MAIN_PAGE_MATCHER = '/^/$/';
/**
 * Special characters in modifier regexps that should be escaped
 */
const ubo_SPECIAL_MODIFIER_REGEX_CHARS = new Set([
    constants/* OPEN_SQUARE_BRACKET */.cU,
    constants/* CLOSE_SQUARE_BRACKET */.A1,
    constants/* COMMA_DOMAIN_LIST_SEPARATOR */.oo,
    constants/* ESCAPE_CHARACTER */.Kx,
]);
/**
 * Helper class for converting cosmetic rule modifiers from ADG to uBO
 */
class UboCosmeticRuleModifierConverter {
    /**
     * Converts a ADG cosmetic rule modifier list to uBO, if possible.
     *
     * @param modifierList Cosmetic rule modifier list node to convert
     * @returns An object which follows the {@link ConversionResult} interface. Its `result` property contains
     * the converted node, and its `isConverted` flag indicates whether the original node was converted.
     * If the node was not converted, the result will contain the original node with the same object reference
     * @throws If the modifier list cannot be converted
     * @see {@link https://github.com/gorhill/uBlock/wiki/Procedural-cosmetic-filters#cosmetic-filter-operators}
     */
    static convertFromAdg(modifierList) {
        const conversionMap = new MultiValueMap();
        let domainList = null;
        let regexDomainValue;
        modifierList.children.forEach((modifier, index) => {
            let value;
            let { exception } = modifier;
            switch (modifier.name.value) {
                // Special case: ADG's $app modifier
                case constants/* ADG_APP_MODIFIER */.Pe:
                    throw new Error('The $app modifier is not supported by uBO');
                // Special case: ADG's $domains modifier
                case constants/* ADG_DOMAINS_MODIFIER */.NW:
                    if (!domainList) {
                        domainList = {
                            type: nodes/* ListNodeType */.h6.DomainList,
                            separator: constants/* COMMA_DOMAIN_LIST_SEPARATOR */.oo,
                            children: [],
                            start: modifier.start,
                            end: modifier.end,
                        };
                    }
                    if (!modifier?.value?.value) {
                        return;
                    }
                    domainList = domain_list_parser/* DomainListParser */.y.parse(modifier.value.value, {}, modifier.start, constants/* PIPE_MODIFIER_SEPARATOR */.fW);
                    conversionMap.add(index, null);
                    break;
                // Special case: ADG's $url modifier
                case constants/* ADG_URL_MODIFIER */.Vw:
                    if (!domainList) {
                        domainList = {
                            type: nodes/* ListNodeType */.h6.DomainList,
                            separator: constants/* COMMA_DOMAIN_LIST_SEPARATOR */.oo,
                            children: [],
                            start: modifier.start,
                            end: modifier.end,
                        };
                    }
                    if (!modifier?.value?.value) {
                        return;
                    }
                    regexDomainValue = RegExpUtils.patternToRegexp(modifier.value.value);
                    domainList = {
                        type: nodes/* ListNodeType */.h6.DomainList,
                        separator: constants/* COMMA_DOMAIN_LIST_SEPARATOR */.oo,
                        children: [
                            {
                                type: nodes/* ListItemNodeType */.WR.Domain,
                                value: RegExpUtils.ensureSlashes(regexDomainValue),
                                exception: modifier?.exception ?? false,
                            },
                        ],
                        start: modifier.start,
                        end: modifier.end,
                    };
                    conversionMap.add(index, null);
                    break;
                // Special case: ADG's $path modifier
                case constants/* ADG_PATH_MODIFIER */.JD:
                    if (!modifier.value) {
                        value = UBO_MAIN_PAGE_MATCHER;
                    }
                    else if (RegExpUtils.isNegatedRegexPattern(modifier.value.value)) {
                        exception = true;
                        value = string/* StringUtils */.$x.escapeCharacters(RegExpUtils.removeNegationFromRegexPattern(modifier.value.value), ubo_SPECIAL_MODIFIER_REGEX_CHARS);
                    }
                    else {
                        value = RegExpUtils.isRegexPattern(modifier.value.value)
                            ? string/* StringUtils */.$x.escapeCharacters(modifier.value.value, ubo_SPECIAL_MODIFIER_REGEX_CHARS)
                            : modifier.value.value;
                    }
                    conversionMap.add(index, createModifierNode(constants/* UBO_MATCHES_PATH_OPERATOR */.I6, value, exception));
                    break;
            }
        });
        // Check if we have any converted modifiers
        if (conversionMap.size) {
            const modifierListClone = clone(modifierList);
            // Replace the original modifiers with the converted ones
            modifierListClone.children = modifierListClone.children
                .map((modifier, index) => {
                const convertedModifier = conversionMap.get(index);
                return convertedModifier ?? modifier;
            })
                .flat()
                .filter((modifier) => modifier !== null);
            return createConversionResult({ modifierList: modifierListClone, domains: domainList || undefined }, true);
        }
        // Otherwise, just return the original modifier list without any changes
        return createConversionResult({ modifierList, domains: undefined }, false);
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/converter/cosmetic/index.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */





















/**
 * @file Cosmetic rule converter
 */
/**
 * Cosmetic rule converter class (also known as "non-basic rule converter")
 *
 * @todo Implement `convertToUbo` and `convertToAbp`
 */
class CosmeticRuleConverter extends RuleConverterBase {
    /**
     * Converts a cosmetic rule to AdGuard syntax, if possible.
     *
     * @param rule Rule node to convert
     * @returns An object which follows the {@link NodeConversionResult} interface. Its `result` property contains
     * the array of converted rule nodes, and its `isConverted` flag indicates whether the original rule was converted.
     * If the rule was not converted, the result array will contain the original node with the same object reference
     * @throws If the rule is invalid or cannot be converted
     */
    static convertToAdg(rule) {
        let subconverterResult;
        // Convert cosmetic rule based on its type
        switch (rule.type) {
            case nodes/* CosmeticRuleType */.k9.ElementHidingRule:
                subconverterResult = ElementHidingRuleConverter.convertToAdg(rule);
                break;
            case nodes/* CosmeticRuleType */.k9.ScriptletInjectionRule:
                subconverterResult = ScriptletRuleConverter.convertToAdg(rule);
                break;
            case nodes/* CosmeticRuleType */.k9.CssInjectionRule:
                subconverterResult = CssInjectionRuleConverter.convertToAdg(rule);
                break;
            case nodes/* CosmeticRuleType */.k9.HtmlFilteringRule:
                // Handle special case: uBO response header filtering rule
                // TODO: Optimize double CSS tokenization here
                subconverterResult = HeaderRemovalRuleConverter.convertToAdg(rule);
                if (subconverterResult.isConverted) {
                    break;
                }
                subconverterResult = HtmlRuleConverter.convertToAdg(rule);
                break;
            // Note: Currently, only ADG supports JS injection rules, so we don't need to convert them
            case nodes/* CosmeticRuleType */.k9.JsInjectionRule:
                subconverterResult = createNodeConversionResult([rule], false);
                break;
            default:
                throw new RuleConversionError('Unsupported cosmetic rule type');
        }
        let convertedModifiers;
        // Convert cosmetic rule modifiers, if any
        if (rule.modifiers) {
            if (rule.syntax === adblockers/* AdblockSyntax */.Y.Ubo) {
                // uBO doesn't support this rule:
                // example.com##+js(set-constant.js, foo, bar):matches-path(/baz)
                if (rule.type === nodes/* CosmeticRuleType */.k9.ScriptletInjectionRule) {
                    throw new RuleConversionError('uBO scriptlet injection rules don\'t support cosmetic rule modifiers');
                }
                convertedModifiers = AdgCosmeticRuleModifierConverter.convertFromUbo(rule.modifiers);
            }
            else if (rule.syntax === adblockers/* AdblockSyntax */.Y.Abp) {
                // TODO: Implement once ABP starts supporting cosmetic rule modifiers
                throw new RuleConversionError('ABP don\'t support cosmetic rule modifiers');
            }
        }
        if ((subconverterResult.result.length > 1 || subconverterResult.isConverted)
            || (convertedModifiers && convertedModifiers.isConverted)) {
            // Add modifier list to the subconverter result rules
            subconverterResult.result.forEach((subconverterRule) => {
                if (convertedModifiers && subconverterRule.category === nodes/* RuleCategory */.$O.Cosmetic) {
                    // eslint-disable-next-line no-param-reassign
                    subconverterRule.modifiers = convertedModifiers.result;
                }
            });
            return subconverterResult;
        }
        return createNodeConversionResult([rule], false);
    }
    /**
     * Converts a cosmetic rule to uBlock Origin syntax, if possible.
     *
     * @param rule Rule node to convert
     * @returns An object which follows the {@link NodeConversionResult} interface. Its `result` property contains
     * the array of converted rule nodes, and its `isConverted` flag indicates whether the original rule was converted.
     * If the rule was not converted, the result array will contain the original node with the same object reference
     * @throws If the rule is invalid or cannot be converted
     */
    // TODO: Add support for other cosmetic rule types
    static convertToUbo(rule) {
        // Skip conversation if the rule is already in uBO format
        if (rule.syntax === adblockers/* AdblockSyntax */.Y.Ubo) {
            return createNodeConversionResult([rule], false);
        }
        // Check if the rule is a simple hiding rule
        // TODO: Handle elemhide rules with extended CSS pseudos even if type is not marked explicitly
        if (rule.type === nodes/* CosmeticRuleType */.k9.ElementHidingRule
            && (rule.separator.value === nodes/* CosmeticRuleSeparator */.p5.ElementHidingException
                || rule.separator.value === nodes/* CosmeticRuleSeparator */.p5.ElementHiding)
            && !rule.modifiers) {
            return createNodeConversionResult([rule], false);
        }
        // Convert cosmetic rule based on its type
        if (rule.type === nodes/* CosmeticRuleType */.k9.ScriptletInjectionRule) {
            if (rule.syntax === adblockers/* AdblockSyntax */.Y.Adg && rule.modifiers?.children.length) {
                // e.g. example.com##+js(set-constant.js, foo, bar):matches-path(/baz)
                throw new RuleConversionError('uBO scriptlet injection rules do not support cosmetic rule modifiers');
            }
            return ScriptletRuleConverter.convertToUbo(rule);
        }
        let convertedModifiers;
        // Convert cosmetic rule modifiers, if any
        if (rule.modifiers) {
            if (rule.syntax === adblockers/* AdblockSyntax */.Y.Abp) {
                // TODO: Implement once ABP starts supporting cosmetic rule modifiers
                throw new RuleConversionError('ABP does not support cosmetic rule modifiers');
            }
            else if (rule.syntax === adblockers/* AdblockSyntax */.Y.Adg) {
                convertedModifiers = UboCosmeticRuleModifierConverter.convertFromAdg(rule.modifiers);
            }
        }
        const result = clone(rule);
        result.syntax = adblockers/* AdblockSyntax */.Y.Ubo;
        if (convertedModifiers && convertedModifiers.isConverted) {
            result.modifiers = convertedModifiers.result.modifierList;
            if (convertedModifiers.result.domains) {
                result.domains = convertedModifiers.result.domains;
                result.domains.separator = constants/* COMMA */.KE;
            }
        }
        // Handle separator to uBO format
        let convertedSeparator = result.separator.value;
        convertedSeparator = rule.exception
            ? nodes/* CosmeticRuleSeparator */.p5.ElementHidingException
            : nodes/* CosmeticRuleSeparator */.p5.ElementHiding;
        result.separator.value = convertedSeparator;
        return createNodeConversionResult([result], true);
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/compatibility-tables/modifiers.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */





/**
 * @file Compatibility tables for modifiers.
 */
/**
 * Transforms the name of the modifier to a normalized form.
 * This is a special case: the noop modifier normally '_', but it can consist of any number of characters,
 * e.g. '____' is also valid. In this case, we need to normalize the name to '_'.
 *
 * @param name Modifier name to normalize.
 * @returns Normalized modifier name.
 */
const noopModifierNameNormalizer = (name) => {
    if (name.startsWith(constants/* UNDERSCORE */.fB)) {
        if (name.split(constants/* EMPTY */.wg).every((char) => char === constants/* UNDERSCORE */.fB)) {
            // in compatibility tables, we just store '_', so we need to reduce the number of underscores to 1
            // before checking the existence of the noop modifier
            return constants/* UNDERSCORE */.fB;
        }
    }
    return name;
};
/**
 * Compatibility table for modifiers.
 */
class ModifiersCompatibilityTable extends CompatibilityTableBase {
    /**
     * Creates a new instance of the compatibility table for modifiers.
     *
     * @param data Compatibility table data.
     */
    constructor(data) {
        super(data, noopModifierNameNormalizer);
    }
}
/**
 * Deep freeze the compatibility table data to avoid accidental modifications.
 */
deepFreeze(modifiersCompatibilityTableData);
/**
 * Compatibility table instance for modifiers.
 */
const modifiersCompatibilityTable = new ModifiersCompatibilityTable(modifiersCompatibilityTableData);



// EXTERNAL MODULE: ./node_modules/.pnpm/zod@3.24.4/node_modules/zod/lib/index.mjs
var lib = __webpack_require__(3290);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/compatibility-tables/schemas/resource-type.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * @file Resource type schema.
 */
/**
 * Resource type.
 *
 * @see {@link https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#type-ResourceType}
 */
const ResourceType = {
    MainFrame: 'main_frame',
    SubFrame: 'sub_frame',
    Stylesheet: 'stylesheet',
    Script: 'script',
    Image: 'image',
    Font: 'font',
    Object: 'object',
    XmlHttpRequest: 'xmlhttprequest',
    Ping: 'ping',
    Media: 'media',
    WebSocket: 'websocket',
    Other: 'other',
};
/**
 * Resource type schema.
 */
const resourceTypeSchema = lib/* default.nativeEnum */.Ay.nativeEnum(ResourceType);



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/compatibility-tables/utils/resource-type-helpers.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * Map of resource types to their corresponding adblock modifier names.
 *
 * @note Record type is used to ensure that all resource types are present in the map.
 */
const RESOURCE_TYPE_MODIFIER_MAP = Object.freeze({
    [ResourceType.MainFrame]: 'document',
    [ResourceType.SubFrame]: 'subdocument',
    [ResourceType.Stylesheet]: 'stylesheet',
    [ResourceType.Script]: 'script',
    [ResourceType.Image]: 'image',
    [ResourceType.Font]: 'font',
    [ResourceType.Object]: 'object',
    [ResourceType.XmlHttpRequest]: 'xmlhttprequest',
    [ResourceType.Ping]: 'ping',
    [ResourceType.Media]: 'media',
    [ResourceType.WebSocket]: 'websocket',
    [ResourceType.Other]: 'other',
});
/**
 * Gets the adblock modifier name for the given resource type.
 *
 * @param resourceType Resource type to get the modifier name for.
 * @param platform Platform to get the modifier for.
 *
 * @returns A string containing the adblock modifier name for the given resource type
 * or `null` if the modifier could not be found.
 */
const getResourceTypeModifier = (resourceType, platform) => {
    const modifierName = RESOURCE_TYPE_MODIFIER_MAP[resourceType];
    if (!modifierName) {
        return null;
    }
    const modifierData = modifiersCompatibilityTable.getFirst(modifierName, platform);
    if ((0,type_guards/* isNull */.kZ)(modifierData)) {
        return null;
    }
    return modifierData.name;
};
/**
 * Checks if the given resource type is valid.
 *
 * @param resourceType Resource type to check.
 *
 * @returns `true` if the resource type is valid, `false` otherwise.
 */
const isValidResourceType = (resourceType) => {
    return Object.values(ResourceType).includes(resourceType);
};



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/compatibility-tables/redirects.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/**
 * @file Compatibility tables for redirects.
 */
/**
 * Prefix for resource redirection names.
 */
const ABP_RESOURCE_PREFIX = 'abp-resource:';
const ABP_RESOURCE_PREFIX_LENGTH = ABP_RESOURCE_PREFIX.length;
/**
 * Normalizes the redirect name.
 *
 * @param name Redirect name to normalize.
 *
 * @returns Normalized redirect name.
 *
 * @example
 * redirectNameNormalizer('abp-resource:my-resource') // => 'my-resource'
 * redirectNameNormalizer('noop.js:99') // => 'noop.js'
 */
const redirectNameNormalizer = (name) => {
    // Remove ABP resource prefix, if present
    if (name.startsWith(ABP_RESOURCE_PREFIX)) {
        return name.slice(ABP_RESOURCE_PREFIX_LENGTH);
    }
    // Remove :[integer] priority suffix from the name, if present
    // See:
    // - https://github.com/AdguardTeam/tsurlfilter/issues/59
    // - https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#redirect
    const colonIndex = name.lastIndexOf(constants/* COLON */.oH);
    if (colonIndex !== -1 && /^\d+$/.test(name.slice(colonIndex + 1))) {
        return name.slice(0, colonIndex);
    }
    return name;
};
/**
 * Compatibility table for redirects.
 */
class RedirectsCompatibilityTable extends CompatibilityTableBase {
    /**
     * Creates a new instance of the compatibility table for redirects.
     *
     * @param data Compatibility table data.
     */
    constructor(data) {
        super(data, redirectNameNormalizer);
    }
    /**
     * Gets the resource type adblock modifiers for the redirect for the given platform
     * based on the `resourceTypes` field.
     *
     * @param redirect Redirect name or redirect data.
     * @param platform Platform to get the modifiers for.
     *
     * @returns Set of resource type modifiers or an empty set if the redirect is not found or has no resource types.
     */
    getResourceTypeModifiers(redirect, platform) {
        let redirectData = null;
        if ((0,type_guards/* isString */.Kg)(redirect)) {
            redirectData = this.getFirst(redirect, platform);
        }
        else {
            redirectData = redirect;
        }
        const modifierNames = new Set();
        if ((0,type_guards/* isNull */.kZ)(redirectData) || (0,type_guards/* isUndefined */.b0)(redirectData.resourceTypes)) {
            return modifierNames;
        }
        for (const resourceType of redirectData.resourceTypes) {
            const modifierName = getResourceTypeModifier(resourceType, platform);
            if ((0,type_guards/* isNull */.kZ)(modifierName)) {
                continue;
            }
            modifierNames.add(modifierName);
        }
        return modifierNames;
    }
}
/**
 * Deep freeze the compatibility table data to avoid accidental modifications.
 */
deepFreeze(redirectsCompatibilityTableData);
/**
 * Compatibility table instance for redirects.
 */
const redirectsCompatibilityTable = new RedirectsCompatibilityTable(redirectsCompatibilityTableData);



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/converter/misc/network-rule-modifier.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */





















/**
 * @file Network rule modifier list converter.
 */
/**
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#csp-modifier}
 */
const CSP_MODIFIER = 'csp';
const CSP_SEPARATOR = constants/* SEMICOLON */.I8 + constants/* SPACE */.t6;
/**
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#csp-modifier}
 * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy}
 */
const COMMON_CSP_PARAMS = '\'self\' \'unsafe-eval\' http: https: data: blob: mediastream: filesystem:';
/**
 * @see {@link https://help.adblockplus.org/hc/en-us/articles/360062733293#rewrite}
 */
const ABP_REWRITE_MODIFIER = 'rewrite';
/**
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#redirect-modifier}
 */
const REDIRECT_MODIFIER = 'redirect';
/**
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#redirect-rule-modifier}
 */
const REDIRECT_RULE_MODIFIER = 'redirect-rule';
/**
 * @see {@link https://github.com/gorhill/uBlock/wiki/Resources-Library#empty-redirect-resources}
 */
const UBO_NOOP_TEXT_RESOURCE = 'noop.txt';
/**
 * Redirect-related modifiers.
 */
const REDIRECT_MODIFIERS = new Set([
    ABP_REWRITE_MODIFIER,
    REDIRECT_MODIFIER,
    REDIRECT_RULE_MODIFIER,
]);
/**
 * Conversion map for ADG network rule modifiers.
 */
const ADG_CONVERSION_MAP = new Map([
    ['1p', [{ name: () => 'third-party', exception: (actual) => !actual }]],
    ['3p', [{ name: () => 'third-party' }]],
    ['css', [{ name: () => 'stylesheet' }]],
    ['doc', [{ name: () => 'document' }]],
    ['ehide', [{ name: () => 'elemhide' }]],
    ['empty', [{ name: () => 'redirect', value: () => 'nooptext' }]],
    ['first-party', [{ name: () => 'third-party', exception: (actual) => !actual }]],
    ['frame', [{ name: () => 'subdocument' }]],
    ['ghide', [{ name: () => 'generichide' }]],
    ['inline-font', [{ name: () => CSP_MODIFIER, value: () => `font-src ${COMMON_CSP_PARAMS}` }]],
    ['inline-script', [{ name: () => CSP_MODIFIER, value: () => `script-src ${COMMON_CSP_PARAMS}` }]],
    ['mp4', [{ name: () => 'redirect', value: () => 'noopmp4-1s' }, { name: () => 'media', value: () => undefined }]],
    ['queryprune', [{ name: () => 'removeparam' }]],
    ['shide', [{ name: () => 'specifichide' }]],
    ['xhr', [{ name: () => 'xmlhttprequest' }]],
]);
/**
 * Helper class for converting network rule modifier lists.
 *
 * @todo Implement `convertToUbo` and `convertToAbp`
 */
class NetworkRuleModifierListConverter extends BaseConverter {
    /**
     * Converts a network rule modifier list to AdGuard format, if possible.
     *
     * @param modifierList Network rule modifier list node to convert
     * @param isException If `true`, the rule is an exception rule
     * @returns An object which follows the {@link ConversionResult} interface. Its `result` property contains
     * the converted node, and its `isConverted` flag indicates whether the original node was converted.
     * If the node was not converted, the result will contain the original node with the same object reference
     * @throws If the conversion is not possible
     */
    static convertToAdg(modifierList, isException = false) {
        const conversionMap = new MultiValueMap();
        // Special case: $csp modifier
        let cspCount = 0;
        modifierList.children.forEach((modifierNode, index) => {
            const modifierConversions = ADG_CONVERSION_MAP.get(modifierNode.name.value);
            if (modifierConversions) {
                for (const modifierConversion of modifierConversions) {
                    const name = modifierConversion.name(modifierNode.name.value);
                    const exception = modifierConversion.exception
                        // If the exception value is undefined in the original modifier, it
                        // means that the modifier isn't negated
                        ? modifierConversion.exception(modifierNode.exception || false)
                        : modifierNode.exception;
                    const value = modifierConversion.value
                        ? modifierConversion.value(modifierNode.value?.value)
                        : modifierNode.value?.value;
                    // Check if the name or the value is different from the original modifier
                    // If so, add the converted modifier to the list
                    if (name !== modifierNode.name.value || value !== modifierNode.value?.value) {
                        conversionMap.add(index, createModifierNode(name, value, exception));
                    }
                    // Special case: $csp modifier
                    if (name === CSP_MODIFIER) {
                        cspCount += 1;
                    }
                }
                return;
            }
            // Handle special case: resource redirection modifiers
            if (REDIRECT_MODIFIERS.has(modifierNode.name.value)) {
                // Redirect modifiers can't be negated
                if (modifierNode.exception === true) {
                    throw new RuleConversionError(`Modifier '${modifierNode.name.value}' cannot be negated`);
                }
                // Convert the redirect resource name to ADG format
                const redirectResource = modifierNode.value?.value;
                // Special case: for exception rules, $redirect without value is allowed,
                // and in this case it means an exception for all redirects
                if (!redirectResource && !isException) {
                    throw new RuleConversionError(`No redirect resource specified for '${modifierNode.name.value}' modifier`);
                }
                // Leave $redirect and $redirect-rule modifiers as is, but convert $rewrite to $redirect
                const modifierName = modifierNode.name.value === ABP_REWRITE_MODIFIER
                    ? REDIRECT_MODIFIER
                    : modifierNode.name.value;
                const convertedRedirectResource = redirectResource
                    ? redirectsCompatibilityTable.getFirst(redirectResource, GenericPlatform.AdgAny)?.name
                    : undefined;
                // Check if the modifier name or the redirect resource name is different from the original modifier.
                // If so, add the converted modifier to the list
                if (modifierName !== modifierNode.name.value
                    || (convertedRedirectResource !== undefined && convertedRedirectResource !== redirectResource)) {
                    conversionMap.add(index, createModifierNode(modifierName, 
                    // If the redirect resource name is unknown, fall back to the original one
                    // Later, the validator will throw an error if the resource name is invalid
                    convertedRedirectResource || redirectResource, modifierNode.exception));
                }
            }
        });
        // Prepare the result if there are any converted modifiers or $csp modifiers
        if (conversionMap.size || cspCount) {
            const modifierListClone = cloneModifierListNode(modifierList);
            // Replace the original modifiers with the converted ones
            // One modifier may be replaced with multiple modifiers, so we need to flatten the array
            modifierListClone.children = modifierListClone.children.map((modifierNode, index) => {
                const conversionRecord = conversionMap.get(index);
                if (conversionRecord) {
                    return conversionRecord;
                }
                return modifierNode;
            }).flat();
            // Special case: $csp modifier: merge multiple $csp modifiers into one
            // and put it at the end of the modifier list
            if (cspCount) {
                const cspValues = [];
                modifierListClone.children = modifierListClone.children.filter((modifierNode) => {
                    if (modifierNode.name.value === CSP_MODIFIER) {
                        if (!modifierNode.value?.value) {
                            throw new RuleConversionError('$csp modifier value is missing');
                        }
                        cspValues.push(modifierNode.value?.value);
                        return false;
                    }
                    return true;
                });
                modifierListClone.children.push(createModifierNode(CSP_MODIFIER, cspValues.join(CSP_SEPARATOR)));
            }
            // Before returning the result, remove duplicated modifiers
            modifierListClone.children = modifierListClone.children.filter((modifierNode, index, self) => self.findIndex((m) => m.name.value === modifierNode.name.value
                && m.exception === modifierNode.exception
                && m.value?.value === modifierNode.value?.value) === index);
            return createConversionResult(modifierListClone, true);
        }
        return createConversionResult(modifierList, false);
    }
    /**
     * Converts a network rule modifier list to uBlock format, if possible.
     *
     * @param modifierList Network rule modifier list node to convert
     * @param isException If `true`, the rule is an exception rule
     * @returns An object which follows the {@link ConversionResult} interface. Its `result` property contains
     * the converted node, and its `isConverted` flag indicates whether the original node was converted.
     * If the node was not converted, the result will contain the original node with the same object reference
     * @throws If the conversion is not possible
     */
    // TODO: Optimize
    static convertToUbo(modifierList, isException = false) {
        const conversionMap = new MultiValueMap();
        const resourceTypeModifiersToAdd = new Set();
        modifierList.children.forEach((modifierNode, index) => {
            const originalModifierName = modifierNode.name.value;
            const modifierData = modifiersCompatibilityTable.getFirst(originalModifierName, GenericPlatform.UboAny);
            // Handle special case: resource redirection modifiers
            if (REDIRECT_MODIFIERS.has(originalModifierName)) {
                // Redirect modifiers cannot be negated
                if (modifierNode.exception === true) {
                    throw new RuleConversionError(`Modifier '${modifierNode.name.value}' cannot be negated`);
                }
                // Convert the redirect resource name to uBO format
                const redirectResourceName = modifierNode.value?.value;
                // Special case: for exception rules, $redirect without value is allowed,
                // and in this case it means an exception for all redirects
                if (!redirectResourceName && !isException) {
                    throw new RuleConversionError(`No redirect resource specified for '${modifierNode.name.value}' modifier`);
                }
                if (!redirectResourceName) {
                    // Jump to the next modifier if the redirect resource is not specified
                    return;
                }
                // Leave $redirect and $redirect-rule modifiers as is, but convert $rewrite to $redirect
                const modifierName = modifierNode.name.value === ABP_REWRITE_MODIFIER
                    ? REDIRECT_MODIFIER
                    : modifierNode.name.value;
                const convertedRedirectResourceData = redirectsCompatibilityTable.getFirst(redirectResourceName, GenericPlatform.UboAny);
                const convertedRedirectResourceName = convertedRedirectResourceData?.name ?? redirectResourceName;
                // uBlock requires the $redirect modifier to have a resource type
                // https://github.com/AdguardTeam/Scriptlets/issues/101
                if (convertedRedirectResourceData?.resourceTypes?.length) {
                    // Convert the resource types to uBO modifiers
                    const uboResourceTypeModifiers = redirectsCompatibilityTable.getResourceTypeModifiers(convertedRedirectResourceData, GenericPlatform.UboAny);
                    // Special case: noop text resource
                    // If any of resource type is already present, we don't need to add other resource types,
                    // otherwise, add all resource types
                    // TODO: Optimize this logic
                    // Check if the current resource is the noop text resource
                    const isNoopTextResource = convertedRedirectResourceName === UBO_NOOP_TEXT_RESOURCE;
                    // Determine if there are any valid resource types already present
                    const hasValidResourceType = modifierList.children.some((modifier) => {
                        const name = modifier.name.value;
                        if (!isValidResourceType(name)) {
                            return false;
                        }
                        const convertedModifierData = modifiersCompatibilityTable.getFirst(name, GenericPlatform.UboAny);
                        return uboResourceTypeModifiers.has(convertedModifierData?.name ?? name);
                    });
                    // If it's not the noop text resource or if no valid resource types are present
                    if (!isNoopTextResource || !hasValidResourceType) {
                        uboResourceTypeModifiers.forEach((resourceType) => {
                            resourceTypeModifiersToAdd.add(resourceType);
                        });
                    }
                }
                // Check if the modifier name or the redirect resource name is different from the original modifier.
                // If so, add the converted modifier to the list
                if (modifierName !== originalModifierName
                    || (!(0,type_guards/* isUndefined */.b0)(convertedRedirectResourceName)
                        && convertedRedirectResourceName !== redirectResourceName)) {
                    conversionMap.add(index, createModifierNode(modifierName, 
                    // If the redirect resource name is unknown, fall back to the original one
                    // Later, the validator will throw an error if the resource name is invalid
                    convertedRedirectResourceName || redirectResourceName, modifierNode.exception));
                }
                return;
            }
            // Generic modifier conversion
            if (modifierData && modifierData.name !== originalModifierName) {
                conversionMap.add(index, createModifierNode(modifierData.name, modifierNode.value?.value, modifierNode.exception));
            }
        });
        // Prepare the result if there are any converted modifiers or $csp modifiers
        if (conversionMap.size || resourceTypeModifiersToAdd.size) {
            const modifierListClone = cloneModifierListNode(modifierList);
            // Replace the original modifiers with the converted ones
            // One modifier may be replaced with multiple modifiers, so we need to flatten the array
            modifierListClone.children = modifierListClone.children.map((modifierNode, index) => {
                const conversionRecord = conversionMap.get(index);
                if (conversionRecord) {
                    return conversionRecord;
                }
                return modifierNode;
            }).flat();
            // Before returning the result, remove duplicated modifiers
            modifierListClone.children = modifierListClone.children.filter((modifierNode, index, self) => self.findIndex((m) => m.name.value === modifierNode.name.value
                && m.exception === modifierNode.exception
                && m.value?.value === modifierNode.value?.value) === index);
            if (resourceTypeModifiersToAdd.size) {
                const modifierNameSet = new Set(modifierList.children.map((m) => m.name.value));
                resourceTypeModifiersToAdd.forEach((resourceType) => {
                    if (!modifierNameSet.has(resourceType)) {
                        modifierListClone.children.push(createModifierNode(resourceType));
                    }
                });
            }
            return createConversionResult(modifierListClone, true);
        }
        return createConversionResult(modifierList, false);
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/converter/network/index.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */





/**
 * @file Network rule converter
 */
/**
 * Network rule converter class (also known as "basic rule converter")
 *
 * @todo Implement `convertToUbo` and `convertToAbp`
 */
class NetworkRuleConverter extends RuleConverterBase {
    /**
     * Converts a network rule to AdGuard format, if possible.
     *
     * @param rule Rule node to convert
     * @returns An object which follows the {@link NodeConversionResult} interface. Its `result` property contains
     * the array of converted rule nodes, and its `isConverted` flag indicates whether the original rule was converted.
     * If the rule was not converted, the result array will contain the original node with the same object reference
     * @throws If the rule is invalid or cannot be converted
     */
    static convertToAdg(rule) {
        // TODO: add support for host rules
        if (rule.type !== nodes/* NetworkRuleType */.vY.NetworkRule) {
            throw new Error(`Invalid rule type: ${rule.type}`);
        }
        if (rule.modifiers) {
            const modifiers = NetworkRuleModifierListConverter.convertToAdg(rule.modifiers, rule.exception);
            // If the object reference is different, it means that the modifiers were converted
            // In this case, we should clone the entire rule and replace the modifiers with the converted ones
            if (modifiers.isConverted) {
                return {
                    result: [{
                            category: nodes/* RuleCategory */.$O.Network,
                            type: nodes/* NetworkRuleType */.vY.NetworkRule,
                            syntax: rule.syntax,
                            exception: rule.exception,
                            pattern: {
                                type: 'Value',
                                value: rule.pattern.value,
                            },
                            modifiers: modifiers.result,
                        }],
                    isConverted: true,
                };
            }
        }
        // If the modifiers were not converted, return the original rule
        return createNodeConversionResult([rule], false);
    }
    /**
     * Converts a network rule to uBlock format, if possible.
     *
     * @param rule Rule node to convert
     * @returns An object which follows the {@link NodeConversionResult} interface. Its `result` property contains
     * the array of converted rule nodes, and its `isConverted` flag indicates whether the original rule was converted.
     * If the rule was not converted, the result array will contain the original node with the same object reference
     * @throws If the rule is invalid or cannot be converted
     */
    static convertToUbo(rule) {
        // TODO: add support for host rules
        if (rule.type !== nodes/* NetworkRuleType */.vY.NetworkRule) {
            throw new Error(`Invalid rule type: ${rule.type}`);
        }
        if (rule.modifiers) {
            const modifiers = NetworkRuleModifierListConverter.convertToUbo(rule.modifiers, rule.exception);
            // If the object reference is different, it means that the modifiers were converted
            // In this case, we should clone the entire rule and replace the modifiers with the converted ones
            if (modifiers.isConverted) {
                return {
                    result: [{
                            category: nodes/* RuleCategory */.$O.Network,
                            type: nodes/* NetworkRuleType */.vY.NetworkRule,
                            syntax: rule.syntax,
                            exception: rule.exception,
                            pattern: {
                                type: 'Value',
                                value: rule.pattern.value,
                            },
                            modifiers: modifiers.result,
                        }],
                    isConverted: true,
                };
            }
        }
        // If the modifiers were not converted, return the original rule
        return createNodeConversionResult([rule], false);
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/converter/rule.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */








/**
 * @file Adblock rule converter
 *
 * This file is the entry point for all rule converters
 * which automatically detects the rule type and calls
 * the corresponding "sub-converter".
 */
/**
 * Adblock filtering rule converter class
 *
 * @todo Implement `convertToUbo` and `convertToAbp`
 */
class RuleConverter extends RuleConverterBase {
    /**
     * Converts an adblock filtering rule to AdGuard format, if possible.
     *
     * @param rule Rule node to convert
     * @returns An object which follows the {@link NodeConversionResult} interface. Its `result` property contains
     * the array of converted rule nodes, and its `isConverted` flag indicates whether the original rule was converted.
     * If the rule was not converted, the result array will contain the original node with the same object reference
     * @throws If the rule is invalid or cannot be converted
     */
    static convertToAdg(rule) {
        // Delegate conversion to the corresponding sub-converter
        // based on the rule category
        switch (rule.category) {
            case nodes/* RuleCategory */.$O.Comment:
                return CommentRuleConverter.convertToAdg(rule);
            case nodes/* RuleCategory */.$O.Cosmetic:
                return CosmeticRuleConverter.convertToAdg(rule);
            case nodes/* RuleCategory */.$O.Network:
                // TODO: Handle hosts rules later
                if (rule.type === nodes/* NetworkRuleType */.vY.HostRule) {
                    return createConversionResult([rule], false);
                }
                return NetworkRuleConverter.convertToAdg(rule);
            case nodes/* RuleCategory */.$O.Invalid:
            case nodes/* RuleCategory */.$O.Empty:
                // Just forward the rule as is
                return createConversionResult([rule], false);
            default:
                // Never happens during normal operation
                throw new RuleConversionError('Unknown rule category');
        }
    }
    /**
     * Converts an adblock filtering rule to uBlock Origin format, if possible.
     *
     * @param rule Rule node to convert
     * @returns An object which follows the {@link NodeConversionResult} interface. Its `result` property contains
     * the array of converted rule nodes, and its `isConverted` flag indicates whether the original rule was converted.
     * If the rule was not converted, the result array will contain the original node with the same object reference
     * @throws If the rule is invalid or cannot be converted
     */
    // TODO: Add support for other rule types
    static convertToUbo(rule) {
        if (rule.category === nodes/* RuleCategory */.$O.Cosmetic) {
            return CosmeticRuleConverter.convertToUbo(rule);
        }
        if (rule.category === nodes/* RuleCategory */.$O.Network) {
            return NetworkRuleConverter.convertToUbo(rule);
        }
        return createConversionResult([rule], false);
    }
}




/***/ }),

/***/ 97907:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  Y: () => (/* binding */ RuleDeserializer)
});

// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/errors/not-implemented-error.js
var not_implemented_error = __webpack_require__(65489);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/base-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * @file Base deserializer class.
 */
/**
 * Base class for deserializers. Each deserializer should extend this class.
 */
class BaseDeserializer {
    /**
     * Deserializes the AST node from a byte buffer.
     *
     * @param buffer Input byte buffer to read from.
     * @param node Destination node to write to.
     * @param args Additional, parser-specific arguments, if needed.
     */
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    static deserialize(buffer, node, ...args) {
        throw new not_implemented_error/* NotImplementedError */.E();
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/constants.js
var constants = __webpack_require__(65523);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/nodes/index.js
var nodes = __webpack_require__(64638);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/adblockers.js
var adblockers = __webpack_require__(88226);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/comment/agent-comment-common.js
var agent_comment_common = __webpack_require__(72778);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/comment/agent-common.js
var agent_common = __webpack_require__(86186);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/common/agent-common.js
var common_agent_common = __webpack_require__(64163);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/misc/value-common.js
var value_common = __webpack_require__(34097);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/misc/binary-type-common.js
var binary_type_common = __webpack_require__(16318);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/misc/value-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */





/**
 * Value deserializer.
 */
class ValueDeserializer extends BaseDeserializer {
    /**
     * Deserializes a value node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     * @param frequentValuesMap Optional map of frequent values.
     * @throws If the binary data is malformed.
     */
    static deserialize(buffer, node, frequentValuesMap) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ValueNode);
        node.type = 'Value';
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case value_common/* ValueNodeMarshallingMap */.e.Value:
                    node.value = buffer.readString();
                    break;
                case value_common/* ValueNodeMarshallingMap */.e.FrequentValue:
                    node.value = frequentValuesMap?.get(buffer.readUint8()) ?? constants/* EMPTY */.wg;
                    break;
                case value_common/* ValueNodeMarshallingMap */.e.Start:
                    node.start = buffer.readUint32();
                    break;
                case value_common/* ValueNodeMarshallingMap */.e.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}`);
            }
            prop = buffer.readUint8();
        }
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/comment/agent-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/* eslint-disable no-param-reassign */
/**
 * `AgentDeserializer` is responsible for deserializing single adblock agent elements.
 *
 * @example
 * If the adblock agent rule is
 * ```adblock
 * [Adblock Plus 2.0; AdGuard]
 * ```
 * then the adblock agents are `Adblock Plus 2.0` and `AdGuard`, and this
 * class is responsible for parsing them. The rule itself is parsed by
 * `AgentCommentSerializer`, which uses this class to parse single agents.
 */
class AgentDeserializer extends BaseDeserializer {
    /**
     * Deserializes an agent node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     * @throws If the binary data is malformed.
     */
    static deserialize(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.AgentNode);
        node.type = 'Agent';
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case agent_common/* AgentNodeMarshallingMap */.o.Adblock:
                    // eslint-disable-next-line max-len
                    ValueDeserializer.deserialize(buffer, node.adblock = {}, agent_common/* FREQUENT_AGENTS_DESERIALIZATION_MAP */.h);
                    if (node.adblock) {
                        node.syntax = (0,common_agent_common/* getAdblockSyntax */.w)(node.adblock.value);
                    }
                    break;
                case agent_common/* AgentNodeMarshallingMap */.o.Version:
                    ValueDeserializer.deserialize(buffer, node.version = {});
                    break;
                case agent_common/* AgentNodeMarshallingMap */.o.Start:
                    node.start = buffer.readUint32();
                    break;
                case agent_common/* AgentNodeMarshallingMap */.o.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}`);
            }
            prop = buffer.readUint8();
        }
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/comment/agent-comment-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */








/* eslint-disable no-param-reassign */
/**
 * `AgentCommentDeserializer` is responsible for deserializing an Adblock agent comments.
 * Adblock agent comment marks that the filter list is supposed to
 * be used by the specified ad blockers.
 *
 * @example
 *  - ```adblock
 *    [AdGuard]
 *    ```
 *  - ```adblock
 *    [Adblock Plus 2.0]
 *    ```
 *  - ```adblock
 *    [uBlock Origin]
 *    ```
 *  - ```adblock
 *    [uBlock Origin 1.45.3]
 *    ```
 *  - ```adblock
 *    [Adblock Plus 2.0; AdGuard]
 *    ```
 */
class AgentCommentDeserializer extends BaseDeserializer {
    /**
     * Deserializes an agent list node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     */
    static deserialize(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.AgentRuleNode);
        node.type = nodes/* CommentRuleType */.gV.AgentCommentRule;
        node.syntax = adblockers/* AdblockSyntax */.Y.Common;
        node.category = nodes/* RuleCategory */.$O.Comment;
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case agent_comment_common/* AgentCommentMarshallingMap */.j.Children:
                    node.children = new Array(buffer.readUint8());
                    // read children
                    for (let i = 0; i < node.children.length; i += 1) {
                        AgentDeserializer.deserialize(buffer, node.children[i] = {});
                    }
                    break;
                case agent_comment_common/* AgentCommentMarshallingMap */.j.Start:
                    node.start = buffer.readUint32();
                    break;
                case agent_comment_common/* AgentCommentMarshallingMap */.j.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}`);
            }
            prop = buffer.readUint8();
        }
        // Maybe children are not present in the binary data,
        // in this case, we should initialize it as an empty array.
        if (!node.children) {
            node.children = [];
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/comment/config-comment-common.js
var config_comment_common = __webpack_require__(92687);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/misc/parameter-list-common.js
var parameter_list_common = __webpack_require__(12974);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/misc/parameter-list-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */






/**
 * Deserializes binary data into parameter list nodes.
 * Optionally uses a map of frequent values for optimization.
 */
class ParameterListDeserializer extends BaseDeserializer {
    /**
     * Deserializes a parameter list node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     * @param frequentValuesMap Optional map of frequent values.
     * @throws If the binary data is malformed.
     */
    static deserialize(buffer, node, frequentValuesMap) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ParameterListNode);
        node.type = 'ParameterList';
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case parameter_list_common/* ParameterListNodeMarshallingMap */._.Children:
                    node.children = new Array(buffer.readUint32());
                    // read children
                    for (let i = 0; i < node.children.length; i += 1) {
                        switch (buffer.peekUint8()) {
                            case binary_type_common/* BinaryTypeMarshallingMap */.u.Null:
                                buffer.readUint8();
                                node.children[i] = null;
                                break;
                            case binary_type_common/* BinaryTypeMarshallingMap */.u.ValueNode:
                                // eslint-disable-next-line max-len
                                ValueDeserializer.deserialize(buffer, node.children[i] = {}, frequentValuesMap);
                                break;
                            default:
                                throw new Error(`Invalid child type: ${buffer.peekUint8()}`);
                        }
                    }
                    break;
                case parameter_list_common/* ParameterListNodeMarshallingMap */._.Start:
                    node.start = buffer.readUint32();
                    break;
                case parameter_list_common/* ParameterListNodeMarshallingMap */._.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}`);
            }
            prop = buffer.readUint8();
        }
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/comment/config-comment-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */









/* eslint-disable no-param-reassign */
/**
 * Value map for binary deserialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 */
let frequentCommandsDeserializationMap;
const getFrequentCommandsDeserializationMap = () => {
    if (!frequentCommandsDeserializationMap) {
        frequentCommandsDeserializationMap = new Map(Array.from(config_comment_common/* FREQUENT_COMMANDS_SERIALIZATION_MAP */.O6).map(([key, value]) => [value, key]));
    }
    return frequentCommandsDeserializationMap;
};
/**
 * `ConfigCommentDeserializer` is responsible for deserializing inline AGLint configuration rules.
 * Generally, the idea is inspired by ESLint inline configuration comments.
 *
 * @see {@link https://eslint.org/docs/latest/user-guide/configuring/rules#using-configuration-comments}
 */
class ConfigCommentDeserializer extends BaseDeserializer {
    /**
     * Deserializes a metadata comment node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     * @throws If the binary data is malformed.
     */
    static deserializeConfigNode(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ConfigNode);
        node.type = 'ConfigNode';
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case config_comment_common/* ConfigNodeMarshallingMap */.H4.Value:
                    // note: it is safe to use JSON.parse here, because we serialized it with JSON.stringify
                    node.value = JSON.parse(buffer.readString());
                    break;
                case config_comment_common/* ConfigNodeMarshallingMap */.H4.Start:
                    node.start = buffer.readUint32();
                    break;
                case config_comment_common/* ConfigNodeMarshallingMap */.H4.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}.`);
            }
            prop = buffer.readUint8();
        }
    }
    /**
     * Deserializes a metadata comment node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     * @throws If the binary data is malformed.
     */
    static deserialize(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ConfigCommentRuleNode);
        node.type = nodes/* CommentRuleType */.gV.ConfigCommentRule;
        node.category = nodes/* RuleCategory */.$O.Comment;
        node.syntax = adblockers/* AdblockSyntax */.Y.Common;
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case config_comment_common/* ConfigCommentRuleMarshallingMap */.E0.Marker:
                    ValueDeserializer.deserialize(buffer, node.marker = {});
                    break;
                case config_comment_common/* ConfigCommentRuleMarshallingMap */.E0.Command:
                    // eslint-disable-next-line max-len
                    ValueDeserializer.deserialize(buffer, node.command = {}, getFrequentCommandsDeserializationMap());
                    break;
                case config_comment_common/* ConfigCommentRuleMarshallingMap */.E0.Params:
                    if (buffer.peekUint8() === binary_type_common/* BinaryTypeMarshallingMap */.u.ConfigNode) {
                        ConfigCommentDeserializer.deserializeConfigNode(buffer, node.params = {});
                    }
                    else {
                        ParameterListDeserializer.deserialize(buffer, node.params = {});
                    }
                    break;
                case config_comment_common/* ConfigCommentRuleMarshallingMap */.E0.Comment:
                    ValueDeserializer.deserialize(buffer, node.comment = {});
                    break;
                case config_comment_common/* ConfigCommentRuleMarshallingMap */.E0.Start:
                    node.start = buffer.readUint32();
                    break;
                case config_comment_common/* ConfigCommentRuleMarshallingMap */.E0.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}`);
            }
            prop = buffer.readUint8();
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/comment/hint-common.js
var hint_common = __webpack_require__(99490);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/comment/hint-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/* eslint-disable no-param-reassign */
/**
 * Value map for binary deserialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 */
let frequentHintsDeserializationMap;
const getFrequentHintsDeserializationMap = () => {
    if (!frequentHintsDeserializationMap) {
        frequentHintsDeserializationMap = new Map(Array.from(hint_common/* FREQUENT_HINTS_SERIALIZATION_MAP */.EX).map(([key, value]) => [value, key]));
    }
    return frequentHintsDeserializationMap;
};
/**
 * Value map for binary deserialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 */
let frequentPlatformsDeserializationMap;
const getFrequentPlatformsDeserializationMap = () => {
    if (!frequentPlatformsDeserializationMap) {
        frequentPlatformsDeserializationMap = new Map(Array.from(hint_common/* FREQUENT_PLATFORMS_SERIALIZATION_MAP */.QE).map(([key, value]) => [value, key]));
    }
    return frequentPlatformsDeserializationMap;
};
/**
 * `HintDeserializer` is responsible for deserializing AdGuard hints.
 *
 * @example
 * If the hint rule is
 * ```adblock
 * !+ NOT_OPTIMIZED PLATFORM(windows)
 * ```
 * then the hints are `NOT_OPTIMIZED` and `PLATFORM(windows)`, and this
 * class is responsible for parsing them. The rule itself is parsed by
 * the `HintRuleParser`, which uses this class to parse single hints.
 */
class HintDeserializer extends BaseDeserializer {
    /**
     * Deserializes a hint node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     * @throws If the binary data is malformed.
     */
    static deserialize(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.HintNode);
        node.type = 'Hint';
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case hint_common/* HintNodeMarshallingMap */.ae.Name:
                    // eslint-disable-next-line max-len
                    ValueDeserializer.deserialize(buffer, node.name = {}, getFrequentHintsDeserializationMap());
                    break;
                case hint_common/* HintNodeMarshallingMap */.ae.Params:
                    // eslint-disable-next-line max-len
                    ParameterListDeserializer.deserialize(buffer, node.params = {}, getFrequentPlatformsDeserializationMap());
                    break;
                case hint_common/* HintNodeMarshallingMap */.ae.Start:
                    node.start = buffer.readUint32();
                    break;
                case hint_common/* HintNodeMarshallingMap */.ae.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}`);
            }
            prop = buffer.readUint8();
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/comment/hint-comment-common.js
var hint_comment_common = __webpack_require__(55762);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/syntax-serialization-map.js
var syntax_serialization_map = __webpack_require__(74252);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/syntax-deserialization-map.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * Value map for binary deserialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 */
let syntaxDeserializationMap;
const getSyntaxDeserializationMap = () => {
    if (!syntaxDeserializationMap) {
        syntaxDeserializationMap = new Map(Array.from((0,syntax_serialization_map/* getSyntaxSerializationMap */.M)(), ([key, value]) => [value, key]));
    }
    return syntaxDeserializationMap;
};



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/comment/hint-comment-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */









/* eslint-disable no-param-reassign */
/**
 * `HintCommentDeserializer` is responsible for deserializing AdGuard hint rules.
 *
 * @example
 * The following hint rule
 * ```adblock
 * !+ NOT_OPTIMIZED PLATFORM(windows)
 * ```
 * contains two hints: `NOT_OPTIMIZED` and `PLATFORM`.
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#hints}
 */
class HintCommentDeserializer extends BaseDeserializer {
    /**
     * Deserializes a hint rule node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     * @throws If the binary data is malformed.
     */
    static deserialize(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.HintRuleNode);
        node.category = nodes/* RuleCategory */.$O.Comment;
        node.type = nodes/* CommentRuleType */.gV.HintCommentRule;
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case hint_comment_common/* HintCommentMarshallingMap */.r.Syntax:
                    node.syntax = getSyntaxDeserializationMap().get(buffer.readUint8()) ?? adblockers/* AdblockSyntax */.Y.Common;
                    break;
                case hint_comment_common/* HintCommentMarshallingMap */.r.Children:
                    node.children = new Array(buffer.readUint8());
                    // read children
                    for (let i = 0; i < node.children.length; i += 1) {
                        HintDeserializer.deserialize(buffer, node.children[i] = {});
                    }
                    break;
                case hint_comment_common/* HintCommentMarshallingMap */.r.Start:
                    node.start = buffer.readUint32();
                    break;
                case hint_comment_common/* HintCommentMarshallingMap */.r.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}`);
            }
            prop = buffer.readUint8();
        }
        // Maybe children are not present in the binary data,
        // in this case, we should initialize it as an empty array.
        if (!node.children) {
            node.children = [];
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/comment/metadata-comment-common.js
var metadata_comment_common = __webpack_require__(89990);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/comment/metadata-comment-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */








/* eslint-disable no-param-reassign */
/**
 * `MetadataCommentDeserializer` is responsible for deserializing metadata comments.
 * Metadata comments are special comments that specify some properties of the list.
 *
 * @example
 * For example, in the case of
 * ```adblock
 * ! Title: My List
 * ```
 * the name of the header is `Title`, and the value is `My List`, which means that
 * the list title is `My List`, and it can be used in the adblocker UI.
 * @see {@link https://help.eyeo.com/adblockplus/how-to-write-filters#special-comments}
 */
class MetadataCommentDeserializer extends BaseDeserializer {
    /**
     * Deserializes a metadata comment node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     * @throws If the binary data is malformed.
     */
    static deserialize(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.MetadataCommentRuleNode);
        node.type = nodes/* CommentRuleType */.gV.MetadataCommentRule;
        node.category = nodes/* RuleCategory */.$O.Comment;
        node.syntax = adblockers/* AdblockSyntax */.Y.Common;
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case metadata_comment_common/* MetadataCommentMarshallingMap */.Z.Marker:
                    ValueDeserializer.deserialize(buffer, node.marker = {});
                    break;
                case metadata_comment_common/* MetadataCommentMarshallingMap */.Z.Header:
                    // eslint-disable-next-line max-len
                    ValueDeserializer.deserialize(buffer, node.header = {}, metadata_comment_common/* FREQUENT_HEADERS_DESERIALIZATION_MAP */.l);
                    break;
                case metadata_comment_common/* MetadataCommentMarshallingMap */.Z.Value:
                    ValueDeserializer.deserialize(buffer, node.value = {});
                    break;
                case metadata_comment_common/* MetadataCommentMarshallingMap */.Z.Start:
                    node.start = buffer.readUint32();
                    break;
                case metadata_comment_common/* MetadataCommentMarshallingMap */.Z.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}`);
            }
            prop = buffer.readUint8();
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/comment/pre-processor-comment-common.js
var pre_processor_comment_common = __webpack_require__(20805);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/misc/logical-expression-common.js
var logical_expression_common = __webpack_require__(11128);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/misc/logical-expression-serializer.js
var logical_expression_serializer = __webpack_require__(58421);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/type-guards.js
var type_guards = __webpack_require__(30239);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/misc/logical-expression-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







let logicalExpressionOperatorMarshallingMapReverse;
const getOperatorBinaryMapReverse = () => {
    if (!logicalExpressionOperatorMarshallingMapReverse) {
        logicalExpressionOperatorMarshallingMapReverse = new Map(Array.from(logical_expression_common/* LOGICAL_EXPRESSION_OPERATOR_SERIALISATION_MAP */.td).map(([key, value]) => [value, key]));
    }
    return logicalExpressionOperatorMarshallingMapReverse;
};
/**
 * Gets the string representation of the operator from the binary representation.
 *
 * @param binary Binary representation of the operator
 * @returns String representation of the operator
 * @throws If the operator is unknown
 */
const getOperatorOrFail = (binary) => {
    const operator = getOperatorBinaryMapReverse().get(binary);
    if ((0,type_guards/* isUndefined */.b0)(operator)) {
        throw new Error(`Unknown operator: ${binary}`);
    }
    return operator;
};
/**
 * Deserialization map for known variables.
 */
let knownVariablesMapReverse;
const getKnownVariablesMapReverse = () => {
    if (!knownVariablesMapReverse) {
        knownVariablesMapReverse = new Map(Array.from(logical_expression_common/* KNOWN_VARIABLES_SERIALIZATION_MAP */.Y5).map(([key, value]) => [value, key]));
    }
    return knownVariablesMapReverse;
};
/**
 * Gets the frequent name of the variable from the binary representation.
 *
 * @param binary Binary representation of the variable
 * @returns Frequent name of the variable
 * @throws If the variable is unknown
 */
const getFrequentNameOrFail = (binary) => {
    const name = getKnownVariablesMapReverse().get(binary);
    if ((0,type_guards/* isUndefined */.b0)(name)) {
        throw new Error(`Unknown frequent name: ${binary}`);
    }
    return name;
};
/**
 * `LogicalExpressionDeserializer` is responsible for deserializing logical expressions.
 *
 * @example
 * From the following rule:
 * ```adblock
 * !#if (adguard_ext_android_cb || adguard_ext_safari)
 * ```
 * this parser will parse the expression `(adguard_ext_android_cb || adguard_ext_safari)`.
 */
// TODO: Refactor this class
class LogicalExpressionDeserializer extends BaseDeserializer {
    /**
     * Deserializes a variable node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     * @throws If the binary data is malformed.
     */
    static deserializeVariableNode(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ExpressionVariableNode);
        node.type = logical_expression_serializer/* NodeType */.Z.Variable;
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case logical_expression_common/* VariableNodeBinaryPropMarshallingMap */.Tf.Name:
                    node.name = buffer.readString();
                    break;
                case logical_expression_common/* VariableNodeBinaryPropMarshallingMap */.Tf.FrequentName:
                    node.name = getFrequentNameOrFail(buffer.readUint8());
                    break;
                case logical_expression_common/* VariableNodeBinaryPropMarshallingMap */.Tf.Start:
                    node.start = buffer.readUint32();
                    break;
                case logical_expression_common/* VariableNodeBinaryPropMarshallingMap */.Tf.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}`);
            }
            prop = buffer.readUint8();
        }
    }
    /**
     * Deserializes a parenthesis node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     * @throws If the binary data is malformed.
     */
    static deserializeParenthesisNode(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ExpressionParenthesisNode);
        node.type = logical_expression_serializer/* NodeType */.Z.Parenthesis;
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case logical_expression_common/* ParenthesisNodeBinaryPropMarshallingMap */.z0.Expression:
                    LogicalExpressionDeserializer.deserialize(buffer, node.expression = {});
                    break;
                case logical_expression_common/* ParenthesisNodeBinaryPropMarshallingMap */.z0.Start:
                    node.start = buffer.readUint32();
                    break;
                case logical_expression_common/* ParenthesisNodeBinaryPropMarshallingMap */.z0.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}`);
            }
            prop = buffer.readUint8();
        }
    }
    /**
     * Deserializes an operator node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     * @throws If the binary data is malformed.
     */
    static deserializeOperatorNode(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ExpressionOperatorNode);
        node.type = logical_expression_serializer/* NodeType */.Z.Operator;
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case logical_expression_common/* OperatorNodeBinaryPropMarshallingMap */.hc.Operator:
                    node.operator = getOperatorOrFail(buffer.readUint8());
                    break;
                case logical_expression_common/* OperatorNodeBinaryPropMarshallingMap */.hc.Left:
                    LogicalExpressionDeserializer.deserialize(buffer, node.left = {});
                    break;
                case logical_expression_common/* OperatorNodeBinaryPropMarshallingMap */.hc.Right:
                    LogicalExpressionDeserializer.deserialize(buffer, node.right = {});
                    break;
                case logical_expression_common/* OperatorNodeBinaryPropMarshallingMap */.hc.Start:
                    node.start = buffer.readUint32();
                    break;
                case logical_expression_common/* OperatorNodeBinaryPropMarshallingMap */.hc.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}`);
            }
            prop = buffer.readUint8();
        }
    }
    /**
     * Deserializes a logical expression node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     * @throws If the binary data is malformed.
     */
    static deserialize(buffer, node) {
        // note: we just do a simple lookahead here, because advancing the buffer is done in the
        // 'sub-deserialize' methods
        let type = buffer.peekUint8();
        while (type !== constants/* NULL */.Cq) {
            switch (type) {
                case binary_type_common/* BinaryTypeMarshallingMap */.u.ExpressionVariableNode:
                    LogicalExpressionDeserializer.deserializeVariableNode(buffer, node);
                    break;
                case binary_type_common/* BinaryTypeMarshallingMap */.u.ExpressionOperatorNode:
                    LogicalExpressionDeserializer.deserializeOperatorNode(buffer, node);
                    break;
                case binary_type_common/* BinaryTypeMarshallingMap */.u.ExpressionParenthesisNode:
                    LogicalExpressionDeserializer.deserializeParenthesisNode(buffer, node);
                    break;
                default:
                    throw new Error(`Unexpected node type: ${type}`);
            }
            type = buffer.peekUint8();
        }
        // consume NULL
        buffer.readUint8();
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/comment/pre-processor-comment-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */











/* eslint-disable no-param-reassign */
/**
 * Value map for binary deserialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 */
let frequentDirectivesDeserializationMap;
const getFrequentDirectivesDeserializationMap = () => {
    if (!frequentDirectivesDeserializationMap) {
        frequentDirectivesDeserializationMap = new Map(Array.from(pre_processor_comment_common/* FREQUENT_DIRECTIVES_SERIALIZATION_MAP */.u_).map(([key, value]) => [value, key]));
    }
    return frequentDirectivesDeserializationMap;
};
/**
 * Value map for binary deserialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 */
let frequentParamsDeserializationMap;
const getFrequentParamsDeserializationMap = () => {
    if (!frequentParamsDeserializationMap) {
        frequentParamsDeserializationMap = new Map(Array.from(pre_processor_comment_common/* FREQUENT_PARAMS_SERIALIZATION_MAP */.k7).map(([key, value]) => [value, key]));
    }
    return frequentParamsDeserializationMap;
};
/**
 * `PreProcessorCommentDeserializer` is responsible for deserializing preprocessor rules.
 * Pre-processor comments are special comments that are used to control the behavior of the filter list processor.
 * Please note that this parser only handles general syntax for now, and does not validate the parameters at
 * the parsing stage.
 *
 * @example
 * If your rule is
 * ```adblock
 * !#if (adguard)
 * ```
 * then the directive's name is `if` and its value is `(adguard)`, but the parameter list
 * is not parsed / validated further.
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#pre-processor-directives}
 * @see {@link https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#pre-parsing-directives}
 */
class PreProcessorCommentDeserializer extends BaseDeserializer {
    /**
     * Deserializes a pre-processor comment node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     * @throws If the binary data is malformed.
     */
    static deserialize(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.PreProcessorCommentRuleNode);
        node.type = nodes/* CommentRuleType */.gV.PreProcessorCommentRule;
        node.category = nodes/* RuleCategory */.$O.Comment;
        node.syntax = adblockers/* AdblockSyntax */.Y.Common;
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case pre_processor_comment_common/* PreProcessorRuleMarshallingMap */.Qz.Name:
                    // eslint-disable-next-line max-len
                    ValueDeserializer.deserialize(buffer, node.name = {}, getFrequentDirectivesDeserializationMap());
                    break;
                case pre_processor_comment_common/* PreProcessorRuleMarshallingMap */.Qz.Syntax:
                    node.syntax = getSyntaxDeserializationMap().get(buffer.readUint8()) ?? adblockers/* AdblockSyntax */.Y.Common;
                    break;
                case pre_processor_comment_common/* PreProcessorRuleMarshallingMap */.Qz.Params:
                    switch (buffer.peekUint8()) {
                        case binary_type_common/* BinaryTypeMarshallingMap */.u.ValueNode:
                            ValueDeserializer.deserialize(buffer, node.params = {});
                            break;
                        case binary_type_common/* BinaryTypeMarshallingMap */.u.ParameterListNode:
                            // eslint-disable-next-line max-len
                            ParameterListDeserializer.deserialize(buffer, node.params = {}, getFrequentParamsDeserializationMap());
                            break;
                        case binary_type_common/* BinaryTypeMarshallingMap */.u.ExpressionOperatorNode:
                        case binary_type_common/* BinaryTypeMarshallingMap */.u.ExpressionParenthesisNode:
                        case binary_type_common/* BinaryTypeMarshallingMap */.u.ExpressionVariableNode:
                            LogicalExpressionDeserializer.deserialize(buffer, node.params = {});
                            break;
                        default:
                            throw new Error(`Invalid binary type: ${prop}`);
                    }
                    break;
                case pre_processor_comment_common/* PreProcessorRuleMarshallingMap */.Qz.Start:
                    node.start = buffer.readUint32();
                    break;
                case pre_processor_comment_common/* PreProcessorRuleMarshallingMap */.Qz.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}`);
            }
            prop = buffer.readUint8();
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/comment/simple-comment-common.js
var simple_comment_common = __webpack_require__(25331);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/comment/simple-comment-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */








/* eslint-disable no-param-reassign */
/**
 * `SimpleCommentDeserializer` is responsible for deserializing simple comments.
 *
 * Some comments have a special meaning in adblock syntax, like agent comments or hints,
 * but this parser is only responsible for parsing regular comments,
 * whose only purpose is to provide some human-readable information.
 *
 * @example
 * ```adblock
 * ! This is a simple comment
 * # This is a simple comment, but in host-like syntax
 * ```
 */
class SimpleCommentDeserializer extends BaseDeserializer {
    /**
     * Deserializes a simple comment node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     * @throws If the binary data is malformed.
     */
    static deserialize(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.CommentRuleNode);
        node.type = nodes/* CommentRuleType */.gV.CommentRule;
        node.category = nodes/* RuleCategory */.$O.Comment;
        node.syntax = adblockers/* AdblockSyntax */.Y.Common;
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case simple_comment_common/* SimpleCommentMarshallingMap */.i.Marker:
                    ValueDeserializer.deserialize(buffer, node.marker = {});
                    break;
                case simple_comment_common/* SimpleCommentMarshallingMap */.i.Text:
                    ValueDeserializer.deserialize(buffer, node.text = {});
                    break;
                case simple_comment_common/* SimpleCommentMarshallingMap */.i.Start:
                    node.start = buffer.readUint32();
                    break;
                case simple_comment_common/* SimpleCommentMarshallingMap */.i.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}`);
            }
            prop = buffer.readUint8();
        }
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/comment/comment-rule-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */









/**
 * `CommentRuleDeserializer` is responsible for deserializing any comment-like adblock rules.
 */
class CommentRuleDeserializer extends BaseDeserializer {
    /**
     * Deserializes a comment rule node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     * @throws If the binary data is malformed.
     */
    static deserialize(buffer, node) {
        const type = buffer.peekUint8();
        switch (type) {
            case binary_type_common/* BinaryTypeMarshallingMap */.u.AgentRuleNode:
                AgentCommentDeserializer.deserialize(buffer, node);
                return;
            case binary_type_common/* BinaryTypeMarshallingMap */.u.HintRuleNode:
                HintCommentDeserializer.deserialize(buffer, node);
                return;
            case binary_type_common/* BinaryTypeMarshallingMap */.u.PreProcessorCommentRuleNode:
                PreProcessorCommentDeserializer.deserialize(buffer, node);
                return;
            case binary_type_common/* BinaryTypeMarshallingMap */.u.MetadataCommentRuleNode:
                MetadataCommentDeserializer.deserialize(buffer, node);
                return;
            case binary_type_common/* BinaryTypeMarshallingMap */.u.ConfigCommentRuleNode:
                ConfigCommentDeserializer.deserialize(buffer, node);
                return;
            case binary_type_common/* BinaryTypeMarshallingMap */.u.CommentRuleNode:
                SimpleCommentDeserializer.deserialize(buffer, node);
                return;
            default:
                throw new Error(`Unknown comment rule type: ${type}`);
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/misc/domain-list-common.js
var domain_list_common = __webpack_require__(44859);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/misc/list-item-common.js
var list_item_common = __webpack_require__(80486);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/misc/list-item-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */






/* eslint-disable no-param-reassign */
/**
 * `ListItemDeserializer` is responsible for deserializing list item nodes from binary format.
 *
 * @example
 * `app`, `domain`, `method`, `stealth-option`
 */
class ListItemDeserializer extends BaseDeserializer {
    /**
     * Deserializes a list item from binary format.
     *
     * @param buffer Input byte buffer.
     * @param node Partial list item to deserialize.
     * @template T Type of the list item.
     */
    static deserialize = (buffer, node) => {
        const type = buffer.readUint8();
        switch (type) {
            case binary_type_common/* BinaryTypeMarshallingMap */.u.AppNode:
                node.type = nodes/* ListItemNodeType */.WR.App;
                break;
            case binary_type_common/* BinaryTypeMarshallingMap */.u.DomainNode:
                node.type = nodes/* ListItemNodeType */.WR.Domain;
                break;
            case binary_type_common/* BinaryTypeMarshallingMap */.u.MethodNode:
                node.type = nodes/* ListItemNodeType */.WR.Method;
                break;
            case binary_type_common/* BinaryTypeMarshallingMap */.u.StealthOptionNode:
                node.type = nodes/* ListItemNodeType */.WR.StealthOption;
                break;
            default:
                throw new Error(`Invalid list item type: ${type}`);
        }
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case list_item_common/* ListItemMarshallingMap */.i.Exception:
                    node.exception = buffer.readUint8() === 1;
                    break;
                case list_item_common/* ListItemMarshallingMap */.i.Value:
                    node.value = buffer.readString();
                    break;
                case list_item_common/* ListItemMarshallingMap */.i.Start:
                    node.start = buffer.readUint32();
                    break;
                case list_item_common/* ListItemMarshallingMap */.i.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${type}`);
            }
            prop = buffer.readUint8();
        }
    };
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/misc/list-items-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * Deserializes lists of items from binary format.
 * Converts binary data to structured item nodes.
 */
class ListItemsDeserializer {
    /**
     * Deserializes a list of items from binary format.
     *
     * @param buffer Input byte buffer.
     * @param items Partial list of items to deserialize.
     * @template T Type of the list items.
     */
    static deserialize = (buffer, items) => {
        const length = buffer.readUint16();
        items.length = length;
        for (let i = 0; i < length; i += 1) {
            ListItemDeserializer.deserialize(buffer, items[i] = {});
        }
    };
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/misc/domain-list-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/* eslint-disable no-param-reassign */
/**
 * Value map for binary deserialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 */
let separatorDeserializationMap;
const getSeparatorDeserializationMap = () => {
    if (!separatorDeserializationMap) {
        separatorDeserializationMap = new Map(Array.from(domain_list_common/* SEPARATOR_SERIALIZATION_MAP */._)
            .map(([key, value]) => [value, key]));
    }
    return separatorDeserializationMap;
};
/**
 * `DomainListDeserializer` is responsible for deserializing a domain list.
 */
class DomainListDeserializer extends BaseDeserializer {
    /**
     * Deserializes a modifier list node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     */
    static deserialize(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.DomainListNode);
        node.type = nodes/* ListNodeType */.h6.DomainList;
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case domain_list_common/* DomainListMarshallingMap */.T.Separator:
                    // eslint-disable-next-line max-len
                    node.separator = (getSeparatorDeserializationMap().get(buffer.readUint8()) ?? constants/* COMMA */.KE);
                    break;
                case domain_list_common/* DomainListMarshallingMap */.T.Children:
                    ListItemsDeserializer.deserialize(buffer, node.children = []);
                    break;
                case domain_list_common/* DomainListMarshallingMap */.T.Start:
                    node.start = buffer.readUint32();
                    break;
                case domain_list_common/* DomainListMarshallingMap */.T.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}.`);
            }
            prop = buffer.readUint8();
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/cosmetic/body/abp-snippet-injection-body-common.js
var abp_snippet_injection_body_common = __webpack_require__(66604);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/cosmetic/scriptlet-body/scriptlet-body-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */






/**
 * Deserializes binary data into scriptlet body nodes.
 * Optionally uses a map of frequently used scriptlet arguments.
 */
class ScriptletBodyDeserializer extends BaseDeserializer {
    /**
     * Deserializes a hint rule node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     * @param frequentScriptletArgs Map of frequently used scriptlet names / arguments
     * and their serialization index (optional).
     * @throws If the binary data is malformed.
     */
    static deserialize = (buffer, node, frequentScriptletArgs) => {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ScriptletInjectionRuleBodyNode);
        node.type = 'ScriptletInjectionRuleBody';
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case abp_snippet_injection_body_common/* AbpSnippetBodyMarshallingMap */.f.Children:
                    node.children = new Array(buffer.readUint8());
                    // read children
                    for (let i = 0; i < node.children.length; i += 1) {
                        ParameterListDeserializer.deserialize(buffer, node.children[i] = {}, frequentScriptletArgs);
                    }
                    break;
                case abp_snippet_injection_body_common/* AbpSnippetBodyMarshallingMap */.f.Start:
                    node.start = buffer.readUint32();
                    break;
                case abp_snippet_injection_body_common/* AbpSnippetBodyMarshallingMap */.f.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}`);
            }
            prop = buffer.readUint8();
        }
    };
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/cosmetic/scriptlet-body/abp-snippet-injection-body-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * Value map for binary deserialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 */
let frequentAbpSnippetArgsDeserializationMap;
const getFrequentAbpSnippetArgsDeserializationMap = () => {
    if (!frequentAbpSnippetArgsDeserializationMap) {
        frequentAbpSnippetArgsDeserializationMap = new Map(Array.from(abp_snippet_injection_body_common/* FREQUENT_ABP_SNIPPET_ARGS_SERIALIZATION_MAP */.T).map(([key, value]) => [value, key]));
    }
    return frequentAbpSnippetArgsDeserializationMap;
};
/**
 * Deserializer for ABP snippet injection rule body nodes.
 * Converts binary data into a structured format using a map of frequently used arguments.
 */
class AbpSnippetInjectionBodyDeserializer extends BaseDeserializer {
    /**
     * Deserializes a scriptlet call body node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     * @throws If the binary data is malformed.
     */
    static deserialize(buffer, node) {
        ScriptletBodyDeserializer.deserialize(buffer, node, getFrequentAbpSnippetArgsDeserializationMap());
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/cosmetic/body/ubo-scriptlet-injection-body-common.js
var ubo_scriptlet_injection_body_common = __webpack_require__(62224);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/cosmetic/scriptlet-body/ubo-scriptlet-injection-body-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * Value map for binary deserialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 */
let frequentUboScriptletArgsDeserializationMap;
const ubo_scriptlet_injection_body_deserializer_getFrequentPlatformsDeserializationMap = () => {
    if (!frequentUboScriptletArgsDeserializationMap) {
        frequentUboScriptletArgsDeserializationMap = new Map(Array.from(ubo_scriptlet_injection_body_common/* FREQUENT_UBO_SCRIPTLET_ARGS_SERIALIZATION_MAP */.Z).map(([key, value]) => [value, key]));
    }
    return frequentUboScriptletArgsDeserializationMap;
};
/**
 * Deserializes uBlock Origin scriptlet injection body nodes from binary data.
 */
class UboScriptletInjectionBodyDeserializer extends BaseDeserializer {
    /**
     * Deserializes a scriptlet call body node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node to populate with deserialized data.
     * @throws If the binary data is malformed.
     */
    static deserialize(buffer, node) {
        ScriptletBodyDeserializer.deserialize(buffer, node, ubo_scriptlet_injection_body_deserializer_getFrequentPlatformsDeserializationMap());
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/cosmetic/body/adg-scriptlet-injection-body-common.js
var adg_scriptlet_injection_body_common = __webpack_require__(56874);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/cosmetic/scriptlet-body/adg-scriptlet-injection-body-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * Value map for binary deserialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 */
let frequentAdgScriptletArgsDeserializationMap;
const getFrequentAdgScriptletArgsDeserializationMap = () => {
    if (!frequentAdgScriptletArgsDeserializationMap) {
        frequentAdgScriptletArgsDeserializationMap = new Map(Array.from(adg_scriptlet_injection_body_common/* FREQUENT_ADG_SCRIPTLET_ARGS_SERIALIZATION_MAP */.T).map(([key, value]) => [value, key]));
    }
    return frequentAdgScriptletArgsDeserializationMap;
};
/**
 * Deserializer for AdGuard scriptlet injection body nodes.
 * Converts binary data into a structured scriptlet call body node specific to AdGuard,
 * using a predefined deserialization map for frequently used scriptlet arguments.
 */
class AdgScriptletInjectionBodyDeserializer extends BaseDeserializer {
    /**
     * Deserializes a scriptlet call body node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     * @throws If the binary data is malformed.
     */
    static deserialize(buffer, node) {
        ScriptletBodyDeserializer.deserialize(buffer, node, getFrequentAdgScriptletArgsDeserializationMap());
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/cosmetic/body/element-hiding-body-common.js
var element_hiding_body_common = __webpack_require__(69803);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/cosmetic/element-hiding-body-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */






/* eslint-disable no-param-reassign */
/**
 * Deserializes element hiding rule body nodes from binary data.
 * Populates the provided node with the deserialized data.
 */
class ElementHidingBodyDeserializer extends BaseDeserializer {
    /**
     * Deserializes an element hiding rule body node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     */
    static deserializeElementHidingBody(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ElementHidingRuleBody);
        node.type = 'ElementHidingRuleBody';
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case element_hiding_body_common/* ElementHidingRuleMarshallingMap */.G.SelectorList:
                    ValueDeserializer.deserialize(buffer, node.selectorList = {});
                    break;
                case element_hiding_body_common/* ElementHidingRuleMarshallingMap */.G.Start:
                    node.start = buffer.readUint32();
                    break;
                case element_hiding_body_common/* ElementHidingRuleMarshallingMap */.G.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Unknown property: ${prop}`);
            }
            prop = buffer.readUint8();
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/cosmetic/body/css-injection-body-common.js
var css_injection_body_common = __webpack_require__(52002);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/cosmetic/css-injection-body-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */






/**
 * Deserializes CSS injection rule body nodes from binary format.
 */
class CssInjectionBodyDeserializer extends BaseDeserializer {
    /**
     * Deserializes CSS injection rule body node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     */
    static deserialize(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.CssInjectionRuleBody);
        node.type = 'CssInjectionRuleBody';
        node.remove = false;
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case css_injection_body_common/* CssInjectionRuleMarshallingMap */.V.MediaQueryList:
                    ValueDeserializer.deserialize(buffer, node.mediaQueryList = {});
                    break;
                case css_injection_body_common/* CssInjectionRuleMarshallingMap */.V.SelectorList:
                    ValueDeserializer.deserialize(buffer, node.selectorList = {});
                    break;
                case css_injection_body_common/* CssInjectionRuleMarshallingMap */.V.DeclarationList:
                    ValueDeserializer.deserialize(buffer, node.declarationList = {});
                    break;
                case css_injection_body_common/* CssInjectionRuleMarshallingMap */.V.Remove:
                    node.remove = true;
                    break;
                case css_injection_body_common/* CssInjectionRuleMarshallingMap */.V.Start:
                    node.start = buffer.readUint32();
                    break;
                case css_injection_body_common/* CssInjectionRuleMarshallingMap */.V.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Unknown property: ${prop}`);
            }
            prop = buffer.readUint8();
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/misc/modifier-common.js
var modifier_common = __webpack_require__(14299);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/misc/modifier-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */






/* eslint-disable no-param-reassign */
/**
 * Value map for binary deserialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 *
 * @note Only 256 values can be represented this way.
 */
let frequentModifiersDeserializationMap;
const getFrequentModifiersDeserializationMap = () => {
    if (!frequentModifiersDeserializationMap) {
        frequentModifiersDeserializationMap = new Map(Array.from(modifier_common/* FREQUENT_MODIFIERS_SERIALIZATION_MAP */.uu).map(([key, value]) => [value, key]));
    }
    return frequentModifiersDeserializationMap;
};
/**
 * Value map for binary deserialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 */
let frequentValuesDeserializationMaps;
const getFrequentValuesDeserializationMaps = () => {
    if (!frequentValuesDeserializationMaps) {
        frequentValuesDeserializationMaps = new Map(Array.from(modifier_common/* FREQUENT_REDIRECT_MODIFIERS_SERIALIZATION_MAP */.vG, ([modifier, valueMap]) => [modifier, new Map(Array.from(valueMap, ([key, value]) => [value, key]))]));
    }
    return frequentValuesDeserializationMaps;
};
/**
 * `ModifierDeserializer` is responsible for deserializing modifiers.
 *
 * @example
 * `match-case`, `~third-party`, `domain=example.com|~example.org`
 */
class ModifierDeserializer extends BaseDeserializer {
    /**
     * Deserializes a modifier node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     */
    static deserialize(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ModifierNode);
        node.type = 'Modifier';
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case modifier_common/* ModifierNodeMarshallingMap */.sD.Name:
                    // eslint-disable-next-line max-len
                    ValueDeserializer.deserialize(buffer, node.name = {}, getFrequentModifiersDeserializationMap());
                    break;
                case modifier_common/* ModifierNodeMarshallingMap */.sD.Value:
                    if (node.name) {
                        // eslint-disable-next-line max-len
                        ValueDeserializer.deserialize(buffer, node.value = {}, getFrequentValuesDeserializationMaps().get(node.name.value));
                    }
                    else {
                        ValueDeserializer.deserialize(buffer, node.value = {});
                    }
                    break;
                case modifier_common/* ModifierNodeMarshallingMap */.sD.Exception:
                    node.exception = buffer.readUint8() === 1;
                    break;
                case modifier_common/* ModifierNodeMarshallingMap */.sD.Start:
                    node.start = buffer.readUint32();
                    break;
                case modifier_common/* ModifierNodeMarshallingMap */.sD.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}.`);
            }
            prop = buffer.readUint8();
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/misc/modifier-list-common.js
var modifier_list_common = __webpack_require__(92006);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/misc/modifier-list-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */






/* eslint-disable no-param-reassign */
/**
 * `ModifierListDeserializer` is responsible for deserializing modifier lists. Please note that the name is not
 * uniform, "modifiers" are also known as "options".
 *
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#basic-rules-modifiers}
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#non-basic-rules-modifiers}
 * @see {@link https://help.eyeo.com/adblockplus/how-to-write-filters#options}
 */
class ModifierListDeserializer extends BaseDeserializer {
    /**
     * Deserializes a modifier list node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     */
    static deserialize(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ModifierListNode);
        node.type = 'ModifierList';
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case modifier_list_common/* ModifierListNodeMarshallingMap */.I.Children:
                    node.children = new Array(buffer.readUint16());
                    // read children
                    for (let i = 0; i < node.children.length; i += 1) {
                        ModifierDeserializer.deserialize(buffer, node.children[i] = {});
                    }
                    break;
                case modifier_list_common/* ModifierListNodeMarshallingMap */.I.Start:
                    node.start = buffer.readUint32();
                    break;
                case modifier_list_common/* ModifierListNodeMarshallingMap */.I.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}.`);
            }
            prop = buffer.readUint8();
        }
        // Maybe children are not present in the binary data,
        // in this case, we should initialize it as an empty array.
        if (!node.children) {
            node.children = [];
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/cosmetic/cosmetic-rule-common.js
var cosmetic_rule_common = __webpack_require__(42983);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/cosmetic/cosmetic-rule-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */

















/* eslint-disable no-param-reassign */
/**
 * Value map for binary deserialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 */
let cosmeticRuleSeparatorDeserializationMap;
const getCosmeticRuleSeparatorDeserializationMap = () => {
    if (!cosmeticRuleSeparatorDeserializationMap) {
        cosmeticRuleSeparatorDeserializationMap = new Map(Array.from(cosmetic_rule_common/* COSMETIC_RULE_SEPARATOR_SERIALIZATION_MAP */.h).map(([key, value]) => [value, key]));
    }
    return cosmeticRuleSeparatorDeserializationMap;
};
/**
 * Value map for binary deserialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 */
const COSMETIC_RULE_TYPE_DESERIALIZATION_MAP = new Map([
    [binary_type_common/* BinaryTypeMarshallingMap */.u.ElementHidingRule, nodes/* CosmeticRuleType */.k9.ElementHidingRule],
    [binary_type_common/* BinaryTypeMarshallingMap */.u.CssInjectionRule, nodes/* CosmeticRuleType */.k9.CssInjectionRule],
    [binary_type_common/* BinaryTypeMarshallingMap */.u.ScriptletInjectionRule, nodes/* CosmeticRuleType */.k9.ScriptletInjectionRule],
    [binary_type_common/* BinaryTypeMarshallingMap */.u.JsInjectionRule, nodes/* CosmeticRuleType */.k9.JsInjectionRule],
    [binary_type_common/* BinaryTypeMarshallingMap */.u.HtmlFilteringRule, nodes/* CosmeticRuleType */.k9.HtmlFilteringRule],
]);
/**
 * Deserializer for cosmetic rules.
 * Converts binary data into structured cosmetic rule nodes, supporting various types
 * like element hiding, CSS injection, scriptlet injection, JavaScript injection, and HTML filtering.
 * Handles rule type, syntax, exceptions, separators, modifiers, and domain lists.
 */
class CosmeticRuleDeserializer extends BaseDeserializer {
    /**
     * Deserializes a cosmetic rule node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     */
    static deserialize(buffer, node) {
        const type = COSMETIC_RULE_TYPE_DESERIALIZATION_MAP.get(buffer.readUint8());
        if ((0,type_guards/* isUndefined */.b0)(type)) {
            throw new Error(`Unknown rule type: ${type}`);
        }
        node.type = type;
        node.category = nodes/* RuleCategory */.$O.Cosmetic;
        const syntax = getSyntaxDeserializationMap().get(buffer.readUint8()) ?? adblockers/* AdblockSyntax */.Y.Common;
        node.syntax = syntax;
        node.modifiers = undefined;
        switch (type) {
            case nodes/* CosmeticRuleType */.k9.ElementHidingRule:
                ElementHidingBodyDeserializer.deserializeElementHidingBody(buffer, node.body = {});
                break;
            case nodes/* CosmeticRuleType */.k9.CssInjectionRule:
                CssInjectionBodyDeserializer.deserialize(buffer, node.body = {});
                break;
            case nodes/* CosmeticRuleType */.k9.JsInjectionRule:
                ValueDeserializer.deserialize(buffer, node.body = {});
                break;
            case nodes/* CosmeticRuleType */.k9.HtmlFilteringRule:
                ValueDeserializer.deserialize(buffer, node.body = {});
                break;
            case nodes/* CosmeticRuleType */.k9.ScriptletInjectionRule:
                switch (syntax) {
                    case adblockers/* AdblockSyntax */.Y.Adg:
                        AdgScriptletInjectionBodyDeserializer.deserialize(buffer, node.body = {});
                        break;
                    case adblockers/* AdblockSyntax */.Y.Abp:
                        AbpSnippetInjectionBodyDeserializer.deserialize(buffer, node.body = {});
                        break;
                    case adblockers/* AdblockSyntax */.Y.Ubo:
                        UboScriptletInjectionBodyDeserializer.deserialize(buffer, node.body = {});
                        break;
                    default:
                        throw new Error('Scriptlet rule should have an explicit syntax');
                }
                break;
            default:
                throw new Error('Unknown cosmetic rule type');
        }
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case cosmetic_rule_common/* CosmeticRuleMarshallingMap */.U.Exception:
                    node.exception = buffer.readUint8() === 1;
                    break;
                case cosmetic_rule_common/* CosmeticRuleMarshallingMap */.U.Separator:
                    ValueDeserializer.deserialize(buffer, node.separator = {}, getCosmeticRuleSeparatorDeserializationMap());
                    break;
                case cosmetic_rule_common/* CosmeticRuleMarshallingMap */.U.Modifiers:
                    node.modifiers = {};
                    ModifierListDeserializer.deserialize(buffer, node.modifiers);
                    break;
                case cosmetic_rule_common/* CosmeticRuleMarshallingMap */.U.Domains:
                    DomainListDeserializer.deserialize(buffer, node.domains = {});
                    break;
                case cosmetic_rule_common/* CosmeticRuleMarshallingMap */.U.Start:
                    node.start = buffer.readUint32();
                    break;
                case cosmetic_rule_common/* CosmeticRuleMarshallingMap */.U.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Unknown property: ${prop}`);
            }
            prop = buffer.readUint8();
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/misc/hostname-list-common.js
var hostname_list_common = __webpack_require__(89410);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/network/hostname-list-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */






/* eslint-disable no-param-reassign */
/**
 * Deserializes hostname list nodes from binary format.
 */
class HostnameListDeserializer extends BaseDeserializer {
    /**
     * Deserializes a hostname list node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     */
    static deserialize(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.HostnameListNode);
        node.type = 'HostnameList';
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case hostname_list_common/* HostnameListNodeMarshallingMap */.W.Children:
                    node.children = new Array(buffer.readUint16());
                    // read children
                    for (let i = 0; i < node.children.length; i += 1) {
                        ValueDeserializer.deserialize(buffer, node.children[i] = {});
                    }
                    break;
                case hostname_list_common/* HostnameListNodeMarshallingMap */.W.Start:
                    node.start = buffer.readUint32();
                    break;
                case hostname_list_common/* HostnameListNodeMarshallingMap */.W.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Unknown property: ${prop}`);
            }
            prop = buffer.readUint8();
        }
        // Maybe children are not present in the binary data,
        // in this case, we should initialize it as an empty array.
        if (!node.children) {
            node.children = [];
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/misc/host-rule-common.js
var host_rule_common = __webpack_require__(41351);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/network/host-rule-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */










/* eslint-disable no-param-reassign */
/**
 * `HostRuleDeserializer` is responsible for deserializing hosts-like rules.
 *
 * HostRule is a structure for simple host-level rules (i.e. /etc/hosts syntax).
 * It also supports "just domain" syntax. In this case, the IP will be set to 0.0.0.0.
 */
class HostRuleDeserializer extends BaseDeserializer {
    /**
     * Deserializes a host rule node from binary format.
     *
     * @param buffer Input byte buffer to read from.
     * @param node Destination node to write to.
     */
    static deserialize(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.HostRuleNode);
        node.category = nodes/* RuleCategory */.$O.Network;
        node.type = nodes/* NetworkRuleType */.vY.HostRule;
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case host_rule_common/* HostRuleMarshallingMap */.J.Syntax:
                    node.syntax = getSyntaxDeserializationMap().get(buffer.readUint8()) ?? adblockers/* AdblockSyntax */.Y.Common;
                    break;
                case host_rule_common/* HostRuleMarshallingMap */.J.Ip:
                    node.ip = {};
                    ValueDeserializer.deserialize(buffer, node.ip);
                    break;
                case host_rule_common/* HostRuleMarshallingMap */.J.HostnameList:
                    node.hostnames = {};
                    HostnameListDeserializer.deserialize(buffer, node.hostnames);
                    break;
                case host_rule_common/* HostRuleMarshallingMap */.J.Comment:
                    node.comment = {};
                    ValueDeserializer.deserialize(buffer, node.comment);
                    break;
                case host_rule_common/* HostRuleMarshallingMap */.J.Start:
                    node.start = buffer.readUint32();
                    break;
                case host_rule_common/* HostRuleMarshallingMap */.J.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}.`);
            }
            prop = buffer.readUint8();
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/network/network-rule-common.js
var network_rule_common = __webpack_require__(49459);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/network/network-rule-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */










/* eslint-disable no-param-reassign */
/**
 * `NetworkRuleDeserializer` is responsible for deserializing network rules.
 *
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#basic-rules}
 * @see {@link https://help.eyeo.com/adblockplus/how-to-write-filters#basic}
 */
class NetworkRuleDeserializer extends BaseDeserializer {
    /**
     * Deserializes a network rule node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     */
    static deserialize(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.NetworkRuleNode);
        node.type = nodes/* NetworkRuleType */.vY.NetworkRule;
        node.category = nodes/* RuleCategory */.$O.Network;
        node.modifiers = undefined;
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case network_rule_common/* NetworkRuleMarshallingMap */.v.Syntax:
                    node.syntax = getSyntaxDeserializationMap().get(buffer.readUint8()) ?? adblockers/* AdblockSyntax */.Y.Common;
                    break;
                case network_rule_common/* NetworkRuleMarshallingMap */.v.Exception:
                    node.exception = buffer.readUint8() === 1;
                    break;
                case network_rule_common/* NetworkRuleMarshallingMap */.v.Pattern:
                    ValueDeserializer.deserialize(buffer, node.pattern = {});
                    break;
                case network_rule_common/* NetworkRuleMarshallingMap */.v.ModifierList:
                    ModifierListDeserializer.deserialize(buffer, node.modifiers = {});
                    break;
                case network_rule_common/* NetworkRuleMarshallingMap */.v.Start:
                    node.start = buffer.readUint32();
                    break;
                case network_rule_common/* NetworkRuleMarshallingMap */.v.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}.`);
            }
            prop = buffer.readUint8();
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/empty-rule-common.js
var empty_rule_common = __webpack_require__(27813);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/empty-rule-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/* eslint-disable no-param-reassign */
/**
 * Deserializer for empty rule nodes.
 * This class handles the deserialization of empty rule nodes from binary format.
 */
class EmptyRuleDeserializer extends BaseDeserializer {
    /**
     * Deserializes an empty rule node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     */
    static deserialize(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.EmptyRule);
        node.type = 'EmptyRule';
        node.category = nodes/* RuleCategory */.$O.Empty;
        node.syntax = adblockers/* AdblockSyntax */.Y.Common;
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case empty_rule_common/* EmptyRuleMarshallingMap */.K.Start:
                    node.start = buffer.readUint32();
                    break;
                case empty_rule_common/* EmptyRuleMarshallingMap */.K.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}.`);
            }
            prop = buffer.readUint8();
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/invalid-rule-error-node-common.js
var invalid_rule_error_node_common = __webpack_require__(6229);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/invalid-rule-error-node-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */





/* eslint-disable no-param-reassign */
/**
 * Deserializer for invalid rule error nodes.
 * Converts binary data into invalid rule error nodes.
 */
class InvalidRuleErrorNodeDeserializer extends BaseDeserializer {
    /**
     * Deserializes an invalid rule error node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     */
    static deserialize(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.InvalidRuleErrorNode);
        node.type = 'InvalidRuleError';
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case invalid_rule_error_node_common/* InvalidRuleErrorNodeMarshallingMap */.K.Name:
                    node.name = buffer.readString();
                    break;
                case invalid_rule_error_node_common/* InvalidRuleErrorNodeMarshallingMap */.K.Message:
                    node.message = buffer.readString();
                    break;
                case invalid_rule_error_node_common/* InvalidRuleErrorNodeMarshallingMap */.K.Start:
                    node.start = buffer.readUint32();
                    break;
                case invalid_rule_error_node_common/* InvalidRuleErrorNodeMarshallingMap */.K.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}.`);
            }
            prop = buffer.readUint8();
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/invalid-rule-common.js
var invalid_rule_common = __webpack_require__(51175);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/invalid-rule-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/* eslint-disable no-param-reassign */
/**
 * Deserializer for invalid rule nodes.
 * Converts binary data into invalid rule nodes.
 */
class InvalidRuleDeserializer extends BaseDeserializer {
    /**
     * Deserializes an invalid rule node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     */
    static deserialize(buffer, node) {
        buffer.assertUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.InvalidRule);
        node.type = 'InvalidRule';
        node.category = nodes/* RuleCategory */.$O.Invalid;
        let prop = buffer.readUint8();
        while (prop !== constants/* NULL */.Cq) {
            switch (prop) {
                case invalid_rule_common/* InvalidRuleMarshallingMap */.W.Error:
                    InvalidRuleErrorNodeDeserializer.deserialize(buffer, node.error = {});
                    break;
                case invalid_rule_common/* InvalidRuleMarshallingMap */.W.Start:
                    node.start = buffer.readUint32();
                    break;
                case invalid_rule_common/* InvalidRuleMarshallingMap */.W.End:
                    node.end = buffer.readUint32();
                    break;
                default:
                    throw new Error(`Invalid property: ${prop}.`);
            }
            prop = buffer.readUint8();
        }
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/rule-deserializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */









/**
 * `RuleDeserializer` is responsible for deserializing the rules.
 *
 * It automatically determines the category and syntax of the rule, so you can pass any kind of rule to it.
 */
class RuleDeserializer extends BaseDeserializer {
    /**
     * Deserializes a rule node from binary format.
     *
     * @param buffer ByteBuffer for reading binary data.
     * @param node Destination node.
     */
    static deserialize(buffer, node) {
        // lookup instead of storing +1 byte
        const type = buffer.peekUint8();
        switch (type) {
            case binary_type_common/* BinaryTypeMarshallingMap */.u.AgentRuleNode:
            case binary_type_common/* BinaryTypeMarshallingMap */.u.HintRuleNode:
            case binary_type_common/* BinaryTypeMarshallingMap */.u.PreProcessorCommentRuleNode:
            case binary_type_common/* BinaryTypeMarshallingMap */.u.MetadataCommentRuleNode:
            case binary_type_common/* BinaryTypeMarshallingMap */.u.ConfigCommentRuleNode:
            case binary_type_common/* BinaryTypeMarshallingMap */.u.CommentRuleNode:
                CommentRuleDeserializer.deserialize(buffer, node);
                break;
            case binary_type_common/* BinaryTypeMarshallingMap */.u.ElementHidingRule:
            case binary_type_common/* BinaryTypeMarshallingMap */.u.CssInjectionRule:
            case binary_type_common/* BinaryTypeMarshallingMap */.u.ScriptletInjectionRule:
            case binary_type_common/* BinaryTypeMarshallingMap */.u.HtmlFilteringRule:
            case binary_type_common/* BinaryTypeMarshallingMap */.u.JsInjectionRule:
                CosmeticRuleDeserializer.deserialize(buffer, node);
                break;
            case binary_type_common/* BinaryTypeMarshallingMap */.u.NetworkRuleNode:
                NetworkRuleDeserializer.deserialize(buffer, node);
                break;
            case binary_type_common/* BinaryTypeMarshallingMap */.u.HostRuleNode:
                HostRuleDeserializer.deserialize(buffer, node);
                break;
            case binary_type_common/* BinaryTypeMarshallingMap */.u.EmptyRule:
                EmptyRuleDeserializer.deserialize(buffer, node);
                break;
            case binary_type_common/* BinaryTypeMarshallingMap */.u.InvalidRule:
                InvalidRuleDeserializer.deserialize(buffer, node);
                break;
            default:
                throw new Error('Unknown rule category');
        }
    }
}




/***/ }),

/***/ 99177:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   q: () => (/* binding */ AdblockSyntaxError)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * @file Customized syntax error class for Adblock Filter Parser.
 */
const ERROR_NAME = 'AdblockSyntaxError';
/**
 * Customized syntax error class for Adblock Filter Parser,
 * which contains the location range of the error.
 */
class AdblockSyntaxError extends SyntaxError {
    /**
     * Start offset of the error.
     */
    start;
    /**
     * End offset of the error.
     */
    end;
    /**
     * Constructs a new `AdblockSyntaxError` instance.
     *
     * @param message Error message.
     * @param start Start offset of the error.
     * @param end End offset of the error.
     */
    constructor(message, start, end) {
        super(message);
        this.name = ERROR_NAME;
        this.start = start;
        this.end = end;
    }
}




/***/ }),

/***/ 65489:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   E: () => (/* binding */ NotImplementedError)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * @file Customized error class for not implemented features.
 */
const ERROR_NAME = 'NotImplementedError';
const BASE_MESSAGE = 'Not implemented';
/**
 * Customized error class for not implemented features.
 */
class NotImplementedError extends Error {
    /**
     * Constructs a new `NotImplementedError` instance.
     *
     * @param message Additional error message (optional)
     */
    constructor(message = undefined) {
        // Prepare the full error message
        const fullMessage = message
            ? `${BASE_MESSAGE}: ${message}`
            : BASE_MESSAGE;
        super(fullMessage);
        this.name = ERROR_NAME;
    }
}




/***/ }),

/***/ 46253:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   t: () => (/* binding */ BaseGenerator)
/* harmony export */ });
/* harmony import */ var _errors_not_implemented_error_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(65489);
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/* eslint-disable @typescript-eslint/no-unused-vars */
/**
 * @file Base generator class.
 */
/**
 * Base class for generators. Each generator should extend this class.
 */
class BaseGenerator {
    /**
     * Generates a string from the AST node.
     *
     * @param node AST node to generate a string from.
     */
    static generate(node) {
        throw new _errors_not_implemented_error_js__WEBPACK_IMPORTED_MODULE_0__/* .NotImplementedError */ .E();
    }
}




/***/ }),

/***/ 98442:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  H: () => (/* binding */ CosmeticRuleBodyGenerator)
});

// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/base-generator.js
var base_generator = __webpack_require__(46253);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/nodes/index.js
var nodes = __webpack_require__(64638);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/constants.js
var constants = __webpack_require__(65523);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/adblockers.js
var adblockers = __webpack_require__(88226);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/misc/parameter-list-generator.js
var parameter_list_generator = __webpack_require__(67529);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/cosmetic/body/adg-scriptlet-injection-body-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * AdGuard scriptlet injection body generator.
 */
class AdgScriptletInjectionBodyGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Error messages used by the generator.
     */
    static ERROR_MESSAGES = {
        NO_MULTIPLE_SCRIPTLET_CALLS: 'ADG syntaxes does not support multiple scriptlet calls within one single rule',
    };
    /**
     * Generates a string representation of the AdGuard scriptlet call body.
     *
     * @param node Scriptlet injection rule body
     * @returns String representation of the rule body
     * @throws Error if the scriptlet call has multiple parameters
     */
    static generate(node) {
        const result = [];
        if (node.children.length > 1) {
            throw new Error(AdgScriptletInjectionBodyGenerator.ERROR_MESSAGES.NO_MULTIPLE_SCRIPTLET_CALLS);
        }
        result.push(constants/* ADG_SCRIPTLET_MASK */.x$);
        result.push(constants/* OPEN_PARENTHESIS */.Cx);
        if (node.children.length > 0) {
            result.push(parameter_list_generator/* ParameterListGenerator */.H.generate(node.children[0]));
        }
        result.push(constants/* CLOSE_PARENTHESIS */.s1);
        return result.join(constants/* EMPTY */.wg);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/css/adg-css-injection-parser.js
var adg_css_injection_parser = __webpack_require__(53088);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/css/adg-css-injection-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * AdGuard CSS injection generator.
 */
class AdgCssInjectionGenerator extends base_generator/* BaseGenerator */.t {
    static removeDeclaration = `${adg_css_injection_parser/* REMOVE_PROPERTY */.JX}${constants/* COLON */.oH}${constants/* SPACE */.t6}${adg_css_injection_parser/* REMOVE_VALUE */.FH}${constants/* SEMICOLON */.I8}`;
    /**
     * Serializes an AdGuard CSS injection node into a raw string.
     *
     * @param node Node to serialize.
     * @returns Raw string.
     */
    static generate(node) {
        const result = [];
        if (node.mediaQueryList) {
            result.push(constants/* CSS_MEDIA_MARKER */.Ae, constants/* SPACE */.t6, node.mediaQueryList.value, constants/* SPACE */.t6, constants/* OPEN_CURLY_BRACKET */.sV, constants/* SPACE */.t6);
        }
        result.push(node.selectorList.value, constants/* SPACE */.t6, constants/* OPEN_CURLY_BRACKET */.sV, constants/* SPACE */.t6);
        if (node.remove) {
            result.push(AdgCssInjectionGenerator.removeDeclaration);
        }
        else if (node.declarationList?.value) {
            result.push(node.declarationList.value);
        }
        result.push(constants/* SPACE */.t6, constants/* CLOSE_CURLY_BRACKET */.wU);
        if (node.mediaQueryList) {
            result.push(constants/* SPACE */.t6, constants/* CLOSE_CURLY_BRACKET */.wU);
        }
        return result.join(constants/* EMPTY */.wg);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/common/abp-snippet-injection-body-common.js
var abp_snippet_injection_body_common = __webpack_require__(89814);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/cosmetic/body/abp-snippet-injection-body-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */





/**
 * Adblock Plus snippet injection body generator.
 */
class AbpSnippetInjectionBodyGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Generates a string representation of the Adblock Plus-style snippet call body.
     *
     * @param node Scriptlet injection rule body
     * @returns String representation of the rule body
     * @throws Error if the scriptlet call is empty
     */
    static generate(node) {
        const result = [];
        if (node.children.length === 0) {
            throw new Error(abp_snippet_injection_body_common/* AbpSnippetInjectionBodyCommon */.H.ERROR_MESSAGES.EMPTY_SCRIPTLET_CALL);
        }
        for (const scriptletCall of node.children) {
            if (scriptletCall.children.length === 0) {
                throw new Error(abp_snippet_injection_body_common/* AbpSnippetInjectionBodyCommon */.H.ERROR_MESSAGES.EMPTY_SCRIPTLET_CALL);
            }
            result.push(parameter_list_generator/* ParameterListGenerator */.H.generate(scriptletCall, constants/* SPACE */.t6));
        }
        return result.join(constants/* SEMICOLON */.I8 + constants/* SPACE */.t6);
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/cosmetic/body/ubo-scriptlet-injection-body-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * uBlock scriptlet injection body generator.
 */
class UboScriptletInjectionBodyGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Error messages used by the generator.
     */
    static ERROR_MESSAGES = {
        NO_MULTIPLE_SCRIPTLET_CALLS: 'uBO syntaxes does not support multiple scriptlet calls within one single rule',
    };
    /**
     * Generates a string representation of the uBlock scriptlet call body.
     *
     * @param node Scriptlet injection rule body
     * @returns String representation of the rule body
     * @throws Error if the scriptlet call has multiple parameters
     */
    static generate(node) {
        const result = [];
        if (node.children.length > 1) {
            throw new Error(UboScriptletInjectionBodyGenerator.ERROR_MESSAGES.NO_MULTIPLE_SCRIPTLET_CALLS);
        }
        // During generation, we only support the modern scriptlet mask
        result.push(constants/* UBO_SCRIPTLET_MASK */.Rq);
        result.push(constants/* OPEN_PARENTHESIS */.Cx);
        if (node.children.length > 0) {
            const [parameterListNode] = node.children;
            result.push(parameter_list_generator/* ParameterListGenerator */.H.generate(parameterListNode));
        }
        result.push(constants/* CLOSE_PARENTHESIS */.s1);
        return result.join(constants/* EMPTY */.wg);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/common/ubo-selector-common.js
var ubo_selector_common = __webpack_require__(31784);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/cosmetic/cosmetic-rule-body-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */










/**
 * Cosmetic rule body generator.
 */
class CosmeticRuleBodyGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Generates the rule body from the node.
     *
     * @param node Cosmetic rule node
     * @returns Raw rule body
     * @example
     * - '##.foo' → '.foo'
     * - 'example.com,example.org##.foo' → '.foo'
     * - 'example.com#%#//scriptlet('foo')' → '//scriptlet('foo')'
     *
     * @throws Error if the rule type is unknown
     */
    static generate(node) {
        let result = constants/* EMPTY */.wg;
        switch (node.type) {
            case nodes/* CosmeticRuleType */.k9.ElementHidingRule:
                result = node.body.selectorList.value;
                break;
            case nodes/* CosmeticRuleType */.k9.CssInjectionRule:
                if (node.syntax === adblockers/* AdblockSyntax */.Y.Adg || node.syntax === adblockers/* AdblockSyntax */.Y.Abp) {
                    result = AdgCssInjectionGenerator.generate(node.body);
                }
                else if (node.syntax === adblockers/* AdblockSyntax */.Y.Ubo) {
                    if (node.body.mediaQueryList) {
                        result += constants/* COLON */.oH;
                        result += ubo_selector_common/* UboPseudoName */.S.MatchesMedia;
                        result += constants/* OPEN_PARENTHESIS */.Cx;
                        result += node.body.mediaQueryList.value;
                        result += constants/* CLOSE_PARENTHESIS */.s1;
                        result += constants/* SPACE */.t6;
                    }
                    result += node.body.selectorList.value;
                    if (node.body.remove) {
                        result += constants/* COLON */.oH;
                        result += ubo_selector_common/* UboPseudoName */.S.Remove;
                        result += constants/* OPEN_PARENTHESIS */.Cx;
                        result += constants/* CLOSE_PARENTHESIS */.s1;
                    }
                    else if (node.body.declarationList) {
                        result += constants/* COLON */.oH;
                        result += ubo_selector_common/* UboPseudoName */.S.Style;
                        result += constants/* OPEN_PARENTHESIS */.Cx;
                        result += node.body.declarationList.value;
                        result += constants/* CLOSE_PARENTHESIS */.s1;
                    }
                }
                break;
            case nodes/* CosmeticRuleType */.k9.HtmlFilteringRule:
            case nodes/* CosmeticRuleType */.k9.JsInjectionRule:
                result = node.body.value;
                break;
            case nodes/* CosmeticRuleType */.k9.ScriptletInjectionRule:
                switch (node.syntax) {
                    case adblockers/* AdblockSyntax */.Y.Adg:
                        result = AdgScriptletInjectionBodyGenerator.generate(node.body);
                        break;
                    case adblockers/* AdblockSyntax */.Y.Abp:
                        result = AbpSnippetInjectionBodyGenerator.generate(node.body);
                        break;
                    case adblockers/* AdblockSyntax */.Y.Ubo:
                        result = UboScriptletInjectionBodyGenerator.generate(node.body);
                        break;
                    default:
                        throw new Error('Scriptlet rule should have an explicit syntax');
                }
                break;
            default:
                throw new Error('Unknown cosmetic rule type');
        }
        return result;
    }
}




/***/ }),

/***/ 67529:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   H: () => (/* binding */ ParameterListGenerator)
/* harmony export */ });
/* harmony import */ var _utils_constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65523);
/* harmony import */ var _base_generator_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(46253);
/* harmony import */ var _value_generator_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(55166);
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * Generator for parameter list nodes.
 */
class ParameterListGenerator extends _base_generator_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseGenerator */ .t {
    /**
     * Converts a parameter list AST to a string.
     *
     * @param params Parameter list AST
     * @param separator Separator character (default: comma)
     * @param allowSpace Allow space between parameters (default: true)
     * @returns String representation of the parameter list
     */
    static generate(params, separator = _utils_constants_js__WEBPACK_IMPORTED_MODULE_1__/* .COMMA */ .KE, allowSpace = true) {
        const collection = [];
        let i = 0;
        for (; i < params.children.length; i += 1) {
            const param = params.children[i];
            if (param === null) {
                collection.push(_utils_constants_js__WEBPACK_IMPORTED_MODULE_1__/* .EMPTY */ .wg);
            }
            else {
                collection.push(_value_generator_js__WEBPACK_IMPORTED_MODULE_2__/* .ValueGenerator */ .R.generate(param));
            }
        }
        let result = _utils_constants_js__WEBPACK_IMPORTED_MODULE_1__/* .EMPTY */ .wg;
        // if allowSpace is true, join with a single separator
        // without space
        if (!allowSpace && separator !== _utils_constants_js__WEBPACK_IMPORTED_MODULE_1__/* .SPACE */ .t6) {
            result = collection.join(separator);
        }
        else {
            // join parameters with separator
            // if the separator is a space, join with a single space
            result = collection.join(separator === _utils_constants_js__WEBPACK_IMPORTED_MODULE_1__/* .SPACE */ .t6 ? separator : `${separator}${_utils_constants_js__WEBPACK_IMPORTED_MODULE_1__/* .SPACE */ .t6}`);
        }
        return result;
    }
}




/***/ }),

/***/ 55166:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   R: () => (/* binding */ ValueGenerator)
/* harmony export */ });
/* harmony import */ var _base_generator_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(46253);
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * Generator for value nodes.
 */
class ValueGenerator extends _base_generator_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseGenerator */ .t {
    /**
     * Converts a value node to a string.
     *
     * @param node Value node.
     * @returns Raw string.
     */
    static generate(node) {
        return node.value;
    }
}




/***/ }),

/***/ 48094:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  u: () => (/* binding */ RuleGenerator)
});

// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/base-generator.js
var base_generator = __webpack_require__(46253);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/nodes/index.js
var nodes = __webpack_require__(64638);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/constants.js
var constants = __webpack_require__(65523);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/type-guards.js
var type_guards = __webpack_require__(30239);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/comment/agent-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * Generator for adblock agent nodes.
 * This class is responsible for converting adblock agent nodes into their string representation.
 */
class AgentGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Converts an adblock agent node to a string.
     *
     * @param value Agent node
     * @returns Raw string
     */
    static generate(value) {
        let result = constants/* EMPTY */.wg;
        // Agent adblock name
        result += value.adblock.value;
        // Agent adblock version (if present)
        if (!(0,type_guards/* isUndefined */.b0)(value.version)) {
            // Add a space between the name and the version
            result += constants/* SPACE */.t6;
            result += value.version.value;
        }
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/comment/agent-comment-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * Generator for agent comment rules.
 */
class AgentCommentGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Converts an adblock agent AST to a string.
     *
     * @param ast Agent rule AST
     * @returns Raw string
     */
    static generate(ast) {
        let result = constants/* OPEN_SQUARE_BRACKET */.cU;
        result += ast.children
            .map(AgentGenerator.generate)
            .join(constants/* SEMICOLON */.I8 + constants/* SPACE */.t6);
        result += constants/* CLOSE_SQUARE_BRACKET */.A1;
        return result;
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/misc/parameter-list-generator.js
var parameter_list_generator = __webpack_require__(67529);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/comment/hint-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * Hint generator.
 */
class HintGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Generates a string representation of a hint.
     *
     * @param hint Hint AST node
     * @returns String representation of the hint
     */
    static generate(hint) {
        let result = constants/* EMPTY */.wg;
        result += hint.name.value;
        if (hint.params && hint.params.children.length > 0) {
            result += constants/* OPEN_PARENTHESIS */.Cx;
            result += parameter_list_generator/* ParameterListGenerator */.H.generate(hint.params, constants/* COMMA */.KE);
            result += constants/* CLOSE_PARENTHESIS */.s1;
        }
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/comment/hint-comment-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * Hint comment generator.
 */
class HintCommentGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Converts a hint rule node to a raw string.
     *
     * @param node Hint rule node
     * @returns Raw string
     */
    static generate(node) {
        let result = constants/* HINT_MARKER */.j6 + constants/* SPACE */.t6;
        result += node.children.map(HintGenerator.generate).join(constants/* SPACE */.t6);
        return result;
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/misc/value-generator.js
var value_generator = __webpack_require__(55166);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/misc/logical-expression-parser.js
var logical_expression_parser = __webpack_require__(92987);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/misc/logical-expression-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * Generator for logical expression nodes.
 */
class LogicalExpressionGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Generates a string representation of the logical expression (serialization).
     *
     * @param node Expression node
     * @returns String representation of the logical expression
     */
    static generate(node) {
        if (node.type === logical_expression_parser/* NodeType */.Z.Variable) {
            return node.name;
        }
        if (node.type === logical_expression_parser/* NodeType */.Z.Operator) {
            const left = LogicalExpressionGenerator.generate(node.left);
            const right = node.right ? LogicalExpressionGenerator.generate(node.right) : undefined;
            const { operator } = node;
            // Special case for NOT operator
            if (operator === nodes/* OperatorValue */.oC.Not) {
                return `${operator}${left}`;
            }
            // Right operand is required for AND and OR operators
            if (!right) {
                throw new Error('Expected right operand');
            }
            return `${left} ${operator} ${right}`;
        }
        if (node.type === logical_expression_parser/* NodeType */.Z.Parenthesis) {
            const expressionString = LogicalExpressionGenerator.generate(node.expression);
            return `(${expressionString})`;
        }
        // Theoretically, this shouldn't happen if the library is used correctly
        throw new Error('Unexpected node type');
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/comment/pre-processor-comment-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */






/**
 * Pre-processor comment generator.
 */
class PreProcessorCommentGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Converts a pre-processor comment node to a string.
     *
     * @param node Pre-processor comment node
     * @returns Raw string
     */
    static generate(node) {
        let result = constants/* EMPTY */.wg;
        result += constants/* PREPROCESSOR_MARKER */.PD;
        result += node.name.value;
        if (node.params) {
            let allowSpaceBetweenParams = true;
            // Space between cb is not allowed for "safari_cb_affinity" directive.
            if (node.name.value === constants/* SAFARI_CB_AFFINITY */.us) {
                allowSpaceBetweenParams = false;
            }
            // Space is not allowed after "safari_cb_affinity" directive, so we need to handle it separately.
            if (node.name.value !== constants/* SAFARI_CB_AFFINITY */.us) {
                result += constants/* SPACE */.t6;
            }
            if (node.params.type === 'Value') {
                result += value_generator/* ValueGenerator */.R.generate(node.params);
            }
            else if (node.params.type === 'ParameterList') {
                result += constants/* OPEN_PARENTHESIS */.Cx;
                result += parameter_list_generator/* ParameterListGenerator */.H.generate(node.params, constants/* COMMA */.KE, allowSpaceBetweenParams);
                result += constants/* CLOSE_PARENTHESIS */.s1;
            }
            else {
                result += LogicalExpressionGenerator.generate(node.params);
            }
        }
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/comment/metadata-comment-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * Metadata comment generator.
 */
class MetadataCommentGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Converts a metadata comment rule node to a string.
     *
     * @param node Metadata comment rule node.
     * @returns Raw string.
     */
    static generate(node) {
        let result = constants/* EMPTY */.wg;
        result += value_generator/* ValueGenerator */.R.generate(node.marker);
        result += constants/* SPACE */.t6;
        result += value_generator/* ValueGenerator */.R.generate(node.header);
        result += constants/* COLON */.oH;
        result += constants/* SPACE */.t6;
        result += value_generator/* ValueGenerator */.R.generate(node.value);
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/comment/config-comment-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * Converts inline configuration comment nodes to their string format.
 */
class ConfigCommentGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Converts an inline configuration comment node to a string.
     *
     * @param node Inline configuration comment node
     * @returns Raw string
     */
    static generate(node) {
        let result = constants/* EMPTY */.wg;
        result += node.marker.value;
        result += constants/* SPACE */.t6;
        result += node.command.value;
        if (node.params) {
            result += constants/* SPACE */.t6;
            if (node.params.type === 'ParameterList') {
                result += parameter_list_generator/* ParameterListGenerator */.H.generate(node.params, constants/* COMMA */.KE);
            }
            else {
                // Trim JSON boundaries
                result += JSON.stringify(node.params.value).slice(1, -1).trim();
            }
        }
        // Add comment within the config comment
        if (node.comment) {
            result += constants/* SPACE */.t6;
            result += node.comment.value;
        }
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/comment/simple-comment-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * Simple comment generator.
 */
class SimpleCommentGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Converts a comment rule node to a string.
     *
     * @param node Comment rule node.
     * @returns Raw string.
     */
    static generate(node) {
        let result = constants/* EMPTY */.wg;
        result += value_generator/* ValueGenerator */.R.generate(node.marker);
        result += value_generator/* ValueGenerator */.R.generate(node.text);
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/comment/comment-rule-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */









/* eslint-disable no-param-reassign */
/**
 * `CommentRuleGenerator` is responsible for generating any comment-like adblock rules.
 */
class CommentRuleGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Converts a comment rule node to a string.
     *
     * @param node Comment rule node
     * @returns Raw string
     */
    static generate(node) {
        switch (node.type) {
            case nodes/* CommentRuleType */.gV.AgentCommentRule:
                return AgentCommentGenerator.generate(node);
            case nodes/* CommentRuleType */.gV.HintCommentRule:
                return HintCommentGenerator.generate(node);
            case nodes/* CommentRuleType */.gV.PreProcessorCommentRule:
                return PreProcessorCommentGenerator.generate(node);
            case nodes/* CommentRuleType */.gV.MetadataCommentRule:
                return MetadataCommentGenerator.generate(node);
            case nodes/* CommentRuleType */.gV.ConfigCommentRule:
                return ConfigCommentGenerator.generate(node);
            case nodes/* CommentRuleType */.gV.CommentRule:
                return SimpleCommentGenerator.generate(node);
            default:
                throw new Error('Unknown comment rule type');
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/adblockers.js
var adblockers = __webpack_require__(88226);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/misc/modifier-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */



/**
 * Generator for modifier nodes.
 */
class ModifierGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Converts a modifier AST node to a string.
     *
     * @param modifier Modifier AST node to convert
     * @returns String representation of the modifier
     */
    static generate(modifier) {
        let result = constants/* EMPTY */.wg;
        if (modifier.exception) {
            result += constants/* NEGATION_MARKER */.bP;
        }
        result += modifier.name.value;
        if (modifier.value !== undefined) {
            result += constants/* MODIFIER_ASSIGN_OPERATOR */.li;
            result += modifier.value.value;
        }
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/misc/modifier-list-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * Generator for modifier list nodes.
 */
class ModifierListGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Converts a modifier list AST to a string.
     *
     * @param ast Modifier list AST
     * @returns Raw string
     */
    static generate(ast) {
        const result = ast.children
            .map(ModifierGenerator.generate)
            .join(constants/* MODIFIERS_SEPARATOR */.b9);
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/misc/list-items-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * Utility class for generating string representations of list items.
 */
class ListItemsGenerator {
    /**
     * Generates a string representation of a list item.
     *
     * @param item List item to generate.
     * @template T Type of the list item.
     *
     * @returns String representation of the list item.
     */
    static generateListItem = (item) => {
        return `${item.exception ? constants/* NEGATION_MARKER */.bP : constants/* EMPTY */.wg}${item.value}`;
    };
    /**
     * Generates a string representation of a list of items.
     *
     * @param items List of items to generate.
     * @param separator Separator character.
     * @template T Type of the list items.
     *
     * @returns String representation of the list of items.
     */
    static generate = (items, separator) => {
        return items.map(ListItemsGenerator.generateListItem)
            .join(separator);
    };
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/misc/domain-list-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */



/**
 * Domain list generator.
 */
class DomainListGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Converts a domain list node to a string.
     *
     * @param node Domain list node.
     *
     * @returns Raw string.
     */
    static generate(node) {
        return ListItemsGenerator.generate(node.children, node.separator);
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/cosmetic/cosmetic-rule-pattern-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */






/**
 * Cosmetic rule pattern generator.
 */
class CosmeticRulePatternGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Generates the rule pattern from the AST.
     *
     * @param node Cosmetic rule node
     * @returns Raw rule pattern
     * @example
     * - '##.foo' → ''
     * - 'example.com,example.org##.foo' → 'example.com,example.org'
     * - '[$path=/foo/bar]example.com##.foo' → '[$path=/foo/bar]example.com'
     */
    static generate(node) {
        let result = constants/* EMPTY */.wg;
        // AdGuard modifiers (if any)
        if (node.syntax === adblockers/* AdblockSyntax */.Y.Adg && node.modifiers && node.modifiers.children.length > 0) {
            result += constants/* OPEN_SQUARE_BRACKET */.cU;
            result += constants/* DOLLAR_SIGN */.nj;
            result += ModifierListGenerator.generate(node.modifiers);
            result += constants/* CLOSE_SQUARE_BRACKET */.A1;
        }
        // Domain list (if any)
        result += DomainListGenerator.generate(node.domains);
        return result;
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/cosmetic/cosmetic-rule-body-generator.js + 4 modules
var cosmetic_rule_body_generator = __webpack_require__(98442);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/cosmetic/cosmetic-rule-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */






/**
 * `CosmeticRuleGenerator` is responsible for generating cosmetic rules from their AST representation.
 *
 * This class takes a parsed cosmetic rule Abstract Syntax Tree (AST) and converts it back into a raw string format.
 * It handles the generation of the pattern, separator, uBO rule modifiers, and the rule body.
 */
class CosmeticRuleGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Converts a cosmetic rule AST into a string.
     *
     * @param node Cosmetic rule AST
     * @returns Raw string
     */
    static generate(node) {
        let result = constants/* EMPTY */.wg;
        // Pattern
        result += CosmeticRulePatternGenerator.generate(node);
        // Separator
        result += node.separator.value;
        // uBO rule modifiers
        if (node.syntax === adblockers/* AdblockSyntax */.Y.Ubo && node.modifiers) {
            node.modifiers.children.forEach((modifier) => {
                if (modifier.exception) {
                    result += constants/* COLON */.oH;
                    result += constants/* CSS_NOT_PSEUDO */.vr;
                    result += constants/* OPEN_PARENTHESIS */.Cx;
                }
                result += constants/* COLON */.oH;
                result += modifier.name.value;
                if (modifier.value) {
                    result += constants/* OPEN_PARENTHESIS */.Cx;
                    result += modifier.value.value;
                    result += constants/* CLOSE_PARENTHESIS */.s1;
                }
                if (modifier.exception) {
                    result += constants/* CLOSE_PARENTHESIS */.s1;
                }
            });
            // If there are at least one modifier, add a space
            if (node.modifiers.children.some((modifier) => modifier?.name.value)) {
                result += constants/* SPACE */.t6;
            }
        }
        // Body
        result += cosmetic_rule_body_generator/* CosmeticRuleBodyGenerator */.H.generate(node);
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/network/host-rule-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */



/**
 * Generator for host rule nodes.
 */
class HostRuleGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Converts a host rule node to a raw string.
     *
     * @param node Host rule node.
     * @returns Raw string.
     */
    static generate(node) {
        const result = [];
        if (node.ip) {
            result.push(node.ip.value);
        }
        if (node.hostnames) {
            result.push(constants/* SPACE */.t6);
            result.push(node.hostnames.children.map(({ value }) => value).join(constants/* SPACE */.t6));
        }
        if (node.comment) {
            result.push(constants/* SPACE */.t6);
            result.push(constants/* HASHMARK */.C);
            result.push(constants/* SPACE */.t6);
            result.push(node.comment.value);
        }
        return result.join(constants/* EMPTY */.wg);
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/network/network-rule-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * Generator for network rule nodes.
 */
class NetworkRuleGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Generates a string from a network rule AST node.
     *
     * @param node Network rule node to generate a string from.
     * @returns Generated string representation of the network rule.
     */
    static generate(node) {
        let result = constants/* EMPTY */.wg;
        // If the rule is an exception, add the exception marker: `@@||example.org`
        if (node.exception) {
            result += constants/* NETWORK_RULE_EXCEPTION_MARKER */.rF;
        }
        // Add the pattern: `||example.org`
        result += node.pattern.value;
        // If there are modifiers, add a separator and the modifiers: `||example.org$important`
        if (node.modifiers && node.modifiers.children.length > 0) {
            result += constants/* NETWORK_RULE_SEPARATOR */.Xj;
            result += ModifierListGenerator.generate(node.modifiers);
        }
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/rule-generator.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */








/**
 * RuleGenerator is responsible for converting adblock rule ASTs to their string representation.
 */
class RuleGenerator extends base_generator/* BaseGenerator */.t {
    /**
     * Converts a rule AST to a string.
     *
     * @param ast - Adblock rule AST
     * @returns Raw string
     * @example
     * Take a look at the following example:
     * ```js
     * // Parse the rule to the AST
     * const ast = RuleParser.parse("example.org##.banner");
     * // Generate the rule from the AST
     * const raw = RuleParser.generate(ast);
     * // Print the generated rule
     * console.log(raw); // "example.org##.banner"
     * ```
     */
    static generate(ast) {
        switch (ast.category) {
            // Empty lines
            case nodes/* RuleCategory */.$O.Empty:
                return constants/* EMPTY */.wg;
            // Invalid rules
            case nodes/* RuleCategory */.$O.Invalid:
                return ast.raw;
            // Comment rules
            case nodes/* RuleCategory */.$O.Comment:
                return CommentRuleGenerator.generate(ast);
            // Cosmetic / non-basic rules
            case nodes/* RuleCategory */.$O.Cosmetic:
                return CosmeticRuleGenerator.generate(ast);
            // Network / basic rules
            case nodes/* RuleCategory */.$O.Network:
                switch (ast.type) {
                    case nodes/* NetworkRuleType */.vY.HostRule:
                        return HostRuleGenerator.generate(ast);
                    case nodes/* NetworkRuleType */.vY.NetworkRule:
                        return NetworkRuleGenerator.generate(ast);
                    default:
                        throw new Error('Unknown network rule type');
                }
            default:
                throw new Error('Unknown rule category');
        }
    }
}




/***/ }),

/***/ 72778:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   j: () => (/* binding */ AgentCommentMarshallingMap)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const AgentCommentMarshallingMap = {
    Children: 1,
    Start: 2,
    End: 3,
};




/***/ }),

/***/ 86186:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   h: () => (/* binding */ FREQUENT_AGENTS_DESERIALIZATION_MAP),
/* harmony export */   o: () => (/* binding */ AgentNodeMarshallingMap)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const AgentNodeMarshallingMap = {
    Adblock: 1,
    Version: 2,
    Start: 3,
    End: 4,
};
/**
 * Value map for binary deserialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 */
const FREQUENT_AGENTS_DESERIALIZATION_MAP = new Map([
    // AdGuard
    [0, 'AdGuard'],
    [1, 'ADG'],
    // uBlock Origin
    [2, 'uBlock Origin'],
    [3, 'uBlock'],
    [4, 'uBO'],
    // Adblock Plus
    [5, 'Adblock Plus'],
    [6, 'AdblockPlus'],
    [7, 'ABP'],
    [8, 'AdBlock'],
]);




/***/ }),

/***/ 92687:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   E0: () => (/* binding */ ConfigCommentRuleMarshallingMap),
/* harmony export */   H4: () => (/* binding */ ConfigNodeMarshallingMap),
/* harmony export */   O6: () => (/* binding */ FREQUENT_COMMANDS_SERIALIZATION_MAP)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const ConfigCommentRuleMarshallingMap = {
    Marker: 1,
    Command: 2,
    Params: 3,
    Comment: 4,
    Start: 5,
    End: 6,
};
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const ConfigNodeMarshallingMap = {
    Value: 1,
    Start: 2,
    End: 3,
};
/**
 * Value map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 *
 * @see {@link https://github.com/AdguardTeam/AGLint/blob/master/src/linter/inline-config.ts}
 */
const FREQUENT_COMMANDS_SERIALIZATION_MAP = new Map([
    ['aglint', 0],
    ['aglint-disable', 1],
    ['aglint-enable', 2],
    ['aglint-disable-next-line', 3],
    ['aglint-enable-next-line', 4],
]);




/***/ }),

/***/ 55762:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   r: () => (/* binding */ HintCommentMarshallingMap)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const HintCommentMarshallingMap = {
    Syntax: 1,
    Children: 2,
    Start: 3,
    End: 4,
};




/***/ }),

/***/ 99490:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   EX: () => (/* binding */ FREQUENT_HINTS_SERIALIZATION_MAP),
/* harmony export */   QE: () => (/* binding */ FREQUENT_PLATFORMS_SERIALIZATION_MAP),
/* harmony export */   ae: () => (/* binding */ HintNodeMarshallingMap)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const HintNodeMarshallingMap = {
    Name: 1,
    Params: 2,
    Start: 3,
    End: 4,
};
/**
 * Value map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const FREQUENT_HINTS_SERIALIZATION_MAP = new Map([
    ['NOT_OPTIMIZED', 0],
    ['PLATFORM', 1],
    ['NOT_PLATFORM', 2],
]);
/**
 * Value map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const FREQUENT_PLATFORMS_SERIALIZATION_MAP = new Map([
    ['windows', 0],
    ['mac', 1],
    ['android', 2],
    ['ios', 3],
    ['ext_chromium', 4],
    ['ext_ff', 5],
    ['ext_edge', 6],
    ['ext_opera', 7],
    ['ext_safari', 8],
    ['ext_android_cb', 9],
    ['ext_ublock', 10],
]);




/***/ }),

/***/ 89990:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (/* binding */ MetadataCommentMarshallingMap),
/* harmony export */   l: () => (/* binding */ FREQUENT_HEADERS_DESERIALIZATION_MAP)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const MetadataCommentMarshallingMap = {
    Marker: 1,
    Header: 2,
    Value: 3,
    Start: 4,
    End: 5,
};
/**
 * Value map for binary deserialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 */
const FREQUENT_HEADERS_DESERIALIZATION_MAP = new Map([
    [1, 'Checksum'],
    [2, 'Description'],
    [3, 'Expires'],
    [4, 'Homepage'],
    [5, 'Last Modified'],
    [6, 'LastModified'],
    [7, 'Licence'],
    [8, 'License'],
    [9, 'Time Updated'],
    [10, 'TimeUpdated'],
    [11, 'Version'],
    [12, 'Title'],
]);




/***/ }),

/***/ 20805:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Qz: () => (/* binding */ PreProcessorRuleMarshallingMap),
/* harmony export */   k7: () => (/* binding */ FREQUENT_PARAMS_SERIALIZATION_MAP),
/* harmony export */   u_: () => (/* binding */ FREQUENT_DIRECTIVES_SERIALIZATION_MAP)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const PreProcessorRuleMarshallingMap = {
    Name: 1,
    Params: 2,
    Syntax: 3,
    Start: 4,
    End: 5,
};
/**
 * Value map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 *
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#preprocessor-directives}
 * @see {@link https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#pre-parsing-directives}
 */
const FREQUENT_DIRECTIVES_SERIALIZATION_MAP = new Map([
    ['if', 0],
    ['else', 1],
    ['endif', 2],
    ['include', 3],
    ['safari_cb_affinity', 4],
]);
/**
 * Value map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const FREQUENT_PARAMS_SERIALIZATION_MAP = new Map([
    // safari_cb_affinity parameters
    ['general', 0],
    ['privacy', 1],
    ['social', 2],
    ['security', 3],
    ['other', 4],
    ['custom', 5],
    ['all', 6],
]);




/***/ }),

/***/ 25331:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   i: () => (/* binding */ SimpleCommentMarshallingMap)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const SimpleCommentMarshallingMap = {
    Marker: 1,
    Text: 2,
    Start: 3,
    End: 4,
};




/***/ }),

/***/ 66604:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   T: () => (/* binding */ FREQUENT_ABP_SNIPPET_ARGS_SERIALIZATION_MAP),
/* harmony export */   f: () => (/* binding */ AbpSnippetBodyMarshallingMap)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const AbpSnippetBodyMarshallingMap = {
    Children: 1,
    Start: 2,
    End: 3,
};
/**
 * Value map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
// TODO: Update this map with the actual values
const FREQUENT_ABP_SNIPPET_ARGS_SERIALIZATION_MAP = new Map([
    ['abort-current-inline-script', 0],
    ['abort-on-property-read', 1],
    ['abort-on-property-write', 2],
    ['json-prune', 3],
    ['log', 4],
    ['prevent-listener', 5],
    ['cookie-remover', 6],
    ['override-property-read', 7],
    ['abort-on-iframe-property-read', 8],
    ['abort-on-iframe-property-write', 9],
    ['freeze-element', 10],
    ['json-override', 11],
    ['simulate-mouse-event', 12],
    ['strip-fetch-query-parameter', 13],
    ['hide-if-contains', 14],
    ['hide-if-contains-image', 15],
    ['hide-if-contains-image-hash', 16],
    ['hide-if-contains-similar-text', 17],
    ['hide-if-contains-visible-text', 18],
    ['hide-if-contains-and-matches-style', 19],
    ['hide-if-graph-matches', 20],
    ['hide-if-has-and-matches-style', 21],
    ['hide-if-labelled-by', 22],
    ['hide-if-matches-xpath', 23],
    ['hide-if-matches-computed-xpath', 24],
    ['hide-if-shadow-contains', 25],
    ['debug', 26],
    ['trace', 27],
    ['race', 28],
]);




/***/ }),

/***/ 56874:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   T: () => (/* binding */ FREQUENT_ADG_SCRIPTLET_ARGS_SERIALIZATION_MAP)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Value map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
// TODO: Update this map with the actual values
const FREQUENT_ADG_SCRIPTLET_ARGS_SERIALIZATION_MAP = new Map([
    ['abort-current-inline-script', 0],
    ['abort-on-property-read', 1],
    ['abort-on-property-write', 2],
    ['abort-on-stack-trace', 3],
    ['adjust-setInterval', 4],
    ['adjust-setTimeout', 5],
    ['close-window', 6],
    ['debug-current-inline-script', 7],
    ['debug-on-property-read', 8],
    ['debug-on-property-write', 9],
    ['dir-string', 10],
    ['disable-newtab-links', 11],
    ['evaldata-prune', 12],
    ['json-prune', 13],
    ['log', 14],
    ['log-addEventListener', 15],
    ['log-eval', 16],
    ['log-on-stack-trace', 17],
    ['m3u-prune', 18],
    ['noeval', 19],
    ['nowebrtc', 20],
    ['no-topics', 21],
    ['prevent-addEventListener', 22],
    ['prevent-adfly', 23],
    ['prevent-bab', 24],
    ['prevent-eval-if', 25],
    ['prevent-fab-3.2.0', 26],
    ['prevent-fetch', 27],
    ['prevent-xhr', 28],
    ['prevent-popads-net', 29],
    ['prevent-refresh', 30],
    ['prevent-requestAnimationFrame', 31],
    ['prevent-setInterval', 32],
    ['prevent-setTimeout', 33],
    ['prevent-window-open', 34],
    ['remove-attr', 35],
    ['remove-class', 36],
    ['remove-cookie', 37],
    ['remove-node-text', 38],
    ['set-attr', 39],
    ['set-constant', 40],
    ['set-cookie', 41],
    ['set-cookie-reload', 42],
    ['set-local-storage-item', 43],
    ['set-popads-dummy', 44],
    ['set-session-storage-item', 45],
    ['xml-prune', 46],
]);




/***/ }),

/***/ 52002:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   V: () => (/* binding */ CssInjectionRuleMarshallingMap)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const CssInjectionRuleMarshallingMap = {
    SelectorList: 1,
    DeclarationList: 2,
    MediaQueryList: 3,
    Remove: 4,
    Start: 5,
    End: 6,
};




/***/ }),

/***/ 69803:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   G: () => (/* binding */ ElementHidingRuleMarshallingMap)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}
 *
 * @note Only 256 values can be represented this way.
 */
const ElementHidingRuleMarshallingMap = {
    SelectorList: 1,
    Start: 2,
    End: 3,
};




/***/ }),

/***/ 62224:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (/* binding */ FREQUENT_UBO_SCRIPTLET_ARGS_SERIALIZATION_MAP)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Value map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
// TODO: Update this map with the actual values
const FREQUENT_UBO_SCRIPTLET_ARGS_SERIALIZATION_MAP = new Map([
    ['abort-current-script.js', 0],
    ['acs.js', 1],
    ['abort-current-inline-script.js', 2],
    ['acis.js', 3],
    ['abort-on-property-read.js', 4],
    ['aopr.js', 5],
    ['abort-on-property-write.js', 6],
    ['aopw.js', 7],
    ['abort-on-stack-trace.js', 8],
    ['aost.js', 9],
    ['adjust-setInterval.js', 10],
    ['nano-setInterval-booster.js', 11],
    ['nano-sib.js', 12],
    ['adjust-setTimeout.js', 13],
    ['nano-setTimeout-booster.js', 14],
    ['nano-stb.js', 15],
    ['close-window.js', 16],
    ['window-close-if.js', 17],
    ['disable-newtab-links.js', 18],
    ['evaldata-prune.js', 19],
    ['json-prune.js', 20],
    ['addEventListener-logger.js', 21],
    ['aell.js', 22],
    ['m3u-prune.js', 23],
    ['nowebrtc.js', 24],
    ['addEventListener-defuser.js', 25],
    ['aeld.js', 26],
    ['prevent-addEventListener.js', 27],
    ['adfly-defuser.js', 28],
    ['noeval-if.js', 29],
    ['prevent-eval-if.js', 30],
    ['no-fetch-if.js', 31],
    ['prevent-fetch.js', 32],
    ['no-xhr-if.js', 33],
    ['prevent-xhr.js', 34],
    ['prevent-refresh.js', 35],
    ['refresh-defuser.js', 36],
    ['no-requestAnimationFrame-if.js', 37],
    ['norafif.js', 38],
    ['prevent-requestAnimationFrame.js', 39],
    ['no-setInterval-if.js', 40],
    ['nosiif.js', 41],
    ['prevent-setInterval.js', 42],
    ['setInterval-defuser.js', 43],
    ['no-setTimeout-if.js', 44],
    ['nostif.js', 45],
    ['prevent-setTimeout.js', 46],
    ['setTimeout-defuser.js', 47],
    ['no-window-open-if.js', 48],
    ['nowoif.js', 49],
    ['prevent-window-open.js', 50],
    ['window.open-defuser.js', 51],
    ['remove-attr.js', 52],
    ['ra.js', 53],
    ['remove-class.js', 54],
    ['rc.js', 55],
    ['remove-cookie.js', 56],
    ['cookie-remover.js', 57],
    ['remove-node-text.js', 58],
    ['rmnt.js', 59],
    ['set-attr.js', 60],
    ['set-constant.js', 61],
    ['set.js', 62],
    ['set-cookie.js', 63],
    ['set-local-storage-item.js', 64],
    ['set-session-storage-item.js', 65],
    ['xml-prune.js', 66],
    ['webrtc-if.js', 67],
    ['overlay-buster.js', 68],
    ['alert-buster.js', 69],
    ['golem.de.js', 70],
    ['href-sanitizer.js', 71],
    ['call-nothrow.js', 72],
    ['window.name-defuser.js', 73],
    ['spoof-css.js', 74],
    ['trusted-set-constant.js', 75],
    ['trusted-set.js', 76],
    ['trusted-set-cookie.js', 77],
    ['trusted-set-local-storage-item.js', 78],
    ['trusted-replace-fetch-response.js', 79],
    ['json-prune-fetch-response.js', 80],
    ['json-prune-xhr-response.js', 81],
    ['trusted-replace-xhr-response.js', 82],
    ['multiup.js', 83],
    ['prevent-canvas.js', 84],
    ['set-cookie-reload.js', 85],
    ['trusted-set-cookie-reload.js', 86],
    ['trusted-click-element.js', 87],
    ['trusted-prune-inbound-object.js', 88],
    ['trusted-prune-outbound-object.js', 89],
    ['trusted-set-session-storage-item.js', 90],
    ['trusted-replace-node-text.js', 91],
    ['trusted-rpnt.js', 92],
    ['replace-node-text.js', 93],
    ['rpnt.js', 94],
]);




/***/ }),

/***/ 42983:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   U: () => (/* binding */ CosmeticRuleMarshallingMap),
/* harmony export */   h: () => (/* binding */ COSMETIC_RULE_SEPARATOR_SERIALIZATION_MAP)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const CosmeticRuleMarshallingMap = {
    Exception: 2,
    Separator: 3,
    Modifiers: 4,
    Domains: 5,
    Start: 7,
    End: 8,
};
/**
 * Value map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const COSMETIC_RULE_SEPARATOR_SERIALIZATION_MAP = new Map([
    ['##', 0],
    ['#@#', 1],
    ['#?#', 2],
    ['#@?#', 3],
    ['#$#', 4],
    ['#$?#', 5],
    ['#@$#', 6],
    ['#@$?#', 7],
    ['#%#', 8],
    ['#@%#', 9],
    ['$$', 10],
    ['$@$', 11],
]);




/***/ }),

/***/ 27813:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   K: () => (/* binding */ EmptyRuleMarshallingMap)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const EmptyRuleMarshallingMap = {
    Start: 1,
    End: 2,
};




/***/ }),

/***/ 51175:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   W: () => (/* binding */ InvalidRuleMarshallingMap)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!!
 *
 * @note Only 256 values can be represented this way.
 */
const InvalidRuleMarshallingMap = {
    Error: 1,
    Start: 2,
    End: 3,
};




/***/ }),

/***/ 6229:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   K: () => (/* binding */ InvalidRuleErrorNodeMarshallingMap)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const InvalidRuleErrorNodeMarshallingMap = {
    Name: 1,
    Message: 2,
    Start: 3,
    End: 4,
};




/***/ }),

/***/ 16318:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   u: () => (/* binding */ BinaryTypeMarshallingMap)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Type map for binary serialization.
 *
 * @note Values should be fit into 8 bits.
 */
const BinaryTypeMarshallingMap = {
    // Basic types
    Null: 1,
    // AGTree nodes
    FilterListNode: 8,
    EmptyRule: 9,
    InvalidRule: 10,
    CommentRuleNode: 11,
    AgentNode: 12,
    AgentRuleNode: 13,
    HintNode: 14,
    HintRuleNode: 15,
    MetadataCommentRuleNode: 16,
    ConfigCommentRuleNode: 17,
    PreProcessorCommentRuleNode: 18,
    ConfigNode: 19,
    NetworkRuleNode: 20,
    HostRuleNode: 21,
    ElementHidingRule: 22,
    CssInjectionRule: 23,
    ScriptletInjectionRule: 24,
    JsInjectionRule: 25,
    HtmlFilteringRule: 26,
    ScriptletInjectionRuleBodyNode: 27,
    ElementHidingRuleBody: 28,
    CssInjectionRuleBody: 29,
    ValueNode: 32,
    ModifierNode: 34,
    ModifierListNode: 35,
    ParameterListNode: 36,
    DomainListNode: 37,
    DomainNode: 38,
    MethodNode: 40,
    StealthOptionNode: 42,
    AppNode: 44,
    HostnameListNode: 45,
    InvalidRuleErrorNode: 46,
    ExpressionVariableNode: 47,
    ExpressionOperatorNode: 48,
    ExpressionParenthesisNode: 49,
};




/***/ }),

/***/ 44859:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   T: () => (/* binding */ DomainListMarshallingMap),
/* harmony export */   _: () => (/* binding */ SEPARATOR_SERIALIZATION_MAP)
/* harmony export */ });
/* harmony import */ var _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(65523);
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const DomainListMarshallingMap = {
    Separator: 1,
    Children: 2,
    Start: 3,
    End: 4,
};
/**
 * Value map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const SEPARATOR_SERIALIZATION_MAP = new Map([
    [_utils_constants_js__WEBPACK_IMPORTED_MODULE_0__/* .COMMA */ .KE, 0],
    [_utils_constants_js__WEBPACK_IMPORTED_MODULE_0__/* .PIPE */ .L5, 1],
]);




/***/ }),

/***/ 41351:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   J: () => (/* binding */ HostRuleMarshallingMap)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const HostRuleMarshallingMap = {
    Syntax: 1,
    Ip: 3,
    HostnameList: 4,
    Comment: 5,
    Start: 6,
    End: 7,
};




/***/ }),

/***/ 89410:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   W: () => (/* binding */ HostnameListNodeMarshallingMap)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const HostnameListNodeMarshallingMap = {
    Children: 1,
    Start: 2,
    End: 3,
};




/***/ }),

/***/ 80486:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   i: () => (/* binding */ ListItemMarshallingMap)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const ListItemMarshallingMap = {
    Exception: 1,
    Value: 2,
    Start: 3,
    End: 4,
};




/***/ }),

/***/ 11128:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Tf: () => (/* binding */ VariableNodeBinaryPropMarshallingMap),
/* harmony export */   Y5: () => (/* binding */ KNOWN_VARIABLES_SERIALIZATION_MAP),
/* harmony export */   hc: () => (/* binding */ OperatorNodeBinaryPropMarshallingMap),
/* harmony export */   td: () => (/* binding */ LOGICAL_EXPRESSION_OPERATOR_SERIALISATION_MAP),
/* harmony export */   z0: () => (/* binding */ ParenthesisNodeBinaryPropMarshallingMap)
/* harmony export */ });
/* harmony import */ var _nodes_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(64638);
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * Property map for binary serialization.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION} !
 */
const VariableNodeBinaryPropMarshallingMap = {
    Name: 1,
    FrequentName: 2,
    Start: 3,
    End: 4,
};
/**
 * Property map for binary serialization.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION} !
 */
const OperatorNodeBinaryPropMarshallingMap = {
    Operator: 1,
    Left: 2,
    Right: 3,
    Start: 4,
    End: 5,
};
/**
 * Property map for binary serialization.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION} !
 */
const ParenthesisNodeBinaryPropMarshallingMap = {
    Expression: 1,
    Start: 2,
    End: 3,
};
/**
 * Property map for binary serialization.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION} !
 */
const LOGICAL_EXPRESSION_OPERATOR_SERIALISATION_MAP = new Map([
    [_nodes_index_js__WEBPACK_IMPORTED_MODULE_0__/* .OperatorValue */ .oC.Not, 0],
    [_nodes_index_js__WEBPACK_IMPORTED_MODULE_0__/* .OperatorValue */ .oC.And, 1],
    [_nodes_index_js__WEBPACK_IMPORTED_MODULE_0__/* .OperatorValue */ .oC.Or, 2],
]);
/**
 * Serialization map for known variables.
 */
const KNOWN_VARIABLES_SERIALIZATION_MAP = new Map([
    ['ext_abp', 0],
    ['ext_ublock', 1],
    ['ext_ubol', 2],
    ['ext_devbuild', 3],
    ['env_chromium', 4],
    ['env_edge', 5],
    ['env_firefox', 6],
    ['env_mobile', 7],
    ['env_safari', 8],
    ['env_mv3', 9],
    ['false', 10],
    ['cap_html_filtering', 11],
    ['cap_user_stylesheet', 12],
    ['adguard', 13],
    ['adguard_app_windows', 14],
    ['adguard_app_mac', 15],
    ['adguard_app_android', 16],
    ['adguard_app_ios', 17],
    ['adguard_ext_safari', 18],
    ['adguard_ext_chromium', 19],
    ['adguard_ext_firefox', 20],
    ['adguard_ext_edge', 21],
    ['adguard_ext_opera', 22],
    ['adguard_ext_android_cb', 23],
    // TODO: Add 'adguard_ext_chromium_mv3' to the list
]);




/***/ }),

/***/ 14299:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   sD: () => (/* binding */ ModifierNodeMarshallingMap),
/* harmony export */   uu: () => (/* binding */ FREQUENT_MODIFIERS_SERIALIZATION_MAP),
/* harmony export */   vG: () => (/* binding */ FREQUENT_REDIRECT_MODIFIERS_SERIALIZATION_MAP)
/* harmony export */ });
/* unused harmony export FREQUENT_REDIRECT_VALUES_SERIALIZATION_MAP */
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const ModifierNodeMarshallingMap = {
    Name: 1,
    Value: 2,
    Exception: 3,
    Start: 4,
    End: 5,
};
/**
 * Value map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const FREQUENT_MODIFIERS_SERIALIZATION_MAP = new Map([
    ['_', 0],
    ['all', 1],
    ['app', 2],
    ['badfilter', 3],
    ['cname', 4],
    ['content', 5],
    ['cookie', 6],
    ['csp', 7],
    ['denyallow', 8],
    ['document', 9],
    ['doc', 10],
    ['domain', 11],
    ['from', 12],
    ['elemhide', 13],
    ['ehide', 14],
    ['empty', 15],
    ['first-party', 16],
    ['1p', 17],
    ['extension', 18],
    ['font', 19],
    ['genericblock', 20],
    ['generichide', 21],
    ['ghide', 22],
    ['header', 23],
    ['hls', 24],
    ['image', 25],
    ['important', 26],
    ['inline-font', 27],
    ['inline-script', 28],
    ['jsinject', 29],
    ['jsonprune', 30],
    ['match-case', 31],
    ['media', 32],
    ['method', 33],
    ['mp4', 34],
    ['network', 35],
    ['object-subrequest', 36],
    ['object', 37],
    ['other', 38],
    ['permissions', 39],
    ['ping', 40],
    ['popunder', 41],
    ['popup', 42],
    ['redirect-rule', 43],
    ['redirect', 44],
    ['rewrite', 45],
    ['referrerpolicy', 46],
    ['removeheader', 47],
    ['removeparam', 48],
    ['replace', 49],
    ['script', 50],
    ['specifichide', 51],
    ['shide', 52],
    ['stealth', 53],
    ['strict1p', 54],
    ['strict3p', 55],
    ['stylesheet', 56],
    ['css', 57],
    ['subdocument', 58],
    ['frame', 59],
    ['third-party', 60],
    ['3p', 61],
    ['to', 62],
    ['urlblock', 63],
    ['webrtc', 64],
    ['websocket', 65],
    ['xmlhttprequest', 66],
    ['xhr', 67],
    // TODO: add new modifiers here
]);
/**
 * Value map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 *
 * ! IMPORTANT: If you change values here, please update the binary schema version
 *
 * @note Only 256 values can be represented this way.
 */
const FREQUENT_REDIRECT_VALUES_SERIALIZATION_MAP = new Map([
    // AdGuard
    ['1x1-transparent.gif', 0],
    ['2x2-transparent.png', 1],
    ['3x2-transparent.png', 2],
    ['32x32-transparent.png', 3],
    ['amazon-apstag', 4],
    ['ati-smarttag', 5],
    ['didomi-loader', 6],
    ['click2load.html', 7],
    ['fingerprintjs2', 8],
    ['fingerprintjs3', 9],
    ['google-analytics', 10],
    ['google-analytics-ga', 11],
    ['googlesyndication-adsbygoogle', 12],
    ['googlesyndication-adsbygoogle', 13],
    ['googletagmanager-gtm', 14],
    ['googletagmanager-gtm', 15],
    ['googletagservices-gpt', 16],
    ['google-ima3', 17],
    ['gemius', 18],
    ['matomo', 19],
    ['metrika-yandex-watch', 20],
    ['metrika-yandex-tag', 21],
    ['naver-wcslog', 22],
    ['noeval', 23],
    ['noopcss', 24],
    ['noopframe', 25],
    ['noopjs', 26],
    ['noopjson', 27],
    ['nooptext', 28],
    ['noopmp3-0.1s', 29],
    ['noopmp4-1s', 30],
    ['noopvmap-1.0', 31],
    ['noopvast-2.0', 32],
    ['noopvast-3.0', 33],
    ['noopvast-4.0', 34],
    ['prebid', 35],
    ['pardot-1.0', 36],
    ['prevent-bab', 37],
    ['prevent-bab2', 38],
    ['prevent-fab-3.2.0', 39],
    ['prevent-fab-3.2.0', 40],
    ['prevent-popads-net', 41],
    ['scorecardresearch-beacon', 42],
    ['set-popads-dummy', 43],
    ['empty', 44],
    ['prebid-ads', 45],
    // empty slots for future use
    // uBlock Origin
    ['1x1.gif', 60],
    ['2x2.png', 61],
    ['3x2.png', 62],
    ['32x32.png', 63],
    ['amazon_apstag.js', 64],
    ['click2load.html', 65],
    ['fingerprint2.js', 66],
    ['fingerprint3.js', 67],
    ['google-analytics_analytics.js', 68],
    ['google-analytics_ga.js', 69],
    ['googlesyndication_adsbygoogle.js', 70],
    ['googlesyndication.com/adsbygoogle.js', 71],
    ['google-analytics_ga.js', 72],
    ['googletagmanager_gtm.js', 73],
    ['googletagservices_gpt.js', 74],
    ['google-ima.js', 75],
    ['noeval-silent.js', 76],
    ['noop.css', 77],
    ['noop.html', 78],
    ['noop.js', 79],
    ['noop.json', 80],
    ['noop.txt', 81],
    ['noop-0.1s.mp3', 82],
    ['noop-1s.mp4', 83],
    ['noop-vmap1.0.xml', 84],
    ['nobab.js', 85],
    ['nobab2.js', 86],
    ['nofab.js', 87],
    ['fuckadblock.js-3.2.0', 88],
    ['popads.js', 89],
    ['scorecardresearch_beacon.js', 90],
    ['popads-dummy.js', 91],
    ['empty', 92],
    ['prebid-ads.js', 93],
    // empty slots for future use
    // Adblock Plus
    ['1x1-transparent-gif', 105],
    ['2x2-transparent-png', 106],
    ['3x2-transparent-png', 107],
    ['32x32-transparent-png', 108],
    ['blank-css', 109],
    ['blank-html', 110],
    ['blank-js', 111],
    ['blank-text', 112],
    ['blank-mp3', 113],
    ['blank-mp4', 114],
    // empty slots for future use
    ['abp-resource:1x1-transparent-gif', 120],
    ['abp-resource:2x2-transparent-png', 121],
    ['abp-resource:3x2-transparent-png', 122],
    ['abp-resource:32x32-transparent-png', 123],
    ['abp-resource:blank-css', 124],
    ['abp-resource:blank-html', 125],
    ['abp-resource:blank-js', 126],
    ['abp-resource:blank-text', 127],
    ['abp-resource:blank-mp3', 128],
    ['abp-resource:blank-mp4', 129],
    // TODO: add other common values
]);
/**
 * Value map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 *
 * @note This is a special map which allows us to use different value maps for different modifiers.
 */
const FREQUENT_REDIRECT_MODIFIERS_SERIALIZATION_MAP = new Map([
    ['redirect', FREQUENT_REDIRECT_VALUES_SERIALIZATION_MAP],
    ['redirect-rule', FREQUENT_REDIRECT_VALUES_SERIALIZATION_MAP],
    ['rewrite', FREQUENT_REDIRECT_VALUES_SERIALIZATION_MAP],
    // TODO: Add other modifiers here
]);




/***/ }),

/***/ 92006:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   I: () => (/* binding */ ModifierListNodeMarshallingMap)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const ModifierListNodeMarshallingMap = {
    Children: 1,
    Start: 2,
    End: 3,
};




/***/ }),

/***/ 12974:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   _: () => (/* binding */ ParameterListNodeMarshallingMap)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const ParameterListNodeMarshallingMap = {
    Children: 1,
    Start: 2,
    End: 3,
};




/***/ }),

/***/ 34097:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   e: () => (/* binding */ ValueNodeMarshallingMap)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const ValueNodeMarshallingMap = {
    Value: 1,
    FrequentValue: 2,
    Start: 3,
    End: 4,
};




/***/ }),

/***/ 49459:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   v: () => (/* binding */ NetworkRuleMarshallingMap)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Property map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent a property.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const NetworkRuleMarshallingMap = {
    Syntax: 1,
    Exception: 3,
    Pattern: 4,
    ModifierList: 5,
    Start: 6,
    End: 7,
};




/***/ }),

/***/ 74252:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   M: () => (/* binding */ getSyntaxSerializationMap)
/* harmony export */ });
/* harmony import */ var _utils_adblockers_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(88226);
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * Value map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
let syntaxSerializationMap;
const getSyntaxSerializationMap = () => {
    if (!syntaxSerializationMap) {
        syntaxSerializationMap = new Map([
            [_utils_adblockers_js__WEBPACK_IMPORTED_MODULE_0__/* .AdblockSyntax */ .Y.Common, 0],
            [_utils_adblockers_js__WEBPACK_IMPORTED_MODULE_0__/* .AdblockSyntax */ .Y.Abp, 1],
            [_utils_adblockers_js__WEBPACK_IMPORTED_MODULE_0__/* .AdblockSyntax */ .Y.Adg, 2],
            [_utils_adblockers_js__WEBPACK_IMPORTED_MODULE_0__/* .AdblockSyntax */ .Y.Ubo, 3],
        ]);
    }
    return syntaxSerializationMap;
};




/***/ }),

/***/ 64638:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   $O: () => (/* binding */ RuleCategory),
/* harmony export */   WR: () => (/* binding */ ListItemNodeType),
/* harmony export */   gV: () => (/* binding */ CommentRuleType),
/* harmony export */   h6: () => (/* binding */ ListNodeType),
/* harmony export */   k9: () => (/* binding */ CosmeticRuleType),
/* harmony export */   oC: () => (/* binding */ OperatorValue),
/* harmony export */   p5: () => (/* binding */ CosmeticRuleSeparator),
/* harmony export */   vY: () => (/* binding */ NetworkRuleType),
/* harmony export */   yg: () => (/* binding */ CommentMarker)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
const OperatorValue = {
    Not: '!',
    And: '&&',
    Or: '||',
};
/**
 * Represents the different comment markers that can be used in an adblock rule.
 *
 * @example
 * - If the rule is `! This is just a comment`, then the marker will be `!`.
 * - If the rule is `# This is just a comment`, then the marker will be `#`.
 */
const CommentMarker = {
    /**
     * Regular comment marker. It is supported by all ad blockers.
     */
    Regular: '!',
    /**
     * Hashmark comment marker. It is supported by uBlock Origin and AdGuard,
     * and also used in hosts files.
     */
    Hashmark: '#',
};
/**
 * Represents the main categories that an adblock rule can belong to.
 * Of course, these include additional subcategories.
 */
const RuleCategory = {
    /**
     * Empty "rules" that are only containing whitespaces. These rules are handled just for convenience.
     */
    Empty: 'Empty',
    /**
     * Syntactically invalid rules (tolerant mode only).
     */
    Invalid: 'Invalid',
    /**
     * Comment rules, such as comment rules, metadata rules, preprocessor rules, etc.
     */
    Comment: 'Comment',
    /**
     * Cosmetic rules, such as element hiding rules, CSS rules, scriptlet rules, HTML rules, and JS rules.
     */
    Cosmetic: 'Cosmetic',
    /**
     * Network rules, such as basic network rules, header remover network rules, redirect network rules,
     * response header filtering rules, etc.
     */
    Network: 'Network',
};
/**
 * Represents similar types of modifiers values
 * which may be separated by a comma `,` (only for DomainList) or a pipe `|`.
 */
const ListNodeType = {
    AppList: 'AppList',
    DomainList: 'DomainList',
    MethodList: 'MethodList',
    StealthOptionList: 'StealthOptionList',
};
/**
 * Represents child items for {@link ListNodeType}.
 */
const ListItemNodeType = {
    Unknown: 'Unknown',
    App: 'App',
    Domain: 'Domain',
    Method: 'Method',
    StealthOption: 'StealthOption',
};
/**
 * Represents possible comment types.
 */
const CommentRuleType = {
    AgentCommentRule: 'AgentCommentRule',
    CommentRule: 'CommentRule',
    ConfigCommentRule: 'ConfigCommentRule',
    HintCommentRule: 'HintCommentRule',
    MetadataCommentRule: 'MetadataCommentRule',
    PreProcessorCommentRule: 'PreProcessorCommentRule',
};
/**
 * Represents possible cosmetic rule types.
 */
const CosmeticRuleType = {
    ElementHidingRule: 'ElementHidingRule',
    CssInjectionRule: 'CssInjectionRule',
    ScriptletInjectionRule: 'ScriptletInjectionRule',
    HtmlFilteringRule: 'HtmlFilteringRule',
    JsInjectionRule: 'JsInjectionRule',
};
/**
 * Represents possible cosmetic rule separators.
 */
const CosmeticRuleSeparator = {
    /**
     * @see {@link https://help.eyeo.com/adblockplus/how-to-write-filters#elemhide_basic}
     */
    ElementHiding: '##',
    /**
     * @see {@link https://help.eyeo.com/adblockplus/how-to-write-filters#elemhide_basic}
     */
    ElementHidingException: '#@#',
    /**
     * @see {@link https://help.eyeo.com/adblockplus/how-to-write-filters#elemhide_basic}
     */
    ExtendedElementHiding: '#?#',
    /**
     * @see {@link https://help.eyeo.com/adblockplus/how-to-write-filters#elemhide_basic}
     */
    ExtendedElementHidingException: '#@?#',
    /**
     * @see {@link https://help.eyeo.com/adblockplus/how-to-write-filters#elemhide_basic}
     */
    AbpSnippet: '#$#',
    /**
     * @see {@link https://help.eyeo.com/adblockplus/how-to-write-filters#elemhide_basic}
     */
    AbpSnippetException: '#@$#',
    /**
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#cosmetic-css-rules}
     */
    AdgCssInjection: '#$#',
    /**
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#cosmetic-css-rules}
     */
    AdgCssInjectionException: '#@$#',
    /**
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#cosmetic-css-rules}
     */
    AdgExtendedCssInjection: '#$?#',
    /**
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#cosmetic-css-rules}
     */
    AdgExtendedCssInjectionException: '#@$?#',
    /**
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#scriptlets}
     */
    AdgJsInjection: '#%#',
    /**
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#scriptlets}
     */
    AdgJsInjectionException: '#@%#',
    /**
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#html-filtering-rules}
     */
    AdgHtmlFiltering: '$$',
    /**
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#html-filtering-rules}
     */
    AdgHtmlFilteringException: '$@$',
};
/**
 * Represents the different types of network rules.
 */
const NetworkRuleType = {
    NetworkRule: 'NetworkRule',
    HostRule: 'HostRule',
};




/***/ }),

/***/ 35581:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   V: () => (/* binding */ BaseParser)
/* harmony export */ });
/* harmony import */ var _errors_not_implemented_error_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(65489);
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * @file Base parser class.
 */
/**
 * Base class for parsers. Each parser should extend this class.
 */
class BaseParser {
    /**
     * Parses the input string and returns the AST node.
     *
     * @param input Input string to parse.
     * @param options Parser options, see {@link ParserOptions}.
     * @param baseOffset Base offset. Locations in the AST node will be relative to this offset.
     * @param args Additional, parser-specific arguments, if needed.
     */
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    static parse(input, options, baseOffset, ...args) {
        throw new _errors_not_implemented_error_js__WEBPACK_IMPORTED_MODULE_0__/* .NotImplementedError */ .E();
    }
}




/***/ }),

/***/ 53088:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   FH: () => (/* binding */ REMOVE_VALUE),
/* harmony export */   JX: () => (/* binding */ REMOVE_PROPERTY),
/* harmony export */   Ye: () => (/* binding */ AdgCssInjectionParser)
/* harmony export */ });
/* unused harmony export ERROR_MESSAGES */
/* harmony import */ var _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(25651);
/* harmony import */ var _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(99177);
/* harmony import */ var _utils_constants_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(65523);
/* harmony import */ var _css_token_stream_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(31478);
/* harmony import */ var _options_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(56928);
/* harmony import */ var _base_parser_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(35581);
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/**
 * @file Parser for AdGuard CSS injections.
 */
const REMOVE_PROPERTY = 'remove';
const REMOVE_VALUE = 'true';
const ERROR_MESSAGES = {
    MEDIA_QUERY_LIST_IS_EMPTY: 'Media query list is empty',
    SELECTOR_LIST_IS_EMPTY: 'Selector list is empty',
    DECLARATION_LIST_IS_EMPTY: 'Declaration list is empty',
};
/**
 * Parser for AdGuard CSS injection.
 */
class AdgCssInjectionParser extends _base_parser_js__WEBPACK_IMPORTED_MODULE_1__/* .BaseParser */ .V {
    /**
     * Parses an AdGuard CSS injection.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     *
     * @returns Parsed AdGuard CSS injection {@link CssInjectionRuleBody}.
     * @throws An {@link AdblockSyntaxError} if the selector list is syntactically invalid.
     */
    static parse(raw, options = _options_js__WEBPACK_IMPORTED_MODULE_2__/* .defaultParserOptions */ .n, baseOffset = 0) {
        let mediaQueryList;
        const selectorList = { type: 'Value', value: _utils_constants_js__WEBPACK_IMPORTED_MODULE_3__/* .EMPTY */ .wg };
        const declarationList = { type: 'Value', value: _utils_constants_js__WEBPACK_IMPORTED_MODULE_3__/* .EMPTY */ .wg };
        const stream = new _css_token_stream_js__WEBPACK_IMPORTED_MODULE_4__/* .CssTokenStream */ .d(raw, baseOffset);
        // Skip leading whitespace characters
        stream.skipWhitespace();
        // We have two possible CSS injection formats:
        // 1. @media (media-query-list) { selector list { declarations separated by semicolons } }
        // 2. selector list { declarations separated by semicolons }
        // Handle '@media' case:
        let balanceShift = 0;
        if (stream.getOrFail().type === _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.AtKeyword) {
            // Currently only '@media' is supported, we should throw an error if we encounter anything else,
            // like '@supports' or '@charset', etc.
            stream.expect(_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.AtKeyword, { value: _utils_constants_js__WEBPACK_IMPORTED_MODULE_3__/* .CSS_MEDIA_MARKER */ .Ae, balance: 0 });
            stream.advance();
            // Skip whitespace characters after @media keyword, if any
            // @media (media-query-list) { ...
            //       ↑
            //       └ this one (if any)
            stream.skipWhitespace();
            const mediaQueryListStart = stream.getOrFail().start;
            // Skip everything until we found the opening curly bracket of the declaration block
            // @media media-query-list { ...
            //                         ↑
            //                         └ this one
            let lastNonWsIndex = -1;
            while (!stream.isEof()) {
                const token = stream.getOrFail();
                if (token.type === _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.OpenCurlyBracket && token.balance === 1) {
                    break;
                }
                if (token.type !== _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.Whitespace) {
                    lastNonWsIndex = token.end;
                }
                stream.advance();
            }
            // If the skipped tokens count is 0 without leading and trailing whitespace characters, then the media query
            // list is empty
            if (lastNonWsIndex === -1) {
                throw new _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_5__/* .AdblockSyntaxError */ .q(ERROR_MESSAGES.MEDIA_QUERY_LIST_IS_EMPTY, baseOffset + mediaQueryListStart, baseOffset + raw.length);
            }
            // It is safe to use non-null assertion here, because we have already checked previous tokens.
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            const mediaQueryListEnd = lastNonWsIndex;
            mediaQueryList = {
                type: 'Value',
                value: raw.slice(mediaQueryListStart, mediaQueryListEnd),
            };
            if (options.isLocIncluded) {
                mediaQueryList.start = baseOffset + mediaQueryListStart;
                mediaQueryList.end = baseOffset + mediaQueryListEnd;
            }
            // Next token should be an open curly bracket
            // @media (media-query-list) { ...
            //                           ↑
            //                           └ this one
            stream.expect(_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.OpenCurlyBracket);
            stream.advance();
            // '@media' at-rule wrap increases the balance level by 1 for the rule within the at-rule, because it
            // has its own { ... } block
            balanceShift = 1;
        }
        // Skip leading whitespace before the rule, if any
        // Note: rule = selector list { declarations separated by semicolons }
        stream.skipWhitespace();
        const selectorStart = stream.getOrFail().start;
        // Jump to the opening curly bracket of the declaration block, based on the balance level
        // .selector { padding-top: 10px; padding-bottom: 10px; }
        //           ↑
        //           └ this one
        const { skippedTrimmed: selectorTokensLength } = stream.skipUntilExt(_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.OpenCurlyBracket, balanceShift + 1);
        stream.expect(_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.OpenCurlyBracket);
        // If the skipped tokens count is 0 without leading and trailing whitespace characters, then the selector list
        // is empty
        if (selectorTokensLength === 0) {
            throw new _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_5__/* .AdblockSyntaxError */ .q(ERROR_MESSAGES.SELECTOR_LIST_IS_EMPTY, baseOffset + selectorStart, baseOffset + raw.length);
        }
        // It is safe to use non-null assertion here, because we have already checked previous tokens.
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        const selectorEnd = stream.lookbehindForNonWs().end;
        selectorList.value = raw.slice(selectorStart, selectorEnd);
        if (options.isLocIncluded) {
            selectorList.start = baseOffset + selectorStart;
            selectorList.end = baseOffset + selectorEnd;
        }
        // Jump to the next token after the opening curly bracket of the declaration block
        // .selector { padding-top: 10px; padding-bottom: 10px; }
        //            ↑
        //            └ this one
        stream.advance();
        // Skip whitespace characters after the opening curly bracket of the declaration block, if any
        stream.skipWhitespace();
        // Jump to the closing curly bracket of the declaration block, based on the balance level
        // .selector { padding-top: 10px; padding-bottom: 10px; }
        //                                                      ↑
        //                                                      └ this one
        const declarationsStart = stream.getOrFail().start;
        const declarations = new Set();
        let declarationsEnd = -1;
        let remove = false;
        let lastNonWsIndex = -1;
        while (!stream.isEof()) {
            const token = stream.getOrFail();
            if (token.type === _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.CloseCurlyBracket && stream.getBalance() === balanceShift) {
                declarationsEnd = lastNonWsIndex;
                break;
            }
            if (token.type !== _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.Whitespace) {
                lastNonWsIndex = token.end;
            }
            if (token.type === _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.Ident && stream.lookahead()?.type === _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.Colon) {
                const ident = raw.slice(token.start, token.end);
                declarations.add(ident);
                // Consume ident and colon
                stream.advance();
                stream.advance();
                // only 'remove: true' is allowed
                if (ident === REMOVE_PROPERTY) {
                    // Skip whitespace after colon, if any
                    stream.skipWhitespace();
                    // Next token should be an ident, with value 'true'
                    stream.expect(_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.Ident, { value: REMOVE_VALUE });
                    stream.advance();
                    remove = true;
                }
            }
            else {
                stream.advance();
            }
        }
        if (declarationsEnd === -1) {
            throw new _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_5__/* .AdblockSyntaxError */ .q(ERROR_MESSAGES.DECLARATION_LIST_IS_EMPTY, baseOffset + declarationsStart, baseOffset + raw.length);
        }
        declarationList.value = raw.slice(declarationsStart, declarationsEnd);
        if (options.isLocIncluded) {
            declarationList.start = baseOffset + declarationsStart;
            declarationList.end = baseOffset + declarationsEnd;
        }
        // Eat the close curly bracket of the declaration block
        // .selector { padding-top: 10px; padding-bottom: 10px; }
        //                                                      ↑
        //                                                      └ this one
        stream.expect(_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.CloseCurlyBracket);
        stream.advance();
        // Skip whitespace after the rule, if any
        stream.skipWhitespace();
        // If we have a media query, we should have an extra close curly bracket
        if (balanceShift === 1) {
            stream.expect(_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.CloseCurlyBracket);
            stream.advance();
        }
        const result = {
            type: 'CssInjectionRuleBody',
            selectorList,
            declarationList,
            remove,
        };
        if (options.isLocIncluded) {
            result.start = baseOffset;
            result.end = baseOffset + raw.length;
        }
        if (mediaQueryList) {
            result.mediaQueryList = mediaQueryList;
        }
        return result;
    }
}




/***/ }),

/***/ 31697:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   g: () => (/* binding */ tokenizeFnBalanced),
/* harmony export */   u: () => (/* binding */ tokenizeBalanced)
/* harmony export */ });
/* harmony import */ var _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(25651);
/* harmony import */ var sprintf_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63607);
/* harmony import */ var _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(99177);
/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(87231);
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */





/**
 * @file Tokenizer helpers for balanced pairs.
 */
/**
 * Map of opening tokens to their corresponding closing tokens.
 */
const standardTokenPairs = new Map([
    [_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.Function, _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.CloseParenthesis],
    [_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.OpenParenthesis, _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.CloseParenthesis],
    [_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.OpenSquareBracket, _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.CloseSquareBracket],
    [_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.OpenCurlyBracket, _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.CloseCurlyBracket],
]);
/**
 * Map of opening tokens to their corresponding closing tokens just for function calls. This makes possible a more
 * lightweight and tolerant check for balanced pairs in some cases.
 */
const functionTokenPairs = new Map([
    [_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.Function, _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.CloseParenthesis],
    [_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.OpenParenthesis, _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.CloseParenthesis],
]);
/**
 * Helper function to tokenize and ensure balanced pairs.
 *
 * @param raw Raw CSS string to tokenize
 * @param onToken Callback which will be invoked for each token, extended with a `balance` parameter
 * @param onError Error callback which is called when a parsing error is found (optional)
 * @param functionHandlers Custom function handlers (optional)
 * @param tokenPairs Map of opening tokens to their corresponding closing tokens
 * @throws If the input is not balanced
 * @todo Consider adding a `tolerant` flag if error throwing seems too aggressive in the future
 */
const tokenizeWithBalancedPairs = (raw, onToken, onError = () => { }, functionHandlers, tokenPairs = standardTokenPairs) => {
    const stack = [];
    const values = new Set(tokenPairs.values());
    (0,_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .tokenizeExtended */ .jz)(raw, (type, start, end, props, stop) => {
        if (tokenPairs.has(type)) {
            // If the token is an opening token, push its corresponding closing token to the stack.
            // It is safe to use non-null assertion here, because we have checked that the token exists in the map.
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            stack.push(tokenPairs.get(type));
        }
        else if (values.has(type)) {
            // If the token is a closing token, check if it matches the last opening token, and if so, pop it.
            if (stack[stack.length - 1] === type) {
                stack.pop();
            }
            else {
                throw new _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_2__/* .AdblockSyntaxError */ .q((0,sprintf_js__WEBPACK_IMPORTED_MODULE_1__.sprintf)(_constants_js__WEBPACK_IMPORTED_MODULE_3__/* .ERROR_MESSAGES */ .U.EXPECTED_TOKEN_BUT_GOT, (0,_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .getFormattedTokenName */ .bZ)(stack[stack.length - 1]), (0,_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .getFormattedTokenName */ .bZ)(type)), start, raw.length);
            }
        }
        onToken(type, start, end, props, stack.length, stop);
    }, onError, functionHandlers);
    // If the stack is not empty, then there are some opening tokens that were not closed.
    if (stack.length > 0) {
        throw new _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_2__/* .AdblockSyntaxError */ .q((0,sprintf_js__WEBPACK_IMPORTED_MODULE_1__.sprintf)(_constants_js__WEBPACK_IMPORTED_MODULE_3__/* .ERROR_MESSAGES */ .U.EXPECTED_TOKEN_BUT_GOT, (0,_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .getFormattedTokenName */ .bZ)(stack[stack.length - 1]), _constants_js__WEBPACK_IMPORTED_MODULE_3__/* .END_OF_INPUT */ .F), raw.length - 1, raw.length);
    }
};
/**
 * Tokenize and ensure balanced pairs for standard CSS.
 *
 * @param raw Raw CSS string to tokenize
 * @param onToken Callback which will be invoked for each token, extended with a `balance` parameter
 * @param onError Error callback which is called when a parsing error is found (optional)
 * @param functionHandlers Custom function handlers (optional)
 * @throws If the input is not balanced
 */
const tokenizeBalanced = (raw, onToken, onError = () => { }, functionHandlers) => {
    tokenizeWithBalancedPairs(raw, onToken, onError, functionHandlers);
};
/**
 * Tokenize and ensure balanced pairs for function calls.
 *
 * @param raw Raw CSS string to tokenize
 * @param onToken Callback which will be invoked for each token, extended with a `balance` parameter
 * @param onError Error callback which is called when a parsing error is found (optional)
 * @param functionHandlers Custom function handlers (optional)
 * @throws If the input is not balanced
 */
const tokenizeFnBalanced = (raw, onToken, onError = () => { }, functionHandlers) => {
    tokenizeWithBalancedPairs(raw, onToken, onError, functionHandlers, functionTokenPairs);
};




/***/ }),

/***/ 87231:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   F: () => (/* binding */ END_OF_INPUT),
/* harmony export */   U: () => (/* binding */ ERROR_MESSAGES)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * @file Error messages for CSS token stream and balancer.
 */
const END_OF_INPUT = 'end of input';
const ERROR_MESSAGES = {
    EXPECTED_ANY_TOKEN_BUT_GOT: "Expected a token, but got '%s'",
    EXPECTED_TOKEN_BUT_GOT: "Expected '%s', but got '%s'",
    EXPECTED_TOKEN_WITH_BALANCE_BUT_GOT: "Expected '%s' with balance '%d', but got '%d'",
    EXPECTED_TOKEN_WITH_VALUE_BUT_GOT: "Expected '%s' with value '%s', but got '%s'",
};




/***/ }),

/***/ 31478:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   d: () => (/* binding */ CssTokenStream)
/* harmony export */ });
/* harmony import */ var _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(25651);
/* harmony import */ var sprintf_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63607);
/* harmony import */ var _balancing_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(31697);
/* harmony import */ var _utils_constants_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(65523);
/* harmony import */ var _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(99177);
/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(87231);
/* harmony import */ var _converter_data_css_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(9119);
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */








/**
 * @file CSS token stream.
 */
/**
 * Represents a stream of CSS tokens.
 */
class CssTokenStream {
    /**
     * The tokens in the stream.
     */
    tokens = [];
    /**
     * The source string.
     */
    source = _utils_constants_js__WEBPACK_IMPORTED_MODULE_2__/* .EMPTY */ .wg;
    /**
     * The current index in the stream.
     */
    index = 0;
    /**
     * The base offset of the source string.
     */
    baseOffset;
    /**
     * Initializes a new instance of the TokenStream class.
     *
     * @param source The source string to tokenize.
     * @param baseOffset The base offset of the source string.
     */
    constructor(source, baseOffset = 0) {
        this.source = source;
        // Tokenize the source string with the CSS tokenizer and add balance level to each token.
        // 'onToken' callback is invoked when a token is found in the source string.
        // Passed parameters:
        // - type: type of the token
        // - start: start index of the token
        // - end: end index of the token
        // - props: additional properties of the token, if any (we don't use it here, this is why we use underscore)
        // - balance: balance level of the token
        try {
            (0,_balancing_js__WEBPACK_IMPORTED_MODULE_3__/* .tokenizeBalanced */ .u)(source, (type, start, end, _, balance) => {
                this.tokens.push({
                    type,
                    start,
                    end,
                    balance,
                });
            });
        }
        catch (error) {
            // If the error is an AdblockSyntaxError, adjust the error positions to the base offset
            if (error instanceof _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_4__/* .AdblockSyntaxError */ .q) {
                error.start += baseOffset;
                error.end += baseOffset;
                throw error;
            }
        }
        this.index = 0;
        this.baseOffset = baseOffset;
    }
    /**
     * Gets the number of tokens in the stream.
     *
     * @returns The number of tokens in the stream.
     */
    get length() {
        return this.tokens.length;
    }
    /**
     * Checks if the end of the token stream is reached.
     *
     * @returns True if the end of the stream is reached, otherwise false.
     */
    isEof() {
        return this.index >= this.tokens.length;
    }
    /**
     * Gets the token at the specified index.
     *
     * @param index The index of the token to retrieve.
     * @returns The token at the specified index or undefined if the index is out of bounds.
     */
    get(index = this.index) {
        return this.tokens[index];
    }
    /**
     * Gets the token at the specified index or throws if no token is found at the specified index.
     *
     * @param index The index of the token to retrieve.
     * @returns The token at the specified index or undefined if the index is out of bounds.
     * @throws If no token is found at the specified index.
     */
    getOrFail(index = this.index) {
        const token = this.get(index);
        if (!token) {
            throw new _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_4__/* .AdblockSyntaxError */ .q((0,sprintf_js__WEBPACK_IMPORTED_MODULE_1__.sprintf)(_constants_js__WEBPACK_IMPORTED_MODULE_5__/* .ERROR_MESSAGES */ .U.EXPECTED_ANY_TOKEN_BUT_GOT, _constants_js__WEBPACK_IMPORTED_MODULE_5__/* .END_OF_INPUT */ .F), this.baseOffset + this.source.length - 1, this.baseOffset + this.source.length);
        }
        return token;
    }
    /**
     * Gets the source fragment of the token at the specified index.
     *
     * @param index The index of the token to retrieve the fragment for.
     * @returns The source fragment of the token or an empty string if the index is out of bounds.
     */
    fragment(index = this.index) {
        const token = this.get(index);
        if (token) {
            return this.source.slice(token.start, token.end);
        }
        return _utils_constants_js__WEBPACK_IMPORTED_MODULE_2__/* .EMPTY */ .wg;
    }
    /**
     * Moves the index to the next token and returns it.
     *
     * @returns The next token or undefined if the end of the stream is reached.
     */
    advance() {
        if (this.isEof()) {
            return undefined;
        }
        this.index += 1;
        return this.tokens[this.index];
    }
    /**
     * Looks ahead in the stream without changing the index.
     *
     * @param index The relative index to look ahead to, starting from the current index.
     * @returns The next token or undefined if the end of the stream is reached.
     */
    lookahead(index = 1) {
        return this.tokens[this.index + Math.max(1, index)];
    }
    /**
     * Looks behind in the stream without changing the index.
     *
     * @param index The relative index to look behind to, starting from the current index.
     * @returns The previous token or undefined if the current token is the first in the stream.
     */
    lookbehind(index = 1) {
        if (this.index === 0) {
            return undefined;
        }
        return this.tokens[this.index - Math.max(1, index)];
    }
    /**
     * Looks behind in the stream for the previous non-whitespace token without changing the index.
     *
     * @returns The previous non-whitespace token or undefined if it could not be found.
     */
    lookbehindForNonWs() {
        for (let i = this.index - 1; i >= 0; i -= 1) {
            if (this.tokens[i].type !== _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.Whitespace) {
                return this.tokens[i];
            }
        }
        return undefined;
    }
    /**
     * Skips whitespace tokens in the stream.
     */
    skipWhitespace() {
        while (this.get()?.type === _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.Whitespace) {
            this.index += 1;
        }
    }
    /**
     * Skips tokens until the current balance level is reached.
     *
     * @returns The number of tokens skipped.
     */
    skipUntilBalanced() {
        if (this.isEof()) {
            return 0;
        }
        // It is safe to use ! here, because we check for EOF above
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        const currentBalance = this.get().balance;
        // If the current balance is 0, do nothing
        if (currentBalance === 0) {
            return 0;
        }
        // Otherwise, skip tokens until the balance is the current balance - 1
        let skipped = 0;
        while (!this.isEof() && this.get()?.balance !== currentBalance - 1) {
            this.index += 1;
            skipped += 1;
        }
        return skipped;
    }
    /**
     * Skips tokens until a token with the specified type or the end of the stream is reached.
     *
     * @param type The type of token to skip until.
     * @param balance The balance level of the token to skip until.
     * @returns The number of tokens skipped.
     */
    skipUntil(type, balance) {
        let skipped = 0;
        while (!this.isEof()
            && (this.get()?.type !== type || (balance !== undefined && this.get()?.balance !== balance))) {
            this.index += 1;
            skipped += 1;
        }
        return skipped;
    }
    /**
     * Skips tokens until a token with the specified type or the end of the stream is reached. This is an extended
     * version of skipUntil that also returns the number of tokens skipped without calculating leading and trailing
     * whitespace tokens.
     *
     * @param type The type of token to skip until.
     * @param balance The balance level of the token to skip until.
     * @returns An array containing the number of tokens skipped and the number of tokens skipped without leading and
     * trailing whitespace tokens.
     */
    skipUntilExt(type, balance) {
        let i = this.index;
        let firstNonWsToken = -1; // -1 means no non-whitespace token found yet
        let lastNonWsToken = -1; // -1 means no non-whitespace token found yet
        while (i < this.tokens.length) {
            const currentToken = this.tokens[i];
            if (currentToken.type === _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.Whitespace) {
                i += 1;
                continue;
            }
            else if (currentToken.type === type && currentToken.balance === balance) {
                break;
            }
            if (firstNonWsToken === -1) {
                firstNonWsToken = i;
            }
            lastNonWsToken = i;
            i += 1;
        }
        const skipped = i - this.index;
        this.index = i;
        return {
            skipped,
            // if firstNonWsToken is -1, then lastNonWsToken is also -1
            skippedTrimmed: firstNonWsToken === -1 ? 0 : lastNonWsToken - firstNonWsToken + 1,
        };
    }
    /**
     * Expects that the end of the stream is not reached.
     */
    expectNotEof() {
        if (this.isEof()) {
            throw new _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_4__/* .AdblockSyntaxError */ .q('Unexpected end of input', this.baseOffset + this.source.length - 1, this.baseOffset + this.source.length);
        }
    }
    /**
     * Expects the current token to have a specific type and optional value and balance level.
     *
     * @param type The expected token type.
     * @param data Optional expectation data.
     * @throws If the end of the stream is reached or if the token type or expectation data does not match.
     */
    expect(type, data) {
        const token = this.get();
        if (!token) {
            throw new _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_4__/* .AdblockSyntaxError */ .q((0,sprintf_js__WEBPACK_IMPORTED_MODULE_1__.sprintf)(_constants_js__WEBPACK_IMPORTED_MODULE_5__/* .ERROR_MESSAGES */ .U.EXPECTED_TOKEN_BUT_GOT, (0,_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .getFormattedTokenName */ .bZ)(type), _constants_js__WEBPACK_IMPORTED_MODULE_5__/* .END_OF_INPUT */ .F), this.baseOffset + this.source.length - 1, this.baseOffset + this.source.length);
        }
        if (token.type !== type) {
            throw new _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_4__/* .AdblockSyntaxError */ .q((0,sprintf_js__WEBPACK_IMPORTED_MODULE_1__.sprintf)(_constants_js__WEBPACK_IMPORTED_MODULE_5__/* .ERROR_MESSAGES */ .U.EXPECTED_TOKEN_BUT_GOT, (0,_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .getFormattedTokenName */ .bZ)(type), (0,_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .getFormattedTokenName */ .bZ)(token.type)), this.baseOffset + token.start, this.baseOffset + token.end);
        }
        if (data?.balance !== undefined && token.balance !== data.balance) {
            throw new _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_4__/* .AdblockSyntaxError */ .q((0,sprintf_js__WEBPACK_IMPORTED_MODULE_1__.sprintf)(_constants_js__WEBPACK_IMPORTED_MODULE_5__/* .ERROR_MESSAGES */ .U.EXPECTED_TOKEN_WITH_BALANCE_BUT_GOT, (0,_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .getFormattedTokenName */ .bZ)(type), data.balance, token.balance), this.baseOffset + token.start, this.baseOffset + token.end);
        }
        if (data?.value && this.fragment() !== data.value) {
            throw new _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_4__/* .AdblockSyntaxError */ .q((0,sprintf_js__WEBPACK_IMPORTED_MODULE_1__.sprintf)(_constants_js__WEBPACK_IMPORTED_MODULE_5__/* .ERROR_MESSAGES */ .U.EXPECTED_TOKEN_WITH_VALUE_BUT_GOT, (0,_adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .getFormattedTokenName */ .bZ)(type), data.value, this.fragment()), this.baseOffset + token.start, this.baseOffset + token.end);
        }
    }
    /**
     * Gets the balance level of the token at the specified index.
     *
     * @param index The index of the token to retrieve the balance level for.
     * @returns The balance level of the token or 0 if the index is out of bounds.
     */
    getBalance(index = this.index) {
        return this.tokens[index]?.balance || 0;
    }
    /**
     * Checks whether the token stream contains any Extended CSS elements, such as `:contains()`, etc.
     *
     * @returns `true` if the stream contains any Extended CSS elements, otherwise `false`.
     */
    hasAnySelectorExtendedCssNode() {
        return this.hasAnySelectorExtendedCssNodeInternal(_converter_data_css_js__WEBPACK_IMPORTED_MODULE_6__/* .EXT_CSS_PSEUDO_CLASSES */ .Ss);
    }
    /**
     * Strictly checks whether the token stream contains any Extended CSS elements, such as `:contains()`.
     * Some Extended CSS elements are natively supported by browsers, like `:has()`.
     * This method is used to check for Extended CSS elements that are not natively supported by browsers,
     * this is why it called "strict", because it strictly checks for Extended CSS elements.
     *
     * @returns `true` if the stream contains any Extended CSS elements, otherwise `false`.
     */
    hasAnySelectorExtendedCssNodeStrict() {
        return this.hasAnySelectorExtendedCssNodeInternal(_converter_data_css_js__WEBPACK_IMPORTED_MODULE_6__/* .EXT_CSS_PSEUDO_CLASSES_STRICT */ .ig);
    }
    /**
     * Checks whether the token stream contains any Extended CSS elements, such as `:has()`, `:contains()`, etc.
     *
     * @param pseudos Set of pseudo-classes to check for.
     *
     * @returns `true` if the stream contains any Extended CSS elements, otherwise `false`.
     */
    hasAnySelectorExtendedCssNodeInternal(pseudos) {
        for (let i = 0; i < this.tokens.length; i += 1) {
            const token = this.tokens[i];
            if (token.type === _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.Function) {
                const name = this.source.slice(token.start, token.end - 1); // omit the last parenthesis
                if (pseudos.has(name)) {
                    return true;
                }
            }
            else if (token.type === _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.OpenSquareBracket) {
                let j = i + 1;
                // skip whitespace
                while (j < this.tokens.length && this.tokens[j].type === _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.Whitespace) {
                    j += 1;
                }
                if (j < this.tokens.length && this.tokens[j].type === _adguard_css_tokenizer__WEBPACK_IMPORTED_MODULE_0__/* .TokenType */ .ks.Ident) {
                    const attr = this.source.slice(this.tokens[j].start, this.tokens[j].end);
                    // [-ext-<name>=...] or [-abp-<name>=...]
                    if (attr.startsWith(_converter_data_css_js__WEBPACK_IMPORTED_MODULE_6__/* .LEGACY_EXT_CSS_ATTRIBUTE_PREFIX */ .at) || attr.startsWith(_converter_data_css_js__WEBPACK_IMPORTED_MODULE_6__/* .ABP_EXT_CSS_PREFIX */ .PY)) {
                        return true;
                    }
                }
                // do not check these tokens again
                i = j;
            }
        }
        return false;
    }
}




/***/ }),

/***/ 26571:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  y: () => (/* binding */ DomainListParser)
});

// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/constants.js
var constants = __webpack_require__(65523);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/nodes/index.js
var nodes = __webpack_require__(64638);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/options.js
var parser_options = __webpack_require__(56928);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/base-parser.js
var base_parser = __webpack_require__(35581);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/string.js
var string = __webpack_require__(54857);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/errors/adblock-syntax-error.js
var adblock_syntax_error = __webpack_require__(99177);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/misc/list-items-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */






/**
 * Prefixes for error messages which are used for parsing of value lists.
 */
const LIST_PARSE_ERROR_PREFIX = {
    EMPTY_ITEM: 'Empty value specified in the list',
    NO_MULTIPLE_NEGATION: 'Exception marker cannot be followed by another exception marker',
    NO_SEPARATOR_AFTER_NEGATION: 'Exception marker cannot be followed by a separator',
    NO_SEPARATOR_AT_THE_BEGINNING: 'Value list cannot start with a separator',
    NO_SEPARATOR_AT_THE_END: 'Value list cannot end with a separator',
    NO_WHITESPACE_AFTER_NEGATION: 'Exception marker cannot be followed by whitespace',
};
/**
 * Parser for list items in modifiers.
 */
class ListItemsParser {
    /**
     * Parses a `raw` modifier value which may be represented as a list of items separated by `separator`.
     * Needed for $app, $denyallow, $domain, $method.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @param separator Separator character (default: comma)
     * @param type Type of the list items (default: {@link ListItemNodeType.Domain}).
     * @template T Type of the list items.
     *
     * @returns List of parsed items.
     * @throws An {@link AdblockSyntaxError} if the list is syntactically invalid
     *
     * @example
     * - parses an app list — `com.example.app|Example.exe`
     * - parses a domain list — `example.com,example.org,~example.org` or `example.com|~example.org`
     * - parses a method list — `~post|~put`
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0, separator = constants/* COMMA */.KE, type = nodes/* ListItemNodeType */.WR.Unknown) {
        // Function body here
        const rawListItems = [];
        let offset = 0;
        // Skip whitespace before the list
        offset = string/* StringUtils */.$x.skipWS(raw, offset);
        // If the first character is a separator, then the list is invalid
        // and no need to continue parsing
        if (raw[offset] === separator) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q(LIST_PARSE_ERROR_PREFIX.NO_SEPARATOR_AT_THE_BEGINNING, baseOffset + offset, baseOffset + raw.length);
        }
        // If the last character is a separator, then the list item is invalid
        // and no need to continue parsing
        const realEndIndex = string/* StringUtils */.$x.skipWSBack(raw);
        if (raw[realEndIndex] === separator) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q(LIST_PARSE_ERROR_PREFIX.NO_SEPARATOR_AT_THE_END, baseOffset + realEndIndex, baseOffset + realEndIndex + 1);
        }
        // Split list items by unescaped separators
        while (offset < raw.length) {
            // Skip whitespace before the list item
            offset = string/* StringUtils */.$x.skipWS(raw, offset);
            let itemStart = offset;
            // Find the index of the first unescaped separator character
            const separatorStartIndex = string/* StringUtils */.$x.findNextUnescapedCharacter(raw, separator, offset);
            const itemEnd = separatorStartIndex === -1
                ? string/* StringUtils */.$x.skipWSBack(raw) + 1
                : string/* StringUtils */.$x.skipWSBack(raw, separatorStartIndex - 1) + 1;
            const exception = raw[itemStart] === constants/* NEGATION_MARKER */.bP;
            // Skip the exception marker
            if (exception) {
                itemStart += 1;
                const item = raw[itemStart];
                // Exception marker cannot be followed by another exception marker
                if (item === constants/* NEGATION_MARKER */.bP) {
                    throw new adblock_syntax_error/* AdblockSyntaxError */.q(LIST_PARSE_ERROR_PREFIX.NO_MULTIPLE_NEGATION, baseOffset + itemStart, baseOffset + itemStart + 1);
                }
                // Exception marker cannot be followed by a separator
                if (item === separator) {
                    throw new adblock_syntax_error/* AdblockSyntaxError */.q(LIST_PARSE_ERROR_PREFIX.NO_SEPARATOR_AFTER_NEGATION, baseOffset + itemStart, baseOffset + itemStart + 1);
                }
                // Exception marker cannot be followed by whitespace
                if (string/* StringUtils */.$x.isWhitespace(item)) {
                    throw new adblock_syntax_error/* AdblockSyntaxError */.q(LIST_PARSE_ERROR_PREFIX.NO_WHITESPACE_AFTER_NEGATION, baseOffset + itemStart, baseOffset + itemStart + 1);
                }
            }
            // List item can't be empty
            // Note we use '<=' instead of '===' because we have bidirectional trim
            // This is needed to handle cases like 'example.com, ,example.org'
            if (itemEnd <= itemStart) {
                throw new adblock_syntax_error/* AdblockSyntaxError */.q(LIST_PARSE_ERROR_PREFIX.EMPTY_ITEM, baseOffset + itemStart, baseOffset + raw.length);
            }
            const listItem = {
                type,
                value: raw.slice(itemStart, itemEnd),
                exception,
            };
            if (options.isLocIncluded) {
                listItem.start = baseOffset + itemStart;
                listItem.end = baseOffset + itemEnd;
            }
            // Collect list item
            rawListItems.push(listItem);
            // Increment the offset to the next list item (or the end of the string)
            offset = separatorStartIndex === -1 ? raw.length : separatorStartIndex + 1;
        }
        return rawListItems;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/misc/domain-list-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */






/**
 * `DomainListParser` is responsible for parsing a domain list.
 *
 * @example
 * - If the rule is `example.com,~example.net##.ads`, the domain list is `example.com,~example.net`.
 * - If the rule is `ads.js^$script,domains=example.com|~example.org`, the domain list is `example.com|~example.org`.
 * This parser is responsible for parsing these domain lists.
 * @see {@link https://help.eyeo.com/adblockplus/how-to-write-filters#elemhide_domains}
 */
class DomainListParser extends base_parser/* BaseParser */.V {
    /**
     * Parses a domain list, eg. `example.com,example.org,~example.org`
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @param separator Separator character (default: comma)
     *
     * @returns Domain list AST.
     * @throws An {@link AdblockSyntaxError} if the domain list is syntactically invalid.
     * @throws An {@link Error} if the options are invalid.
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0, separator = constants/* COMMA */.KE) {
        if (separator !== constants/* COMMA */.KE && separator !== constants/* PIPE */.L5) {
            throw new Error(`Invalid separator: ${separator}`);
        }
        const result = {
            type: nodes/* ListNodeType */.h6.DomainList,
            separator,
            children: ListItemsParser.parse(raw, options, baseOffset, separator, nodes/* ListItemNodeType */.WR.Domain),
        };
        if (options.isLocIncluded) {
            result.start = baseOffset;
            result.end = baseOffset + raw.length;
        }
        return result;
    }
}




/***/ }),

/***/ 92987:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (/* binding */ NodeType),
/* harmony export */   f: () => (/* binding */ LogicalExpressionParser)
/* harmony export */ });
/* harmony import */ var _utils_string_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(54857);
/* harmony import */ var _nodes_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(64638);
/* harmony import */ var _utils_constants_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(65523);
/* harmony import */ var _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(99177);
/* harmony import */ var _options_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(56928);
/* harmony import */ var _base_parser_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(35581);
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/**
 * Possible token types in the logical expression.
 */
const TokenType = {
    Variable: 0,
    Operator: 1,
    Parenthesis: 2,
};
/**
 * Possible node types in the logical expression.
 */
const NodeType = {
    Variable: 'Variable',
    Operator: 'Operator',
    Parenthesis: 'Parenthesis',
};
/**
 * Precedence of the operators, larger number means higher precedence.
 */
const OPERATOR_PRECEDENCE = {
    [_nodes_index_js__WEBPACK_IMPORTED_MODULE_0__/* .OperatorValue */ .oC.Not]: 3,
    [_nodes_index_js__WEBPACK_IMPORTED_MODULE_0__/* .OperatorValue */ .oC.And]: 2,
    [_nodes_index_js__WEBPACK_IMPORTED_MODULE_0__/* .OperatorValue */ .oC.Or]: 1,
};
/**
 * `LogicalExpressionParser` is responsible for parsing logical expressions.
 *
 * @example
 * From the following rule:
 * ```adblock
 * !#if (adguard_ext_android_cb || adguard_ext_safari)
 * ```
 * this parser will parse the expression `(adguard_ext_android_cb || adguard_ext_safari)`.
 */
// TODO: Refactor this class
class LogicalExpressionParser extends _base_parser_js__WEBPACK_IMPORTED_MODULE_1__/* .BaseParser */ .V {
    /**
     * Split the expression into tokens.
     *
     * @param raw Source code of the expression
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @returns Token list
     * @throws {AdblockSyntaxError} If the expression is invalid
     */
    static tokenize(raw, baseOffset = 0) {
        const tokens = [];
        let offset = 0;
        while (offset < raw.length) {
            const char = raw[offset];
            if (_utils_string_js__WEBPACK_IMPORTED_MODULE_2__/* .StringUtils */ .$x.isWhitespace(char)) {
                // Ignore whitespace
                offset += 1;
            }
            else if (_utils_string_js__WEBPACK_IMPORTED_MODULE_2__/* .StringUtils */ .$x.isLetter(char)) {
                // Save the start offset of the variable name
                const nameStart = offset;
                // Variable name shouldn't start with a number or underscore,
                // but can contain them
                while (offset + 1 < raw.length
                    && (_utils_string_js__WEBPACK_IMPORTED_MODULE_2__/* .StringUtils */ .$x.isAlphaNumeric(raw[offset + 1]) || raw[offset + 1] === _utils_constants_js__WEBPACK_IMPORTED_MODULE_3__/* .UNDERSCORE */ .fB)) {
                    offset += 1;
                }
                tokens.push({
                    type: TokenType.Variable,
                    start: nameStart,
                    end: offset + 1,
                });
                offset += 1;
            }
            else if (char === _utils_constants_js__WEBPACK_IMPORTED_MODULE_3__/* .OPEN_PARENTHESIS */ .Cx || char === _utils_constants_js__WEBPACK_IMPORTED_MODULE_3__/* .CLOSE_PARENTHESIS */ .s1) {
                // Parenthesis
                tokens.push({
                    type: TokenType.Parenthesis,
                    start: offset,
                    end: offset + 1,
                });
                offset += 1;
            }
            else if (char === _utils_constants_js__WEBPACK_IMPORTED_MODULE_3__/* .AMPERSAND */ .e0 || char === _utils_constants_js__WEBPACK_IMPORTED_MODULE_3__/* .PIPE */ .L5) {
                // Parse operator
                if (offset + 1 < raw.length && raw[offset + 1] === char) {
                    tokens.push({
                        type: TokenType.Operator,
                        start: offset,
                        end: offset + 2,
                    });
                    offset += 2;
                }
                else {
                    throw new _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_4__/* .AdblockSyntaxError */ .q(`Unexpected character "${char}"`, baseOffset + offset, baseOffset + offset + 1);
                }
            }
            else if (char === _utils_constants_js__WEBPACK_IMPORTED_MODULE_3__/* .EXCLAMATION_MARK */ .Ec) {
                tokens.push({
                    type: TokenType.Operator,
                    start: offset,
                    end: offset + 1,
                });
                offset += 1;
            }
            else {
                throw new _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_4__/* .AdblockSyntaxError */ .q(`Unexpected character "${char}"`, baseOffset + offset, baseOffset + offset + 1);
            }
        }
        return tokens;
    }
    /**
     * Parses a logical expression.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @returns Parsed expression
     * @throws {AdblockSyntaxError} If the expression is invalid
     */
    // TODO: Create a separate TokenStream class
    static parse(raw, options = _options_js__WEBPACK_IMPORTED_MODULE_5__/* .defaultParserOptions */ .n, baseOffset = 0) {
        // Tokenize the source (produces an array of tokens)
        const tokens = LogicalExpressionParser.tokenize(raw, baseOffset);
        // Current token index
        let tokenIndex = 0;
        /**
         * Consumes a token of the expected type.
         *
         * @param type Expected token type
         * @returns The consumed token
         */
        function consume(type) {
            const token = tokens[tokenIndex];
            if (!token) {
                throw new _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_4__/* .AdblockSyntaxError */ .q(`Expected token of type "${type}", but reached end of input`, baseOffset, baseOffset + raw.length);
            }
            // We only use this function internally, so we can safely ignore this
            // from the coverage report
            // istanbul ignore next
            if (token.type !== type) {
                throw new _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_4__/* .AdblockSyntaxError */ .q(`Expected token of type "${type}", but got "${token.type}"`, baseOffset + token.start, baseOffset + token.end);
            }
            tokenIndex += 1;
            return token;
        }
        /**
         * Parses a variable.
         *
         * @returns Variable node
         */
        function parseVariable() {
            const token = consume(TokenType.Variable);
            const result = {
                type: NodeType.Variable,
                name: raw.slice(token.start, token.end),
            };
            if (options.isLocIncluded) {
                result.start = baseOffset + token.start;
                result.end = baseOffset + token.end;
            }
            return result;
        }
        /**
         * Parses a binary expression.
         *
         * @param left Left-hand side of the expression
         * @param minPrecedence Minimum precedence of the operator
         * @returns Binary expression node
         */
        function parseBinaryExpression(left, minPrecedence = 0) {
            let node = left;
            let operatorToken;
            while (tokens[tokenIndex]) {
                operatorToken = tokens[tokenIndex];
                if (!operatorToken || operatorToken.type !== TokenType.Operator) {
                    break;
                }
                // It is safe to cast here, because we already checked the type
                const operator = raw.slice(operatorToken.start, operatorToken.end);
                const precedence = OPERATOR_PRECEDENCE[operator];
                if (precedence < minPrecedence) {
                    break;
                }
                tokenIndex += 1;
                // eslint-disable-next-line @typescript-eslint/no-use-before-define
                const right = parseExpression(precedence + 1);
                const newNode = {
                    type: NodeType.Operator,
                    operator,
                    left: node,
                    right,
                };
                if (options.isLocIncluded) {
                    newNode.start = node.start ?? baseOffset + operatorToken.start;
                    newNode.end = right.end ?? baseOffset + operatorToken.end;
                }
                node = newNode;
            }
            return node;
        }
        /**
         * Parses a parenthesized expression.
         *
         * @returns Parenthesized expression node
         */
        function parseParenthesizedExpression() {
            consume(TokenType.Parenthesis);
            // eslint-disable-next-line @typescript-eslint/no-use-before-define
            const expression = parseExpression();
            consume(TokenType.Parenthesis);
            const result = {
                type: NodeType.Parenthesis,
                expression,
            };
            if (options.isLocIncluded) {
                result.start = expression.start;
                result.end = expression.end;
            }
            return result;
        }
        /**
         * Parses an expression.
         *
         * @param minPrecedence Minimum precedence of the operator
         * @returns Expression node
         */
        function parseExpression(minPrecedence = 0) {
            let node;
            const token = tokens[tokenIndex];
            const value = raw.slice(token.start, token.end);
            if (token.type === TokenType.Variable) {
                node = parseVariable();
            }
            else if (token.type === TokenType.Operator && value === _nodes_index_js__WEBPACK_IMPORTED_MODULE_0__/* .OperatorValue */ .oC.Not) {
                tokenIndex += 1;
                const expression = parseExpression(OPERATOR_PRECEDENCE[_nodes_index_js__WEBPACK_IMPORTED_MODULE_0__/* .OperatorValue */ .oC.Not]);
                node = {
                    type: NodeType.Operator,
                    operator: _nodes_index_js__WEBPACK_IMPORTED_MODULE_0__/* .OperatorValue */ .oC.Not,
                    left: expression,
                };
                if (options.isLocIncluded) {
                    if (expression.end) {
                        node.start = baseOffset + token.start;
                        // no need to shift the node location, because it's already shifted
                        node.end = expression.end;
                    }
                    else {
                        node.start = baseOffset + token.start;
                        node.end = baseOffset + token.end;
                    }
                }
            }
            else if (token.type === TokenType.Parenthesis && value === _utils_constants_js__WEBPACK_IMPORTED_MODULE_3__/* .OPEN_PARENTHESIS */ .Cx) {
                node = parseParenthesizedExpression();
            }
            else {
                throw new _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_4__/* .AdblockSyntaxError */ .q(`Unexpected token "${value}"`, baseOffset + token.start, baseOffset + token.end);
            }
            return parseBinaryExpression(node, minPrecedence);
        }
        const expression = parseExpression();
        if (tokenIndex !== tokens.length) {
            throw new _errors_adblock_syntax_error_js__WEBPACK_IMPORTED_MODULE_4__/* .AdblockSyntaxError */ .q(`Unexpected token "${tokens[tokenIndex].type}"`, baseOffset + tokens[tokenIndex].start, baseOffset + tokens[tokenIndex].end);
        }
        return expression;
    }
}




/***/ }),

/***/ 56928:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   n: () => (/* binding */ defaultParserOptions)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * @file Common options for all parsers.
 */
/**
 * Default parser options.
 */
const defaultParserOptions = Object.freeze({
    tolerant: false,
    isLocIncluded: true,
    parseAbpSpecificRules: true,
    parseUboSpecificRules: true,
    includeRaws: true,
    ignoreComments: false,
    parseHostRules: false,
});




/***/ }),

/***/ 58660:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  G: () => (/* binding */ RuleParser)
});

// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/adblockers.js
var adblockers = __webpack_require__(88226);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/constants.js
var constants = __webpack_require__(65523);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/string.js
var string = __webpack_require__(54857);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/nodes/index.js
var nodes = __webpack_require__(64638);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/errors/adblock-syntax-error.js
var adblock_syntax_error = __webpack_require__(99177);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/base-parser.js
var base_parser = __webpack_require__(35581);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/options.js
var parser_options = __webpack_require__(56928);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/misc/value-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */



/**
 * Value parser.
 * This parser is very simple, it just exists to provide a consistent interface for parsing.
 */
class ValueParser extends base_parser/* BaseParser */.V {
    /**
     * Parses a value.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     *
     * @returns Value node.
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0) {
        const result = {
            type: 'Value',
            value: raw,
        };
        if (options.isLocIncluded) {
            result.start = baseOffset;
            result.end = baseOffset + raw.length;
        }
        return result;
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/type-guards.js
var type_guards = __webpack_require__(30239);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/common/agent-common.js
var agent_common = __webpack_require__(64163);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/comment/agent-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */









/**
 * `AgentParser` is responsible for parsing single adblock agent elements.
 *
 * @example
 * If the adblock agent rule is
 * ```adblock
 * [Adblock Plus 2.0; AdGuard]
 * ```
 * then the adblock agents are `Adblock Plus 2.0` and `AdGuard`, and this
 * class is responsible for parsing them. The rule itself is parsed by
 * `AgentCommentParser`, which uses this class to parse single agents.
 */
class AgentParser extends base_parser/* BaseParser */.V {
    /**
     * Regex to match a version inside a string.
     */
    static VERSION_REGEX = /\b\d+\.\d+(\.\d+)?\b/;
    /**
     * Checks if the string is a valid version.
     *
     * The string can have a version in formats like
     * [Adblock Plus 2.0], or [Adblock Plus 3.1; AdGuard].
     *
     * @param str String to check
     * @returns `true` if the string is a valid version, `false` otherwise
     */
    static isValidVersion(str) {
        // Check if the string contains a valid version pattern
        return AgentParser.VERSION_REGEX.test(str);
    }
    /**
     * Parses a raw rule as an adblock agent comment.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @returns Agent rule AST
     * @throws {AdblockSyntaxError} If the raw rule cannot be parsed as an adblock agent
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0) {
        let offset = 0;
        // Save name start position
        const nameStartIndex = offset;
        let nameEndIndex = offset;
        // Prepare variables for name and version
        let name;
        let version;
        // default value for the syntax
        let syntax = adblockers/* AdblockSyntax */.Y.Common;
        // Get agent parts by splitting it by spaces. The last part may be a version.
        // Example: "Adblock Plus 2.0"
        while (offset < raw.length) {
            // Skip whitespace before the part
            offset = string/* StringUtils */.$x.skipWS(raw, offset);
            const partEnd = string/* StringUtils */.$x.findNextWhitespaceCharacter(raw, offset);
            const part = raw.slice(offset, partEnd);
            if (AgentParser.isValidVersion(part)) {
                if (!(0,type_guards/* isUndefined */.b0)(version)) {
                    throw new adblock_syntax_error/* AdblockSyntaxError */.q('Duplicated versions are not allowed', baseOffset + offset, baseOffset + partEnd);
                }
                const parsedNamePart = raw.slice(nameStartIndex, nameEndIndex);
                name = ValueParser.parse(parsedNamePart, options, baseOffset + nameStartIndex);
                version = ValueParser.parse(part, options, baseOffset + offset);
                syntax = (0,agent_common/* getAdblockSyntax */.w)(parsedNamePart);
            }
            else {
                nameEndIndex = partEnd;
            }
            // Skip whitespace after the part
            offset = string/* StringUtils */.$x.skipWS(raw, partEnd);
        }
        // If we didn't find a version, the whole string is the name
        if ((0,type_guards/* isUndefined */.b0)(name)) {
            const parsedNamePart = raw.slice(nameStartIndex, nameEndIndex);
            name = ValueParser.parse(parsedNamePart, options, baseOffset + nameStartIndex);
            syntax = (0,agent_common/* getAdblockSyntax */.w)(parsedNamePart);
        }
        // Agent name cannot be empty
        if (name.value.length === 0) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q('Agent name cannot be empty', baseOffset, baseOffset + raw.length);
        }
        const result = {
            type: 'Agent',
            adblock: name,
            syntax,
        };
        // only add version if it's present
        if (version) {
            result.version = version;
        }
        if (options.isLocIncluded) {
            result.start = baseOffset;
            result.end = baseOffset + raw.length;
        }
        return result;
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/cosmetic-rule-separator.js
var cosmetic_rule_separator = __webpack_require__(90692);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/comment/agent-comment-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */











/**
 * `AgentParser` is responsible for parsing an Adblock agent rules.
 * Adblock agent comment marks that the filter list is supposed to
 * be used by the specified ad blockers.
 *
 * @example
 *  - ```adblock
 *    [AdGuard]
 *    ```
 *  - ```adblock
 *    [Adblock Plus 2.0]
 *    ```
 *  - ```adblock
 *    [uBlock Origin]
 *    ```
 *  - ```adblock
 *    [uBlock Origin 1.45.3]
 *    ```
 *  - ```adblock
 *    [Adblock Plus 2.0; AdGuard]
 *    ```
 */
class AgentCommentParser extends base_parser/* BaseParser */.V {
    /**
     * Checks if the raw rule is an adblock agent comment.
     *
     * @param raw Raw rule
     * @returns `true` if the rule is an adblock agent, `false` otherwise
     */
    static isAgentRule(raw) {
        const rawTrimmed = raw.trim();
        if (rawTrimmed.startsWith(constants/* OPEN_SQUARE_BRACKET */.cU) && rawTrimmed.endsWith(constants/* CLOSE_SQUARE_BRACKET */.A1)) {
            // Avoid this case: [$adg-modifier]##[class^="adg-"]
            return (0,type_guards/* isNull */.kZ)(cosmetic_rule_separator/* CosmeticRuleSeparatorUtils */.m.find(rawTrimmed));
        }
        return false;
    }
    /**
     * Parses a raw rule as an adblock agent comment.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @returns Agent rule AST or null (if the raw rule cannot be parsed as an adblock agent comment)
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0) {
        // Ignore non-agent rules
        if (!AgentCommentParser.isAgentRule(raw)) {
            return null;
        }
        let offset = 0;
        // Skip whitespace characters before the rule
        offset = string/* StringUtils */.$x.skipWS(raw, offset);
        // Skip opening bracket
        offset += 1;
        // last character should be a closing bracket
        const closingBracketIndex = string/* StringUtils */.$x.skipWSBack(raw, raw.length - 1);
        if (closingBracketIndex === -1 || raw[closingBracketIndex] !== constants/* CLOSE_SQUARE_BRACKET */.A1) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q('Missing closing bracket', offset, offset + raw.length);
        }
        // Initialize the agent list
        const result = {
            type: nodes/* CommentRuleType */.gV.AgentCommentRule,
            syntax: adblockers/* AdblockSyntax */.Y.Common,
            category: nodes/* RuleCategory */.$O.Comment,
            children: [],
        };
        if (options.includeRaws) {
            result.raws = {
                text: raw,
            };
        }
        if (options.isLocIncluded) {
            result.start = baseOffset;
            result.end = baseOffset + raw.length;
        }
        while (offset < closingBracketIndex) {
            // Skip whitespace characters before the agent
            offset = string/* StringUtils */.$x.skipWS(raw, offset);
            // Find the separator or the closing bracket
            let separatorIndex = raw.indexOf(constants/* SEMICOLON */.I8, offset);
            if (separatorIndex === -1) {
                separatorIndex = closingBracketIndex;
            }
            // Find the last non-whitespace character of the agent
            // [AdGuard  ; Adblock Plus 2.0]
            //        ^
            // (if we have spaces between the agent name and the separator)
            const agentEndIndex = string/* StringUtils */.$x.findLastNonWhitespaceCharacter(raw.slice(offset, separatorIndex)) + offset + 1;
            // Collect the agent
            result.children.push(AgentParser.parse(raw.slice(offset, agentEndIndex), options, baseOffset + offset));
            // Set the offset to the next agent or the end of the rule
            offset = separatorIndex + 1;
        }
        if (result.children.length === 0) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q('Empty agent list', baseOffset, baseOffset + raw.length);
        }
        return result;
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/json5@2.2.3/node_modules/json5/dist/index.js
var dist = __webpack_require__(91801);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/misc/parameter-list-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */






/**
 * Parser for parameter lists.
 */
class ParameterListParser extends base_parser/* BaseParser */.V {
    /**
     * Parses a raw parameter list.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @param separator Separator character (default: comma)
     * @returns Parameter list AST
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0, separator = constants/* COMMA */.KE) {
        // Prepare the parameter list node
        const params = {
            type: 'ParameterList',
            children: [],
        };
        const { length } = raw;
        if (options.isLocIncluded) {
            params.start = baseOffset;
            params.end = baseOffset + length;
        }
        let offset = 0;
        // Parse parameters: skip whitespace before and after each parameter, and
        // split parameters by the separator character.
        while (offset < length) {
            // Skip whitespace before parameter
            offset = string/* StringUtils */.$x.skipWS(raw, offset);
            // Parameter may only contain whitespace
            // In this case, we reached the end of the parameter list
            if (raw[offset] === separator || offset === length) {
                // Add a null for empty parameter
                params.children.push(null);
                // Skip separator
                offset += 1;
            }
            else {
                // Get parameter start position
                const paramStart = offset;
                // Get next unescaped separator position
                const nextSeparator = string/* StringUtils */.$x.findUnescapedNonStringNonRegexChar(raw, separator, offset);
                // Get parameter end position
                const paramEnd = nextSeparator !== -1
                    ? string/* StringUtils */.$x.skipWSBack(raw, nextSeparator - 1)
                    : string/* StringUtils */.$x.skipWSBack(raw);
                // Add parameter to the list
                const param = ValueParser.parse(raw.slice(paramStart, paramEnd + 1), options, baseOffset + paramStart);
                params.children.push(param);
                // Set offset to the next separator position + 1
                offset = nextSeparator !== -1 ? nextSeparator + 1 : length;
            }
        }
        // If the last character was a separator, add an additional null parameter
        if (raw[length - 1] === separator) {
            params.children.push(null);
        }
        return params;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/comment/config-comment-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */










/**
 * @file AGLint configuration comments. Inspired by ESLint inline configuration comments.
 * @see {@link https://eslint.org/docs/latest/user-guide/configuring/rules#using-configuration-comments}
 */
/**
 * `ConfigCommentParser` is responsible for parsing inline AGLint configuration rules.
 * Generally, the idea is inspired by ESLint inline configuration comments.
 *
 * @see {@link https://eslint.org/docs/latest/user-guide/configuring/rules#using-configuration-comments}
 */
class ConfigCommentParser extends base_parser/* BaseParser */.V {
    /**
     * Checks if the raw rule is an inline configuration comment rule.
     *
     * @param raw Raw rule
     * @returns `true` if the rule is an inline configuration comment rule, otherwise `false`.
     */
    static isConfigComment(raw) {
        const trimmed = raw.trim();
        if (trimmed[0] === nodes/* CommentMarker */.yg.Regular || trimmed[0] === nodes/* CommentMarker */.yg.Hashmark) {
            // Skip comment marker and trim comment text (it is necessary because of "!     something")
            const text = raw.slice(1).trim();
            // The code below is "not pretty", but it runs fast, which is necessary, since it will run on EVERY comment
            // The essence of the indicator is that the control comment always starts with the "aglint" prefix
            return ((text[0] === 'a' || text[0] === 'A')
                && (text[1] === 'g' || text[1] === 'G')
                && (text[2] === 'l' || text[2] === 'L')
                && (text[3] === 'i' || text[3] === 'I')
                && (text[4] === 'n' || text[4] === 'N')
                && (text[5] === 't' || text[5] === 'T'));
        }
        return false;
    }
    /**
     * Parses a raw rule as an inline configuration comment.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @returns
     * Inline configuration comment AST or null (if the raw rule cannot be parsed as configuration comment)
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0) {
        if (!ConfigCommentParser.isConfigComment(raw)) {
            return null;
        }
        let offset = 0;
        // Skip leading whitespace (if any)
        offset = string/* StringUtils */.$x.skipWS(raw, offset);
        // Get comment marker
        const marker = ValueParser.parse(raw[offset], options, baseOffset + offset);
        // Skip marker
        offset += 1;
        // Skip whitespace (if any)
        offset = string/* StringUtils */.$x.skipWS(raw, offset);
        // Save the command start position
        const commandStart = offset;
        // Get comment text, for example: "aglint-disable-next-line"
        offset = string/* StringUtils */.$x.findNextWhitespaceCharacter(raw, offset);
        const command = ValueParser.parse(raw.slice(commandStart, offset), options, baseOffset + commandStart);
        // Skip whitespace after command
        offset = string/* StringUtils */.$x.skipWS(raw, offset);
        // Get comment (if any)
        const commentStart = raw.indexOf(constants/* AGLINT_CONFIG_COMMENT_MARKER */.Ez, offset);
        const commentEnd = commentStart !== -1 ? string/* StringUtils */.$x.skipWSBack(raw) + 1 : -1;
        let comment;
        // Check if there is a comment
        if (commentStart !== -1) {
            comment = ValueParser.parse(raw.slice(commentStart, commentEnd), options, baseOffset + commentStart);
        }
        // Get parameter
        const paramsStart = offset;
        const paramsEnd = commentStart !== -1
            ? string/* StringUtils */.$x.skipWSBack(raw, commentStart - 1) + 1
            : string/* StringUtils */.$x.skipWSBack(raw) + 1;
        let params;
        // `! aglint ...` config comment
        if (command.value === constants/* AGLINT_COMMAND_PREFIX */.BH) {
            params = {
                type: 'ConfigNode',
                // It is necessary to use JSON5.parse instead of JSON.parse because JSON5 allows unquoted keys.
                // But don't forget to add { } to the beginning and end of the string,
                // otherwise JSON5 will not be able to parse it.
                // TODO: Better solution? ESLint uses "levn" package for parsing these comments.
                value: dist.parse(`{${raw.slice(paramsStart, paramsEnd)}}`),
            };
            if (options.isLocIncluded) {
                params.start = paramsStart;
                params.end = paramsEnd;
            }
            // Throw error for empty config
            if (Object.keys(params.value).length === 0) {
                throw new Error('Empty AGLint config');
            }
        }
        else if (paramsStart < paramsEnd) {
            params = ParameterListParser.parse(raw.slice(paramsStart, paramsEnd), options, baseOffset + paramsStart, constants/* COMMA */.KE);
        }
        const result = {
            type: nodes/* CommentRuleType */.gV.ConfigCommentRule,
            category: nodes/* RuleCategory */.$O.Comment,
            syntax: adblockers/* AdblockSyntax */.Y.Common,
            marker,
            command,
            params,
            comment,
        };
        if (options.includeRaws) {
            result.raws = {
                text: raw,
            };
        }
        if (options.isLocIncluded) {
            result.start = baseOffset;
            result.end = baseOffset + raw.length;
        }
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/comment/hint-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */








/* eslint-disable no-param-reassign */
/**
 * @file AdGuard Hints
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#hints}
 */
/**
 * `HintParser` is responsible for parsing AdGuard hints.
 *
 * @example
 * If the hint rule is
 * ```adblock
 * !+ NOT_OPTIMIZED PLATFORM(windows)
 * ```
 * then the hints are `NOT_OPTIMIZED` and `PLATFORM(windows)`, and this
 * class is responsible for parsing them. The rule itself is parsed by
 * the `HintRuleParser`, which uses this class to parse single hints.
 */
class HintParser extends base_parser/* BaseParser */.V {
    /**
     * Parses a raw rule as a hint.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @returns Hint rule AST or null
     * @throws If the syntax is invalid
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0) {
        let offset = 0;
        // Skip whitespace characters before the hint
        offset = string/* StringUtils */.$x.skipWS(raw);
        // Hint should start with the hint name in every case
        // Save the start offset of the hint name
        const nameStartIndex = offset;
        // Parse the hint name
        for (; offset < raw.length; offset += 1) {
            const char = raw[offset];
            // Abort consuming the hint name if we encounter a whitespace character
            // or an opening parenthesis, which means 'HIT_NAME(' case
            if (char === constants/* OPEN_PARENTHESIS */.Cx || char === constants/* SPACE */.t6) {
                break;
            }
            // Hint name should only contain letters, digits, and underscores
            if (!string/* StringUtils */.$x.isAlphaNumeric(char) && char !== constants/* UNDERSCORE */.fB) {
                throw new adblock_syntax_error/* AdblockSyntaxError */.q(`Invalid character "${char}" in hint name: "${char}"`, baseOffset + nameStartIndex, baseOffset + offset);
            }
        }
        // Save the end offset of the hint name
        const nameEndIndex = offset;
        // Save the hint name token
        const name = raw.slice(nameStartIndex, nameEndIndex);
        // Hint name cannot be empty
        if (name === constants/* EMPTY */.wg) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q('Empty hint name', baseOffset, baseOffset + nameEndIndex);
        }
        // Now we have two case:
        //  1. We have HINT_NAME and should return it
        //  2. We have HINT_NAME(PARAMS) and should continue parsing
        // Skip whitespace characters after the hint name
        offset = string/* StringUtils */.$x.skipWS(raw, offset);
        // Throw error for 'HINT_NAME (' case
        if (offset > nameEndIndex && raw[offset] === constants/* OPEN_PARENTHESIS */.Cx) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q('Unexpected whitespace(s) between hint name and opening parenthesis', baseOffset + nameEndIndex, baseOffset + offset);
        }
        // Create the hint name node (we can reuse it in the 'HINT_NAME' case, if needed)
        const nameNode = ValueParser.parse(name, options, baseOffset + nameStartIndex);
        // Just return the hint name if we have 'HINT_NAME' case (no params)
        if (raw[offset] !== constants/* OPEN_PARENTHESIS */.Cx) {
            const result = {
                type: 'Hint',
                name: nameNode,
            };
            if (options.isLocIncluded) {
                result.start = baseOffset;
                result.end = baseOffset + offset;
            }
            return result;
        }
        // Skip the opening parenthesis
        offset += 1;
        // Find closing parenthesis
        const closeParenthesisIndex = raw.lastIndexOf(constants/* CLOSE_PARENTHESIS */.s1);
        // Throw error if we don't have closing parenthesis
        if (closeParenthesisIndex === -1) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q(`Missing closing parenthesis for hint "${name}"`, baseOffset + nameStartIndex, baseOffset + raw.length);
        }
        // Save the start and end index of the params
        const paramsStartIndex = offset;
        const paramsEndIndex = closeParenthesisIndex;
        // Parse the params
        const params = ParameterListParser.parse(raw.slice(paramsStartIndex, paramsEndIndex), options, baseOffset + paramsStartIndex, constants/* COMMA */.KE);
        offset = closeParenthesisIndex + 1;
        // Skip whitespace characters after the closing parenthesis
        offset = string/* StringUtils */.$x.skipWS(raw, offset);
        // Throw error if we don't reach the end of the input
        if (offset !== raw.length) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q(
            // eslint-disable-next-line max-len
            `Unexpected input after closing parenthesis for hint "${name}": "${raw.slice(closeParenthesisIndex + 1, offset + 1)}"`, baseOffset + closeParenthesisIndex + 1, baseOffset + offset + 1);
        }
        // Return the HINT_NAME(PARAMS) case AST
        const result = {
            type: 'Hint',
            name: nameNode,
            params,
        };
        if (options.isLocIncluded) {
            result.start = baseOffset;
            result.end = baseOffset + offset;
        }
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/comment/hint-comment-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */









/**
 * `HintRuleParser` is responsible for parsing AdGuard hint rules.
 *
 * @example
 * The following hint rule
 * ```adblock
 * !+ NOT_OPTIMIZED PLATFORM(windows)
 * ```
 * contains two hints: `NOT_OPTIMIZED` and `PLATFORM`.
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#hints}
 */
class HintCommentParser extends base_parser/* BaseParser */.V {
    /**
     * Checks if the raw rule is a hint rule.
     *
     * @param raw Raw rule
     * @returns `true` if the rule is a hint rule, `false` otherwise
     */
    static isHintRule(raw) {
        return raw.trim().startsWith(constants/* HINT_MARKER */.j6);
    }
    /**
     * Parses a raw rule as a hint comment.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @returns Hint AST or null (if the raw rule cannot be parsed as a hint comment)
     * @throws If the input matches the HINT pattern but syntactically invalid
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#hints-1}
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0) {
        // Ignore non-hint rules
        if (!HintCommentParser.isHintRule(raw)) {
            return null;
        }
        let offset = 0;
        // Skip whitespace characters before the rule
        offset = string/* StringUtils */.$x.skipWS(raw);
        // Skip hint marker
        offset += constants/* HINT_MARKER_LEN */.BR;
        const hints = [];
        // Collect hints. Each hint is a string, optionally followed by a parameter list,
        // enclosed in parentheses. One rule can contain multiple hints.
        while (offset < raw.length) {
            // Split rule into raw hints (e.g. 'HINT_NAME' or 'HINT_NAME(PARAMS)')
            // Hints are separated by whitespace characters, but we should ignore
            // whitespace characters inside the parameter list
            // Ignore whitespace characters before the hint
            offset = string/* StringUtils */.$x.skipWS(raw, offset);
            // Save the start index of the hint
            const hintStartIndex = offset;
            // Find the end of the hint
            let hintEndIndex = offset;
            let balance = 0;
            while (hintEndIndex < raw.length) {
                if (raw[hintEndIndex] === constants/* OPEN_PARENTHESIS */.Cx && raw[hintEndIndex - 1] !== constants/* BACKSLASH */.r_) {
                    balance += 1;
                    // Throw error for nesting
                    if (balance > 1) {
                        throw new adblock_syntax_error/* AdblockSyntaxError */.q('Invalid hint: nested parentheses are not allowed', baseOffset + hintStartIndex, baseOffset + hintEndIndex);
                    }
                }
                else if (raw[hintEndIndex] === constants/* CLOSE_PARENTHESIS */.s1 && raw[hintEndIndex - 1] !== constants/* BACKSLASH */.r_) {
                    balance -= 1;
                }
                else if (string/* StringUtils */.$x.isWhitespace(raw[hintEndIndex]) && balance === 0) {
                    break;
                }
                hintEndIndex += 1;
            }
            offset = hintEndIndex;
            // Skip whitespace characters after the hint
            offset = string/* StringUtils */.$x.skipWS(raw, offset);
            // Parse the hint
            const hint = HintParser.parse(raw.slice(hintStartIndex, hintEndIndex), options, baseOffset + hintStartIndex);
            hints.push(hint);
        }
        // Throw error if no hints were found
        if (hints.length === 0) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q('Empty hint rule', baseOffset, baseOffset + offset);
        }
        const result = {
            type: nodes/* CommentRuleType */.gV.HintCommentRule,
            category: nodes/* RuleCategory */.$O.Comment,
            syntax: adblockers/* AdblockSyntax */.Y.Adg,
            children: hints,
        };
        if (options.includeRaws) {
            result.raws = {
                text: raw,
            };
        }
        if (options.isLocIncluded) {
            result.start = baseOffset;
            result.end = baseOffset + offset;
        }
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/comment/metadata-comment-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */








/**
 * @file Metadata comments
 */
/**
 * Set of known metadata headers. This helps to quickly identify and validate
 * metadata headers in the comments.
 */
const KNOWN_METADATA_HEADERS = new Set([
    'Checksum',
    'Description',
    'Expires',
    'Homepage',
    'Last Modified',
    'LastModified',
    'Licence',
    'License',
    'Time Updated',
    'TimeUpdated',
    'Version',
    'Title',
]);
/**
 * `MetadataParser` is responsible for parsing metadata comments.
 * Metadata comments are special comments that specify some properties of the list.
 *
 * @example
 * For example, in the case of
 * ```adblock
 * ! Title: My List
 * ```
 * the name of the header is `Title`, and the value is `My List`, which means that
 * the list title is `My List`, and it can be used in the adblocker UI.
 * @see {@link https://help.eyeo.com/adblockplus/how-to-write-filters#special-comments}
 */
class MetadataCommentParser extends base_parser/* BaseParser */.V {
    /**
     * Parses a raw rule as a metadata comment.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @returns Metadata comment AST or null (if the raw rule cannot be parsed as a metadata comment)
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0) {
        // Fast check to avoid unnecessary work
        if (raw.indexOf(constants/* COLON */.oH) === -1) {
            return null;
        }
        let offset = 0;
        // Skip leading spaces before the comment marker
        offset = string/* StringUtils */.$x.skipWS(raw, offset);
        // Check if the rule starts with a comment marker (first non-space sequence)
        if (raw[offset] !== nodes/* CommentMarker */.yg.Regular && raw[offset] !== nodes/* CommentMarker */.yg.Hashmark) {
            return null;
        }
        // Consume the comment marker
        const marker = ValueParser.parse(raw[offset], options, baseOffset + offset);
        offset += 1;
        // Skip spaces
        offset = string/* StringUtils */.$x.skipWS(raw, offset);
        // Save header start position
        const headerStart = offset;
        // Check if the comment text starts with a known header
        const text = raw.slice(offset);
        for (const knownHeader of KNOWN_METADATA_HEADERS) {
            // Check if the comment text starts with the header (case-insensitive)
            if (text.toLocaleLowerCase().startsWith(knownHeader.toLocaleLowerCase())) {
                // Skip the header
                offset += knownHeader.length;
                // Save header
                const header = ValueParser.parse(raw.slice(headerStart, offset), options, baseOffset + headerStart);
                // Skip spaces after the header
                offset = string/* StringUtils */.$x.skipWS(raw, offset);
                // Check if the rule contains a separator after the header
                if (raw[offset] !== constants/* COLON */.oH) {
                    return null;
                }
                // Skip the separator
                offset += 1;
                // Skip spaces after the separator
                offset = string/* StringUtils */.$x.skipWS(raw, offset);
                // Save the value start position
                const valueStart = offset;
                // Check if the rule contains a value
                if (offset >= raw.length) {
                    return null;
                }
                const valueEnd = string/* StringUtils */.$x.skipWSBack(raw, raw.length - 1) + 1;
                // Save the value
                const value = ValueParser.parse(raw.slice(valueStart, valueEnd), options, baseOffset + valueStart);
                const result = {
                    type: nodes/* CommentRuleType */.gV.MetadataCommentRule,
                    category: nodes/* RuleCategory */.$O.Comment,
                    syntax: adblockers/* AdblockSyntax */.Y.Common,
                    marker,
                    header,
                    value,
                };
                if (options.includeRaws) {
                    result.raws = {
                        text: raw,
                    };
                }
                if (options.isLocIncluded) {
                    result.start = baseOffset;
                    result.end = baseOffset + raw.length;
                }
                return result;
            }
        }
        return null;
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/misc/logical-expression-parser.js
var logical_expression_parser = __webpack_require__(92987);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/comment/preprocessor-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */











/**
 * Pre-processor directives
 *
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#pre-processor-directives}
 * @see {@link https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#pre-parsing-directives}
 */
/**
 * `PreProcessorParser` is responsible for parsing preprocessor rules.
 * Pre-processor comments are special comments that are used to control the behavior of the filter list processor.
 * Please note that this parser only handles general syntax for now, and does not validate the parameters at
 * the parsing stage.
 *
 * @example
 * If your rule is
 * ```adblock
 * !#if (adguard)
 * ```
 * then the directive's name is `if` and its value is `(adguard)`, but the parameter list
 * is not parsed / validated further.
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#pre-processor-directives}
 * @see {@link https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#pre-parsing-directives}
 */
class PreProcessorCommentParser extends base_parser/* BaseParser */.V {
    /**
     * Determines whether the rule is a pre-processor rule.
     *
     * @param raw Raw rule
     * @returns `true` if the rule is a pre-processor rule, `false` otherwise
     */
    static isPreProcessorRule(raw) {
        const trimmed = raw.trim();
        // Avoid this case: !##... (commonly used in AdGuard filters)
        return trimmed.startsWith(constants/* PREPROCESSOR_MARKER */.PD) && trimmed[constants/* PREPROCESSOR_MARKER_LEN */.nx] !== constants/* HASHMARK */.C;
    }
    /**
     * Parses a raw rule as a pre-processor comment.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @returns
     * Pre-processor comment AST or null (if the raw rule cannot be parsed as a pre-processor comment)
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0) {
        // Ignore non-pre-processor rules
        if (!PreProcessorCommentParser.isPreProcessorRule(raw)) {
            return null;
        }
        let offset = 0;
        // Ignore whitespace characters before the rule (if any)
        offset = string/* StringUtils */.$x.skipWS(raw, offset);
        // Ignore the pre-processor marker
        offset += constants/* PREPROCESSOR_MARKER_LEN */.nx;
        // Ignore whitespace characters after the pre-processor marker (if any)
        // Note: this is incorrect according to the spec, but we do it for tolerance
        offset = string/* StringUtils */.$x.skipWS(raw, offset);
        // Directive name should start at this offset, so we save this offset now
        const nameStart = offset;
        // Consume directive name, so parse the sequence until the first
        // whitespace / opening parenthesis / end of string
        while (offset < raw.length) {
            const ch = raw[offset];
            if (ch === constants/* PREPROCESSOR_SEPARATOR */.sA || ch === constants/* OPEN_PARENTHESIS */.Cx) {
                break;
            }
            offset += 1;
        }
        // Save name end offset
        const nameEnd = offset;
        // Create name node
        const name = ValueParser.parse(raw.slice(nameStart, nameEnd), options, baseOffset + nameStart);
        // Ignore whitespace characters after the directive name (if any)
        // Note: this may incorrect according to the spec, but we do it for tolerance
        offset = string/* StringUtils */.$x.skipWS(raw, offset);
        // If the directive name is "safari_cb_affinity", then we have a special case
        if (name.value === constants/* SAFARI_CB_AFFINITY */.us) {
            // Throw error if there are spaces after the directive name
            if (offset > nameEnd) {
                throw new adblock_syntax_error/* AdblockSyntaxError */.q(`Unexpected whitespace after "${constants/* SAFARI_CB_AFFINITY */.us}" directive name`, baseOffset + nameEnd, baseOffset + offset);
            }
            // safari_cb_affinity directive optionally accepts a parameter list
            // So at this point we should check if there are parameters or not
            // (cb_affinity directive followed by an opening parenthesis or if we
            // skip the whitespace we reach the end of the string)
            if (string/* StringUtils */.$x.skipWS(raw, offset) !== raw.length) {
                if (raw[offset] !== constants/* OPEN_PARENTHESIS */.Cx) {
                    throw new adblock_syntax_error/* AdblockSyntaxError */.q(`Unexpected character '${raw[offset]}' after '${constants/* SAFARI_CB_AFFINITY */.us}' directive name`, baseOffset + offset, baseOffset + offset + 1);
                }
                // If we have parameters, then we should parse them
                // Note: we don't validate the parameters at this stage
                // Ignore opening parenthesis
                offset += 1;
                // Save parameter list start offset
                const parameterListStart = offset;
                // Check for closing parenthesis
                const closingParenthesesIndex = string/* StringUtils */.$x.skipWSBack(raw);
                if (closingParenthesesIndex === -1 || raw[closingParenthesesIndex] !== constants/* CLOSE_PARENTHESIS */.s1) {
                    throw new adblock_syntax_error/* AdblockSyntaxError */.q(`Missing closing parenthesis for '${constants/* SAFARI_CB_AFFINITY */.us}' directive`, baseOffset + offset, baseOffset + raw.length);
                }
                // Save parameter list end offset
                const parameterListEnd = closingParenthesesIndex;
                // Parse parameters between the opening and closing parentheses
                const result = {
                    type: nodes/* CommentRuleType */.gV.PreProcessorCommentRule,
                    category: nodes/* RuleCategory */.$O.Comment,
                    syntax: adblockers/* AdblockSyntax */.Y.Adg,
                    name,
                    // comma separated list of parameters
                    params: ParameterListParser.parse(raw.slice(parameterListStart, parameterListEnd), options, baseOffset + parameterListStart, constants/* COMMA */.KE),
                };
                if (options.includeRaws) {
                    result.raws = {
                        text: raw,
                    };
                }
                if (options.isLocIncluded) {
                    result.start = baseOffset;
                    result.end = baseOffset + raw.length;
                }
                return result;
            }
        }
        // If we reached the end of the string, then we have a directive without parameters
        // (e.g. "!#safari_cb_affinity" or "!#endif")
        // No need to continue parsing in this case.
        if (offset === raw.length) {
            // Throw error if the directive name is "if" or "include", because these directives
            // should have parameters
            if (name.value === constants.IF || name.value === constants/* INCLUDE */.rM) {
                throw new adblock_syntax_error/* AdblockSyntaxError */.q(`Directive "${name.value}" requires parameters`, baseOffset, baseOffset + raw.length);
            }
            const result = {
                type: nodes/* CommentRuleType */.gV.PreProcessorCommentRule,
                category: nodes/* RuleCategory */.$O.Comment,
                syntax: adblockers/* AdblockSyntax */.Y.Common,
                name,
            };
            if (options.includeRaws) {
                result.raws = {
                    text: raw,
                };
            }
            if (options.isLocIncluded) {
                result.start = baseOffset;
                result.end = baseOffset + raw.length;
            }
            return result;
        }
        // Get start and end offsets of the directive parameters
        const paramsStart = offset;
        const paramsEnd = string/* StringUtils */.$x.skipWSBack(raw) + 1;
        // Prepare parameters node
        let params;
        // Parse parameters. Handle "if" and "safari_cb_affinity" directives
        // separately.
        if (name.value === constants.IF) {
            params = logical_expression_parser/* LogicalExpressionParser */.f.parse(raw.slice(paramsStart, paramsEnd), options, baseOffset + paramsStart);
        }
        else {
            params = ValueParser.parse(raw.slice(paramsStart, paramsEnd), options, baseOffset + paramsStart);
        }
        const result = {
            type: nodes/* CommentRuleType */.gV.PreProcessorCommentRule,
            category: nodes/* RuleCategory */.$O.Comment,
            syntax: adblockers/* AdblockSyntax */.Y.Common,
            name,
            params,
        };
        if (options.includeRaws) {
            result.raws = {
                text: raw,
            };
        }
        if (options.isLocIncluded) {
            result.start = baseOffset;
            result.end = baseOffset + raw.length;
        }
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/comment/simple-comment-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */








/**
 * `SimpleCommentParser` is responsible for parsing simple comments.
 * Some comments have a special meaning in adblock syntax, like agent comments or hints,
 * but this parser is only responsible for parsing regular comments,
 * whose only purpose is to provide some human-readable information.
 *
 * @example
 * ```adblock
 * ! This is a simple comment
 * # This is a simple comment, but in host-like syntax
 * ```
 */
class SimpleCommentParser extends base_parser/* BaseParser */.V {
    /**
     * Checks if the raw rule is a simple comment.
     *
     * @param raw Raw input to check.
     * @returns `true` if the input is a simple comment, `false` otherwise.
     * @note This method does not check for adblock agent comments.
     */
    static isSimpleComment(raw) {
        const trimmed = raw.trim();
        // Exclamation mark based comments
        if (trimmed.startsWith(nodes/* CommentMarker */.yg.Regular)) {
            return true;
        }
        // Hashmark based comments
        // Note: in this case, we must be sure that we do not mistakenly parse a cosmetic rule as a #-like comment,
        // since most cosmetic rule separators also start with #
        if (trimmed.startsWith(nodes/* CommentMarker */.yg.Hashmark)) {
            const result = cosmetic_rule_separator/* CosmeticRuleSeparatorUtils */.m.find(trimmed);
            // If we cannot find a separator, it means that the rule is definitely a comment
            if (result === null) {
                return true;
            }
            // Otherwise, we must check if the separator is followed by a valid selector
            const { end } = result;
            // No valid selector
            if (!trimmed[end + 1]
                || string/* StringUtils */.$x.isWhitespace(trimmed[end + 1])
                || (trimmed[end + 1] === nodes/* CommentMarker */.yg.Hashmark && trimmed[end + 2] === nodes/* CommentMarker */.yg.Hashmark)) {
                return true;
            }
        }
        return false;
    }
    /**
     * Parses a raw rule as a simple comment.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @returns Comment rule node or null (if the raw rule cannot be parsed as a simple comment).
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0) {
        // Ignore non-comment rules
        if (!this.isSimpleComment(raw)) {
            return null;
        }
        // If we are here, it means that the rule is a regular comment
        let offset = 0;
        // Skip leading whitespace (if any)
        offset = string/* StringUtils */.$x.skipWS(raw, offset);
        // Get comment marker
        const marker = ValueParser.parse(raw[offset], options, baseOffset + offset);
        // Skip marker
        offset += 1;
        // Get comment text
        const text = ValueParser.parse(raw.slice(offset), options, baseOffset + offset);
        // Regular comment rule
        const result = {
            category: nodes/* RuleCategory */.$O.Comment,
            type: nodes/* CommentRuleType */.gV.CommentRule,
            // TODO: Change syntax when hashmark is used
            syntax: adblockers/* AdblockSyntax */.Y.Common,
            marker,
            text,
        };
        if (options.includeRaws) {
            result.raws = {
                text: raw,
            };
        }
        if (options.isLocIncluded) {
            result.start = baseOffset;
            result.end = baseOffset + raw.length;
        }
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/comment/comment-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */









/* eslint-disable no-param-reassign */
/**
 * `CommentParser` is responsible for parsing any comment-like adblock rules.
 *
 * @example
 * Example rules:
 *  - Adblock agent rules:
 *      - ```adblock
 *        [AdGuard]
 *        ```
 *      - ```adblock
 *        [Adblock Plus 2.0]
 *        ```
 *      - etc.
 *  - AdGuard hint rules:
 *      - ```adblock
 *        !+ NOT_OPTIMIZED
 *        ```
 *      - ```adblock
 *        !+ NOT_OPTIMIZED PLATFORM(windows)
 *        ```
 *      - etc.
 *  - Pre-processor rules:
 *      - ```adblock
 *        !#if (adguard)
 *        ```
 *      - ```adblock
 *        !#endif
 *        ```
 *      - etc.
 *  - Metadata rules:
 *      - ```adblock
 *        ! Title: My List
 *        ```
 *      - ```adblock
 *        ! Version: 2.0.150
 *        ```
 *      - etc.
 *  - AGLint inline config rules:
 *      - ```adblock
 *        ! aglint-enable some-rule
 *        ```
 *      - ```adblock
 *        ! aglint-disable some-rule
 *        ```
 *      - etc.
 *  - Simple comments:
 *      - Regular version:
 *        ```adblock
 *        ! This is just a comment
 *        ```
 *      - uBlock Origin / "hostlist" version:
 *        ```adblock
 *        # This is just a comment
 *        ```
 *      - etc.
 */
class CommentParser extends base_parser/* BaseParser */.V {
    /**
     * Checks whether a rule is a comment.
     *
     * @param raw Raw rule
     * @returns `true` if the rule is a comment, `false` otherwise
     */
    static isCommentRule(raw) {
        const trimmed = raw.trim();
        return SimpleCommentParser.isSimpleComment(trimmed) || AgentCommentParser.isAgentRule(trimmed);
    }
    /**
     * Parses a raw rule as comment.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @returns Comment AST or null (if the raw rule cannot be parsed as comment)
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0) {
        // Ignore non-comment rules
        if (!CommentParser.isCommentRule(raw)) {
            return null;
        }
        // Note: we parse non-functional comments at the end,
        // if the input does not match any of the previous, more specific comment patterns
        return AgentCommentParser.parse(raw, options, baseOffset)
            || HintCommentParser.parse(raw, options, baseOffset)
            || PreProcessorCommentParser.parse(raw, options, baseOffset)
            || MetadataCommentParser.parse(raw, options, baseOffset)
            || ConfigCommentParser.parse(raw, options, baseOffset)
            || SimpleCommentParser.parse(raw, options, baseOffset);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/sprintf-js@1.1.3/node_modules/sprintf-js/src/sprintf.js
var sprintf = __webpack_require__(63607);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+css-tokenizer@1.2.0/node_modules/@adguard/css-tokenizer/dist/csstokenizer.mjs
var csstokenizer = __webpack_require__(25651);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/misc/domain-list-parser.js + 1 modules
var domain_list_parser = __webpack_require__(26571);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/misc/modifier-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/**
 * `ModifierParser` is responsible for parsing modifiers.
 *
 * @example
 * `match-case`, `~third-party`, `domain=example.com|~example.org`
 */
class ModifierParser extends base_parser/* BaseParser */.V {
    /**
     * Parses a modifier.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     *
     * @returns Parsed modifier
     * @throws An error if modifier name or value is empty.
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0) {
        let offset = 0;
        // Skip leading whitespace
        offset = string/* StringUtils */.$x.skipWS(raw, offset);
        // Save the offset of the first character of the modifier (whole modifier)
        const modifierStart = offset;
        // Check if the modifier is an exception
        let exception = false;
        if (raw[offset] === constants/* NEGATION_MARKER */.bP) {
            offset += constants/* NEGATION_MARKER */.bP.length;
            exception = true;
        }
        // Skip whitespace after the exception marker (if any)
        offset = string/* StringUtils */.$x.skipWS(raw, offset);
        // Save the offset of the first character of the modifier name
        const modifierNameStart = offset;
        // Find assignment operator
        const assignmentIndex = string/* StringUtils */.$x.findNextUnescapedCharacter(raw, constants/* MODIFIER_ASSIGN_OPERATOR */.li);
        // Find the end of the modifier
        const modifierEnd = Math.max(string/* StringUtils */.$x.skipWSBack(raw) + 1, modifierNameStart);
        // Modifier name can't be empty
        if (modifierNameStart === modifierEnd) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q('Modifier name cannot be empty', baseOffset, baseOffset + raw.length);
        }
        let modifier;
        let value;
        // If there is no assignment operator, the whole modifier is the name
        // without a value
        if (assignmentIndex === -1) {
            modifier = ValueParser.parse(raw.slice(modifierNameStart, modifierEnd), options, baseOffset + modifierNameStart);
        }
        else {
            // If there is an assignment operator, first we need to find the
            // end of the modifier name, then we can parse the value
            const modifierNameEnd = string/* StringUtils */.$x.skipWSBack(raw, assignmentIndex - 1) + 1;
            modifier = ValueParser.parse(raw.slice(modifierNameStart, modifierNameEnd), options, baseOffset + modifierNameStart);
            // Value can't be empty
            if (assignmentIndex + 1 === modifierEnd) {
                throw new adblock_syntax_error/* AdblockSyntaxError */.q('Modifier value cannot be empty', baseOffset, baseOffset + raw.length);
            }
            // Skip whitespace after the assignment operator
            const valueStart = string/* StringUtils */.$x.skipWS(raw, assignmentIndex + constants/* MODIFIER_ASSIGN_OPERATOR */.li.length);
            value = ValueParser.parse(raw.slice(valueStart, modifierEnd), options, baseOffset + valueStart);
        }
        const result = {
            type: 'Modifier',
            name: modifier,
            value,
            exception,
        };
        if (options.isLocIncluded) {
            result.start = baseOffset + modifierStart;
            result.end = baseOffset + modifierEnd;
        }
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/misc/modifier-list.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */






/* eslint-disable no-param-reassign */
/**
 * `ModifierListParser` is responsible for parsing modifier lists. Please note that the name is not
 * uniform, "modifiers" are also known as "options".
 *
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#basic-rules-modifiers}
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#non-basic-rules-modifiers}
 * @see {@link https://help.eyeo.com/adblockplus/how-to-write-filters#options}
 */
class ModifierListParser extends base_parser/* BaseParser */.V {
    /**
     * Parses the cosmetic rule modifiers, eg. `third-party,domain=example.com|~example.org`.
     *
     * _Note:_ you should remove `$` separator before passing the raw modifiers to this function,
     *  or it will be parsed in the first modifier.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @returns Parsed modifiers interface
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0) {
        const result = {
            type: 'ModifierList',
            children: [],
        };
        if (options.isLocIncluded) {
            result.start = baseOffset;
            result.end = baseOffset + raw.length;
        }
        let offset = string/* StringUtils */.$x.skipWS(raw);
        let separatorIndex = -1;
        // Split modifiers by unescaped commas
        while (offset < raw.length) {
            // Skip whitespace before the modifier
            offset = string/* StringUtils */.$x.skipWS(raw, offset);
            const modifierStart = offset;
            // Find the index of the first unescaped comma
            separatorIndex = string/* StringUtils */.$x.findNextUnescapedCharacter(raw, constants/* MODIFIERS_SEPARATOR */.b9, offset);
            const modifierEnd = separatorIndex === -1
                ? raw.length
                : string/* StringUtils */.$x.skipWSBack(raw, separatorIndex - 1) + 1;
            // Parse the modifier
            const modifier = ModifierParser.parse(raw.slice(modifierStart, modifierEnd), options, baseOffset + modifierStart);
            result.children.push(modifier);
            // Increment the offset to the next modifier (or the end of the string)
            offset = separatorIndex === -1 ? raw.length : separatorIndex + 1;
        }
        // Check if there are any modifiers after the last separator
        if (separatorIndex !== -1) {
            const modifierStart = string/* StringUtils */.$x.skipWS(raw, separatorIndex + 1);
            result.children.push(ModifierParser.parse(raw.slice(modifierStart, raw.length), options, baseOffset + modifierStart));
        }
        return result;
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/css/balancing.js
var balancing = __webpack_require__(31697);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/common/ubo-selector-common.js
var ubo_selector_common = __webpack_require__(31784);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/css/ubo-selector-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */









/**
 * @file Parser for special uBO selectors.
 */
/**
 * Possible error messages for uBO selectors. Formatted with {@link sprintf}.
 */
const ERROR_MESSAGES = {
    DUPLICATED_UBO_MODIFIER: "uBO modifier '%s' cannot be used more than once",
    EXPECTED_BUT_GOT_BEFORE: "Expected '%s' but got '%s' before '%s'",
    // eslint-disable-next-line max-len
    NEGATED_UBO_MODIFIER_CANNOT_BE_FOLLOWED_BY: "Negated uBO modifier '%s' cannot be followed by anything else than a closing parenthesis or a whitespace",
    NEGATED_UBO_MODIFIER_CANNOT_BE_PRECEDED_BY: "Negated uBO modifier '%s' cannot be preceded by '%s'",
    PSEUDO_CANNOT_BE_NESTED: "uBO modifier '%s' cannot be nested inside '%s', only '%s' is allowed as a wrapper",
    UBO_MODIFIER_CANNOT_BE_NESTED: "uBO modifier '%s' cannot be nested",
    UBO_STYLE_CANNOT_BE_FOLLOWED: 'uBO style injection cannot be followed by anything else than a whitespace',
};
/**
 * Dummy parameter for uBO modifiers in error messages.
 */
const DUMMY_PARAM = '...';
/**
 * Set of known uBO modifiers.
 *
 * @note We use `string` instead of `UboPseudoName` because we use this set for checking if a modifier is a known uBO,
 * and an unknown sequence is just a string.
 */
const KNOWN_UBO_MODIFIERS = new Set([
    ubo_selector_common/* UboPseudoName */.S.MatchesMedia,
    ubo_selector_common/* UboPseudoName */.S.MatchesPath,
    ubo_selector_common/* UboPseudoName */.S.Remove,
    ubo_selector_common/* UboPseudoName */.S.Style,
]);
/**
 * Helper function to check if the given selector has any uBO modifier. This function should be fast, because it's used
 * in the hot path of the parser.
 *
 * @param raw Raw selector string.
 * @returns `true` if the selector has any uBO modifier, `false` otherwise.
 */
const hasAnyUboModifier = (raw) => {
    // Find the first colon
    let colonIndex = raw.indexOf(constants/* COLON */.oH);
    while (colonIndex !== -1) {
        // Find next opening parenthesis
        const openingParenthesisIndex = raw.indexOf(constants/* OPEN_PARENTHESIS */.Cx, colonIndex + 1);
        // If there is no opening parenthesis, then the selector doesn't contain any uBO modifier
        if (openingParenthesisIndex === -1) {
            return false;
        }
        // Check if the modifier is a known uBO modifier
        if (KNOWN_UBO_MODIFIERS.has(raw.slice(colonIndex + 1, openingParenthesisIndex))) {
            return true;
        }
        // Find next colon
        colonIndex = raw.indexOf(constants/* COLON */.oH, openingParenthesisIndex + 1);
    }
    return false;
};
/**
 * A simple helper function to format a pseudo name for error messages.
 *
 * @param name Pseudo name.
 * @param wrapper Wrapper pseudo name (eg. `not`) (optional, defaults to `undefined`).
 * @returns Formatted pseudo name.
 * @example
 * ```ts
 * formatPseudoName('matches-path', 'not'); // => ':not(:matches-path(...))'
 * formatPseudoName('matches-media'); // => ':matches-media(...)'
 * ```
 */
const formatPseudoName = (name, wrapper) => {
    const result = [];
    if (wrapper) {
        result.push(constants/* COLON */.oH, wrapper, constants/* OPEN_PARENTHESIS */.Cx);
    }
    result.push(constants/* COLON */.oH, name, constants/* OPEN_PARENTHESIS */.Cx, DUMMY_PARAM, constants/* CLOSE_PARENTHESIS */.s1);
    if (wrapper) {
        result.push(constants/* CLOSE_PARENTHESIS */.s1);
    }
    return result.join(constants/* EMPTY */.wg);
};
/**
 * Parser for uBO selectors.
 */
class UboSelectorParser extends base_parser/* BaseParser */.V {
    /**
     * Parses a uBO selector list, eg. `div:matches-path(/path)`.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     *
     * @returns Parsed uBO selector {@link UboSelectorParser}.
     * @throws An {@link AdblockSyntaxError} if the selector list is syntactically invalid.
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0) {
        // Prepare helper variables
        const modifiers = {
            type: 'ModifierList',
            children: [],
        };
        if (options.isLocIncluded) {
            modifiers.start = baseOffset;
            modifiers.end = baseOffset + raw.length;
        }
        // Do not perform any parsing if the selector doesn't contain any uBO modifier
        // Parsing is a relatively expensive operation, but this check is cheap, so we can avoid unnecessary work
        // TODO: Move this check to the cosmetic parser (adjustable syntaxes - if uBO syntax is disabled, then we don't
        // need to check for uBO modifiers)
        if (!hasAnyUboModifier(raw)) {
            const selector = {
                type: 'Value',
                value: raw,
            };
            if (options.isLocIncluded) {
                selector.start = baseOffset;
                selector.end = baseOffset + raw.length;
            }
            const result = {
                type: 'UboSelector',
                selector,
                modifiers,
            };
            if (options.isLocIncluded) {
                result.start = baseOffset;
                result.end = baseOffset + raw.length;
            }
            return result;
        }
        // Simple way to check if a modifier is already processed to avoid duplicate modifiers
        const processedModifiers = new Set();
        // We need to keep track of the tokens for handling negations properly
        const tokens = [];
        // This array is used to mark the character slots in the selector string that are occupied by uBO modifiers
        const uboIndexes = new Array(raw.length);
        const uboModifierStack = [];
        let i = 0;
        // Helper function to stack a uBO modifier
        const stackModifier = (modifier) => {
            if (processedModifiers.has(modifier.name)) {
                throw new adblock_syntax_error/* AdblockSyntaxError */.q((0,sprintf.sprintf)(ERROR_MESSAGES.DUPLICATED_UBO_MODIFIER, formatPseudoName(modifier.name)), baseOffset + modifier.modifierStart, baseOffset + raw.length);
            }
            uboModifierStack.push(modifier);
        };
        // Tokenize the selector, calculate the balance
        (0,balancing/* tokenizeFnBalanced */.g)(raw, (type, start, end, _, balance) => {
            // Special case: style injection (`:style(...)` and `:remove()`) can only be used at the end of the
            // selector, like
            //  - `div:style(...)`,
            //  - `div:matches-media(...):style(...)`,
            //  - `div:remove()`,
            // etc.
            //
            // But not like
            //  - `:style(...) div`,
            //  - `:matches-media(...):style(...) div`,
            //  - `:remove() div`,
            // etc.
            //
            // The one exception is whitespace, which is allowed after style injection, like
            //  - `div:style(...) `,
            //  - `div:matches-media(...):style(...) `,
            //  - `div:remove() `,
            // etc.
            if ((processedModifiers.has(ubo_selector_common/* UboPseudoName */.S.Style)
                || processedModifiers.has(ubo_selector_common/* UboPseudoName */.S.Remove))
                && type !== csstokenizer/* TokenType */.ks.Whitespace) {
                throw new adblock_syntax_error/* AdblockSyntaxError */.q(ERROR_MESSAGES.UBO_STYLE_CANNOT_BE_FOLLOWED, baseOffset + start, baseOffset + raw.length);
            }
            // Check for pseudo classes (colon followed by a function)
            if (tokens[i - 1]?.type === csstokenizer/* TokenType */.ks.Colon && type === csstokenizer/* TokenType */.ks.Function) {
                // Since closing parenthesis is always included in the function token, but we only need the function
                // name, we need to cut off the last character, this is why we use `end - 1` here
                const fn = raw.slice(start, end - 1);
                // Check if the pseudo class is a known uBO modifier
                if (KNOWN_UBO_MODIFIERS.has(fn)) {
                    // Generally, uBO modifiers cannot be nested, like
                    //  - `:any(:matches-media(...))`,
                    //  - `:matches-media(:matches-media(...))`,
                    //  - `:not(style(...))`,
                    //  etc.
                    if (balance > 1) {
                        // However, we have one exception: `:matches-path()` can be nested inside `:not()`s, like:
                        //  - `:not(:matches-path(...))`,
                        //  - `:not(:not(:matches-path(...)))`,
                        //  etc.
                        //
                        // But it can't be nested inside any other pseudo class, like:
                        //  - `:anything(:matches-path(...))`,
                        //  etc.
                        //
                        // Moreover, :not() can't contain any other data, like
                        //  - `:not(div:matches-path(...))`,
                        //  - `:not(:matches-path(...):matches-path(...))`,
                        //  - `:not(:matches-path(...) div)`,
                        // etc.
                        if (fn === ubo_selector_common/* UboPseudoName */.S.MatchesPath) {
                            if (uboModifierStack.length > 0) {
                                throw new adblock_syntax_error/* AdblockSyntaxError */.q((0,sprintf.sprintf)(ERROR_MESSAGES.PSEUDO_CANNOT_BE_NESTED, formatPseudoName(ubo_selector_common/* UboPseudoName */.S.MatchesPath), formatPseudoName(uboModifierStack[uboModifierStack.length - 1].name), formatPseudoName(constants/* CSS_NOT_PSEUDO */.vr)), baseOffset + start - 1, baseOffset + raw.length);
                            }
                            let isException = false;
                            let modifierBalance = balance;
                            let modifierStart = start;
                            for (let j = i - 1; j >= 0; j -= 1) {
                                // If we have reached the root level, then we should check if the `not` function is
                                // preceded by a colon (which means that it's a pseudo class)
                                if (tokens[j].balance === 0) {
                                    modifierStart = tokens[j].start;
                                    modifierBalance = tokens[j].balance;
                                    break;
                                }
                                else if (tokens[j].type === csstokenizer/* TokenType */.ks.Colon
                                    || tokens[j].type === csstokenizer/* TokenType */.ks.Whitespace) {
                                    continue;
                                }
                                else if (tokens[j].type === csstokenizer/* TokenType */.ks.Function) {
                                    const wrapperFnName = raw.slice(tokens[j].start, tokens[j].end - 1);
                                    if (wrapperFnName !== constants/* CSS_NOT_PSEUDO */.vr) {
                                        throw new adblock_syntax_error/* AdblockSyntaxError */.q((0,sprintf.sprintf)(ERROR_MESSAGES.PSEUDO_CANNOT_BE_NESTED, formatPseudoName(ubo_selector_common/* UboPseudoName */.S.MatchesPath), formatPseudoName(wrapperFnName), formatPseudoName(constants/* CSS_NOT_PSEUDO */.vr)), baseOffset + tokens[j].start - 1, baseOffset + raw.length);
                                    }
                                    if (tokens[j - 1]?.type !== csstokenizer/* TokenType */.ks.Colon) {
                                        const got = tokens[j - 1]?.type
                                            ? (0,csstokenizer/* getFormattedTokenName */.bZ)(tokens[j - 1]?.type)
                                            : 'nothing';
                                        throw new adblock_syntax_error/* AdblockSyntaxError */.q((0,sprintf.sprintf)(ERROR_MESSAGES.EXPECTED_BUT_GOT_BEFORE, (0,csstokenizer/* getFormattedTokenName */.bZ)(csstokenizer/* TokenType */.ks.Colon), got, formatPseudoName(ubo_selector_common/* UboPseudoName */.S.MatchesPath, constants/* CSS_NOT_PSEUDO */.vr)), 
                                        // eslint-disable-next-line no-unsafe-optional-chaining
                                        baseOffset + tokens[j - 1]?.start || 0, baseOffset + raw.length);
                                    }
                                    isException = !isException;
                                    continue;
                                }
                                else {
                                    throw new adblock_syntax_error/* AdblockSyntaxError */.q((0,sprintf.sprintf)(ERROR_MESSAGES.NEGATED_UBO_MODIFIER_CANNOT_BE_PRECEDED_BY, formatPseudoName(ubo_selector_common/* UboPseudoName */.S.MatchesPath), (0,csstokenizer/* getFormattedTokenName */.bZ)(tokens[j].type)), baseOffset + tokens[j].start, baseOffset + raw.length);
                                }
                            }
                            stackModifier({
                                name: fn,
                                modifierStart,
                                modifierBalance,
                                nameStart: start,
                                nameEnd: end - 1, // ignore opening parenthesis
                                valueStart: end,
                                valueBalance: balance,
                                isException,
                            });
                        }
                        else {
                            throw new adblock_syntax_error/* AdblockSyntaxError */.q((0,sprintf.sprintf)(ERROR_MESSAGES.UBO_MODIFIER_CANNOT_BE_NESTED, formatPseudoName(fn)), baseOffset + start - 1, baseOffset + raw.length);
                        }
                    }
                    else {
                        stackModifier({
                            name: fn,
                            modifierStart: start - 1, // Include the colon
                            modifierBalance: balance,
                            nameStart: start,
                            nameEnd: end - 1, // ignore opening parenthesis
                            valueStart: end,
                            valueBalance: balance,
                            isException: false,
                        });
                    }
                }
            }
            else {
                // Get the last stacked modifier
                const lastStackedModifier = uboModifierStack[uboModifierStack.length - 1];
                // Do not allow any other token after `:matches-path(...)` inside `:not(...)`
                if (lastStackedModifier?.name === ubo_selector_common/* UboPseudoName */.S.MatchesPath && lastStackedModifier?.isException) {
                    if (!(type === csstokenizer/* TokenType */.ks.CloseParenthesis || type === csstokenizer/* TokenType */.ks.Whitespace)
                        && balance < lastStackedModifier.valueBalance) {
                        throw new adblock_syntax_error/* AdblockSyntaxError */.q((0,sprintf.sprintf)(ERROR_MESSAGES.NEGATED_UBO_MODIFIER_CANNOT_BE_FOLLOWED_BY, formatPseudoName(ubo_selector_common/* UboPseudoName */.S.MatchesPath), (0,csstokenizer/* getFormattedTokenName */.bZ)(type)), baseOffset + start, baseOffset + raw.length);
                    }
                }
                // If we have reached a closing parenthesis, then we should check if it closes the last stacked modifier
                // and if so, pop it from the stack
                if (type === csstokenizer/* TokenType */.ks.CloseParenthesis && lastStackedModifier) {
                    if (balance === Math.max(0, lastStackedModifier.valueBalance - 1)) {
                        lastStackedModifier.valueEnd = start;
                    }
                    if (balance === Math.max(0, lastStackedModifier.modifierBalance - 1)) {
                        const modifierName = {
                            type: 'Value',
                            value: lastStackedModifier.name,
                        };
                        if (options.isLocIncluded) {
                            // TODO: Refactor
                            modifierName.start = baseOffset + lastStackedModifier.nameStart;
                            modifierName.end = baseOffset + lastStackedModifier.nameEnd;
                        }
                        const value = {
                            type: 'Value',
                            value: raw.slice(lastStackedModifier.valueStart, lastStackedModifier.valueEnd),
                        };
                        if (options.isLocIncluded) {
                            value.start = baseOffset + lastStackedModifier.valueStart;
                            // It's safe to use `!` here, because we determined the value end index in the
                            // previous `if` statement
                            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
                            value.end = baseOffset + lastStackedModifier.valueEnd;
                        }
                        const modifier = {
                            type: 'Modifier',
                            name: modifierName,
                            value,
                            exception: lastStackedModifier.isException,
                        };
                        if (options.isLocIncluded) {
                            modifier.start = baseOffset + lastStackedModifier.modifierStart;
                            modifier.end = baseOffset + end;
                        }
                        modifiers.children.push(modifier);
                        processedModifiers.add(lastStackedModifier.name);
                        uboModifierStack.pop();
                        // Mark the character slots in the selector string that are occupied by uBO modifiers
                        uboIndexes.fill(true, lastStackedModifier.modifierStart, end);
                    }
                }
            }
            // Save the token to the history and increase the index
            tokens.push({
                type,
                start,
                end,
                balance,
            });
            i += 1;
        });
        const selector = {
            type: 'Value',
            value: raw
                .split(constants/* EMPTY */.wg)
                .map((char, p) => (uboIndexes[p] ? constants/* EMPTY */.wg : char))
                .join(constants/* EMPTY */.wg)
                .trim(),
        };
        if (options.isLocIncluded) {
            selector.start = baseOffset;
            selector.end = baseOffset + raw.length;
        }
        const result = {
            type: 'UboSelector',
            selector,
            modifiers,
        };
        if (options.isLocIncluded) {
            result.start = baseOffset;
            result.end = baseOffset + raw.length;
        }
        return result;
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/css/adg-css-injection-parser.js
var adg_css_injection_parser = __webpack_require__(53088);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/common/abp-snippet-injection-body-common.js
var abp_snippet_injection_body_common = __webpack_require__(89814);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/cosmetic/body/abp-snippet-injection-body-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */








/**
 * @file uBlock scriptlet injection body parser
 */
/**
 * `AbpSnippetInjectionBodyParser` is responsible for parsing the body of an Adblock Plus-style snippet rule.
 *
 * Please note that the parser will parse any scriptlet rule if it is syntactically correct.
 * For example, it will parse this:
 * ```adblock
 * example.com#$#snippet0 arg0
 * ```
 *
 * but it didn't check if the scriptlet `snippet0` actually supported by any adblocker.
 *
 * @see {@link https://help.eyeo.com/adblockplus/snippet-filters-tutorial}
 */
class AbpSnippetInjectionBodyParser extends base_parser/* BaseParser */.V {
    /**
     * Parses the body of an Adblock Plus-style snippet rule.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @returns Node of the parsed scriptlet call body
     * @throws If the body is syntactically incorrect
     * @example
     * ```
     * #$#snippet0 arg0
     * ```
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0) {
        const result = {
            type: 'ScriptletInjectionRuleBody',
            children: [],
        };
        if (options.isLocIncluded) {
            result.start = baseOffset;
            result.end = baseOffset + raw.length;
        }
        let offset = 0;
        // Skip leading spaces
        offset = string/* StringUtils */.$x.skipWS(raw, offset);
        while (offset < raw.length) {
            offset = string/* StringUtils */.$x.skipWS(raw, offset);
            const scriptletCallStart = offset;
            // Find the next semicolon or the end of the string
            let semicolonIndex = string/* StringUtils */.$x.findUnescapedNonStringNonRegexChar(raw, constants/* SEMICOLON */.I8, offset);
            if (semicolonIndex === -1) {
                semicolonIndex = raw.length;
            }
            const scriptletCallEnd = Math.max(string/* StringUtils */.$x.skipWSBack(raw, semicolonIndex - 1) + 1, scriptletCallStart);
            const params = ParameterListParser.parse(raw.slice(scriptletCallStart, scriptletCallEnd), options, baseOffset + scriptletCallStart, constants/* SPACE */.t6);
            // Parse the scriptlet call
            result.children.push(params);
            // Skip the semicolon
            offset = semicolonIndex + 1;
        }
        if (result.children.length === 0) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q(abp_snippet_injection_body_common/* AbpSnippetInjectionBodyCommon */.H.ERROR_MESSAGES.EMPTY_SCRIPTLET_CALL, baseOffset, baseOffset + raw.length);
        }
        return result;
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/quotes.js
var quotes = __webpack_require__(8725);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/misc/ubo-parameter-list-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */








/**
 * Parser for uBO-specific parameter lists.
 */
class UboParameterListParser extends ParameterListParser {
    /**
     * Parses an "uBO-specific parameter list".
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @param separator Separator character (default: comma).
     * @param requireQuotes Whether to require quotes around the parameter values (default: false).
     * @param supportedQuotes Set of accepted quotes (default: {@link QUOTE_SET}).
     * @returns Parameter list node.
     *
     * @note Based on {@link https://github.com/gorhill/uBlock/blob/f9ab4b75041815e6e5690d80851189ae3dc660d0/src/js/static-filtering-parser.js#L607-L699} to provide consistency.
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0, separator = constants/* COMMA */.KE, requireQuotes = false, supportedQuotes = quotes/* QUOTE_SET */.iO) {
        // Prepare the parameter list node
        const params = {
            type: 'ParameterList',
            children: [],
        };
        const { length } = raw;
        if (options.isLocIncluded) {
            params.start = baseOffset;
            params.end = baseOffset + length;
        }
        let offset = 0;
        // TODO: Eliminate the need for extraNull
        let extraNull = false;
        while (offset < length) {
            offset = string/* StringUtils */.$x.skipWS(raw, offset);
            const paramStart = offset;
            let paramEnd = offset;
            if (supportedQuotes.has(raw[offset])) {
                // Find the closing quote
                const possibleClosingQuoteIndex = string/* StringUtils */.$x.findNextUnescapedCharacter(raw, raw[offset], offset + 1);
                if (possibleClosingQuoteIndex !== -1) {
                    // Next non-whitespace character after the closing quote should be the separator
                    const nextSeparatorIndex = string/* StringUtils */.$x.skipWS(raw, possibleClosingQuoteIndex + 1);
                    if (nextSeparatorIndex === length) {
                        // If the separator is not found, the param end is the end of the string
                        paramEnd = string/* StringUtils */.$x.skipWSBack(raw, length - 1) + 1;
                        offset = length;
                    }
                    else if (raw[nextSeparatorIndex] === separator) {
                        // If the quote is followed by a separator, we can use it as a closing quote
                        paramEnd = possibleClosingQuoteIndex + 1;
                        offset = nextSeparatorIndex + 1;
                    }
                    else {
                        if (requireQuotes) {
                            throw new adblock_syntax_error/* AdblockSyntaxError */.q(`Expected separator, got: '${raw[nextSeparatorIndex]}'`, baseOffset + nextSeparatorIndex, baseOffset + length);
                        }
                        /**
                         * At that point found `possibleClosingQuoteIndex` is wrong
                         * | is `offset`
                         * ~ is `possibleClosingQuoteIndex`
                         * ^ is `nextSeparatorIndex`
                         *
                         * Example 1: "abc, ').cba='1'"
                         *                  |      ~^
                         * Example 2: "abc, ').cba, '1'"
                         *                  |       ~^
                         * Example 3: "abc, ').cba='1', cba"
                         *                  |      ~^
                         *
                         * Search for separator before `possibleClosingQuoteIndex`
                         */
                        const separatorIndexBeforeQuote = string/* StringUtils */.$x.findNextUnescapedCharacterBackwards(raw, separator, possibleClosingQuoteIndex, constants/* ESCAPE_CHARACTER */.Kx, offset + 1);
                        if (separatorIndexBeforeQuote !== -1) {
                            // Found separator before (Example 2)
                            paramEnd = string/* StringUtils */.$x.skipWSBack(raw, separatorIndexBeforeQuote - 1) + 1;
                            offset = separatorIndexBeforeQuote + 1;
                        }
                        else {
                            // Didn't found separator before, search after
                            const separatorIndexAfterQuote = string/* StringUtils */.$x.findNextUnescapedCharacter(raw, separator, possibleClosingQuoteIndex);
                            if (separatorIndexAfterQuote !== -1) {
                                // We found separator after (Example 3)
                                paramEnd = string/* StringUtils */.$x.skipWSBack(raw, separatorIndexAfterQuote - 1) + 1;
                                offset = separatorIndexAfterQuote + 1;
                            }
                            else {
                                // If the separator is not found, the param end is the end of the string (Example 1)
                                paramEnd = string/* StringUtils */.$x.skipWSBack(raw, length - 1) + 1;
                                offset = length;
                            }
                        }
                    }
                }
                else {
                    if (requireQuotes) {
                        throw new adblock_syntax_error/* AdblockSyntaxError */.q('Expected closing quote, got end of string', baseOffset + offset, baseOffset + length);
                    }
                    // If the closing quote is not found, the param end is the end of the string
                    paramEnd = string/* StringUtils */.$x.skipWSBack(raw, length - 1) + 1;
                    offset = length;
                }
            }
            else {
                if (requireQuotes) {
                    throw new adblock_syntax_error/* AdblockSyntaxError */.q(`Expected quote, got: '${raw[offset]}'`, baseOffset + offset, baseOffset + length);
                }
                const nextSeparator = string/* StringUtils */.$x.findNextUnescapedCharacter(raw, separator, offset);
                if (nextSeparator === -1) {
                    // If the separator is not found, the param end is the end of the string
                    paramEnd = string/* StringUtils */.$x.skipWSBack(raw, length - 1) + 1;
                    offset = length;
                }
                else {
                    // Param end should be the last non-whitespace character before the separator
                    paramEnd = string/* StringUtils */.$x.skipWSBack(raw, nextSeparator - 1) + 1;
                    offset = nextSeparator + 1;
                    if (string/* StringUtils */.$x.skipWS(raw, length - 1) === nextSeparator) {
                        extraNull = true;
                    }
                }
            }
            if (paramStart < paramEnd) {
                params.children.push(ValueParser.parse(raw.slice(paramStart, paramEnd), options, baseOffset + paramStart));
            }
            else {
                params.children.push(null);
            }
        }
        if (extraNull) {
            params.children.push(null);
        }
        return params;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/cosmetic/body/ubo-scriptlet-injection-body-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/**
 * @file uBlock scriptlet injection body parser
 */
/**
 * `UboScriptletInjectionBodyParser` is responsible for parsing the body of a uBlock-style scriptlet rule.
 *
 * Please note that the parser will parse any scriptlet rule if it is syntactically correct.
 * For example, it will parse this:
 * ```adblock
 * example.com##+js(scriptlet0, arg0)
 * ```
 *
 * but it didn't check if the scriptlet `scriptlet0` actually supported by any adblocker.
 *
 * @see {@link https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#scriptlet-injection}
 */
class UboScriptletInjectionBodyParser extends base_parser/* BaseParser */.V {
    /**
     * Error messages used by the parser.
     */
    static ERROR_MESSAGES = {
        NO_SCRIPTLET_MASK: `Invalid uBO scriptlet call, no scriptlet call mask '${constants/* UBO_SCRIPTLET_MASK */.Rq}' found`,
        NO_OPENING_PARENTHESIS: `Invalid uBO scriptlet call, no opening parentheses '${constants/* OPEN_PARENTHESIS */.Cx}' found`,
        NO_CLOSING_PARENTHESIS: `Invalid uBO scriptlet call, no closing parentheses '${constants/* CLOSE_PARENTHESIS */.s1}' found`,
        NO_SCRIPTLET_NAME: 'Invalid uBO scriptlet call, no scriptlet name specified',
        WHITESPACE_AFTER_MASK: 'Invalid uBO scriptlet call, whitespace is not allowed after the scriptlet call mask',
    };
    /**
     * Parses the body of a uBlock-style scriptlet rule.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @returns Node of the parsed scriptlet call body
     * @throws If the body is syntactically incorrect
     * @example
     * ```
     * ##+js(scriptlet0, arg0)
     * ```
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0) {
        let offset = 0;
        // Skip leading spaces
        offset = string/* StringUtils */.$x.skipWS(raw, offset);
        let scriptletMaskLength = 0;
        if (raw.startsWith(constants/* UBO_SCRIPTLET_MASK */.Rq, offset)) {
            scriptletMaskLength = constants/* UBO_SCRIPTLET_MASK */.Rq.length;
        }
        else if (raw.startsWith(constants/* UBO_SCRIPTLET_MASK_LEGACY */.Vs, offset)) {
            scriptletMaskLength = constants/* UBO_SCRIPTLET_MASK_LEGACY */.Vs.length;
        }
        // Scriptlet call should start with "+js"
        if (!scriptletMaskLength) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q(this.ERROR_MESSAGES.NO_SCRIPTLET_MASK, baseOffset + offset, baseOffset + raw.length);
        }
        offset += scriptletMaskLength;
        // Whitespace is not allowed after the mask
        if (raw[offset] === constants/* SPACE */.t6) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q(this.ERROR_MESSAGES.WHITESPACE_AFTER_MASK, baseOffset + offset, baseOffset + raw.length);
        }
        // Parameter list should be wrapped in parentheses
        if (raw[offset] !== constants/* OPEN_PARENTHESIS */.Cx) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q(this.ERROR_MESSAGES.NO_OPENING_PARENTHESIS, baseOffset + offset, baseOffset + raw.length);
        }
        // Save the offset of the opening parentheses
        const openingParenthesesIndex = offset;
        // Skip whitespace from the end
        const closingParenthesesIndex = string/* StringUtils */.$x.skipWSBack(raw, raw.length - 1);
        // Closing parentheses should be present
        if (raw[closingParenthesesIndex] !== constants/* CLOSE_PARENTHESIS */.s1
            || raw[closingParenthesesIndex - 1] === constants/* ESCAPE_CHARACTER */.Kx) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q(this.ERROR_MESSAGES.NO_CLOSING_PARENTHESIS, baseOffset + offset, baseOffset + raw.length);
        }
        const result = {
            type: 'ScriptletInjectionRuleBody',
            children: [],
        };
        if (options.isLocIncluded) {
            result.start = baseOffset;
            result.end = baseOffset + raw.length;
        }
        // Special case: empty scriptlet call, like +js(), +js( ), etc.
        if (string/* StringUtils */.$x.skipWS(raw, openingParenthesesIndex + 1) === closingParenthesesIndex) {
            return result;
        }
        // Parse parameter list
        const params = UboParameterListParser.parse(raw.slice(openingParenthesesIndex + 1, closingParenthesesIndex), options, baseOffset + openingParenthesesIndex + 1, constants/* COMMA */.KE);
        // Do not allow parameters without scriptlet: +js(, arg0, arg1)
        if (params.children.length > 0 && params.children[0] === null) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q(this.ERROR_MESSAGES.NO_SCRIPTLET_NAME, baseOffset + offset, baseOffset + raw.length);
        }
        result.children.push(params);
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/cosmetic/body/adg-scriptlet-injection-body-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */









/**
 * @file AdGuard scriptlet injection body parser
 */
/**
 * `AdgScriptletInjectionBodyParser` is responsible for parsing the body of an AdGuard-style scriptlet rule.
 *
 * Please note that the parser will parse any scriptlet rule if it is syntactically correct.
 * For example, it will parse this:
 * ```adblock
 * example.com#%#//scriptlet('scriptlet0', 'arg0')
 * ```
 *
 * but it didn't check if the scriptlet `scriptlet0` actually supported by any adblocker.
 *
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#scriptlets}
 */
class AdgScriptletInjectionBodyParser extends base_parser/* BaseParser */.V {
    /**
     * Error messages used by the parser.
     */
    static ERROR_MESSAGES = {
        NO_SCRIPTLET_MASK: `Invalid ADG scriptlet call, no scriptlet call mask '${constants/* ADG_SCRIPTLET_MASK */.x$}' found`,
        NO_OPENING_PARENTHESIS: `Invalid ADG scriptlet call, no opening parentheses '${constants/* OPEN_PARENTHESIS */.Cx}' found`,
        NO_CLOSING_PARENTHESIS: `Invalid ADG scriptlet call, no closing parentheses '${constants/* CLOSE_PARENTHESIS */.s1}' found`,
        WHITESPACE_AFTER_MASK: 'Invalid ADG scriptlet call, whitespace is not allowed after the scriptlet call mask',
        NO_INCONSISTENT_QUOTES: 'Invalid ADG scriptlet call, inconsistent quotes',
        NO_UNCLOSED_PARAMETER: 'Invalid ADG scriptlet call, unclosed parameter',
        EXPECTED_QUOTE: "Invalid ADG scriptlet call, expected quote, got '%s'",
        EXPECTED_COMMA: "Invalid ADG scriptlet call, expected comma, got '%s'",
    };
    /**
     * Parses the body of an AdGuard-style scriptlet rule.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @returns Node of the parsed scriptlet call body
     * @throws If the body is syntactically incorrect
     * @example
     * ```
     * //scriptlet('scriptlet0', 'arg0')
     * ```
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0) {
        let offset = 0;
        // Skip leading spaces
        offset = string/* StringUtils */.$x.skipWS(raw, offset);
        // Scriptlet call should start with "//scriptlet"
        if (!raw.startsWith(constants/* ADG_SCRIPTLET_MASK */.x$, offset)) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q(this.ERROR_MESSAGES.NO_SCRIPTLET_MASK, baseOffset + offset, baseOffset + raw.length);
        }
        offset += constants/* ADG_SCRIPTLET_MASK */.x$.length;
        // Whitespace is not allowed after the mask
        if (raw[offset] === constants/* SPACE */.t6) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q(this.ERROR_MESSAGES.WHITESPACE_AFTER_MASK, baseOffset + offset, baseOffset + raw.length);
        }
        // Parameter list should be wrapped in parentheses
        if (raw[offset] !== constants/* OPEN_PARENTHESIS */.Cx) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q(this.ERROR_MESSAGES.NO_OPENING_PARENTHESIS, baseOffset + offset, baseOffset + raw.length);
        }
        // Save the offset of the opening parentheses
        const openingParenthesesIndex = offset;
        // Skip whitespace from the end
        const closingParenthesesIndex = string/* StringUtils */.$x.skipWSBack(raw, raw.length - 1);
        // Closing parentheses should be present
        if (raw[closingParenthesesIndex] !== constants/* CLOSE_PARENTHESIS */.s1
            || raw[closingParenthesesIndex - 1] === constants/* ESCAPE_CHARACTER */.Kx) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q(this.ERROR_MESSAGES.NO_CLOSING_PARENTHESIS, baseOffset + offset, baseOffset + raw.length);
        }
        // Skip space, if any
        offset = string/* StringUtils */.$x.skipWS(raw, offset + 1);
        const result = {
            type: 'ScriptletInjectionRuleBody',
            children: [],
        };
        if (options.isLocIncluded) {
            result.start = baseOffset;
            result.end = baseOffset + raw.length;
        }
        // Special case: empty scriptlet call, like `//scriptlet()`, `//scriptlet( )` etc.
        if (string/* StringUtils */.$x.skipWS(raw, openingParenthesesIndex + 1) === closingParenthesesIndex) {
            return result;
        }
        let detectedQuote = null;
        const parameterList = {
            type: 'ParameterList',
            children: [],
        };
        if (options.isLocIncluded) {
            parameterList.start = baseOffset + openingParenthesesIndex + 1;
            parameterList.end = baseOffset + closingParenthesesIndex;
        }
        while (offset < closingParenthesesIndex) {
            // Skip whitespace
            offset = string/* StringUtils */.$x.skipWS(raw, offset);
            // Expect comma if not first parameter
            if (parameterList.children.length > 0) {
                if (raw[offset] !== constants/* COMMA */.KE) {
                    throw new adblock_syntax_error/* AdblockSyntaxError */.q((0,sprintf.sprintf)(AdgScriptletInjectionBodyParser.ERROR_MESSAGES.EXPECTED_COMMA, raw[offset]), baseOffset + offset, baseOffset + raw.length);
                }
                // Eat the comma
                offset += 1;
                // Skip whitespace
                offset = string/* StringUtils */.$x.skipWS(raw, offset);
            }
            // Next character should be a quote
            if (raw[offset] === constants/* SINGLE_QUOTE */.ur || raw[offset] === constants/* DOUBLE_QUOTE */.fi) {
                if ((0,type_guards/* isNull */.kZ)(detectedQuote)) {
                    detectedQuote = raw[offset];
                }
                else if (detectedQuote !== raw[offset]) {
                    throw new adblock_syntax_error/* AdblockSyntaxError */.q(AdgScriptletInjectionBodyParser.ERROR_MESSAGES.NO_INCONSISTENT_QUOTES, baseOffset + offset, baseOffset + raw.length);
                }
                // Find next unescaped same quote
                const closingQuoteIndex = string/* StringUtils */.$x.findNextUnescapedCharacter(raw, detectedQuote, offset + 1);
                if (closingQuoteIndex === -1) {
                    throw new adblock_syntax_error/* AdblockSyntaxError */.q(AdgScriptletInjectionBodyParser.ERROR_MESSAGES.NO_UNCLOSED_PARAMETER, baseOffset + offset, baseOffset + raw.length);
                }
                // Save the parameter
                const parameter = ValueParser.parse(raw.slice(offset, closingQuoteIndex + 1), options, baseOffset + offset);
                parameterList.children.push(parameter);
                // Move after the closing quote
                offset = string/* StringUtils */.$x.skipWS(raw, closingQuoteIndex + 1);
            }
            else {
                throw new adblock_syntax_error/* AdblockSyntaxError */.q((0,sprintf.sprintf)(AdgScriptletInjectionBodyParser.ERROR_MESSAGES.EXPECTED_QUOTE, raw[offset]), baseOffset + offset, baseOffset + raw.length);
            }
        }
        result.children.push(parameterList);
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/cosmetic/cosmetic-rule-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




















/**
 * Possible error messages for uBO selectors. Formatted with {@link sprintf}.
 */
const cosmetic_rule_parser_ERROR_MESSAGES = {
    EMPTY_RULE_BODY: 'Empty rule body',
    INVALID_BODY_FOR_SEPARATOR: "Body '%s' is not valid for the '%s' cosmetic rule separator",
    MISSING_ADGUARD_MODIFIER_LIST_END: "Missing '%s' at the end of the AdGuard modifier list in pattern '%s'",
    MISSING_ADGUARD_MODIFIER_LIST_MARKER: "Missing '%s' at the beginning of the AdGuard modifier list in pattern '%s'",
    SYNTAXES_CANNOT_BE_MIXED: "'%s' syntax cannot be mixed with '%s' syntax",
    SYNTAX_DISABLED: "Parsing '%s' syntax is disabled, but the rule uses it",
};
const ADG_CSS_INJECTION_PATTERN = /^(?:.+){(?:.+)}$/;
/**
 * `CosmeticRuleParser` is responsible for parsing cosmetic rules.
 *
 * Where possible, it automatically detects the difference between supported syntaxes:
 *  - AdGuard
 *  - uBlock Origin
 *  - Adblock Plus
 *
 * If the syntax is common / cannot be determined, the parser gives `Common` syntax.
 *
 * Please note that syntactically correct rules are parsed even if they are not actually
 * compatible with the given adblocker. This is a completely natural behavior, meaningful
 * checking of compatibility is not done at the parser level.
 */
// TODO: Make raw body parsing optional
// TODO: Split into smaller sections
class CosmeticRuleParser extends base_parser/* BaseParser */.V {
    /**
     * Determines whether a rule is a cosmetic rule. The rule is considered cosmetic if it
     * contains a cosmetic rule separator.
     *
     * @param raw Raw rule
     * @returns `true` if the rule is a cosmetic rule, `false` otherwise
     */
    static isCosmeticRule(raw) {
        const trimmed = raw.trim();
        if (CommentParser.isCommentRule(trimmed)) {
            return false;
        }
        return cosmetic_rule_separator/* CosmeticRuleSeparatorUtils */.m.find(trimmed) !== null;
    }
    /**
     * Parses a cosmetic rule. The structure of the cosmetic rules:
     *  - pattern (AdGuard pattern can have modifiers, other syntaxes don't)
     *  - separator
     *  - body
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @returns
     * Parsed cosmetic rule AST or null if it failed to parse based on the known cosmetic rules
     * @throws If the input matches the cosmetic rule pattern but syntactically invalid
     */
    // TODO: Split to smaller functions
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0) {
        // Find cosmetic rule separator - each cosmetic rule must have it, otherwise it is not a cosmetic rule
        const separatorResult = cosmetic_rule_separator/* CosmeticRuleSeparatorUtils */.m.find(raw);
        if (!separatorResult) {
            return null;
        }
        let syntax = adblockers/* AdblockSyntax */.Y.Common;
        let modifiers;
        const patternStart = string/* StringUtils */.$x.skipWS(raw);
        const patternEnd = string/* StringUtils */.$x.skipWSBack(raw, separatorResult.start - 1) + 1;
        const bodyStart = string/* StringUtils */.$x.skipWS(raw, separatorResult.end);
        const bodyEnd = string/* StringUtils */.$x.skipWSBack(raw) + 1;
        // Note we use '<=' instead of '===' because we have bidirectional trim
        if (bodyEnd <= bodyStart) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q(cosmetic_rule_parser_ERROR_MESSAGES.EMPTY_RULE_BODY, baseOffset, baseOffset + raw.length);
        }
        // Step 1. Parse the pattern: it can be a domain list or a domain list with modifiers (AdGuard)
        const rawPattern = raw.slice(patternStart, patternEnd);
        let patternOffset = patternStart;
        if (rawPattern[patternOffset] === constants/* OPEN_SQUARE_BRACKET */.cU) {
            // Save offset to the beginning of the modifier list for later
            const modifierListStart = patternOffset;
            // Consume opening square bracket
            patternOffset += 1;
            // Skip whitespace after opening square bracket
            patternOffset = string/* StringUtils */.$x.skipWS(rawPattern, patternOffset);
            // Open square bracket should be followed by a modifier separator: [$
            if (rawPattern[patternOffset] !== constants/* DOLLAR_SIGN */.nj) {
                throw new adblock_syntax_error/* AdblockSyntaxError */.q((0,sprintf.sprintf)(cosmetic_rule_parser_ERROR_MESSAGES.MISSING_ADGUARD_MODIFIER_LIST_MARKER, constants/* DOLLAR_SIGN */.nj, rawPattern), baseOffset + patternOffset, baseOffset + rawPattern.length);
            }
            // Consume modifier separator
            patternOffset += 1;
            // Skip whitespace after modifier separator
            patternOffset = string/* StringUtils */.$x.skipWS(rawPattern, patternOffset);
            // Modifier list ends with the last unescaped square bracket
            // We search for the last unescaped square bracket, because some modifiers can contain square brackets,
            // e.g. [$domain=/example[0-9]\.(com|org)/]##.ad
            const modifierListEnd = string/* StringUtils */.$x.findLastUnescapedCharacter(rawPattern, constants/* CLOSE_SQUARE_BRACKET */.A1);
            if (modifierListEnd === -1) {
                throw new adblock_syntax_error/* AdblockSyntaxError */.q((0,sprintf.sprintf)(cosmetic_rule_parser_ERROR_MESSAGES.MISSING_ADGUARD_MODIFIER_LIST_END, constants/* CLOSE_SQUARE_BRACKET */.A1, rawPattern), baseOffset + patternOffset, baseOffset + rawPattern.length);
            }
            // Parse modifier list
            modifiers = ModifierListParser.parse(raw.slice(patternOffset, modifierListEnd), options, baseOffset + patternOffset);
            // Expand modifier list location to include the opening and closing square brackets
            if (options.isLocIncluded) {
                modifiers.start = baseOffset + modifierListStart;
                modifiers.end = baseOffset + modifierListEnd + 1;
            }
            // Consume modifier list
            patternOffset = modifierListEnd + 1;
            // Change the syntax to ADG
            syntax = adblockers/* AdblockSyntax */.Y.Adg;
        }
        // Skip whitespace after modifier list
        patternOffset = string/* StringUtils */.$x.skipWS(rawPattern, patternOffset);
        // Parse domains
        const domains = domain_list_parser/* DomainListParser */.y.parse(rawPattern.slice(patternOffset), options, baseOffset + patternOffset);
        // Step 2. Parse the separator
        const separator = {
            type: 'Value',
            value: separatorResult.separator,
        };
        if (options.isLocIncluded) {
            separator.start = baseOffset + separatorResult.start;
            separator.end = baseOffset + separatorResult.end;
        }
        const exception = cosmetic_rule_separator/* CosmeticRuleSeparatorUtils */.m.isException(separatorResult.separator);
        // Step 3. Parse the rule body
        let rawBody = raw.slice(bodyStart, bodyEnd);
        /**
         * Ensures that the rule syntax is common or the expected one. This function is used to prevent mixing
         * different syntaxes in the same rule.
         *
         * @example
         * The following rule mixes AdGuard and uBO syntaxes, because it uses AdGuard modifier list and uBO
         * CSS injection:
         * ```adblock
         * [$path=/something]example.com##.foo:style(color: red)
         * ```
         * In this case, parser sets syntax to AdGuard, because it detects the AdGuard modifier list, but
         * when parsing the rule body, it detects uBO CSS injection, which is not compatible with AdGuard.
         *
         * @param expectedSyntax Expected syntax
         * @throws If the rule syntax is not common or the expected one
         */
        const expectCommonOrSpecificSyntax = (expectedSyntax) => {
            if (syntax !== adblockers/* AdblockSyntax */.Y.Common && syntax !== expectedSyntax) {
                throw new adblock_syntax_error/* AdblockSyntaxError */.q((0,sprintf.sprintf)(cosmetic_rule_parser_ERROR_MESSAGES.SYNTAXES_CANNOT_BE_MIXED, expectedSyntax, syntax), baseOffset + patternStart, baseOffset + bodyEnd);
            }
        };
        let uboSelector;
        // Parse UBO rule modifiers
        if (options.parseUboSpecificRules) {
            uboSelector = UboSelectorParser.parse(rawBody, options, baseOffset + bodyStart);
            rawBody = uboSelector.selector.value;
            // Do not allow ADG modifiers and UBO modifiers in the same rule
            if (uboSelector.modifiers && uboSelector.modifiers.children.length > 0) {
                // If modifiers are present, that means that the ADG modifier list was parsed
                expectCommonOrSpecificSyntax(adblockers/* AdblockSyntax */.Y.Ubo);
                // Change the syntax to uBO
                syntax = adblockers/* AdblockSyntax */.Y.Ubo;
                // Store the rule modifiers
                // Please note that not each special uBO modifier is a rule modifier, some of them are
                // used for CSS injection, for example `:style()` and `:remove()`
                for (const modifier of uboSelector.modifiers.children) {
                    // TODO: Add support for matches-media and element hiding rules
                    // TODO: Improve this condition if new uBO modifiers are added
                    if (modifier.name.value === ubo_selector_common/* UboPseudoName */.S.MatchesPath) {
                        // Prepare the modifier list if it does not exist yet
                        if (!modifiers) {
                            modifiers = {
                                type: 'ModifierList',
                                children: [],
                            };
                            if (options.isLocIncluded) {
                                modifiers.start = baseOffset + bodyStart;
                                modifiers.end = baseOffset + bodyEnd;
                            }
                        }
                        modifiers.children.push(modifier);
                    }
                }
            }
        }
        const raws = {
            text: raw,
        };
        const baseRule = {
            category: nodes/* RuleCategory */.$O.Cosmetic,
            exception,
            modifiers,
            domains,
            separator,
        };
        if (options.includeRaws) {
            baseRule.raws = raws;
        }
        if (options.isLocIncluded) {
            baseRule.start = baseOffset;
            baseRule.end = baseOffset + raw.length;
        }
        const parseUboCssInjection = () => {
            if (!uboSelector || !uboSelector.modifiers || uboSelector.modifiers.children?.length < 1) {
                return null;
            }
            expectCommonOrSpecificSyntax(adblockers/* AdblockSyntax */.Y.Ubo);
            const selectorList = uboSelector.selector;
            let declarationList;
            let mediaQueryList;
            let remove = false;
            for (const modifier of uboSelector.modifiers.children) {
                switch (modifier.name.value) {
                    case ubo_selector_common/* UboPseudoName */.S.Style:
                        declarationList = modifier.value;
                        break;
                    case ubo_selector_common/* UboPseudoName */.S.Remove:
                        declarationList = {
                            type: 'Value',
                            value: '',
                        };
                        remove = true;
                        break;
                    case ubo_selector_common/* UboPseudoName */.S.MatchesMedia:
                        mediaQueryList = modifier.value;
                        break;
                }
            }
            // If neither `:style()` nor `:remove()` is present
            if (!declarationList) {
                return null;
            }
            const body = {
                type: 'CssInjectionRuleBody',
                selectorList,
                declarationList,
                mediaQueryList,
                remove,
            };
            if (options.isLocIncluded) {
                body.start = baseOffset + bodyStart;
                body.end = baseOffset + bodyEnd;
            }
            return {
                syntax: adblockers/* AdblockSyntax */.Y.Ubo,
                type: nodes/* CosmeticRuleType */.k9.CssInjectionRule,
                body,
            };
        };
        const parseElementHiding = () => {
            const selectorList = {
                type: 'Value',
                value: rawBody,
            };
            if (options.isLocIncluded) {
                selectorList.start = baseOffset + bodyStart;
                selectorList.end = baseOffset + bodyEnd;
            }
            const body = {
                type: 'ElementHidingRuleBody',
                selectorList,
            };
            if (options.isLocIncluded) {
                body.start = baseOffset + bodyStart;
                body.end = baseOffset + bodyEnd;
            }
            return {
                syntax,
                type: nodes/* CosmeticRuleType */.k9.ElementHidingRule,
                body,
            };
        };
        const parseAdgCssInjection = () => {
            // TODO: Improve this detection. Need to cover the following cases:
            // #$#body { color: red;
            // #$#@media (min-width: 100px) { body { color: red; }
            // ADG CSS injection
            if (!ADG_CSS_INJECTION_PATTERN.test(rawBody)) {
                return null;
            }
            expectCommonOrSpecificSyntax(adblockers/* AdblockSyntax */.Y.Adg);
            return {
                syntax: adblockers/* AdblockSyntax */.Y.Adg,
                type: nodes/* CosmeticRuleType */.k9.CssInjectionRule,
                body: adg_css_injection_parser/* AdgCssInjectionParser */.Ye.parse(rawBody, options, baseOffset + bodyStart),
            };
        };
        /**
         * Parses Adb CSS injection rules
         * eg: example.com##.foo { display: none; }
         *
         * @returns parsed rule
         */
        const parseAbpCssInjection = () => {
            if (!options.parseAbpSpecificRules) {
                return null;
            }
            // check if the rule contains both CSS block open and close characters
            // if none of them is present we can stop parsing
            if (rawBody.indexOf(constants/* CSS_BLOCK_OPEN */.zW) === -1 && rawBody.indexOf(constants/* CSS_BLOCK_CLOSE */.pi) === -1) {
                return null;
            }
            if (!(0,csstokenizer/* hasToken */.y0)(rawBody, new Set([csstokenizer/* TokenType */.ks.OpenCurlyBracket, csstokenizer/* TokenType */.ks.CloseCurlyBracket]))) {
                return null;
            }
            // try to parse the raw body as an AdGuard CSS injection rule
            const body = adg_css_injection_parser/* AdgCssInjectionParser */.Ye.parse(rawBody, options, baseOffset + bodyStart);
            // if the parsed rule type is a 'CssInjectionRuleBody', return the parsed rule
            return {
                syntax: adblockers/* AdblockSyntax */.Y.Abp,
                type: nodes/* CosmeticRuleType */.k9.CssInjectionRule,
                body,
            };
        };
        const parseAbpSnippetInjection = () => {
            if (!options.parseAbpSpecificRules) {
                throw new adblock_syntax_error/* AdblockSyntaxError */.q((0,sprintf.sprintf)(cosmetic_rule_parser_ERROR_MESSAGES.SYNTAX_DISABLED, adblockers/* AdblockSyntax */.Y.Abp), baseOffset + bodyStart, baseOffset + bodyEnd);
            }
            expectCommonOrSpecificSyntax(adblockers/* AdblockSyntax */.Y.Abp);
            const body = AbpSnippetInjectionBodyParser.parse(rawBody, options, baseOffset + bodyStart);
            if (options.isLocIncluded) {
                body.start = baseOffset + bodyStart;
                body.end = baseOffset + bodyEnd;
            }
            return {
                syntax: adblockers/* AdblockSyntax */.Y.Abp,
                type: nodes/* CosmeticRuleType */.k9.ScriptletInjectionRule,
                body,
            };
        };
        const parseUboScriptletInjection = () => {
            if (!rawBody.startsWith(constants/* UBO_SCRIPTLET_MASK */.Rq) && !rawBody.startsWith(constants/* UBO_SCRIPTLET_MASK_LEGACY */.Vs)) {
                return null;
            }
            if (!options.parseUboSpecificRules) {
                throw new adblock_syntax_error/* AdblockSyntaxError */.q((0,sprintf.sprintf)(cosmetic_rule_parser_ERROR_MESSAGES.SYNTAX_DISABLED, adblockers/* AdblockSyntax */.Y.Ubo), baseOffset + bodyStart, baseOffset + bodyEnd);
            }
            expectCommonOrSpecificSyntax(adblockers/* AdblockSyntax */.Y.Ubo);
            const body = UboScriptletInjectionBodyParser.parse(rawBody, options, baseOffset + bodyStart);
            if (options.isLocIncluded) {
                body.start = baseOffset + bodyStart;
                body.end = baseOffset + bodyEnd;
            }
            return {
                syntax: adblockers/* AdblockSyntax */.Y.Ubo,
                type: nodes/* CosmeticRuleType */.k9.ScriptletInjectionRule,
                body,
            };
        };
        const parseAdgScriptletInjection = () => {
            // ADG scriptlet injection
            if (!rawBody.startsWith(constants/* ADG_SCRIPTLET_MASK */.x$)) {
                return null;
            }
            expectCommonOrSpecificSyntax(adblockers/* AdblockSyntax */.Y.Adg);
            const body = AdgScriptletInjectionBodyParser.parse(rawBody, options, baseOffset + bodyStart);
            if (options.isLocIncluded) {
                body.start = baseOffset + bodyStart;
                body.end = baseOffset + bodyEnd;
            }
            return {
                syntax: adblockers/* AdblockSyntax */.Y.Adg,
                type: nodes/* CosmeticRuleType */.k9.ScriptletInjectionRule,
                body,
            };
        };
        const parseAdgJsInjection = () => {
            expectCommonOrSpecificSyntax(adblockers/* AdblockSyntax */.Y.Adg);
            const body = {
                type: 'Value',
                value: rawBody,
            };
            if (options.isLocIncluded) {
                body.start = baseOffset + bodyStart;
                body.end = baseOffset + bodyEnd;
            }
            return {
                syntax: adblockers/* AdblockSyntax */.Y.Adg,
                type: nodes/* CosmeticRuleType */.k9.JsInjectionRule,
                body,
            };
        };
        const parseUboHtmlFiltering = () => {
            if (!rawBody.startsWith(constants/* UBO_HTML_MASK */._h)) {
                return null;
            }
            if (!options.parseUboSpecificRules) {
                throw new adblock_syntax_error/* AdblockSyntaxError */.q((0,sprintf.sprintf)(cosmetic_rule_parser_ERROR_MESSAGES.SYNTAX_DISABLED, adblockers/* AdblockSyntax */.Y.Ubo), baseOffset + bodyStart, baseOffset + bodyEnd);
            }
            expectCommonOrSpecificSyntax(adblockers/* AdblockSyntax */.Y.Ubo);
            const body = {
                type: 'Value',
                value: rawBody,
            };
            if (options.isLocIncluded) {
                body.start = baseOffset + bodyStart;
                body.end = baseOffset + bodyEnd;
            }
            return {
                syntax: adblockers/* AdblockSyntax */.Y.Ubo,
                type: nodes/* CosmeticRuleType */.k9.HtmlFilteringRule,
                body,
            };
        };
        const parseAdgHtmlFiltering = () => {
            expectCommonOrSpecificSyntax(adblockers/* AdblockSyntax */.Y.Adg);
            const body = {
                type: 'Value',
                value: rawBody,
            };
            if (options.isLocIncluded) {
                body.start = baseOffset + bodyStart;
                body.end = baseOffset + bodyEnd;
            }
            return {
                syntax: adblockers/* AdblockSyntax */.Y.Adg,
                type: nodes/* CosmeticRuleType */.k9.HtmlFilteringRule,
                body,
            };
        };
        // Create a fast lookup table for cosmetic rule separators and their parsing functions.
        // One separator can have multiple parsing functions. If the first function returns null,
        // the next function is called, and so on.
        // If all functions return null, an error should be thrown.
        const separatorMap = {
            '##': [
                parseUboHtmlFiltering,
                parseUboScriptletInjection,
                parseUboCssInjection,
                parseAbpCssInjection,
                parseElementHiding,
            ],
            '#@#': [
                parseUboHtmlFiltering,
                parseUboScriptletInjection,
                parseUboCssInjection,
                parseAbpCssInjection,
                parseElementHiding,
            ],
            '#?#': [parseUboCssInjection, parseAbpCssInjection, parseElementHiding],
            '#@?#': [parseUboCssInjection, parseAbpCssInjection, parseElementHiding],
            '#$#': [parseAdgCssInjection, parseAbpSnippetInjection],
            '#@$#': [parseAdgCssInjection, parseAbpSnippetInjection],
            '#$?#': [parseAdgCssInjection],
            '#@$?#': [parseAdgCssInjection],
            '#%#': [parseAdgScriptletInjection, parseAdgJsInjection],
            '#@%#': [parseAdgScriptletInjection, parseAdgJsInjection],
            $$: [parseAdgHtmlFiltering],
            '$@$': [parseAdgHtmlFiltering],
        };
        const parseFunctions = separatorMap[separatorResult.separator];
        let restProps;
        for (const parseFunction of parseFunctions) {
            restProps = parseFunction();
            if (restProps) {
                break;
            }
        }
        // If none of the parsing functions returned a result, it means that the rule is unknown / invalid.
        if (!restProps) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q((0,sprintf.sprintf)(cosmetic_rule_parser_ERROR_MESSAGES.INVALID_BODY_FOR_SEPARATOR, rawBody, separatorResult.separator), baseOffset + bodyStart, baseOffset + bodyEnd);
        }
        // Combine the base rule with the rest of the properties.
        return {
            ...baseRule,
            ...restProps,
        };
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/network/network-rule-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */










/**
 * `NetworkRuleParser` is responsible for parsing network rules.
 *
 * Please note that this will parse all syntactically correct network rules.
 * Modifier compatibility is not checked at the parser level.
 *
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#basic-rules}
 * @see {@link https://help.eyeo.com/adblockplus/how-to-write-filters#basic}
 */
class NetworkRuleParser extends base_parser/* BaseParser */.V {
    /**
     * Parses a network rule (also known as basic rule).
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @returns Network rule AST
     *
     * @throws If the rule is syntactically incorrect.
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0) {
        let offset = 0;
        // Skip leading whitespace
        offset = string/* StringUtils */.$x.skipWS(raw, offset);
        // Handle exception rules
        let exception = false;
        // Rule starts with exception marker, eg @@||example.com,
        // where @@ is the exception marker
        if (raw.startsWith(constants/* NETWORK_RULE_EXCEPTION_MARKER */.rF, offset)) {
            offset += constants/* NETWORK_RULE_EXCEPTION_MARKER_LEN */.Lb;
            exception = true;
        }
        // Save the start of the pattern
        const patternStart = offset;
        // Find corresponding (last) separator ($) character (if any)
        const separatorIndex = NetworkRuleParser.findNetworkRuleSeparatorIndex(raw);
        // Save the end of the pattern
        const patternEnd = separatorIndex === -1
            ? string/* StringUtils */.$x.skipWSBack(raw) + 1
            : string/* StringUtils */.$x.skipWSBack(raw, separatorIndex - 1) + 1;
        // Parse pattern
        const pattern = ValueParser.parse(raw.slice(patternStart, patternEnd), options, baseOffset + patternStart);
        // Parse modifiers (if any)
        let modifiers;
        // Get a last non-whitespace index
        const lastNonWsIndex = string/* StringUtils */.$x.skipWSBack(raw);
        // Find start and end index of the modifiers
        const modifiersStart = separatorIndex + 1;
        const modifiersEnd = string/* StringUtils */.$x.skipWSBack(raw) + 1;
        if (separatorIndex !== -1) {
            // Check for empty modifiers
            if (separatorIndex === lastNonWsIndex) {
                throw new adblock_syntax_error/* AdblockSyntaxError */.q('Empty modifiers are not allowed', baseOffset + separatorIndex, baseOffset + raw.length);
            }
            modifiers = ModifierListParser.parse(raw.slice(modifiersStart, modifiersEnd), options, baseOffset + modifiersStart);
        }
        // Throw error if there is no pattern and no modifiers
        if (pattern.value.length === 0 && (modifiers === undefined || modifiers.children.length === 0)) {
            throw new adblock_syntax_error/* AdblockSyntaxError */.q('Network rule must have a pattern or modifiers', baseOffset, baseOffset + raw.length);
        }
        const result = {
            type: nodes/* NetworkRuleType */.vY.NetworkRule,
            category: nodes/* RuleCategory */.$O.Network,
            syntax: adblockers/* AdblockSyntax */.Y.Common,
            exception,
            pattern,
            modifiers,
        };
        if (options.includeRaws) {
            result.raws = {
                text: raw,
            };
        }
        if (options.isLocIncluded) {
            result.start = baseOffset;
            result.end = baseOffset + raw.length;
        }
        return result;
    }
    /**
     * Finds the index of the separator character in a network rule.
     *
     * @param rule Network rule to check
     * @returns The index of the separator character, or -1 if there is no separator
     */
    static findNetworkRuleSeparatorIndex(rule) {
        // As we are looking for the last separator, we start from the end of the string
        for (let i = rule.length - 1; i >= 0; i -= 1) {
            // If we find a potential separator, we should check
            // - if it's not escaped
            // - if it's not followed by a regex marker, for example: `example.org^$removeparam=/regex$/`
            // eslint-disable-next-line max-len
            if (rule[i] === constants/* NETWORK_RULE_SEPARATOR */.Xj && rule[i + 1] !== constants/* REGEX_MARKER */.Vb && rule[i - 1] !== constants/* ESCAPE_CHARACTER */.Kx) {
                return i;
            }
        }
        return -1;
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/tldts@5.7.112/node_modules/tldts/dist/es6/index.js + 12 modules
var es6 = __webpack_require__(13548);
// EXTERNAL MODULE: ./node_modules/.pnpm/is-ip@3.1.0/node_modules/is-ip/index.js
var is_ip = __webpack_require__(85183);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/network/host-rule-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */









/* eslint-disable no-param-reassign */
/**
 * `HostRuleParser` is responsible for parsing hosts-like rules.
 *
 * HostRule is a structure for simple host-level rules (i.e. /etc/hosts syntax).
 * It also supports "just domain" syntax. In this case, the IP will be set to 0.0.0.0.
 *
 * Rules syntax looks like this:
 * ```text
 * IP_address canonical_hostname [aliases...]
 * ```
 *
 * @example
 * `192.168.1.13 bar.mydomain.org bar` -- ipv4
 * `ff02::1 ip6-allnodes` -- ipv6
 * `::1 localhost ip6-localhost ip6-loopback` -- ipv6 aliases
 * `example.org` -- "just domain" syntax
 * @see {@link http://man7.org/linux/man-pages/man5/hosts.5.html}
 */
class HostRuleParser extends base_parser/* BaseParser */.V {
    static NULL_IP = '0.0.0.0';
    static COMMENT_MARKER = '#';
    /**
     * Parses an etc/hosts-like rule.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @returns Host rule node.
     *
     * @throws If the input contains invalid data.
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0) {
        let offset = string/* StringUtils */.$x.skipWS(raw, 0);
        const parts = [];
        let lastPartStartIndex = offset;
        let comment = null;
        const rawLength = raw.length;
        const parsePartIfNeeded = (startIndex, endIndex) => {
            if (startIndex < endIndex) {
                parts.push(ValueParser.parse(raw.slice(startIndex, endIndex), options, baseOffset + startIndex));
            }
        };
        while (offset < rawLength) {
            if (string/* StringUtils */.$x.isWhitespace(raw[offset])) {
                parsePartIfNeeded(lastPartStartIndex, offset);
                offset = string/* StringUtils */.$x.skipWS(raw, offset);
                lastPartStartIndex = offset;
            }
            else if (raw[offset] === HostRuleParser.COMMENT_MARKER) {
                const commentStart = offset;
                offset = string/* StringUtils */.$x.skipWS(raw, offset + 1);
                comment = ValueParser.parse(raw.slice(offset), options, baseOffset + commentStart);
                offset = rawLength;
                lastPartStartIndex = offset;
            }
            else {
                offset += 1;
            }
        }
        parsePartIfNeeded(lastPartStartIndex, offset);
        const partsLength = parts.length;
        if (partsLength < 1) {
            throw new Error('Host rule must have at least one domain name or an IP address and a domain name');
        }
        const result = {
            category: nodes/* RuleCategory */.$O.Network,
            type: nodes/* NetworkRuleType */.vY.HostRule,
            syntax: adblockers/* AdblockSyntax */.Y.Common,
        };
        if (partsLength === 1) {
            // "Just domain" syntax, e.g. `example.org`
            // In this case, domain should be valid and IP will be set to 0.0.0.0 by default
            if ((0,es6/* getDomain */.FB)(parts[0].value) !== parts[0].value) {
                throw new Error(`Not a valid domain: ${parts[0].value}`);
            }
            result.ip = {
                type: 'Value',
                value: HostRuleParser.NULL_IP,
            };
            result.hostnames = {
                type: 'HostnameList',
                children: parts,
            };
        }
        else if (partsLength > 1) {
            // IP + domain list syntax
            const [ip, ...hostnames] = parts;
            if (!is_ip(ip.value)) {
                throw new Error(`Invalid IP address: ${ip.value}`);
            }
            for (const { value } of hostnames) {
                if ((0,es6/* getHostname */.EW)(value) !== value) {
                    throw new Error(`Not a valid hostname: ${value}`);
                }
            }
            result.ip = ip;
            result.hostnames = {
                type: 'HostnameList',
                children: hostnames,
            };
        }
        if (comment) {
            result.comment = comment;
        }
        if (options.includeRaws) {
            result.raws = {
                text: raw,
            };
        }
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/rule-parser.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */










/* eslint-disable no-param-reassign */
/**
 * `RuleParser` is responsible for parsing the rules.
 *
 * It automatically determines the category and syntax of the rule, so you can pass any kind of rule to it.
 */
class RuleParser extends base_parser/* BaseParser */.V {
    /**
     * Helper method to parse host rules if the `parseHostRules` option is enabled, otherwise it will
     * parse network rules.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @returns Host rule or network rule node.
     */
    static parseHostOrNetworkRule(raw, options, baseOffset) {
        if (options.parseHostRules) {
            try {
                return HostRuleParser.parse(raw, options, baseOffset);
            }
            catch (error) {
                // Ignore the error, and fall back to network rule parser
            }
        }
        return NetworkRuleParser.parse(raw, options, baseOffset);
    }
    /**
     * Parse an adblock rule. You can pass any kind of rule to this method, since it will automatically determine
     * the category and syntax. If the rule is syntactically invalid, then an error will be thrown. If the
     * syntax / compatibility cannot be determined clearly, then the value of the `syntax` property will be
     * `Common`.
     *
     * For example, let's have this network rule:
     * ```adblock
     * ||example.org^$important
     * ```
     * The `syntax` property will be `Common`, since the rule is syntactically correct in every adblockers, but we
     * cannot determine at parsing level whether `important` is an existing option or not, nor if it exists, then
     * which adblocker supports it. This is why the `syntax` property is simply `Common` at this point.
     * The concrete COMPATIBILITY of the rule will be determined later, in a different, higher-level layer, called
     * "Compatibility table".
     *
     * But we can determinate the concrete syntax of this rule:
     * ```adblock
     * example.org#%#//scriptlet("scriptlet0", "arg0")
     * ```
     * since it is clearly an AdGuard-specific rule and no other adblockers uses this syntax natively. However, we also
     * cannot determine the COMPATIBILITY of this rule, as it is not clear at this point whether the `scriptlet0`
     * scriptlet is supported by AdGuard or not. This is also the task of the "Compatibility table". Here, we simply
     * mark the rule with the `AdGuard` syntax in this case.
     *
     * @param raw Raw input to parse.
     * @param options Global parser options.
     * @param baseOffset Starting offset of the input. Node locations are calculated relative to this offset.
     * @returns Adblock rule node
     * @throws If the input matches a pattern but syntactically invalid
     * @example
     * Take a look at the following example:
     * ```js
     * // Parse a network rule
     * const ast1 = RuleParser.parse("||example.org^$important");
     *
     * // Parse another network rule
     * const ast2 = RuleParser.parse("/ads.js^$important,third-party,domain=example.org|~example.com");
     *
     * // Parse a cosmetic rule
     * const ast2 = RuleParser.parse("example.org##.banner");
     *
     * // Parse another cosmetic rule
     * const ast3 = RuleParser.parse("example.org#?#.banner:-abp-has(.ad)");
     *
     * // Parse a comment rule
     * const ast4 = RuleParser.parse("! Comment");
     *
     * // Parse an empty rule
     * const ast5 = RuleParser.parse("");
     *
     * // Parse a comment rule (with metadata)
     * const ast6 = RuleParser.parse("! Title: Example");
     *
     * // Parse a pre-processor rule
     * const ast7 = RuleParser.parse("!#if (adguard)");
     * ```
     */
    static parse(raw, options = parser_options/* defaultParserOptions */.n, baseOffset = 0) {
        try {
            // Empty lines / rules (handle it just for convenience)
            if (raw.trim().length === 0) {
                const result = {
                    type: 'EmptyRule',
                    category: nodes/* RuleCategory */.$O.Empty,
                    syntax: adblockers/* AdblockSyntax */.Y.Common,
                };
                if (options.includeRaws) {
                    result.raws = {
                        text: raw,
                    };
                }
                if (options.isLocIncluded) {
                    result.start = baseOffset;
                    result.end = baseOffset + raw.length;
                }
                return result;
            }
            // Try to parse the rule with all sub-parsers. If a rule doesn't match
            // the pattern of a parser, then it will return `null`. For example, a
            // network rule will not match the pattern of a comment rule, since it
            // doesn't start with comment marker. But if the rule matches the
            // pattern of a parser, then it will return the AST of the rule, or
            // throw an error if the rule is syntactically invalid.
            if (options.ignoreComments) {
                if (CommentParser.isCommentRule(raw)) {
                    const result = {
                        type: 'EmptyRule',
                        category: nodes/* RuleCategory */.$O.Empty,
                        syntax: adblockers/* AdblockSyntax */.Y.Common,
                    };
                    if (options.includeRaws) {
                        result.raws = {
                            text: raw,
                        };
                    }
                    if (options.isLocIncluded) {
                        result.start = baseOffset;
                        result.end = baseOffset + raw.length;
                    }
                    return result;
                }
                return CosmeticRuleParser.parse(raw, options, baseOffset)
                    || RuleParser.parseHostOrNetworkRule(raw, options, baseOffset);
            }
            return CommentParser.parse(raw, options, baseOffset)
                || CosmeticRuleParser.parse(raw, options, baseOffset)
                || RuleParser.parseHostOrNetworkRule(raw, options, baseOffset);
        }
        catch (error) {
            // If tolerant mode is disabled or the error is not known, then simply
            // re-throw the error
            if (!options.tolerant || !(error instanceof Error)) {
                throw error;
            }
            const errorNode = {
                type: 'InvalidRuleError',
                name: error.name,
                message: error.message,
            };
            // If the error is an AdblockSyntaxError, then we can add the
            // location of the error to the result
            if (error instanceof adblock_syntax_error/* AdblockSyntaxError */.q) {
                errorNode.start = error.start;
                errorNode.end = error.end;
            }
            // Otherwise, return an invalid rule (tolerant mode)
            const result = {
                type: 'InvalidRule',
                category: nodes/* RuleCategory */.$O.Invalid,
                syntax: adblockers/* AdblockSyntax */.Y.Common,
                raw,
                error: errorNode,
            };
            if (options.includeRaws) {
                result.raws = {
                    text: raw,
                };
            }
            if (options.isLocIncluded) {
                result.start = baseOffset;
                result.end = baseOffset + raw.length;
            }
            return result;
        }
    }
}




/***/ }),

/***/ 54349:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   S: () => (/* binding */ BaseSerializer)
/* harmony export */ });
/* harmony import */ var _errors_not_implemented_error_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(65489);
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * @file Base serializer class.
 */
/**
 * Base class for serializers. Each serializer should extend this class.
 */
class BaseSerializer {
    /**
     * Serializes the AST node to a byte buffer.
     *
     * @param node AST node to serialize.
     * @param buffer Output byte buffer to write to.
     * @param args Additional, parser-specific arguments, if needed.
     */
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    static serialize(node, buffer, ...args) {
        throw new _errors_not_implemented_error_js__WEBPACK_IMPORTED_MODULE_0__/* .NotImplementedError */ .E();
    }
}




/***/ }),

/***/ 58421:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (/* binding */ NodeType),
/* harmony export */   y: () => (/* binding */ LogicalExpressionSerializer)
/* harmony export */ });
/* harmony import */ var _utils_constants_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(65523);
/* harmony import */ var _utils_type_guards_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(30239);
/* harmony import */ var _base_serializer_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54349);
/* harmony import */ var _marshalling_utils_misc_logical_expression_common_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(11128);
/* harmony import */ var _marshalling_utils_misc_binary_type_common_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16318);
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */






/**
 * Possible node types in the logical expression.
 */
const NodeType = {
    Variable: 'Variable',
    Operator: 'Operator',
    Parenthesis: 'Parenthesis',
};
/**
 * `LogicalExpressionSerializer` is responsible for serializing logical expressions.
 *
 * @example
 * From the following rule:
 * ```adblock
 * !#if (adguard_ext_android_cb || adguard_ext_safari)
 * ```
 * this parser will parse the expression `(adguard_ext_android_cb || adguard_ext_safari)`.
 */
// TODO: Refactor this class
class LogicalExpressionSerializer extends _base_serializer_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseSerializer */ .S {
    /**
     * Serializes a variable node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    // TODO: create a common serialize / deserialize interface for such nodes (Variable, Value, Parameter, etc.)
    static serializeVariableNode(node, buffer) {
        buffer.writeUint8(_marshalling_utils_misc_binary_type_common_js__WEBPACK_IMPORTED_MODULE_1__/* .BinaryTypeMarshallingMap */ .u.ExpressionVariableNode);
        const frequentName = _marshalling_utils_misc_logical_expression_common_js__WEBPACK_IMPORTED_MODULE_2__/* .KNOWN_VARIABLES_SERIALIZATION_MAP */ .Y5.get(node.name);
        if (!(0,_utils_type_guards_js__WEBPACK_IMPORTED_MODULE_3__/* .isUndefined */ .b0)(frequentName)) {
            buffer.writeUint8(_marshalling_utils_misc_logical_expression_common_js__WEBPACK_IMPORTED_MODULE_2__/* .VariableNodeBinaryPropMarshallingMap */ .Tf.FrequentName);
            buffer.writeUint8(frequentName);
        }
        else {
            buffer.writeUint8(_marshalling_utils_misc_logical_expression_common_js__WEBPACK_IMPORTED_MODULE_2__/* .VariableNodeBinaryPropMarshallingMap */ .Tf.Name);
            buffer.writeString(node.name);
        }
        if (!(0,_utils_type_guards_js__WEBPACK_IMPORTED_MODULE_3__/* .isUndefined */ .b0)(node.start)) {
            buffer.writeUint8(_marshalling_utils_misc_logical_expression_common_js__WEBPACK_IMPORTED_MODULE_2__/* .VariableNodeBinaryPropMarshallingMap */ .Tf.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,_utils_type_guards_js__WEBPACK_IMPORTED_MODULE_3__/* .isUndefined */ .b0)(node.end)) {
            buffer.writeUint8(_marshalling_utils_misc_logical_expression_common_js__WEBPACK_IMPORTED_MODULE_2__/* .VariableNodeBinaryPropMarshallingMap */ .Tf.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(_utils_constants_js__WEBPACK_IMPORTED_MODULE_4__/* .NULL */ .Cq);
    }
    /**
     * Serializes a parenthesis node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    static serializeParenthesisNode(node, buffer) {
        buffer.writeUint8(_marshalling_utils_misc_binary_type_common_js__WEBPACK_IMPORTED_MODULE_1__/* .BinaryTypeMarshallingMap */ .u.ExpressionParenthesisNode);
        buffer.writeUint8(_marshalling_utils_misc_logical_expression_common_js__WEBPACK_IMPORTED_MODULE_2__/* .ParenthesisNodeBinaryPropMarshallingMap */ .z0.Expression);
        LogicalExpressionSerializer.serialize(node.expression, buffer);
        if (!(0,_utils_type_guards_js__WEBPACK_IMPORTED_MODULE_3__/* .isUndefined */ .b0)(node.start)) {
            buffer.writeUint8(_marshalling_utils_misc_logical_expression_common_js__WEBPACK_IMPORTED_MODULE_2__/* .ParenthesisNodeBinaryPropMarshallingMap */ .z0.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,_utils_type_guards_js__WEBPACK_IMPORTED_MODULE_3__/* .isUndefined */ .b0)(node.end)) {
            buffer.writeUint8(_marshalling_utils_misc_logical_expression_common_js__WEBPACK_IMPORTED_MODULE_2__/* .ParenthesisNodeBinaryPropMarshallingMap */ .z0.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(_utils_constants_js__WEBPACK_IMPORTED_MODULE_4__/* .NULL */ .Cq);
    }
    /**
     * Serializes an operator node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    static serializeOperatorNode(node, buffer) {
        buffer.writeUint8(_marshalling_utils_misc_binary_type_common_js__WEBPACK_IMPORTED_MODULE_1__/* .BinaryTypeMarshallingMap */ .u.ExpressionOperatorNode);
        buffer.writeUint8(_marshalling_utils_misc_logical_expression_common_js__WEBPACK_IMPORTED_MODULE_2__/* .OperatorNodeBinaryPropMarshallingMap */ .hc.Operator);
        const operatorBinary = _marshalling_utils_misc_logical_expression_common_js__WEBPACK_IMPORTED_MODULE_2__/* .LOGICAL_EXPRESSION_OPERATOR_SERIALISATION_MAP */ .td.get(node.operator);
        if ((0,_utils_type_guards_js__WEBPACK_IMPORTED_MODULE_3__/* .isUndefined */ .b0)(operatorBinary)) {
            throw new Error(`Unknown operator: ${node.operator}`);
        }
        buffer.writeUint8(operatorBinary);
        buffer.writeUint8(_marshalling_utils_misc_logical_expression_common_js__WEBPACK_IMPORTED_MODULE_2__/* .OperatorNodeBinaryPropMarshallingMap */ .hc.Left);
        LogicalExpressionSerializer.serialize(node.left, buffer);
        if (node.right) {
            buffer.writeUint8(_marshalling_utils_misc_logical_expression_common_js__WEBPACK_IMPORTED_MODULE_2__/* .OperatorNodeBinaryPropMarshallingMap */ .hc.Right);
            LogicalExpressionSerializer.serialize(node.right, buffer);
        }
        if (!(0,_utils_type_guards_js__WEBPACK_IMPORTED_MODULE_3__/* .isUndefined */ .b0)(node.start)) {
            buffer.writeUint8(_marshalling_utils_misc_logical_expression_common_js__WEBPACK_IMPORTED_MODULE_2__/* .OperatorNodeBinaryPropMarshallingMap */ .hc.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,_utils_type_guards_js__WEBPACK_IMPORTED_MODULE_3__/* .isUndefined */ .b0)(node.end)) {
            buffer.writeUint8(_marshalling_utils_misc_logical_expression_common_js__WEBPACK_IMPORTED_MODULE_2__/* .OperatorNodeBinaryPropMarshallingMap */ .hc.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(_utils_constants_js__WEBPACK_IMPORTED_MODULE_4__/* .NULL */ .Cq);
    }
    /**
     * Serializes a logical expression node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    static serialize(node, buffer) {
        switch (node.type) {
            case NodeType.Variable:
                LogicalExpressionSerializer.serializeVariableNode(node, buffer);
                break;
            case NodeType.Operator:
                LogicalExpressionSerializer.serializeOperatorNode(node, buffer);
                break;
            case NodeType.Parenthesis:
                LogicalExpressionSerializer.serializeParenthesisNode(node, buffer);
                break;
            default:
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                throw new Error(`Unexpected node type: ${node.type}`);
        }
        buffer.writeUint8(_utils_constants_js__WEBPACK_IMPORTED_MODULE_4__/* .NULL */ .Cq);
    }
}




/***/ }),

/***/ 88226:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Y: () => (/* binding */ AdblockSyntax)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * @file Possible adblock syntaxes are listed here.
 */
/**
 * Possible adblock syntaxes (supported by this library)
 */
const AdblockSyntax = {
    /**
     * Common syntax, which is supported by more than one adblocker (or by all adblockers).
     *
     * We typically use this syntax when we cannot determine the concrete syntax of the rule,
     * because the syntax is used by more than one adblocker natively.
     *
     * @example
     * - `||example.org^$important` is a common syntax, since it is used by all adblockers natively, and
     * we cannot determine at parsing level whether `important` is a valid option or not, and if it is valid,
     * then which adblocker supports it.
     */
    Common: 'Common',
    /**
     * Adblock Plus syntax.
     *
     * @example
     * - `example.org#$#abort-on-property-read alert` is an Adblock Plus syntax, since it is not used by any other
     * adblockers directly (probably supported by some on-the-fly conversion, but this is not the native syntax).
     * @see {@link https://adblockplus.org/}
     */
    Abp: 'AdblockPlus',
    /**
     * uBlock Origin syntax.
     *
     * @example
     * - `example.com##+js(set, atob, noopFunc)` is an uBlock Origin syntax, since it is not used by any other
     * adblockers directly (probably supported by some on-the-fly conversion, but this is not the native syntax).
     * @see {@link https://github.com/gorhill/uBlock}
     */
    Ubo: 'UblockOrigin',
    /**
     * AdGuard syntax.
     *
     * @example
     * - `example.org#%#//scriptlet("abort-on-property-read", "alert")` is an AdGuard syntax, since it is not used
     * by any other adblockers directly (probably supported by some on-the-fly conversion, but this is not the native
     * syntax).
     * @see {@link https://adguard.com/}
     */
    Adg: 'AdGuard',
};




/***/ }),

/***/ 63396:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   T: () => (/* binding */ BINARY_SCHEMA_VERSION)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * @file Binary schema version.
 */
/**
 * Binary schema version.
 * This version number is used to ensure that the binary format is compatible with the current library version.
 * We increment this number if the serialized format changes in a way that is not backwards-compatible.
 */
const BINARY_SCHEMA_VERSION = 1;




/***/ }),

/***/ 96489:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   $: () => (/* binding */ ByteBuffer)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/* eslint-disable no-bitwise */
/**
 * @file Core ByteBuffer implementation for handling binary data in chunks.
 */
/**
 * Core ByteBuffer implementation for handling binary data in chunks.
 * This class allows for efficient byte storage and manipulation by organizing data into chunks
 * and providing methods to read and write bytes.
 */
class ByteBuffer {
    /**
     * The size of each chunk in bytes (32 KB).
     */
    // ! IMPORTANT: If you ever change this value, make sure to update optimized bitwise operations in the code.
    static CHUNK_SIZE = 32768; // 32 * 1024
    /**
     * An array of Uint8Array chunks that make up the buffer.
     */
    chunks;
    /**
     * The total number of chunks in the buffer.
     */
    chunksLength;
    /**
     * Constructs a new ByteBuffer instance.
     *
     * @param chunks Optional array of chunks to initialize the ByteBuffer with.
     * @param cloneChunks Flag indicating if the chunks should be cloned. For performance reasons,
     * its default value is `false`. If the original chunks are guaranteed not to change,
     * leave this flag as `false` to avoid unnecessary copying.
     */
    constructor(chunks, cloneChunks = false) {
        const chunksToUse = chunks ?? [];
        this.chunks = cloneChunks ? chunksToUse.map((chunk) => new Uint8Array(chunk)) : chunksToUse;
        this.chunksLength = chunks?.length ?? 0;
    }
    /**
     * Ensures that the buffer has enough capacity to accommodate a given position.
     * This method adjusts the `chunks` array size to ensure it can hold the specified position.
     *
     * @param position The position to ensure capacity for.
     */
    ensureCapacity(position) {
        // same as Math.floor(position / chunk size), just optimized for the 32 KB chunk size
        const requiredChunkIndex = position >>> 0x000F;
        for (let i = this.chunksLength; i <= requiredChunkIndex; i += 1) {
            this.chunks.push(new Uint8Array(ByteBuffer.CHUNK_SIZE));
            this.chunksLength += 1;
        }
    }
    /**
     * Writes a byte to the buffer at the specified position.
     * If the position is outside of the buffer's current size, the buffer is resized to accommodate it.
     *
     * @param position The position at which to write the byte.
     * @param value The byte value to write (0-255).
     */
    writeByte(position, value) {
        // same as Math.floor(position / chunk size), just optimized for the 32 KB chunk size
        const chunkIndex = position >>> 0x000F;
        // same as position % chunk size, just optimized for the 32 KB chunk size
        const chunkOffset = position & 0x7FFF;
        if (chunkIndex >= this.chunksLength) {
            this.ensureCapacity(position);
        }
        this.chunks[chunkIndex][chunkOffset] = value;
    }
    /**
     * Reads a byte from the specified position in the buffer.
     * Returns `undefined` if the position is outside of the buffer's current size.
     *
     * @param position The position from which to read the byte.
     * @returns The read byte value, or `undefined` if the position is out of bounds.
     */
    readByte(position) {
        const chunkIndex = position >>> 0x000F;
        const chunkOffset = position & 0x7FFF;
        if (chunkIndex >= this.chunksLength) {
            return undefined;
        }
        return this.chunks[chunkIndex][chunkOffset];
    }
}




/***/ }),

/***/ 65523:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A1: () => (/* binding */ CLOSE_SQUARE_BRACKET),
/* harmony export */   AT: () => (/* binding */ SMALL_LETTER_Z),
/* harmony export */   Ae: () => (/* binding */ CSS_MEDIA_MARKER),
/* harmony export */   BH: () => (/* binding */ AGLINT_COMMAND_PREFIX),
/* harmony export */   BR: () => (/* binding */ HINT_MARKER_LEN),
/* harmony export */   C: () => (/* binding */ HASHMARK),
/* harmony export */   CG: () => (/* binding */ CSS_PSEUDO_CLOSE),
/* harmony export */   CR: () => (/* binding */ CR),
/* harmony export */   Cq: () => (/* binding */ NULL),
/* harmony export */   Cx: () => (/* binding */ OPEN_PARENTHESIS),
/* harmony export */   Ec: () => (/* binding */ EXCLAMATION_MARK),
/* harmony export */   Ez: () => (/* binding */ AGLINT_CONFIG_COMMENT_MARKER),
/* harmony export */   FF: () => (/* binding */ FF),
/* harmony export */   H3: () => (/* binding */ SMALL_LETTER_A),
/* harmony export */   I6: () => (/* binding */ UBO_MATCHES_PATH_OPERATOR),
/* harmony export */   I8: () => (/* binding */ SEMICOLON),
/* harmony export */   IF: () => (/* binding */ IF),
/* harmony export */   II: () => (/* binding */ UINT8_MAX),
/* harmony export */   JD: () => (/* binding */ ADG_PATH_MODIFIER),
/* harmony export */   KE: () => (/* binding */ COMMA),
/* harmony export */   KT: () => (/* binding */ CRLF),
/* harmony export */   Kx: () => (/* binding */ ESCAPE_CHARACTER),
/* harmony export */   L5: () => (/* binding */ PIPE),
/* harmony export */   LF: () => (/* binding */ LF),
/* harmony export */   Lb: () => (/* binding */ NETWORK_RULE_EXCEPTION_MARKER_LEN),
/* harmony export */   Ln: () => (/* binding */ ASTERISK),
/* harmony export */   NW: () => (/* binding */ ADG_DOMAINS_MODIFIER),
/* harmony export */   Nb: () => (/* binding */ QUESTION_MARK),
/* harmony export */   PD: () => (/* binding */ PREPROCESSOR_MARKER),
/* harmony export */   Pe: () => (/* binding */ ADG_APP_MODIFIER),
/* harmony export */   Rq: () => (/* binding */ UBO_SCRIPTLET_MASK),
/* harmony export */   U4: () => (/* binding */ CSS_PSEUDO_MARKER),
/* harmony export */   UT: () => (/* binding */ EQUALS),
/* harmony export */   Vb: () => (/* binding */ REGEX_MARKER),
/* harmony export */   Vs: () => (/* binding */ UBO_SCRIPTLET_MASK_LEGACY),
/* harmony export */   Vw: () => (/* binding */ ADG_URL_MODIFIER),
/* harmony export */   Xj: () => (/* binding */ NETWORK_RULE_SEPARATOR),
/* harmony export */   _h: () => (/* binding */ UBO_HTML_MASK),
/* harmony export */   b9: () => (/* binding */ MODIFIERS_SEPARATOR),
/* harmony export */   bP: () => (/* binding */ NEGATION_MARKER),
/* harmony export */   bs: () => (/* binding */ WILDCARD),
/* harmony export */   cP: () => (/* binding */ CARET),
/* harmony export */   cU: () => (/* binding */ OPEN_SQUARE_BRACKET),
/* harmony export */   e0: () => (/* binding */ AMPERSAND),
/* harmony export */   e2: () => (/* binding */ CSS_PSEUDO_OPEN),
/* harmony export */   fB: () => (/* binding */ UNDERSCORE),
/* harmony export */   fW: () => (/* binding */ PIPE_MODIFIER_SEPARATOR),
/* harmony export */   fi: () => (/* binding */ DOUBLE_QUOTE),
/* harmony export */   g9: () => (/* binding */ NUMBER_9),
/* harmony export */   hk: () => (/* binding */ CAPITAL_LETTER_Z),
/* harmony export */   j6: () => (/* binding */ HINT_MARKER),
/* harmony export */   li: () => (/* binding */ MODIFIER_ASSIGN_OPERATOR),
/* harmony export */   nC: () => (/* binding */ NUMBER_0),
/* harmony export */   nj: () => (/* binding */ DOLLAR_SIGN),
/* harmony export */   nx: () => (/* binding */ PREPROCESSOR_MARKER_LEN),
/* harmony export */   o: () => (/* binding */ SLASH),
/* harmony export */   oH: () => (/* binding */ COLON),
/* harmony export */   oo: () => (/* binding */ COMMA_DOMAIN_LIST_SEPARATOR),
/* harmony export */   ot: () => (/* binding */ CAPITAL_LETTER_A),
/* harmony export */   pi: () => (/* binding */ CSS_BLOCK_CLOSE),
/* harmony export */   rF: () => (/* binding */ NETWORK_RULE_EXCEPTION_MARKER),
/* harmony export */   rM: () => (/* binding */ INCLUDE),
/* harmony export */   r_: () => (/* binding */ BACKSLASH),
/* harmony export */   s1: () => (/* binding */ CLOSE_PARENTHESIS),
/* harmony export */   sA: () => (/* binding */ PREPROCESSOR_SEPARATOR),
/* harmony export */   sV: () => (/* binding */ OPEN_CURLY_BRACKET),
/* harmony export */   t6: () => (/* binding */ SPACE),
/* harmony export */   ur: () => (/* binding */ SINGLE_QUOTE),
/* harmony export */   us: () => (/* binding */ SAFARI_CB_AFFINITY),
/* harmony export */   uu: () => (/* binding */ PLUS),
/* harmony export */   vr: () => (/* binding */ CSS_NOT_PSEUDO),
/* harmony export */   w1: () => (/* binding */ BACKTICK_QUOTE),
/* harmony export */   wH: () => (/* binding */ AT_SIGN),
/* harmony export */   wU: () => (/* binding */ CLOSE_CURLY_BRACKET),
/* harmony export */   wg: () => (/* binding */ EMPTY),
/* harmony export */   wn: () => (/* binding */ TAB),
/* harmony export */   x$: () => (/* binding */ ADG_SCRIPTLET_MASK),
/* harmony export */   y0: () => (/* binding */ DOT),
/* harmony export */   zW: () => (/* binding */ CSS_BLOCK_OPEN),
/* harmony export */   zg: () => (/* binding */ UINT16_MAX)
/* harmony export */ });
/* unused harmony exports CAPITAL_LETTERS, CAPITAL_LETTER_B, CAPITAL_LETTER_C, CAPITAL_LETTER_D, CAPITAL_LETTER_E, CAPITAL_LETTER_F, CAPITAL_LETTER_G, CAPITAL_LETTER_H, CAPITAL_LETTER_I, CAPITAL_LETTER_J, CAPITAL_LETTER_K, CAPITAL_LETTER_L, CAPITAL_LETTER_M, CAPITAL_LETTER_N, CAPITAL_LETTER_O, CAPITAL_LETTER_P, CAPITAL_LETTER_Q, CAPITAL_LETTER_R, CAPITAL_LETTER_S, CAPITAL_LETTER_T, CAPITAL_LETTER_U, CAPITAL_LETTER_V, CAPITAL_LETTER_W, CAPITAL_LETTER_X, CAPITAL_LETTER_Y, NEWLINE, NUMBERS, NUMBER_1, NUMBER_2, NUMBER_3, NUMBER_4, NUMBER_5, NUMBER_6, NUMBER_7, NUMBER_8, SMALL_LETTERS, SMALL_LETTER_B, SMALL_LETTER_C, SMALL_LETTER_D, SMALL_LETTER_E, SMALL_LETTER_F, SMALL_LETTER_G, SMALL_LETTER_H, SMALL_LETTER_I, SMALL_LETTER_J, SMALL_LETTER_K, SMALL_LETTER_L, SMALL_LETTER_M, SMALL_LETTER_N, SMALL_LETTER_O, SMALL_LETTER_P, SMALL_LETTER_Q, SMALL_LETTER_R, SMALL_LETTER_S, SMALL_LETTER_T, SMALL_LETTER_U, SMALL_LETTER_V, SMALL_LETTER_W, SMALL_LETTER_X, SMALL_LETTER_Y */
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * @file Constant values used by all parts of the library
 */
// TODO: remove unused constants
// General
/**
 * Empty string.
 */
const EMPTY = '';
const SPACE = ' ';
const TAB = '\t';
const COLON = ':';
const COMMA = ',';
const DOT = '.';
const SEMICOLON = ';';
const AMPERSAND = '&';
const ASTERISK = '*';
const AT_SIGN = '@';
const CARET = '^';
const DOLLAR_SIGN = '$';
const EQUALS = '=';
const EXCLAMATION_MARK = '!';
const HASHMARK = '#';
const PIPE = '|';
const PLUS = '+';
const QUESTION_MARK = '?';
const SLASH = '/';
const UNDERSCORE = '_';
// Escape characters
const BACKSLASH = '\\';
const ESCAPE_CHARACTER = BACKSLASH;
// Newlines
const CR = '\r';
const FF = '\f';
const LF = '\n';
const CRLF = CR + LF;
const NEWLINE = (/* unused pure expression or super */ null && (LF));
// Quotes
const BACKTICK_QUOTE = '`';
const DOUBLE_QUOTE = '"';
const SINGLE_QUOTE = '\'';
// Brackets
const OPEN_PARENTHESIS = '(';
const CLOSE_PARENTHESIS = ')';
const OPEN_SQUARE_BRACKET = '[';
const CLOSE_SQUARE_BRACKET = ']';
const OPEN_CURLY_BRACKET = '{';
const CLOSE_CURLY_BRACKET = '}';
// Letters
const SMALL_LETTER_A = 'a';
const SMALL_LETTER_B = 'b';
const SMALL_LETTER_C = 'c';
const SMALL_LETTER_D = 'd';
const SMALL_LETTER_E = 'e';
const SMALL_LETTER_F = 'f';
const SMALL_LETTER_G = 'g';
const SMALL_LETTER_H = 'h';
const SMALL_LETTER_I = 'i';
const SMALL_LETTER_J = 'j';
const SMALL_LETTER_K = 'k';
const SMALL_LETTER_L = 'l';
const SMALL_LETTER_M = 'm';
const SMALL_LETTER_N = 'n';
const SMALL_LETTER_O = 'o';
const SMALL_LETTER_P = 'p';
const SMALL_LETTER_Q = 'q';
const SMALL_LETTER_R = 'r';
const SMALL_LETTER_S = 's';
const SMALL_LETTER_T = 't';
const SMALL_LETTER_U = 'u';
const SMALL_LETTER_V = 'v';
const SMALL_LETTER_W = 'w';
const SMALL_LETTER_X = 'x';
const SMALL_LETTER_Y = 'y';
const SMALL_LETTER_Z = 'z';
/**
 * Set of all small letters.
 */
const SMALL_LETTERS = new Set([
    SMALL_LETTER_A,
    SMALL_LETTER_B,
    SMALL_LETTER_C,
    SMALL_LETTER_D,
    SMALL_LETTER_E,
    SMALL_LETTER_F,
    SMALL_LETTER_G,
    SMALL_LETTER_H,
    SMALL_LETTER_I,
    SMALL_LETTER_J,
    SMALL_LETTER_K,
    SMALL_LETTER_L,
    SMALL_LETTER_M,
    SMALL_LETTER_N,
    SMALL_LETTER_O,
    SMALL_LETTER_P,
    SMALL_LETTER_Q,
    SMALL_LETTER_R,
    SMALL_LETTER_S,
    SMALL_LETTER_T,
    SMALL_LETTER_U,
    SMALL_LETTER_V,
    SMALL_LETTER_W,
    SMALL_LETTER_X,
    SMALL_LETTER_Y,
    SMALL_LETTER_Z,
]);
// Capital letters
const CAPITAL_LETTER_A = 'A';
const CAPITAL_LETTER_B = 'B';
const CAPITAL_LETTER_C = 'C';
const CAPITAL_LETTER_D = 'D';
const CAPITAL_LETTER_E = 'E';
const CAPITAL_LETTER_F = 'F';
const CAPITAL_LETTER_G = 'G';
const CAPITAL_LETTER_H = 'H';
const CAPITAL_LETTER_I = 'I';
const CAPITAL_LETTER_J = 'J';
const CAPITAL_LETTER_K = 'K';
const CAPITAL_LETTER_L = 'L';
const CAPITAL_LETTER_M = 'M';
const CAPITAL_LETTER_N = 'N';
const CAPITAL_LETTER_O = 'O';
const CAPITAL_LETTER_P = 'P';
const CAPITAL_LETTER_Q = 'Q';
const CAPITAL_LETTER_R = 'R';
const CAPITAL_LETTER_S = 'S';
const CAPITAL_LETTER_T = 'T';
const CAPITAL_LETTER_U = 'U';
const CAPITAL_LETTER_V = 'V';
const CAPITAL_LETTER_W = 'W';
const CAPITAL_LETTER_X = 'X';
const CAPITAL_LETTER_Y = 'Y';
const CAPITAL_LETTER_Z = 'Z';
/**
 * Set of all capital letters.
 */
const CAPITAL_LETTERS = new Set([
    CAPITAL_LETTER_A,
    CAPITAL_LETTER_B,
    CAPITAL_LETTER_C,
    CAPITAL_LETTER_D,
    CAPITAL_LETTER_E,
    CAPITAL_LETTER_F,
    CAPITAL_LETTER_G,
    CAPITAL_LETTER_H,
    CAPITAL_LETTER_I,
    CAPITAL_LETTER_J,
    CAPITAL_LETTER_K,
    CAPITAL_LETTER_L,
    CAPITAL_LETTER_M,
    CAPITAL_LETTER_N,
    CAPITAL_LETTER_O,
    CAPITAL_LETTER_P,
    CAPITAL_LETTER_Q,
    CAPITAL_LETTER_R,
    CAPITAL_LETTER_S,
    CAPITAL_LETTER_T,
    CAPITAL_LETTER_U,
    CAPITAL_LETTER_V,
    CAPITAL_LETTER_W,
    CAPITAL_LETTER_X,
    CAPITAL_LETTER_Y,
    CAPITAL_LETTER_Z,
]);
// Numbers as strings
const NUMBER_0 = '0';
const NUMBER_1 = '1';
const NUMBER_2 = '2';
const NUMBER_3 = '3';
const NUMBER_4 = '4';
const NUMBER_5 = '5';
const NUMBER_6 = '6';
const NUMBER_7 = '7';
const NUMBER_8 = '8';
const NUMBER_9 = '9';
/**
 * Set of all numbers as strings.
 */
const NUMBERS = new Set([
    NUMBER_0,
    NUMBER_1,
    NUMBER_2,
    NUMBER_3,
    NUMBER_4,
    NUMBER_5,
    NUMBER_6,
    NUMBER_7,
    NUMBER_8,
    NUMBER_9,
]);
const REGEX_MARKER = '/';
const ADG_SCRIPTLET_MASK = '//scriptlet';
const UBO_SCRIPTLET_MASK = '+js';
const UBO_SCRIPTLET_MASK_LEGACY = 'script:inject';
const UBO_HTML_MASK = '^';
const UBO_MATCHES_PATH_OPERATOR = 'matches-path';
const ADG_PATH_MODIFIER = 'path';
const ADG_DOMAINS_MODIFIER = 'domain';
const ADG_APP_MODIFIER = 'app';
const ADG_URL_MODIFIER = 'url';
// Modifiers are separated by ",". For example: "script,domain=example.com"
const MODIFIERS_SEPARATOR = ',';
const MODIFIER_ASSIGN_OPERATOR = '=';
const NEGATION_MARKER = '~';
/**
 * The wildcard symbol — `*`.
 */
const WILDCARD = ASTERISK;
/**
 * Classic domain separator.
 *
 * @example
 * ```adblock
 * ! Domains are separated by ",":
 * example.com,~example.org##.ads
 * ```
 */
const COMMA_DOMAIN_LIST_SEPARATOR = ',';
/**
 * Modifier separator for $app, $denyallow, $domain, $method.
 *
 * @example
 * ```adblock
 * ! Domains are separated by "|":
 * ads.js^$script,domains=example.com|~example.org
 * ```
 */
const PIPE_MODIFIER_SEPARATOR = '|';
const CSS_MEDIA_MARKER = '@media';
const CSS_PSEUDO_MARKER = ':';
const CSS_PSEUDO_OPEN = '(';
const CSS_PSEUDO_CLOSE = ')';
const CSS_NOT_PSEUDO = 'not';
const CSS_BLOCK_OPEN = '{';
const CSS_BLOCK_CLOSE = '}';
const HINT_MARKER = '!+';
const HINT_MARKER_LEN = HINT_MARKER.length;
const NETWORK_RULE_EXCEPTION_MARKER = '@@';
const NETWORK_RULE_EXCEPTION_MARKER_LEN = NETWORK_RULE_EXCEPTION_MARKER.length;
const NETWORK_RULE_SEPARATOR = '$';
const AGLINT_COMMAND_PREFIX = 'aglint';
const AGLINT_CONFIG_COMMENT_MARKER = '--';
const PREPROCESSOR_MARKER = '!#';
const PREPROCESSOR_MARKER_LEN = PREPROCESSOR_MARKER.length;
const PREPROCESSOR_SEPARATOR = ' ';
const SAFARI_CB_AFFINITY = 'safari_cb_affinity';
const IF = 'if';
const INCLUDE = 'include';
const NULL = 0;
const UINT8_MAX = 255;
const UINT16_MAX = 65535;




/***/ }),

/***/ 90692:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   m: () => (/* binding */ CosmeticRuleSeparatorUtils)
/* harmony export */ });
/* harmony import */ var _nodes_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(64638);
/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(65523);
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */



/**
 * @file Cosmetic rule separator finder and categorizer
 */
/**
 * Utility class for cosmetic rule separators.
 */
class CosmeticRuleSeparatorUtils {
    /**
     * Checks whether the specified separator is an exception.
     *
     * @param separator Separator to check
     * @returns `true` if the separator is an exception, `false` otherwise
     */
    static isException(separator) {
        // Simply check the second character
        return separator[1] === _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .AT_SIGN */ .wH;
    }
    /**
     * Checks whether the specified separator is marks an Extended CSS cosmetic rule.
     *
     * @param separator Separator to check
     * @returns `true` if the separator is marks an Extended CSS cosmetic rule, `false` otherwise
     */
    static isExtendedCssMarker(separator) {
        return (separator === _nodes_index_js__WEBPACK_IMPORTED_MODULE_1__/* .CosmeticRuleSeparator */ .p5.ExtendedElementHiding
            || separator === _nodes_index_js__WEBPACK_IMPORTED_MODULE_1__/* .CosmeticRuleSeparator */ .p5.ExtendedElementHidingException
            || separator === _nodes_index_js__WEBPACK_IMPORTED_MODULE_1__/* .CosmeticRuleSeparator */ .p5.AdgExtendedCssInjection
            || separator === _nodes_index_js__WEBPACK_IMPORTED_MODULE_1__/* .CosmeticRuleSeparator */ .p5.AdgExtendedCssInjectionException);
    }
    /**
     * Looks for the cosmetic rule separator in the rule. This is a simplified version that
     * masks the recursive function.
     *
     * @param rule Raw rule
     * @returns Separator result or null if no separator was found
     */
    static find(rule) {
        /**
         * Helper function to create results of the `find` method.
         *
         * @param start Start position
         * @param separator Separator type
         * @returns Cosmetic rule separator node
         */
        // eslint-disable-next-line max-len
        function createResult(start, separator) {
            return {
                separator,
                start,
                end: start + separator.length,
            };
        }
        for (let i = 0; i < rule.length; i += 1) {
            if (rule[i] === '#') {
                if (rule[i + 1] === '#' && rule[i - 1] !== _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SPACE */ .t6) {
                    // ##
                    return createResult(i, _nodes_index_js__WEBPACK_IMPORTED_MODULE_1__/* .CosmeticRuleSeparator */ .p5.ElementHiding);
                }
                if (rule[i + 1] === '?' && rule[i + 2] === '#') {
                    // #?#
                    return createResult(i, _nodes_index_js__WEBPACK_IMPORTED_MODULE_1__/* .CosmeticRuleSeparator */ .p5.ExtendedElementHiding);
                }
                if (rule[i + 1] === '%' && rule[i + 2] === '#') {
                    // #%#
                    return createResult(i, _nodes_index_js__WEBPACK_IMPORTED_MODULE_1__/* .CosmeticRuleSeparator */ .p5.AdgJsInjection);
                }
                if (rule[i + 1] === '$') {
                    if (rule[i + 2] === '#') {
                        // #$#
                        return createResult(i, _nodes_index_js__WEBPACK_IMPORTED_MODULE_1__/* .CosmeticRuleSeparator */ .p5.AdgCssInjection);
                    }
                    if (rule[i + 2] === '?' && rule[i + 3] === '#') {
                        // #$?#
                        return createResult(i, _nodes_index_js__WEBPACK_IMPORTED_MODULE_1__/* .CosmeticRuleSeparator */ .p5.AdgExtendedCssInjection);
                    }
                }
                // Exceptions
                if (rule[i + 1] === '@') {
                    if (rule[i + 2] === '#' && rule[i - 1] !== _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SPACE */ .t6) {
                        // #@#
                        return createResult(i, _nodes_index_js__WEBPACK_IMPORTED_MODULE_1__/* .CosmeticRuleSeparator */ .p5.ElementHidingException);
                    }
                    if (rule[i + 2] === '?' && rule[i + 3] === '#') {
                        // #@?#
                        return createResult(i, _nodes_index_js__WEBPACK_IMPORTED_MODULE_1__/* .CosmeticRuleSeparator */ .p5.ExtendedElementHidingException);
                    }
                    if (rule[i + 2] === '%' && rule[i + 3] === '#') {
                        // #@%#
                        return createResult(i, _nodes_index_js__WEBPACK_IMPORTED_MODULE_1__/* .CosmeticRuleSeparator */ .p5.AdgJsInjectionException);
                    }
                    if (rule[i + 2] === '$') {
                        if (rule[i + 3] === '#') {
                            // #@$#
                            return createResult(i, _nodes_index_js__WEBPACK_IMPORTED_MODULE_1__/* .CosmeticRuleSeparator */ .p5.AdgCssInjectionException);
                        }
                        if (rule[i + 3] === '?' && rule[i + 4] === '#') {
                            // #@$?#
                            return createResult(i, _nodes_index_js__WEBPACK_IMPORTED_MODULE_1__/* .CosmeticRuleSeparator */ .p5.AdgExtendedCssInjectionException);
                        }
                    }
                }
            }
            if (rule[i] === '$') {
                if (rule[i + 1] === '$') {
                    // $$
                    return createResult(i, _nodes_index_js__WEBPACK_IMPORTED_MODULE_1__/* .CosmeticRuleSeparator */ .p5.AdgHtmlFiltering);
                }
                if (rule[i + 1] === '@' && rule[i + 2] === '$') {
                    // $@$
                    return createResult(i, _nodes_index_js__WEBPACK_IMPORTED_MODULE_1__/* .CosmeticRuleSeparator */ .p5.AdgHtmlFilteringException);
                }
            }
        }
        return null;
    }
}




/***/ }),

/***/ 35508:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Aw: () => (/* binding */ DomainUtils)
/* harmony export */ });
/* unused harmony exports WILDCARD_SUBDOMAIN, WILDCARD_TLD */
/* harmony import */ var tldts__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(13548);
/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65523);
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */



/**
 * @file Utility functions for domain and hostname validation.
 */
/**
 * Marker for a wildcard top-level domain — `.*`.
 *
 * @example
 * `example.*` — matches with any TLD, e.g. `example.org`, `example.com`, etc.
 */
const WILDCARD_TLD = _constants_js__WEBPACK_IMPORTED_MODULE_1__/* .DOT */ .y0 + _constants_js__WEBPACK_IMPORTED_MODULE_1__/* .WILDCARD */ .bs;
/**
 * Marker for a wildcard subdomain — `*.`.
 *
 * @example
 * `*.example.org` — matches with any subdomain, e.g. `foo.example.org` or `bar.example.org`
 */
const WILDCARD_SUBDOMAIN = _constants_js__WEBPACK_IMPORTED_MODULE_1__/* .WILDCARD */ .bs + _constants_js__WEBPACK_IMPORTED_MODULE_1__/* .DOT */ .y0;
/**
 * Utility functions for domain and hostname validation.
 */
class DomainUtils {
    /**
     * Check if the input is a valid domain or hostname.
     *
     * @param domain Domain to check
     * @returns `true` if the domain is valid, `false` otherwise
     */
    static isValidDomainOrHostname(domain) {
        let domainToCheck = domain;
        // Wildcard-only domain, typically a generic rule
        if (domainToCheck === _constants_js__WEBPACK_IMPORTED_MODULE_1__/* .WILDCARD */ .bs) {
            return true;
        }
        // https://adguard.com/kb/general/ad-filtering/create-own-filters/#wildcard-for-tld
        if (domainToCheck.endsWith(WILDCARD_TLD)) {
            // Remove the wildcard TLD
            domainToCheck = domainToCheck.substring(0, domainToCheck.length - WILDCARD_TLD.length);
        }
        if (domainToCheck.startsWith(WILDCARD_SUBDOMAIN)) {
            // Remove the wildcard subdomain
            domainToCheck = domainToCheck.substring(WILDCARD_SUBDOMAIN.length);
        }
        // Parse the domain with tldts
        const tldtsResult = (0,tldts__WEBPACK_IMPORTED_MODULE_0__/* .parse */ .qg)(domainToCheck);
        // Check if the domain is valid
        return domainToCheck === tldtsResult.domain || domainToCheck === tldtsResult.hostname;
    }
}




/***/ }),

/***/ 35629:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  N: () => (/* binding */ InputByteBuffer)
});

// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/byte-buffer.js
var byte_buffer = __webpack_require__(96489);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/type-guards.js
var type_guards = __webpack_require__(30239);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/is-chromium.js
var is_chromium = __webpack_require__(13753);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/constants.js
var constants = __webpack_require__(65523);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/text-decoder-polyfill.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/* eslint-disable no-plusplus */
/* eslint-disable no-bitwise */
/**
 * @file Optimized utility for decoding strings from byte sequences.
 */
const REPLACEMENT_CHAR = String.fromCodePoint(0xFFFD);
/**
 * Decodes a byte sequence into an UTF-8 string according to the WHATWG spec.
 * Optimized for performance.
 *
 * @param buffer Buffer to read the bytes from.
 * @param start Start offset in the buffer.
 * @param end End offset in the buffer.
 * @returns Decoded string.
 * @see {@link https://encoding.spec.whatwg.org/#utf-8-decoder}
 */
const decodeTextPolyfill = (buffer, start = 0, end = -1) => {
    let codePoint = 0;
    let bytesSeen = 0;
    let bytesNeeded = 0;
    let lowerBoundary = 0x0080;
    let upperBoundary = 0x00BF;
    let i = start;
    const { length } = buffer;
    const realEnd = end === -1 ? length : Math.min(end, length);
    const result = new Array(realEnd - start);
    let resIdx = 0;
    for (; i < realEnd; i += 1) {
        const byte = buffer[i];
        if (bytesNeeded === 0) {
            if (byte <= 0x007F) {
                codePoint = byte & 0x00FF;
            }
            else if (byte >= 0x00C2 && byte <= 0x00DF) {
                bytesNeeded = 1;
                codePoint = byte & 0x001F;
            }
            else if (byte >= 0x00E0 && byte <= 0x00EF) {
                bytesNeeded = 2;
                codePoint = byte & 0x000F;
                if (byte === 0x00E0) {
                    // Adjust lower boundary for exclusion of overlong sequences
                    lowerBoundary = 0x00A0;
                }
                else if (byte === 0x00ED) {
                    // Adjust upper boundary to exclude surrogates
                    upperBoundary = 0x009F;
                }
            }
            else if (byte >= 0x00F0 && byte <= 0x00F4) {
                bytesNeeded = 3;
                codePoint = byte & 0x0007;
                if (byte === 0x00F0) {
                    // Adjust lower boundary for exclusion of overlong sequences
                    lowerBoundary = 0x0090;
                }
                else if (byte === 0x00F4) {
                    // Adjust upper boundary to limit to valid Unicode range
                    upperBoundary = 0x008F;
                }
            }
            else {
                // For bytes that are not valid initial bytes of UTF-8 sequences, add replacement character
                result[resIdx++] = REPLACEMENT_CHAR;
                continue;
            }
        }
        else {
            // For subsequent bytes in a multibyte sequence, check if the byte is in the expected range
            if (!(byte >= lowerBoundary && byte <= upperBoundary)) {
                // Reset the state for illegal sequences and add replacement character
                bytesNeeded = 0;
                bytesSeen = 0;
                lowerBoundary = 0x0080;
                upperBoundary = 0x00BF;
                result[resIdx++] = REPLACEMENT_CHAR;
                // Decrement `i` to re-evaluate this byte as the start of a new sequence
                i -= 1;
                continue;
            }
            codePoint = (codePoint << 6) | (byte & 0x003F);
            // Reset boundaries for next bytes
            lowerBoundary = 0x0080;
            upperBoundary = 0x00BF;
            bytesSeen += 1;
        }
        if (bytesSeen === bytesNeeded) {
            // Complete the code point assembly and add it to the result
            result[resIdx++] = String.fromCodePoint(codePoint);
            // Reset for the next character
            bytesNeeded = 0;
            bytesSeen = 0;
            codePoint = 0;
        }
    }
    return result.join(constants/* EMPTY */.wg);
};



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/binary-schema-version.js
var binary_schema_version = __webpack_require__(63396);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/errors/binary-schema-mismatch-error.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * @file Customized error for binary schema mismatch.
 */
const ERROR_NAME = 'BinarySchemaMismatchError';
/**
 * Customized error for binary schema mismatch.
 */
class BinarySchemaMismatchError extends Error {
    /**
     * Expected schema version.
     */
    expectedVersion;
    /**
     * Actual schema version.
     */
    actualVersion;
    /**
     * Constructs a new `BinarySchemaMismatchError` instance.
     *
     * @param expectedVersion Expected schema version.
     * @param actualVersion Actual schema version.
     */
    constructor(expectedVersion, actualVersion) {
        super(`Expected schema version ${expectedVersion}, but got ${actualVersion}`);
        this.name = ERROR_NAME;
        this.expectedVersion = expectedVersion;
        this.actualVersion = actualVersion;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/input-byte-buffer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/* eslint-disable max-len */
/* eslint-disable no-plusplus */
/* eslint-disable no-bitwise */
/**
 * @file Input byte buffer for reading binary data.
 */
/**
 * Input byte buffer for reading binary data.
 *
 * @note Internally, this class uses a {@link ByteBuffer} instance, just providing a convenient API for reading data.
 */
class InputByteBuffer extends byte_buffer/* ByteBuffer */.$ {
    /**
     * Current offset in the buffer for reading.
     */
    offset;
    /**
     * Shared native decoder for decoding strings.
     */
    sharedNativeDecoder;
    /**
     * Flag indicating if the current environment is Chromium.
     * This is used for performance optimizations, because Chromium's TextEncoder/TextDecoder has a relatively
     * large marshalling overhead for small strings.
     */
    isChromium;
    /**
     * Constructs a new `InputByteBuffer` instance.
     *
     * @param chunks Array of chunks to initialize the ByteBuffer with.
     * @param cloneChunks Flag indicating if the chunks should be cloned. For performance reasons,
     * its default value is `false`. If the original chunks are guaranteed not to change,
     * leave this flag as `false` to avoid unnecessary copying.
     * @param initialOffset Initial offset in the buffer for reading.
     *
     * @throws If the specified chunks array is empty.
     * @throws If the binary schema version in the buffer is not equal to the expected version.
     * @throws If the initial offset is out of bounds.
     */
    constructor(chunks, cloneChunks = false, initialOffset = 0) {
        super(chunks, cloneChunks);
        // TODO: Consider accepting an empty array of chunks
        // Check binary schema version
        if (chunks.length === 0) {
            throw new Error('No data in the buffer');
        }
        const actualVersion = this.readSchemaVersion();
        if (actualVersion !== binary_schema_version/* BINARY_SCHEMA_VERSION */.T) {
            throw new BinarySchemaMismatchError(binary_schema_version/* BINARY_SCHEMA_VERSION */.T, actualVersion);
        }
        // Throw an error if the initial offset is out of bounds
        if (initialOffset < 0 || initialOffset > this.chunks.length * byte_buffer/* ByteBuffer */.$.CHUNK_SIZE) {
            throw new Error(`Invalid offset: ${initialOffset}`);
        }
        // Schema version is always stored at the beginning of the buffer - skip it, because it is already processed
        this.offset = Math.max(4, initialOffset);
        this.sharedNativeDecoder = new TextDecoder();
        this.isChromium = (0,is_chromium/* isChromium */.F)();
    }
    /**
     * Creates a new InputByteBuffer instance from a Storage instance by reading chunks from the storage.
     *
     * @param storage Storage instance.
     * @param key Key to read from the storage.
     * @returns New InputByteBuffer instance.
     * @note For performance reasons, chunks are passed by reference and not copied.
     */
    static async createFromStorage(storage, key) {
        const chunks = await storage.get(key);
        if (!(0,type_guards/* isArrayOfUint8Arrays */.r_)(chunks)) {
            throw new Error('The data from storage is not an array of Uint8Arrays');
        }
        return new InputByteBuffer(chunks);
    }
    /**
     * Reads a 8-bit unsigned integer from the buffer.
     *
     * @returns 8-bit unsigned integer from the buffer.
     */
    readUint8() {
        const result = this.readByte(this.offset++) ?? 0;
        return result;
    }
    /**
     * Reads a 16-bit unsigned integer from the buffer.
     *
     * @returns 16-bit unsigned integer from the buffer.
     */
    readUint16() {
        const result = (((this.readByte(this.offset++) ?? 0) << 8)
            | ((this.readByte(this.offset++) ?? 0))) >>> 0;
        return result;
    }
    /**
     * Reads a 32-bit unsigned integer from the buffer at the specified index.
     *
     * @param index Index to read the 32-bit unsigned integer from.
     *
     * @returns 32-bit unsigned integer from the buffer.
     */
    readUint32FromIndex(index) {
        const result = (((this.readByte(index) ?? 0) << 24)
            | ((this.readByte(index + 1) ?? 0) << 16)
            | ((this.readByte(index + 2) ?? 0) << 8)
            | ((this.readByte(index + 3) ?? 0))) >>> 0;
        return result;
    }
    /**
     * Reads a 32-bit unsigned integer from the buffer.
     *
     * @returns 32-bit unsigned integer from the buffer.
     */
    readUint32() {
        const result = this.readUint32FromIndex(this.offset);
        this.offset += 4;
        return result;
    }
    /**
     * Reads schema version from the buffer.
     *
     * @returns 32-bit unsigned integer from the buffer.
     * @note Schema version is always stored at the beginning of the buffer.
     */
    readSchemaVersion() {
        return this.readUint32FromIndex(0);
    }
    /**
     * Reads a 32-bit signed integer from the buffer.
     *
     * @returns 32-bit signed integer from the buffer.
     */
    readInt32() {
        const result = this.readUint32();
        return result > 0x7fffffff ? result - 0x100000000 : result;
    }
    /**
     * Reads an optimized unsigned integer from the buffer.
     * 'Optimized' means that the integer is stored in a variable number of bytes, depending on its value,
     * so that smaller numbers occupy less space.
     *
     * @returns Decoded unsigned integer from the buffer.
     */
    readOptimizedUint() {
        let result = 0;
        let shift = 0;
        while (shift <= 28) {
            const byteValue = this.readByte(this.offset++) ?? 0;
            result |= (byteValue & 0x7F) << shift;
            shift += 7;
            if ((byteValue & 0x80) === 0) {
                break;
            }
        }
        return result;
    }
    /**
     * Reads a string from the buffer.
     *
     * @returns Decoded string from the buffer.
     */
    readString() {
        const length = this.readOptimizedUint();
        let chunkIndex = this.offset >>> 0x000F;
        const chunkOffset = this.offset & 0x7FFF; // offset is only relevant for the first chunk
        const endOffset = chunkOffset + length;
        // In most cases, the string is stored in the current chunk
        if (endOffset < byte_buffer/* ByteBuffer */.$.CHUNK_SIZE) {
            this.offset += length;
            if (this.isChromium) {
                return decodeTextPolyfill(this.chunks[chunkIndex], chunkOffset, endOffset);
            }
            return this.sharedNativeDecoder.decode(this.chunks[chunkIndex].subarray(chunkOffset, endOffset));
        }
        const result = [];
        result.push(this.sharedNativeDecoder.decode(this.chunks[chunkIndex++].subarray(chunkOffset), { stream: true }));
        let remaining = length - (byte_buffer/* ByteBuffer */.$.CHUNK_SIZE - chunkOffset);
        while (remaining) {
            const chunk = this.chunks[chunkIndex];
            if (!chunk) {
                break;
            }
            const toRead = Math.min(remaining, byte_buffer/* ByteBuffer */.$.CHUNK_SIZE);
            result.push(this.sharedNativeDecoder.decode(chunk.subarray(0, toRead), { stream: true }));
            remaining -= toRead;
            chunkIndex += 1;
        }
        // Finish decoding, if something is left
        result.push(this.sharedNativeDecoder.decode());
        this.offset += length;
        return result.join('');
    }
    /**
     * Reads a 8-bit unsigned integer from the buffer without advancing the offset.
     *
     * @returns 8-bit unsigned integer from the buffer.
     */
    peekUint8() {
        return this.readByte(this.offset) ?? 0;
    }
    /**
     * Helper method for asserting the next 8-bit unsigned integer in the buffer.
     *
     * @param value Expected value.
     * @throws If the next value in the buffer is not equal to the expected value.
     */
    assertUint8(value) {
        const result = this.readUint8();
        if (result !== value) {
            throw new Error(`Expected ${value}, but got ${result}`);
        }
    }
    /**
     * Creates a new `InputByteBuffer` instance with the given initial offset.
     *
     * @param initialOffset Initial offset for the new buffer.
     * @param cloneChunks Flag indicating if the chunks should be cloned. For performance reasons,
     * its default value is `false`. If the original chunks are guaranteed not to change,
     * leave this flag as `false` to avoid unnecessary copying.
     *
     * @returns New `InputByteBuffer` instance with the given initial offset.
     *
     * @note This method is useful if you want to read some data from a specific index.
     */
    createCopyWithOffset(initialOffset, cloneChunks = false) {
        return new InputByteBuffer(this.chunks, cloneChunks, initialOffset);
    }
    /**
     * Gets the current offset in the buffer for reading.
     *
     * @returns Current offset in the buffer for reading.
     */
    get currentOffset() {
        return this.offset;
    }
    /**
     * Gets the capacity of the buffer.
     *
     * @returns Capacity of the buffer.
     */
    get capacity() {
        return this.chunks.length * byte_buffer/* ByteBuffer */.$.CHUNK_SIZE;
    }
    /**
     * Gets the chunks of the buffer.
     *
     * @returns Chunks of the buffer.
     */
    getChunks() {
        return this.chunks;
    }
}




/***/ }),

/***/ 13753:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   F: () => (/* binding */ isChromium)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * A simple function to check if the current browser is Chromium-based.
 *
 * @returns `true` if the current browser is Chromium-based, `false` otherwise.
 * @see {@link https://stackoverflow.com/a/62797156}
 */
const isChromium = () => {
    return typeof window !== 'undefined'
        && (Object.prototype.hasOwnProperty.call(window, 'chrome')
            || (typeof window.navigator !== 'undefined'
                && /chrome/i.test(window.navigator.userAgent)));
};




/***/ }),

/***/ 8725:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Qj: () => (/* binding */ QuoteUtils),
/* harmony export */   XA: () => (/* binding */ QuoteType),
/* harmony export */   iO: () => (/* binding */ QUOTE_SET)
/* harmony export */ });
/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(65523);
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * @file Utility functions for working with quotes
 */
/**
 * Set of all possible quote characters supported by the library
 */
const QUOTE_SET = new Set([
    _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SINGLE_QUOTE */ .ur,
    _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .DOUBLE_QUOTE */ .fi,
    _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .BACKTICK_QUOTE */ .w1,
]);
/**
 * Possible quote types for scriptlet parameters
 */
const QuoteType = {
    /**
     * No quotes at all
     */
    None: 'none',
    /**
     * Single quotes (`'`)
     */
    Single: 'single',
    /**
     * Double quotes (`"`)
     */
    Double: 'double',
    /**
     * Backtick quotes (`` ` ``)
     */
    Backtick: 'backtick',
};
/**
 * Utility functions for working with quotes
 */
class QuoteUtils {
    /**
     * Escape all unescaped occurrences of the character
     *
     * @param string String to escape
     * @param char Character to escape
     * @returns Escaped string
     */
    static escapeUnescapedOccurrences(string, char) {
        let result = _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .EMPTY */ .wg;
        for (let i = 0; i < string.length; i += 1) {
            if (string[i] === char && (i === 0 || string[i - 1] !== _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .ESCAPE_CHARACTER */ .Kx)) {
                result += _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .ESCAPE_CHARACTER */ .Kx;
            }
            result += string[i];
        }
        return result;
    }
    /**
     * Unescape all single escaped occurrences of the character
     *
     * @param string String to unescape
     * @param char Character to unescape
     * @returns Unescaped string
     */
    static unescapeSingleEscapedOccurrences(string, char) {
        let result = _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .EMPTY */ .wg;
        for (let i = 0; i < string.length; i += 1) {
            if (string[i] === char
                && string[i - 1] === _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .ESCAPE_CHARACTER */ .Kx
                && (i === 1 || string[i - 2] !== _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .ESCAPE_CHARACTER */ .Kx)) {
                result = result.slice(0, -1);
            }
            result += string[i];
        }
        return result;
    }
    /**
     * Get quote type of the string
     *
     * @param string String to check
     * @returns Quote type of the string
     */
    static getStringQuoteType(string) {
        // Don't check 1-character strings to avoid false positives
        if (string.length > 1) {
            if (string.startsWith(_constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SINGLE_QUOTE */ .ur) && string.endsWith(_constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SINGLE_QUOTE */ .ur)) {
                return QuoteType.Single;
            }
            if (string.startsWith(_constants_js__WEBPACK_IMPORTED_MODULE_0__/* .DOUBLE_QUOTE */ .fi) && string.endsWith(_constants_js__WEBPACK_IMPORTED_MODULE_0__/* .DOUBLE_QUOTE */ .fi)) {
                return QuoteType.Double;
            }
            if (string.startsWith(_constants_js__WEBPACK_IMPORTED_MODULE_0__/* .BACKTICK_QUOTE */ .w1) && string.endsWith(_constants_js__WEBPACK_IMPORTED_MODULE_0__/* .BACKTICK_QUOTE */ .w1)) {
                return QuoteType.Backtick;
            }
        }
        return QuoteType.None;
    }
    /**
     * Set quote type of the string
     *
     * @param string String to set quote type of
     * @param quoteType Quote type to set
     * @returns String with the specified quote type
     */
    static setStringQuoteType(string, quoteType) {
        const actualQuoteType = QuoteUtils.getStringQuoteType(string);
        switch (quoteType) {
            case QuoteType.None:
                if (actualQuoteType === QuoteType.Single) {
                    return QuoteUtils.escapeUnescapedOccurrences(string.slice(1, -1), _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SINGLE_QUOTE */ .ur);
                }
                if (actualQuoteType === QuoteType.Double) {
                    return QuoteUtils.escapeUnescapedOccurrences(string.slice(1, -1), _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .DOUBLE_QUOTE */ .fi);
                }
                if (actualQuoteType === QuoteType.Backtick) {
                    return QuoteUtils.escapeUnescapedOccurrences(string.slice(1, -1), _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .BACKTICK_QUOTE */ .w1);
                }
                return string;
            case QuoteType.Single:
                if (actualQuoteType === QuoteType.None) {
                    return _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SINGLE_QUOTE */ .ur + QuoteUtils.escapeUnescapedOccurrences(string, _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SINGLE_QUOTE */ .ur) + _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SINGLE_QUOTE */ .ur;
                }
                if (actualQuoteType === QuoteType.Double) {
                    return _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SINGLE_QUOTE */ .ur
                        + QuoteUtils.escapeUnescapedOccurrences(QuoteUtils.unescapeSingleEscapedOccurrences(string.slice(1, -1), _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .DOUBLE_QUOTE */ .fi), _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SINGLE_QUOTE */ .ur) + _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SINGLE_QUOTE */ .ur;
                }
                if (actualQuoteType === QuoteType.Backtick) {
                    return _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SINGLE_QUOTE */ .ur
                        + QuoteUtils.escapeUnescapedOccurrences(QuoteUtils.unescapeSingleEscapedOccurrences(string.slice(1, -1), _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .BACKTICK_QUOTE */ .w1), _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SINGLE_QUOTE */ .ur) + _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SINGLE_QUOTE */ .ur;
                }
                return string;
            case QuoteType.Double:
                if (actualQuoteType === QuoteType.None) {
                    return _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .DOUBLE_QUOTE */ .fi + QuoteUtils.escapeUnescapedOccurrences(string, _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .DOUBLE_QUOTE */ .fi) + _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .DOUBLE_QUOTE */ .fi;
                }
                if (actualQuoteType !== QuoteType.Double) {
                    // eslint-disable-next-line max-len
                    return _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .DOUBLE_QUOTE */ .fi
                        + QuoteUtils.escapeUnescapedOccurrences(QuoteUtils.unescapeSingleEscapedOccurrences(string.slice(1, -1), _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SINGLE_QUOTE */ .ur), _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .DOUBLE_QUOTE */ .fi) + _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .DOUBLE_QUOTE */ .fi;
                }
                return string;
            case QuoteType.Backtick:
                if (actualQuoteType === QuoteType.None) {
                    // eslint-disable-next-line max-len
                    return _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .BACKTICK_QUOTE */ .w1 + QuoteUtils.escapeUnescapedOccurrences(string, _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .BACKTICK_QUOTE */ .w1) + _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .BACKTICK_QUOTE */ .w1;
                }
                if (actualQuoteType !== QuoteType.Backtick) {
                    // eslint-disable-next-line max-len
                    return _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .BACKTICK_QUOTE */ .w1
                        + QuoteUtils.escapeUnescapedOccurrences(QuoteUtils.unescapeSingleEscapedOccurrences(string.slice(1, -1), _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SINGLE_QUOTE */ .ur), _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .BACKTICK_QUOTE */ .w1) + _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .BACKTICK_QUOTE */ .w1;
                }
                return string;
            default:
                return string;
        }
    }
    /**
     * Removes bounding quotes from a string, if any
     *
     * @param string Input string
     * @returns String without quotes
     */
    static removeQuotes(string) {
        if (
        // We should check for string length to avoid false positives
        string.length > 1
            && (string[0] === _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SINGLE_QUOTE */ .ur || string[0] === _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .DOUBLE_QUOTE */ .fi || string[0] === _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .BACKTICK_QUOTE */ .w1)
            && string[0] === string[string.length - 1]) {
            return string.slice(1, -1);
        }
        return string;
    }
    /**
     * Removes bounding quotes from a string, if any, and unescapes the escaped quotes,
     * like transforming `'abc\'def'` to `abc'def`.
     *
     * @param string Input string
     * @returns String without quotes
     */
    static removeQuotesAndUnescape(string) {
        if (
        // We should check for string length to avoid false positives
        string.length > 1
            && (string[0] === _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SINGLE_QUOTE */ .ur || string[0] === _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .DOUBLE_QUOTE */ .fi || string[0] === _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .BACKTICK_QUOTE */ .w1)
            && string[0] === string[string.length - 1]) {
            return QuoteUtils.unescapeSingleEscapedOccurrences(string.slice(1, -1), string[0]);
        }
        return string;
    }
    /**
     * Wraps given `strings` with `quote` (defaults to single quote `'`)
     * and joins them with `separator` (defaults to comma+space `, `).
     *
     * @param strings Strings to quote and join.
     * @param quoteType Quote to use.
     * @param separator Separator to use.
     *
     * @returns String with joined items.
     *
     * @example
     * ['abc', 'def']: strings[]  ->  "'abc', 'def'": string
     */
    static quoteAndJoinStrings(strings, quoteType = QuoteType.Single, separator = `${_constants_js__WEBPACK_IMPORTED_MODULE_0__/* .COMMA */ .KE}${_constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SPACE */ .t6}`) {
        return strings
            .map((s) => QuoteUtils.setStringQuoteType(s, quoteType))
            .join(separator);
    }
}




/***/ }),

/***/ 54857:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   $x: () => (/* binding */ StringUtils),
/* harmony export */   E0: () => (/* binding */ DOUBLE_QUOTE_MARKER)
/* harmony export */ });
/* unused harmony export SINGLE_QUOTE_MARKER */
/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(65523);
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * @file Utility functions for string manipulation.
 */
const SINGLE_QUOTE_MARKER = "'";
const DOUBLE_QUOTE_MARKER = '"';
/**
 * Utility functions for string manipulation.
 */
class StringUtils {
    /**
     * Finds the first occurrence of a character that:
     * - isn't preceded by an escape character
     *
     * @param pattern - Source pattern
     * @param searchedCharacter - Searched character
     * @param start - Start index
     * @param escapeCharacter - Escape character, \ by default
     * @param end - End index (excluded)
     * @returns Index or -1 if the character not found
     */
    static findNextUnescapedCharacter(pattern, searchedCharacter, start = 0, escapeCharacter = _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .ESCAPE_CHARACTER */ .Kx, end = pattern.length) {
        for (let i = start; i < end; i += 1) {
            // The searched character cannot be preceded by an escape
            if (pattern[i] === searchedCharacter && pattern[i - 1] !== escapeCharacter) {
                return i;
            }
        }
        return -1;
    }
    /**
     * Finds the first occurrence in backward direction of a character that isn't preceded by an escape character.
     *
     * @param pattern - Source pattern
     * @param searchedCharacter - Searched character
     * @param start - Start index
     * @param escapeCharacter - Escape character, \ by default
     * @param end - End index (Included)
     * @returns Index or -1 if the character not found
     */
    static findNextUnescapedCharacterBackwards(pattern, searchedCharacter, start = pattern.length - 1, escapeCharacter = _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .ESCAPE_CHARACTER */ .Kx, end = 0) {
        for (let i = start; i >= end; i -= 1) {
            // The searched character cannot be preceded by an escape
            if (pattern[i] === searchedCharacter && pattern[i - 1] !== escapeCharacter) {
                return i;
            }
        }
        return -1;
    }
    /**
     * Finds the last occurrence of a character that:
     * - isn't preceded by an escape character
     *
     * @param pattern - Source pattern
     * @param searchedCharacter - Searched character
     * @param escapeCharacter - Escape character, \ by default
     * @returns Index or -1 if the character not found
     */
    static findLastUnescapedCharacter(pattern, searchedCharacter, escapeCharacter = _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .ESCAPE_CHARACTER */ .Kx) {
        for (let i = pattern.length - 1; i >= 0; i -= 1) {
            // The searched character cannot be preceded by an escape
            if (pattern[i] === searchedCharacter && pattern[i - 1] !== escapeCharacter) {
                return i;
            }
        }
        return -1;
    }
    /**
     * Finds the next occurrence of a character that:
     * - isn't preceded by an escape character
     * - isn't followed by the specified character
     *
     * @param pattern - Source pattern
     * @param start - Start index
     * @param searchedCharacter - Searched character
     * @param notFollowedBy - Searched character not followed by this character
     * @param escapeCharacter - Escape character, \ by default
     * @returns Index or -1 if the character not found
     */
    static findNextUnescapedCharacterThatNotFollowedBy(pattern, start, searchedCharacter, notFollowedBy, escapeCharacter = _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .ESCAPE_CHARACTER */ .Kx) {
        for (let i = start; i < pattern.length; i += 1) {
            // The searched character cannot be preceded by an escape
            if (pattern[i] === searchedCharacter
                && pattern[i + 1] !== notFollowedBy
                && pattern[i - 1] !== escapeCharacter) {
                return i;
            }
        }
        return -1;
    }
    /**
     * Finds the last occurrence of a character that:
     * - isn't preceded by an escape character
     * - isn't followed by the specified character
     *
     * @param pattern - Source pattern
     * @param searchedCharacter - Searched character
     * @param notFollowedBy - Searched character not followed by this character
     * @param escapeCharacter - Escape character, \ by default
     * @returns Index or -1 if the character not found
     */
    static findLastUnescapedCharacterThatNotFollowedBy(pattern, searchedCharacter, notFollowedBy, escapeCharacter = _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .ESCAPE_CHARACTER */ .Kx) {
        for (let i = pattern.length - 1; i >= 0; i -= 1) {
            // The searched character cannot be preceded by an escape
            if (pattern[i] === searchedCharacter
                && pattern[i + 1] !== notFollowedBy
                && pattern[i - 1] !== escapeCharacter) {
                return i;
            }
        }
        return -1;
    }
    /**
     * Finds the next occurrence of a character that:
     * - isn't part of any string literal ('literal' or "literal")
     * - isn't part of any RegExp expression (/regexp/)
     *
     * @param pattern - Source pattern
     * @param searchedCharacter - Searched character
     * @param start - Start index
     * @returns Index or -1 if the character not found
     */
    static findUnescapedNonStringNonRegexChar(pattern, searchedCharacter, start = 0) {
        let open = null;
        for (let i = start; i < pattern.length; i += 1) {
            if ((pattern[i] === SINGLE_QUOTE_MARKER
                || pattern[i] === DOUBLE_QUOTE_MARKER
                || pattern[i] === _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .REGEX_MARKER */ .Vb)
                && pattern[i - 1] !== _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .ESCAPE_CHARACTER */ .Kx) {
                if (open === pattern[i]) {
                    open = null;
                }
                else if (open === null) {
                    open = pattern[i];
                }
            }
            else if (open === null && pattern[i] === searchedCharacter && pattern[i - 1] !== _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .ESCAPE_CHARACTER */ .Kx) {
                return i;
            }
        }
        return -1;
    }
    /**
     * Finds the next occurrence of a character that:
     * - isn't part of any string literal ('literal' or "literal")
     * - isn't preceded by an escape character
     *
     * @param pattern - Source pattern
     * @param searchedCharacter - Searched character
     * @param start - Start index
     * @param escapeCharacter - Escape character, \ by default
     * @returns Index or -1 if the character not found
     */
    static findNextUnquotedUnescapedCharacter(pattern, searchedCharacter, start = 0, escapeCharacter = _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .ESCAPE_CHARACTER */ .Kx) {
        let openQuote = null;
        for (let i = start; i < pattern.length; i += 1) {
            // Unescaped ' or "
            if ((pattern[i] === SINGLE_QUOTE_MARKER || pattern[i] === DOUBLE_QUOTE_MARKER)
                && pattern[i - 1] !== escapeCharacter) {
                if (!openQuote)
                    openQuote = pattern[i];
                else if (openQuote === pattern[i])
                    openQuote = null;
            }
            else if (pattern[i] === searchedCharacter && pattern[i - 1] !== escapeCharacter) {
                // Unescaped character
                if (!openQuote) {
                    return i;
                }
            }
        }
        return -1;
    }
    /**
     * Finds the next occurrence of a character that:
     * - isn't "bracketed"
     * - isn't preceded by an escape character
     *
     * @param pattern - Source pattern
     * @param searchedCharacter - Searched character
     * @param start - Start index
     * @param escapeCharacter - Escape character, \ by default
     * @param openBracket - Open bracket, ( by default
     * @param closeBracket - Close bracket, ( by default
     * @throws If the opening and closing brackets are the same
     * @returns Index or -1 if the character not found
     */
    static findNextNotBracketedUnescapedCharacter(pattern, searchedCharacter, start = 0, escapeCharacter = _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .ESCAPE_CHARACTER */ .Kx, openBracket = '(', closeBracket = ')') {
        if (openBracket === closeBracket) {
            throw new Error('Open and close bracket cannot be the same');
        }
        let depth = 0;
        for (let i = start; i < pattern.length; i += 1) {
            if (pattern[i] === openBracket) {
                depth += 1;
            }
            else if (pattern[i] === closeBracket) {
                depth -= 1;
            }
            else if (depth < 1 && pattern[i] === searchedCharacter && pattern[i - 1] !== escapeCharacter) {
                return i;
            }
        }
        return -1;
    }
    /**
     * Splits the source pattern along characters that:
     * - isn't part of any string literal ('literal' or "literal")
     * - isn't preceded by an escape character
     *
     * @param pattern - Source pattern
     * @param delimeterCharacter - Delimeter character
     * @returns Splitted string
     */
    static splitStringByUnquotedUnescapedCharacter(pattern, delimeterCharacter) {
        const parts = [];
        let delimeterIndex = -1;
        do {
            const prevDelimeterIndex = delimeterIndex;
            delimeterIndex = StringUtils.findNextUnquotedUnescapedCharacter(pattern, delimeterCharacter, delimeterIndex + 1);
            if (delimeterIndex !== -1) {
                parts.push(pattern.substring(prevDelimeterIndex + 1, delimeterIndex));
            }
            else {
                parts.push(pattern.substring(prevDelimeterIndex + 1, pattern.length));
            }
        } while (delimeterIndex !== -1);
        return parts;
    }
    /**
     * Splits the source pattern along characters that:
     * - isn't part of any string literal ('literal' or "literal")
     * - isn't part of any RegExp expression (/regexp/)
     * - isn't preceded by an escape character
     *
     * @param pattern - Source pattern
     * @param delimeterCharacter - Delimeter character
     * @returns Splitted string
     */
    static splitStringByUnescapedNonStringNonRegexChar(pattern, delimeterCharacter) {
        const parts = [];
        let delimeterIndex = -1;
        do {
            const prevDelimeterIndex = delimeterIndex;
            delimeterIndex = StringUtils.findUnescapedNonStringNonRegexChar(pattern, delimeterCharacter, delimeterIndex + 1);
            if (delimeterIndex !== -1) {
                parts.push(pattern.substring(prevDelimeterIndex + 1, delimeterIndex));
            }
            else {
                parts.push(pattern.substring(prevDelimeterIndex + 1, pattern.length));
            }
        } while (delimeterIndex !== -1);
        return parts;
    }
    /**
     * Splits the source pattern along characters that:
     * - isn't preceded by an escape character
     *
     * @param pattern - Source pattern
     * @param delimeterCharacter - Delimeter character
     * @returns Splitted string
     */
    static splitStringByUnescapedCharacter(pattern, delimeterCharacter) {
        const parts = [];
        let delimeterIndex = -1;
        do {
            const prevDelimeterIndex = delimeterIndex;
            delimeterIndex = StringUtils.findNextUnescapedCharacter(pattern, delimeterCharacter, delimeterIndex + 1);
            if (delimeterIndex !== -1) {
                parts.push(pattern.substring(prevDelimeterIndex + 1, delimeterIndex));
            }
            else {
                parts.push(pattern.substring(prevDelimeterIndex + 1, pattern.length));
            }
        } while (delimeterIndex !== -1);
        return parts;
    }
    /**
     * Determines whether the given character is a space or tab character.
     *
     * @param char - The character to check.
     * @returns true if the given character is a space or tab character, false otherwise.
     */
    static isWhitespace(char) {
        return char === _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SPACE */ .t6 || char === _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .TAB */ .wn;
    }
    /**
     * Checks if the given character is a digit.
     *
     * @param char The character to check.
     * @returns `true` if the given character is a digit, `false` otherwise.
     */
    static isDigit(char) {
        return char >= _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .NUMBER_0 */ .nC && char <= _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .NUMBER_9 */ .g9;
    }
    /**
     * Checks if the given character is a small letter.
     *
     * @param char The character to check.
     * @returns `true` if the given character is a small letter, `false` otherwise.
     */
    static isSmallLetter(char) {
        return char >= _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SMALL_LETTER_A */ .H3 && char <= _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .SMALL_LETTER_Z */ .AT;
    }
    /**
     * Checks if the given character is a capital letter.
     *
     * @param char The character to check.
     * @returns `true` if the given character is a capital letter, `false` otherwise.
     */
    static isCapitalLetter(char) {
        return char >= _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .CAPITAL_LETTER_A */ .ot && char <= _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .CAPITAL_LETTER_Z */ .hk;
    }
    /**
     * Checks if the given character is a letter (small or capital).
     *
     * @param char The character to check.
     * @returns `true` if the given character is a letter, `false` otherwise.
     */
    static isLetter(char) {
        return StringUtils.isSmallLetter(char) || StringUtils.isCapitalLetter(char);
    }
    /**
     * Checks if the given character is a letter or a digit.
     *
     * @param char Character to check
     * @returns `true` if the given character is a letter or a digit, `false` otherwise.
     */
    static isAlphaNumeric(char) {
        return StringUtils.isLetter(char) || StringUtils.isDigit(char);
    }
    /**
     * Searches for the first non-whitespace character in the source pattern.
     *
     * @param pattern - Source pattern
     * @param start - Start index
     * @returns Index or -1 if the character not found
     */
    static findFirstNonWhitespaceCharacter(pattern, start = 0) {
        for (let i = start; i < pattern.length; i += 1) {
            if (!StringUtils.isWhitespace(pattern[i])) {
                return i;
            }
        }
        return -1;
    }
    /**
     * Searches for the last non-whitespace character in the source pattern.
     *
     * @param pattern - Source pattern
     * @returns Index or -1 if the character not found
     */
    static findLastNonWhitespaceCharacter(pattern) {
        for (let i = pattern.length - 1; i >= 0; i -= 1) {
            if (!StringUtils.isWhitespace(pattern[i])) {
                return i;
            }
        }
        return -1;
    }
    /**
     * Finds the next whitespace character in the pattern.
     *
     * @param pattern Pattern to search in
     * @param start Start index
     * @returns Index of the next whitespace character or the length of the pattern if not found
     */
    static findNextWhitespaceCharacter(pattern, start = 0) {
        for (let i = start; i < pattern.length; i += 1) {
            if (StringUtils.isWhitespace(pattern[i])) {
                return i;
            }
        }
        return pattern.length;
    }
    /**
     * Escapes a specified character in the string.
     *
     * @param pattern - Input string
     * @param character - Character to escape
     * @param escapeCharacter - Escape character (optional)
     * @returns Escaped string
     */
    static escapeCharacter(pattern, character, escapeCharacter = _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .ESCAPE_CHARACTER */ .Kx) {
        let result = _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .EMPTY */ .wg;
        for (let i = 0; i < pattern.length; i += 1) {
            if (pattern[i] === character && pattern[i - 1] !== escapeCharacter) {
                result += escapeCharacter;
            }
            result += pattern[i];
        }
        return result;
    }
    /**
     * Searches for the next non-whitespace character in the source pattern.
     *
     * @param pattern Pattern to search
     * @param start Start index
     * @returns Index of the next non-whitespace character or the length of the pattern
     */
    static skipWS(pattern, start = 0) {
        let i = start;
        while (i < pattern.length && StringUtils.isWhitespace(pattern[i])) {
            i += 1;
        }
        return Math.min(i, pattern.length);
    }
    /**
     * Searches for the previous non-whitespace character in the source pattern.
     *
     * @param pattern Pattern to search
     * @param start Start index
     * @returns Index of the previous non-whitespace character or -1
     */
    static skipWSBack(pattern, start = pattern.length - 1) {
        let i = start;
        while (i >= 0 && StringUtils.isWhitespace(pattern[i])) {
            i -= 1;
        }
        return Math.max(i, -1);
    }
    /**
     * Checks if the given character is a new line character.
     *
     * @param char Character to check
     * @returns `true` if the given character is a new line character, `false` otherwise.
     */
    static isEOL(char) {
        return char === _constants_js__WEBPACK_IMPORTED_MODULE_0__.CR || char === _constants_js__WEBPACK_IMPORTED_MODULE_0__.LF || char === _constants_js__WEBPACK_IMPORTED_MODULE_0__.FF;
    }
    /**
     * Splits a string along newline characters.
     *
     * @param input - Input string
     * @returns Splitted string
     */
    static splitStringByNewLines(input) {
        return input.split(/\r?\n/);
    }
    /**
     * Splits a string by new lines and stores the new line type for each line
     *
     * @param input The input string to be split
     * @returns An array of tuples, where each tuple contains a line of the input string and its
     * corresponding new line type ("lf", "crlf", or "cr")
     */
    static splitStringByNewLinesEx(input) {
        // Array to store the tuples of line and new line type
        const result = [];
        let currentLine = _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .EMPTY */ .wg;
        let newLineType = null;
        // Iterate over each character in the input string
        for (let i = 0; i < input.length; i += 1) {
            const char = input[i];
            if (char === _constants_js__WEBPACK_IMPORTED_MODULE_0__.CR) {
                if (input[i + 1] === _constants_js__WEBPACK_IMPORTED_MODULE_0__.LF) {
                    newLineType = 'crlf';
                    i += 1;
                }
                else {
                    newLineType = 'cr';
                }
                result.push([currentLine, newLineType]);
                currentLine = _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .EMPTY */ .wg;
                newLineType = null;
            }
            else if (char === _constants_js__WEBPACK_IMPORTED_MODULE_0__.LF) {
                newLineType = 'lf';
                result.push([currentLine, newLineType]);
                currentLine = _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .EMPTY */ .wg;
                newLineType = null;
            }
            else {
                currentLine += char;
            }
        }
        if (result.length === 0 || currentLine !== _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .EMPTY */ .wg) {
            result.push([currentLine, newLineType]);
        }
        return result;
    }
    /**
     * Merges an array of tuples (line, newLineType) into a single string
     *
     * @param input The array of tuples to be merged
     * @returns A single string containing the lines and new line characters from the input array
     */
    static mergeStringByNewLines(input) {
        let result = _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .EMPTY */ .wg;
        // Iterate over each tuple in the input array
        for (let i = 0; i < input.length; i += 1) {
            const [line, newLineType] = input[i];
            // Add the line to the result string
            result += line;
            // Add the appropriate new line character based on the newLineType
            if (newLineType !== null) {
                if (newLineType === 'crlf') {
                    result += _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .CRLF */ .KT;
                }
                else if (newLineType === 'cr') {
                    result += _constants_js__WEBPACK_IMPORTED_MODULE_0__.CR;
                }
                else {
                    result += _constants_js__WEBPACK_IMPORTED_MODULE_0__.LF;
                }
            }
        }
        return result;
    }
    /**
     * Helper method to parse a raw string as a number
     *
     * @param raw Raw string to parse
     * @returns Parsed number
     * @throws If the raw string can't be parsed as a number
     */
    static parseNumber(raw) {
        const result = parseInt(raw, 10);
        if (Number.isNaN(result)) {
            throw new Error('Expected a number');
        }
        return result;
    }
    /**
     * Checks if the given value is a string.
     *
     * @param value Value to check
     * @returns `true` if the value is a string, `false` otherwise
     */
    static isString(value) {
        return typeof value === 'string';
    }
    /**
     * Escapes the given characters in the input string.
     *
     * @param input Input string
     * @param characters Characters to escape (by default, no characters are escaped)
     * @returns Escaped string
     */
    static escapeCharacters(input, characters = new Set()) {
        let result = _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .EMPTY */ .wg;
        for (let i = 0; i < input.length; i += 1) {
            if (characters.has(input[i])) {
                result += _constants_js__WEBPACK_IMPORTED_MODULE_0__/* .ESCAPE_CHARACTER */ .Kx;
            }
            result += input[i];
        }
        return result;
    }
}




/***/ }),

/***/ 30239:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Kg: () => (/* binding */ isString),
/* harmony export */   b0: () => (/* binding */ isUndefined),
/* harmony export */   kZ: () => (/* binding */ isNull),
/* harmony export */   r_: () => (/* binding */ isArrayOfUint8Arrays)
/* harmony export */ });
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Checks whether the given value is undefined.
 *
 * @param value Value to check.
 *
 * @returns `true` if the value is 'undefined', `false` otherwise.
 */
const isUndefined = (value) => {
    return typeof value === 'undefined';
};
/**
 * Checks whether the given value is null.
 *
 * @param value Value to check.
 *
 * @returns `true` if the value is 'null', `false` otherwise.
 */
const isNull = (value) => {
    return value === null;
};
/**
 * Checks whether the given value is a string.
 *
 * @param value Value to check.
 * @returns `true` if the value is a string, `false` otherwise.
 */
const isString = (value) => {
    return typeof value === 'string';
};
/**
 * Checks whether the given value is an array of Uint8Arrays.
 *
 * @param value Value to check.
 *
 * @returns True if the value type is an array of Uint8Arrays.
 */
const isArrayOfUint8Arrays = (value) => {
    return Array.isArray(value) && value.every((chunk) => chunk instanceof Uint8Array);
};




/***/ }),

/***/ 61702:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   t: () => (/* binding */ SCRIPTLETS_VERSION)
/* harmony export */ });


var version = "2.1.6";

var SCRIPTLETS_VERSION = version;




/***/ }),

/***/ 3030:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   e: () => (/* binding */ scriptlets)
/* harmony export */ });
function AmazonApstag(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function AmazonApstag(source) {
        var apstagWrapper = {
            fetchBids(a, b) {
                if (typeof b === "function") {
                    b([]);
                }
            },
            init: noopFunc,
            setDisplayBids: noopFunc,
            targetingKeys: noopFunc
        };
        window.apstag = apstagWrapper;
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopFunc() {}
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        AmazonApstag.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function DidomiLoader(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function DidomiLoader(source) {
        function UserConsentStatusForVendorSubscribe() {}
        UserConsentStatusForVendorSubscribe.prototype.filter = function() {
            return new UserConsentStatusForVendorSubscribe;
        };
        UserConsentStatusForVendorSubscribe.prototype.subscribe = noopFunc;
        function UserConsentStatusForVendor() {}
        UserConsentStatusForVendor.prototype.first = function() {
            return new UserConsentStatusForVendorSubscribe;
        };
        UserConsentStatusForVendor.prototype.filter = function() {
            return new UserConsentStatusForVendorSubscribe;
        };
        UserConsentStatusForVendor.prototype.subscribe = noopFunc;
        var DidomiWrapper = {
            isConsentRequired: falseFunc,
            getUserConsentStatusForPurpose: trueFunc,
            getUserConsentStatus: trueFunc,
            getUserStatus: noopFunc,
            getRequiredPurposes: noopArray,
            getUserConsentStatusForVendor: trueFunc,
            Purposes: {
                Cookies: "cookies"
            },
            notice: {
                configure: noopFunc,
                hide: noopFunc,
                isVisible: falseFunc,
                show: noopFunc,
                showDataProcessing: trueFunc
            },
            isUserConsentStatusPartial: falseFunc,
            on() {
                return {
                    actions: {},
                    emitter: {},
                    services: {},
                    store: {}
                };
            },
            shouldConsentBeCollected: falseFunc,
            getUserConsentStatusForAll: noopFunc,
            getObservableOnUserConsentStatusForVendor() {
                return new UserConsentStatusForVendor;
            }
        };
        window.Didomi = DidomiWrapper;
        var didomiStateWrapper = {
            didomiExperimentId: "",
            didomiExperimentUserGroup: "",
            didomiGDPRApplies: 1,
            didomiIABConsent: "",
            didomiPurposesConsent: "",
            didomiPurposesConsentDenied: "",
            didomiPurposesConsentUnknown: "",
            didomiVendorsConsent: "",
            didomiVendorsConsentDenied: "",
            didomiVendorsConsentUnknown: "",
            didomiVendorsRawConsent: "",
            didomiVendorsRawConsentDenied: "",
            didomiVendorsRawConsentUnknown: ""
        };
        window.didomiState = didomiStateWrapper;
        var tcData = {
            eventStatus: "tcloaded",
            gdprApplies: false,
            listenerId: noopFunc,
            vendor: {
                consents: []
            },
            purpose: {
                consents: []
            }
        };
        var __tcfapiWrapper = function __tcfapiWrapper(command, version, callback) {
            if (typeof callback !== "function" || command === "removeEventListener") {
                return;
            }
            callback(tcData, true);
        };
        window.__tcfapi = __tcfapiWrapper;
        var didomiEventListenersWrapper = {
            stub: true,
            push: noopFunc
        };
        window.didomiEventListeners = didomiEventListenersWrapper;
        var didomiOnReadyWrapper = {
            stub: true,
            push(arg) {
                if (typeof arg !== "function") {
                    return;
                }
                if (document.readyState !== "complete") {
                    window.addEventListener("load", (function() {
                        setTimeout(arg(window.Didomi));
                    }));
                } else {
                    setTimeout(arg(window.Didomi));
                }
            }
        };
        window.didomiOnReady = window.didomiOnReady || didomiOnReadyWrapper;
        if (Array.isArray(window.didomiOnReady)) {
            window.didomiOnReady.forEach((function(arg) {
                if (typeof arg === "function") {
                    try {
                        setTimeout(arg(window.Didomi));
                    } catch (e) {}
                }
            }));
        }
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopFunc() {}
    function noopArray() {
        return [];
    }
    function trueFunc() {
        return true;
    }
    function falseFunc() {
        return false;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        DidomiLoader.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function Fingerprintjs2(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function Fingerprintjs2(source) {
        var browserId = "";
        for (var i = 0; i < 8; i += 1) {
            browserId += (Math.random() * 65536 + 4096).toString(16).slice(-4);
        }
        var Fingerprint2 = function Fingerprint2() {};
        Fingerprint2.get = function(options, callback) {
            if (!callback) {
                callback = options;
            }
            setTimeout((function() {
                if (callback) {
                    callback(browserId, []);
                }
            }), 1);
        };
        Fingerprint2.prototype = {
            get: Fingerprint2.get
        };
        window.Fingerprint2 = Fingerprint2;
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        Fingerprintjs2.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function Fingerprintjs3(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function Fingerprintjs3(source) {
        var visitorId = function() {
            var id = "";
            for (var i = 0; i < 8; i += 1) {
                id += (Math.random() * 65536 + 4096).toString(16).slice(-4);
            }
            return id;
        }();
        var FingerprintJS = function FingerprintJS() {};
        FingerprintJS.prototype = {
            load() {
                return Promise.resolve(new FingerprintJS);
            },
            get() {
                return Promise.resolve({
                    visitorId: visitorId
                });
            },
            hashComponents: noopStr
        };
        window.FingerprintJS = new FingerprintJS;
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopStr() {
        return "";
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        Fingerprintjs3.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function Gemius(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function Gemius(source) {
        var GemiusPlayer = function GemiusPlayer() {};
        GemiusPlayer.prototype = {
            setVideoObject: noopFunc,
            newProgram: noopFunc,
            programEvent: noopFunc,
            newAd: noopFunc,
            adEvent: noopFunc
        };
        window.GemiusPlayer = GemiusPlayer;
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopFunc() {}
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        Gemius.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function GoogleAnalytics(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function GoogleAnalytics(source) {
        var _window$googleAnalyti;
        var Tracker = function Tracker() {};
        var proto = Tracker.prototype;
        proto.get = noopFunc;
        proto.set = noopFunc;
        proto.send = noopFunc;
        var googleAnalyticsName = window.GoogleAnalyticsObject || "ga";
        var queue = (_window$googleAnalyti = window[googleAnalyticsName]) === null || _window$googleAnalyti === void 0 ? void 0 : _window$googleAnalyti.q;
        function ga(a) {
            var len = arguments.length;
            if (len === 0) {
                return;
            }
            var lastArg = arguments[len - 1];
            var replacer;
            if (lastArg instanceof Object && lastArg !== null && typeof lastArg.hitCallback === "function") {
                replacer = lastArg.hitCallback;
            } else if (typeof lastArg === "function") {
                replacer = function replacer() {
                    lastArg(ga.create());
                };
            }
            try {
                setTimeout(replacer, 1);
            } catch (ex) {}
        }
        ga.create = function() {
            return new Tracker;
        };
        ga.getByName = function() {
            return new Tracker;
        };
        ga.getAll = function() {
            return [ new Tracker ];
        };
        ga.remove = noopFunc;
        ga.loaded = true;
        window[googleAnalyticsName] = ga;
        if (Array.isArray(queue)) {
            var push = function push(arg) {
                ga(...arg);
            };
            queue.push = push;
            queue.forEach(push);
        }
        var {dataLayer: dataLayer, google_optimize: google_optimize} = window;
        if (dataLayer instanceof Object === false) {
            return;
        }
        if (dataLayer.hide instanceof Object && typeof dataLayer.hide.end === "function") {
            dataLayer.hide.end();
        }
        var handleCallback = function handleCallback(dataObj, funcName) {
            if (dataObj && typeof dataObj[funcName] === "function") {
                setTimeout(dataObj[funcName]);
            }
        };
        if (typeof dataLayer.push === "function") {
            dataLayer.push = function(data) {
                if (data instanceof Object) {
                    handleCallback(data, "eventCallback");
                    for (var key in data) {
                        handleCallback(data[key], "event_callback");
                    }
                    if (!data.hasOwnProperty("eventCallback") && !data.hasOwnProperty("eventCallback")) {
                        [].push.call(window.dataLayer, data);
                    }
                }
                if (Array.isArray(data)) {
                    data.forEach((function(arg) {
                        handleCallback(arg, "callback");
                    }));
                }
                return noopFunc;
            };
        }
        if (google_optimize instanceof Object && typeof google_optimize.get === "function") {
            var googleOptimizeWrapper = {
                get: noopFunc
            };
            window.google_optimize = googleOptimizeWrapper;
        }
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopFunc() {}
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        GoogleAnalytics.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function GoogleAnalyticsGa(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function GoogleAnalyticsGa(source) {
        function Gaq() {}
        Gaq.prototype.Na = noopFunc;
        Gaq.prototype.O = noopFunc;
        Gaq.prototype.Sa = noopFunc;
        Gaq.prototype.Ta = noopFunc;
        Gaq.prototype.Va = noopFunc;
        Gaq.prototype._createAsyncTracker = noopFunc;
        Gaq.prototype._getAsyncTracker = noopFunc;
        Gaq.prototype._getPlugin = noopFunc;
        Gaq.prototype.push = function(data) {
            if (typeof data === "function") {
                data();
                return;
            }
            if (Array.isArray(data) === false) {
                return;
            }
            if (typeof data[0] === "string" && /(^|\.)_link$/.test(data[0]) && typeof data[1] === "string") {
                window.location.assign(data[1]);
            }
            if (data[0] === "_set" && data[1] === "hitCallback" && typeof data[2] === "function") {
                data[2]();
            }
        };
        var gaq = new Gaq;
        var asyncTrackers = window._gaq || [];
        if (Array.isArray(asyncTrackers)) {
            while (asyncTrackers[0]) {
                gaq.push(asyncTrackers.shift());
            }
        }
        window._gaq = gaq.qf = gaq;
        function Gat() {}
        var api = [ "_addIgnoredOrganic", "_addIgnoredRef", "_addItem", "_addOrganic", "_addTrans", "_clearIgnoredOrganic", "_clearIgnoredRef", "_clearOrganic", "_cookiePathCopy", "_deleteCustomVar", "_getName", "_setAccount", "_getAccount", "_getClientInfo", "_getDetectFlash", "_getDetectTitle", "_getLinkerUrl", "_getLocalGifPath", "_getServiceMode", "_getVersion", "_getVisitorCustomVar", "_initData", "_link", "_linkByPost", "_setAllowAnchor", "_setAllowHash", "_setAllowLinker", "_setCampContentKey", "_setCampMediumKey", "_setCampNameKey", "_setCampNOKey", "_setCampSourceKey", "_setCampTermKey", "_setCampaignCookieTimeout", "_setCampaignTrack", "_setClientInfo", "_setCookiePath", "_setCookiePersistence", "_setCookieTimeout", "_setCustomVar", "_setDetectFlash", "_setDetectTitle", "_setDomainName", "_setLocalGifPath", "_setLocalRemoteServerMode", "_setLocalServerMode", "_setReferrerOverride", "_setRemoteServerMode", "_setSampleRate", "_setSessionTimeout", "_setSiteSpeedSampleRate", "_setSessionCookieTimeout", "_setVar", "_setVisitorCookieTimeout", "_trackEvent", "_trackPageLoadTime", "_trackPageview", "_trackSocial", "_trackTiming", "_trackTrans", "_visitCode" ];
        var tracker = api.reduce((function(res, funcName) {
            res[funcName] = noopFunc;
            return res;
        }), {});
        tracker._getLinkerUrl = function(a) {
            return a;
        };
        tracker._link = function(url) {
            if (typeof url !== "string") {
                return;
            }
            try {
                window.location.assign(url);
            } catch (e) {
                logMessage(source, e);
            }
        };
        Gat.prototype._anonymizeIP = noopFunc;
        Gat.prototype._createTracker = noopFunc;
        Gat.prototype._forceSSL = noopFunc;
        Gat.prototype._getPlugin = noopFunc;
        Gat.prototype._getTracker = function() {
            return tracker;
        };
        Gat.prototype._getTrackerByName = function() {
            return tracker;
        };
        Gat.prototype._getTrackers = noopFunc;
        Gat.prototype.aa = noopFunc;
        Gat.prototype.ab = noopFunc;
        Gat.prototype.hb = noopFunc;
        Gat.prototype.la = noopFunc;
        Gat.prototype.oa = noopFunc;
        Gat.prototype.pa = noopFunc;
        Gat.prototype.u = noopFunc;
        var gat = new Gat;
        window._gat = gat;
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopFunc() {}
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        GoogleAnalyticsGa.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function GoogleIma3(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function GoogleIma3(source) {
        var _window$google$ima;
        var VERSION = "3.453.0";
        var ima = {};
        var AdDisplayContainer = function AdDisplayContainer(containerElement) {
            var divElement = document.createElement("div");
            divElement.style.setProperty("display", "none", "important");
            divElement.style.setProperty("visibility", "collapse", "important");
            if (containerElement) {
                containerElement.appendChild(divElement);
            }
        };
        AdDisplayContainer.prototype.destroy = noopFunc;
        AdDisplayContainer.prototype.initialize = noopFunc;
        var ImaSdkSettings = function ImaSdkSettings() {};
        ImaSdkSettings.CompanionBackfillMode = {
            ALWAYS: "always",
            ON_MASTER_AD: "on_master_ad"
        };
        ImaSdkSettings.VpaidMode = {
            DISABLED: 0,
            ENABLED: 1,
            INSECURE: 2
        };
        ImaSdkSettings.prototype = {
            c: true,
            f: {},
            i: false,
            l: "",
            p: "",
            r: 0,
            t: "",
            v: "",
            getCompanionBackfill: noopFunc,
            getDisableCustomPlaybackForIOS10Plus() {
                return this.i;
            },
            getDisabledFlashAds: function getDisabledFlashAds() {
                return true;
            },
            getFeatureFlags() {
                return this.f;
            },
            getLocale() {
                return this.l;
            },
            getNumRedirects() {
                return this.r;
            },
            getPlayerType() {
                return this.t;
            },
            getPlayerVersion() {
                return this.v;
            },
            getPpid() {
                return this.p;
            },
            getVpaidMode() {
                return this.C;
            },
            isCookiesEnabled() {
                return this.c;
            },
            isVpaidAdapter() {
                return this.M;
            },
            setCompanionBackfill: noopFunc,
            setAutoPlayAdBreaks(a) {
                this.K = a;
            },
            setCookiesEnabled(c) {
                this.c = !!c;
            },
            setDisableCustomPlaybackForIOS10Plus(i) {
                this.i = !!i;
            },
            setDisableFlashAds: noopFunc,
            setFeatureFlags(f) {
                this.f = !!f;
            },
            setIsVpaidAdapter(a) {
                this.M = a;
            },
            setLocale(l) {
                this.l = !!l;
            },
            setNumRedirects(r) {
                this.r = !!r;
            },
            setPageCorrelator(a) {
                this.R = a;
            },
            setPlayerType(t) {
                this.t = !!t;
            },
            setPlayerVersion(v) {
                this.v = !!v;
            },
            setPpid(p) {
                this.p = !!p;
            },
            setVpaidMode(a) {
                this.C = a;
            },
            setSessionId: noopFunc,
            setStreamCorrelator: noopFunc,
            setVpaidAllowed: noopFunc,
            CompanionBackfillMode: {
                ALWAYS: "always",
                ON_MASTER_AD: "on_master_ad"
            },
            VpaidMode: {
                DISABLED: 0,
                ENABLED: 1,
                INSECURE: 2
            }
        };
        var EventHandler = function EventHandler() {
            this.listeners = new Map;
            this._dispatch = function(e) {
                var listeners = this.listeners.get(e.type);
                listeners = listeners ? listeners.values() : [];
                for (var _i = 0, _Array$from = Array.from(listeners); _i < _Array$from.length; _i++) {
                    var listener = _Array$from[_i];
                    try {
                        listener(e);
                    } catch (r) {
                        logMessage(source, r);
                    }
                }
            };
            this.addEventListener = function(types, callback, options, context) {
                if (!Array.isArray(types)) {
                    types = [ types ];
                }
                for (var i = 0; i < types.length; i += 1) {
                    var type = types[i];
                    if (!this.listeners.has(type)) {
                        this.listeners.set(type, new Map);
                    }
                    this.listeners.get(type).set(callback, callback.bind(context || this));
                }
            };
            this.removeEventListener = function(types, callback) {
                if (!Array.isArray(types)) {
                    types = [ types ];
                }
                for (var i = 0; i < types.length; i += 1) {
                    var _this$listeners$get;
                    var type = types[i];
                    (_this$listeners$get = this.listeners.get(type)) === null || _this$listeners$get === void 0 || _this$listeners$get.delete(callback);
                }
            };
        };
        var AdsManager = new EventHandler;
        AdsManager.volume = 1;
        AdsManager.collapse = noopFunc;
        AdsManager.configureAdsManager = noopFunc;
        AdsManager.destroy = noopFunc;
        AdsManager.discardAdBreak = noopFunc;
        AdsManager.expand = noopFunc;
        AdsManager.focus = noopFunc;
        AdsManager.getAdSkippableState = function() {
            return false;
        };
        AdsManager.getCuePoints = function() {
            return [ 0 ];
        };
        AdsManager.getCurrentAd = function() {
            return currentAd;
        };
        AdsManager.getCurrentAdCuePoints = function() {
            return [];
        };
        AdsManager.getRemainingTime = function() {
            return 0;
        };
        AdsManager.getVolume = function() {
            return this.volume;
        };
        AdsManager.init = noopFunc;
        AdsManager.isCustomClickTrackingUsed = function() {
            return false;
        };
        AdsManager.isCustomPlaybackUsed = function() {
            return false;
        };
        AdsManager.pause = noopFunc;
        AdsManager.requestNextAdBreak = noopFunc;
        AdsManager.resize = noopFunc;
        AdsManager.resume = noopFunc;
        AdsManager.setVolume = function(v) {
            this.volume = v;
        };
        AdsManager.skip = noopFunc;
        AdsManager.start = function() {
            for (var _i2 = 0, _arr = [ AdEvent.Type.ALL_ADS_COMPLETED, AdEvent.Type.CONTENT_RESUME_REQUESTED ]; _i2 < _arr.length; _i2++) {
                var type = _arr[_i2];
                try {
                    this._dispatch(new ima.AdEvent(type));
                } catch (e) {
                    logMessage(source, e);
                }
            }
        };
        AdsManager.stop = noopFunc;
        AdsManager.updateAdsRenderingSettings = noopFunc;
        var manager = Object.create(AdsManager);
        var AdsManagerLoadedEvent = function AdsManagerLoadedEvent(type, adsRequest, userRequestContext) {
            this.type = type;
            this.adsRequest = adsRequest;
            this.userRequestContext = userRequestContext;
        };
        AdsManagerLoadedEvent.prototype = {
            getAdsManager: function getAdsManager() {
                return manager;
            },
            getUserRequestContext() {
                if (this.userRequestContext) {
                    return this.userRequestContext;
                }
                return {};
            }
        };
        AdsManagerLoadedEvent.Type = {
            ADS_MANAGER_LOADED: "adsManagerLoaded"
        };
        var AdsLoader = EventHandler;
        AdsLoader.prototype.settings = new ImaSdkSettings;
        AdsLoader.prototype.contentComplete = noopFunc;
        AdsLoader.prototype.destroy = noopFunc;
        AdsLoader.prototype.getSettings = function() {
            return this.settings;
        };
        AdsLoader.prototype.getVersion = function() {
            return VERSION;
        };
        AdsLoader.prototype.requestAds = function(adsRequest, userRequestContext) {
            var _this = this;
            requestAnimationFrame((function() {
                var {ADS_MANAGER_LOADED: ADS_MANAGER_LOADED} = AdsManagerLoadedEvent.Type;
                var event = new ima.AdsManagerLoadedEvent(ADS_MANAGER_LOADED, adsRequest, userRequestContext);
                _this._dispatch(event);
            }));
            var e = new ima.AdError("adPlayError", 1205, 1205, "The browser prevented playback initiated without user interaction.", adsRequest, userRequestContext);
            requestAnimationFrame((function() {
                _this._dispatch(new ima.AdErrorEvent(e));
            }));
        };
        var AdsRenderingSettings = noopFunc;
        var AdsRequest = function AdsRequest() {};
        AdsRequest.prototype = {
            setAdWillAutoPlay: noopFunc,
            setAdWillPlayMuted: noopFunc,
            setContinuousPlayback: noopFunc
        };
        var AdPodInfo = function AdPodInfo() {};
        AdPodInfo.prototype = {
            getAdPosition: function getAdPosition() {
                return 1;
            },
            getIsBumper: function getIsBumper() {
                return false;
            },
            getMaxDuration: function getMaxDuration() {
                return -1;
            },
            getPodIndex: function getPodIndex() {
                return 1;
            },
            getTimeOffset: function getTimeOffset() {
                return 0;
            },
            getTotalAds: function getTotalAds() {
                return 1;
            }
        };
        var UniversalAdIdInfo = function UniversalAdIdInfo() {};
        UniversalAdIdInfo.prototype.getAdIdRegistry = function() {
            return "";
        };
        UniversalAdIdInfo.prototype.getAdIsValue = function() {
            return "";
        };
        var Ad = function Ad() {};
        Ad.prototype = {
            pi: new AdPodInfo,
            getAdId: function getAdId() {
                return "";
            },
            getAdPodInfo() {
                return this.pi;
            },
            getAdSystem: function getAdSystem() {
                return "";
            },
            getAdvertiserName: function getAdvertiserName() {
                return "";
            },
            getApiFramework: function getApiFramework() {
                return null;
            },
            getCompanionAds: function getCompanionAds() {
                return [];
            },
            getContentType: function getContentType() {
                return "";
            },
            getCreativeAdId: function getCreativeAdId() {
                return "";
            },
            getDealId: function getDealId() {
                return "";
            },
            getDescription: function getDescription() {
                return "";
            },
            getDuration: function getDuration() {
                return 8.5;
            },
            getHeight: function getHeight() {
                return 0;
            },
            getMediaUrl: function getMediaUrl() {
                return null;
            },
            getMinSuggestedDuration: function getMinSuggestedDuration() {
                return -2;
            },
            getSkipTimeOffset: function getSkipTimeOffset() {
                return -1;
            },
            getSurveyUrl: function getSurveyUrl() {
                return null;
            },
            getTitle: function getTitle() {
                return "";
            },
            getTraffickingParametersString: function getTraffickingParametersString() {
                return "";
            },
            getUiElements: function getUiElements() {
                return [ "" ];
            },
            getUniversalAdIdRegistry: function getUniversalAdIdRegistry() {
                return "unknown";
            },
            getUniversalAdIds: function getUniversalAdIds() {
                return [ new UniversalAdIdInfo ];
            },
            getUniversalAdIdValue: function getUniversalAdIdValue() {
                return "unknown";
            },
            getVastMediaBitrate: function getVastMediaBitrate() {
                return 0;
            },
            getVastMediaHeight: function getVastMediaHeight() {
                return 0;
            },
            getVastMediaWidth: function getVastMediaWidth() {
                return 0;
            },
            getWidth: function getWidth() {
                return 0;
            },
            getWrapperAdIds: function getWrapperAdIds() {
                return [ "" ];
            },
            getWrapperAdSystems: function getWrapperAdSystems() {
                return [ "" ];
            },
            getWrapperCreativeIds: function getWrapperCreativeIds() {
                return [ "" ];
            },
            isLinear: function isLinear() {
                return true;
            },
            isSkippable() {
                return true;
            }
        };
        var CompanionAd = function CompanionAd() {};
        CompanionAd.prototype = {
            getAdSlotId: function getAdSlotId() {
                return "";
            },
            getContent: function getContent() {
                return "";
            },
            getContentType: function getContentType() {
                return "";
            },
            getHeight: function getHeight() {
                return 1;
            },
            getWidth: function getWidth() {
                return 1;
            }
        };
        var AdError = function AdError(type, code, vast, message, adsRequest, userRequestContext) {
            this.errorCode = code;
            this.message = message;
            this.type = type;
            this.adsRequest = adsRequest;
            this.userRequestContext = userRequestContext;
            this.getErrorCode = function() {
                return this.errorCode;
            };
            this.getInnerError = function() {
                return null;
            };
            this.getMessage = function() {
                return this.message;
            };
            this.getType = function() {
                return this.type;
            };
            this.getVastErrorCode = function() {
                return this.vastErrorCode;
            };
            this.toString = function() {
                return `AdError ${this.errorCode}: ${this.message}`;
            };
        };
        AdError.ErrorCode = {};
        AdError.Type = {};
        var isEngadget = function isEngadget() {
            try {
                for (var _i3 = 0, _Object$values = Object.values(window.vidible._getContexts()); _i3 < _Object$values.length; _i3++) {
                    var _ctx$getPlayer;
                    var ctx = _Object$values[_i3];
                    if ((_ctx$getPlayer = ctx.getPlayer()) !== null && _ctx$getPlayer !== void 0 && (_ctx$getPlayer = _ctx$getPlayer.div) !== null && _ctx$getPlayer !== void 0 && _ctx$getPlayer.innerHTML.includes("www.engadget.com")) {
                        return true;
                    }
                }
            } catch (e) {}
            return false;
        };
        var currentAd = isEngadget() ? undefined : new Ad;
        var AdEvent = function AdEvent(type) {
            this.type = type;
        };
        AdEvent.prototype = {
            getAd: function getAd() {
                return currentAd;
            },
            getAdData: function getAdData() {}
        };
        AdEvent.Type = {
            AD_BREAK_READY: "adBreakReady",
            AD_BUFFERING: "adBuffering",
            AD_CAN_PLAY: "adCanPlay",
            AD_METADATA: "adMetadata",
            AD_PROGRESS: "adProgress",
            ALL_ADS_COMPLETED: "allAdsCompleted",
            CLICK: "click",
            COMPLETE: "complete",
            CONTENT_PAUSE_REQUESTED: "contentPauseRequested",
            CONTENT_RESUME_REQUESTED: "contentResumeRequested",
            DURATION_CHANGE: "durationChange",
            EXPANDED_CHANGED: "expandedChanged",
            FIRST_QUARTILE: "firstQuartile",
            IMPRESSION: "impression",
            INTERACTION: "interaction",
            LINEAR_CHANGE: "linearChange",
            LINEAR_CHANGED: "linearChanged",
            LOADED: "loaded",
            LOG: "log",
            MIDPOINT: "midpoint",
            PAUSED: "pause",
            RESUMED: "resume",
            SKIPPABLE_STATE_CHANGED: "skippableStateChanged",
            SKIPPED: "skip",
            STARTED: "start",
            THIRD_QUARTILE: "thirdQuartile",
            USER_CLOSE: "userClose",
            VIDEO_CLICKED: "videoClicked",
            VIDEO_ICON_CLICKED: "videoIconClicked",
            VIEWABLE_IMPRESSION: "viewable_impression",
            VOLUME_CHANGED: "volumeChange",
            VOLUME_MUTED: "mute"
        };
        var AdErrorEvent = function AdErrorEvent(error) {
            this.error = error;
            this.type = "adError";
            this.getError = function() {
                return this.error;
            };
            this.getUserRequestContext = function() {
                var _this$error;
                if ((_this$error = this.error) !== null && _this$error !== void 0 && _this$error.userRequestContext) {
                    return this.error.userRequestContext;
                }
                return {};
            };
        };
        AdErrorEvent.Type = {
            AD_ERROR: "adError"
        };
        var CustomContentLoadedEvent = function CustomContentLoadedEvent() {};
        CustomContentLoadedEvent.Type = {
            CUSTOM_CONTENT_LOADED: "deprecated-event"
        };
        var CompanionAdSelectionSettings = function CompanionAdSelectionSettings() {};
        CompanionAdSelectionSettings.CreativeType = {
            ALL: "All",
            FLASH: "Flash",
            IMAGE: "Image"
        };
        CompanionAdSelectionSettings.ResourceType = {
            ALL: "All",
            HTML: "Html",
            IFRAME: "IFrame",
            STATIC: "Static"
        };
        CompanionAdSelectionSettings.SizeCriteria = {
            IGNORE: "IgnoreSize",
            SELECT_EXACT_MATCH: "SelectExactMatch",
            SELECT_NEAR_MATCH: "SelectNearMatch"
        };
        var AdCuePoints = function AdCuePoints() {};
        AdCuePoints.prototype = {
            getCuePoints: function getCuePoints() {
                return [];
            },
            getAdIdRegistry: function getAdIdRegistry() {
                return "";
            },
            getAdIdValue: function getAdIdValue() {
                return "";
            }
        };
        var AdProgressData = noopFunc;
        Object.assign(ima, {
            AdCuePoints: AdCuePoints,
            AdDisplayContainer: AdDisplayContainer,
            AdError: AdError,
            AdErrorEvent: AdErrorEvent,
            AdEvent: AdEvent,
            AdPodInfo: AdPodInfo,
            AdProgressData: AdProgressData,
            AdsLoader: AdsLoader,
            AdsManager: manager,
            AdsManagerLoadedEvent: AdsManagerLoadedEvent,
            AdsRenderingSettings: AdsRenderingSettings,
            AdsRequest: AdsRequest,
            CompanionAd: CompanionAd,
            CompanionAdSelectionSettings: CompanionAdSelectionSettings,
            CustomContentLoadedEvent: CustomContentLoadedEvent,
            gptProxyInstance: {},
            ImaSdkSettings: ImaSdkSettings,
            OmidAccessMode: {
                DOMAIN: "domain",
                FULL: "full",
                LIMITED: "limited"
            },
            OmidVerificationVendor: {
                1: "OTHER",
                2: "MOAT",
                3: "DOUBLEVERIFY",
                4: "INTEGRAL_AD_SCIENCE",
                5: "PIXELATE",
                6: "NIELSEN",
                7: "COMSCORE",
                8: "MEETRICS",
                9: "GOOGLE",
                OTHER: 1,
                MOAT: 2,
                DOUBLEVERIFY: 3,
                INTEGRAL_AD_SCIENCE: 4,
                PIXELATE: 5,
                NIELSEN: 6,
                COMSCORE: 7,
                MEETRICS: 8,
                GOOGLE: 9
            },
            settings: new ImaSdkSettings,
            UiElements: {
                AD_ATTRIBUTION: "adAttribution",
                COUNTDOWN: "countdown"
            },
            UniversalAdIdInfo: UniversalAdIdInfo,
            VERSION: VERSION,
            ViewMode: {
                FULLSCREEN: "fullscreen",
                NORMAL: "normal"
            }
        });
        if (!window.google) {
            window.google = {};
        }
        if ((_window$google$ima = window.google.ima) !== null && _window$google$ima !== void 0 && _window$google$ima.dai) {
            ima.dai = window.google.ima.dai;
        }
        window.google.ima = ima;
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopFunc() {}
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        GoogleIma3.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function GoogleSyndicationAdsByGoogle(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function GoogleSyndicationAdsByGoogle(source) {
        window.adsbygoogle = {
            loaded: true,
            push(arg) {
                if (typeof this.length === "undefined") {
                    this.length = 0;
                    this.length += 1;
                }
                if (arg !== null && arg instanceof Object && arg.constructor.name === "Object") {
                    for (var _i = 0, _Object$keys = Object.keys(arg); _i < _Object$keys.length; _i++) {
                        var key = _Object$keys[_i];
                        if (typeof arg[key] === "function") {
                            try {
                                arg[key].call(this, {});
                            } catch (_unused) {}
                        }
                    }
                }
            }
        };
        var adElems = document.querySelectorAll(".adsbygoogle");
        var css = "height:1px!important;max-height:1px!important;max-width:1px!important;width:1px!important;";
        var statusAttrName = "data-adsbygoogle-status";
        var ASWIFT_IFRAME_MARKER = "aswift_";
        var GOOGLE_ADS_IFRAME_MARKER = "google_ads_iframe_";
        var executed = false;
        for (var i = 0; i < adElems.length; i += 1) {
            var adElemChildNodes = adElems[i].childNodes;
            var childNodesQuantity = adElemChildNodes.length;
            var areIframesDefined = false;
            if (childNodesQuantity > 0) {
                areIframesDefined = childNodesQuantity === 2 && adElemChildNodes[0].nodeName.toLowerCase() === "iframe" && adElemChildNodes[0].id.includes(ASWIFT_IFRAME_MARKER) && adElemChildNodes[1].nodeName.toLowerCase() === "iframe" && adElemChildNodes[1].id.includes(GOOGLE_ADS_IFRAME_MARKER);
            }
            if (!areIframesDefined) {
                adElems[i].setAttribute(statusAttrName, "done");
                var aswiftIframe = document.createElement("iframe");
                aswiftIframe.id = `${ASWIFT_IFRAME_MARKER}${i}`;
                aswiftIframe.style = css;
                adElems[i].appendChild(aswiftIframe);
                var innerAswiftIframe = document.createElement("iframe");
                aswiftIframe.contentWindow.document.body.appendChild(innerAswiftIframe);
                var googleadsIframe = document.createElement("iframe");
                googleadsIframe.id = `${GOOGLE_ADS_IFRAME_MARKER}${i}`;
                googleadsIframe.style = css;
                adElems[i].appendChild(googleadsIframe);
                var innerGoogleadsIframe = document.createElement("iframe");
                googleadsIframe.contentWindow.document.body.appendChild(innerGoogleadsIframe);
                executed = true;
            }
        }
        if (executed) {
            hit(source);
        }
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        GoogleSyndicationAdsByGoogle.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function GoogleTagServicesGpt(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function GoogleTagServicesGpt(source) {
        var slots = new Map;
        var slotsById = new Map;
        var slotsPerPath = new Map;
        var slotCreatives = new Map;
        var eventCallbacks = new Map;
        var gTargeting = new Map;
        var addEventListener = function addEventListener(name, listener) {
            if (!eventCallbacks.has(name)) {
                eventCallbacks.set(name, new Set);
            }
            eventCallbacks.get(name).add(listener);
            return this;
        };
        var removeEventListener = function removeEventListener(name, listener) {
            if (eventCallbacks.has(name)) {
                return eventCallbacks.get(name).delete(listener);
            }
            return false;
        };
        var fireSlotEvent = function fireSlotEvent(name, slot) {
            return new Promise((function(resolve) {
                requestAnimationFrame((function() {
                    var size = [ 0, 0 ];
                    var callbacksSet = eventCallbacks.get(name) || [];
                    var callbackArray = Array.from(callbacksSet);
                    for (var i = 0; i < callbackArray.length; i += 1) {
                        callbackArray[i]({
                            isEmpty: true,
                            size: size,
                            slot: slot
                        });
                    }
                    resolve();
                }));
            }));
        };
        var emptySlotElement = function emptySlotElement(slot) {
            var node = document.getElementById(slot.getSlotElementId());
            while (node !== null && node !== void 0 && node.lastChild) {
                node.lastChild.remove();
            }
        };
        var recreateIframeForSlot = function recreateIframeForSlot(slot) {
            var _document$getElementB;
            var eid = `google_ads_iframe_${slot.getId()}`;
            (_document$getElementB = document.getElementById(eid)) === null || _document$getElementB === void 0 || _document$getElementB.remove();
            var node = document.getElementById(slot.getSlotElementId());
            if (node) {
                var f = document.createElement("iframe");
                f.id = eid;
                f.srcdoc = "<body></body>";
                f.style = "position:absolute; width:0; height:0; left:0; right:0; z-index:-1; border:0";
                f.setAttribute("width", 0);
                f.setAttribute("height", 0);
                f.setAttribute("data-load-complete", true);
                f.setAttribute("data-google-container-id", true);
                f.setAttribute("sandbox", "");
                node.appendChild(f);
            }
        };
        var displaySlot = function displaySlot(slot) {
            if (!slot) {
                return;
            }
            var id = slot.getSlotElementId();
            if (!document.getElementById(id)) {
                return;
            }
            var parent = document.getElementById(id);
            if (parent) {
                parent.appendChild(document.createElement("div"));
            }
            emptySlotElement(slot);
            recreateIframeForSlot(slot);
            fireSlotEvent("slotRenderEnded", slot);
            fireSlotEvent("slotRequested", slot);
            fireSlotEvent("slotResponseReceived", slot);
            fireSlotEvent("slotOnload", slot);
            fireSlotEvent("impressionViewable", slot);
        };
        var companionAdsService = {
            addEventListener: addEventListener,
            removeEventListener: removeEventListener,
            enableSyncLoading: noopFunc,
            setRefreshUnfilledSlots: noopFunc,
            getSlots: noopArray
        };
        var contentService = {
            addEventListener: addEventListener,
            removeEventListener: removeEventListener,
            setContent: noopFunc
        };
        function PassbackSlot() {}
        PassbackSlot.prototype.display = noopFunc;
        PassbackSlot.prototype.get = noopNull;
        PassbackSlot.prototype.set = noopThis;
        PassbackSlot.prototype.setClickUrl = noopThis;
        PassbackSlot.prototype.setTagForChildDirectedTreatment = noopThis;
        PassbackSlot.prototype.setTargeting = noopThis;
        PassbackSlot.prototype.updateTargetingFromMap = noopThis;
        function SizeMappingBuilder() {}
        SizeMappingBuilder.prototype.addSize = noopThis;
        SizeMappingBuilder.prototype.build = noopNull;
        var getTargetingValue = function getTargetingValue(v) {
            if (typeof v === "string") {
                return [ v ];
            }
            try {
                return Array.prototype.flat.call(v);
            } catch (_unused) {}
            return [];
        };
        var updateTargeting = function updateTargeting(targeting, map) {
            if (typeof map === "object") {
                for (var key in map) {
                    if (Object.prototype.hasOwnProperty.call(map, key)) {
                        targeting.set(key, getTargetingValue(map[key]));
                    }
                }
            }
        };
        var defineSlot = function defineSlot(adUnitPath, creatives, optDiv) {
            if (slotsById.has(optDiv)) {
                var _document$getElementB2;
                (_document$getElementB2 = document.getElementById(optDiv)) === null || _document$getElementB2 === void 0 || _document$getElementB2.remove();
                return slotsById.get(optDiv);
            }
            var attributes = new Map;
            var targeting = new Map;
            var exclusions = new Set;
            var response = {
                advertiserId: undefined,
                campaignId: undefined,
                creativeId: undefined,
                creativeTemplateId: undefined,
                lineItemId: undefined
            };
            var sizes = [ {
                getHeight: function getHeight() {
                    return 2;
                },
                getWidth: function getWidth() {
                    return 2;
                }
            } ];
            var num = (slotsPerPath.get(adUnitPath) || 0) + 1;
            slotsPerPath.set(adUnitPath, num);
            var id = `${adUnitPath}_${num}`;
            var clickUrl = "";
            var collapseEmptyDiv = null;
            var services = new Set;
            var slot = {
                addService(e) {
                    services.add(e);
                    return slot;
                },
                clearCategoryExclusions: noopThis,
                clearTargeting(k) {
                    if (k === undefined) {
                        targeting.clear();
                    } else {
                        targeting.delete(k);
                    }
                },
                defineSizeMapping(mapping) {
                    slotCreatives.set(optDiv, mapping);
                    return this;
                },
                get: function get(k) {
                    return attributes.get(k);
                },
                getAdUnitPath: function getAdUnitPath() {
                    return adUnitPath;
                },
                getAttributeKeys: function getAttributeKeys() {
                    return Array.from(attributes.keys());
                },
                getCategoryExclusions: function getCategoryExclusions() {
                    return Array.from(exclusions);
                },
                getClickUrl: function getClickUrl() {
                    return clickUrl;
                },
                getCollapseEmptyDiv: function getCollapseEmptyDiv() {
                    return collapseEmptyDiv;
                },
                getContentUrl: function getContentUrl() {
                    return "";
                },
                getDivStartsCollapsed: function getDivStartsCollapsed() {
                    return null;
                },
                getDomId: function getDomId() {
                    return optDiv;
                },
                getEscapedQemQueryId: function getEscapedQemQueryId() {
                    return "";
                },
                getFirstLook: function getFirstLook() {
                    return 0;
                },
                getId: function getId() {
                    return id;
                },
                getHtml: function getHtml() {
                    return "";
                },
                getName: function getName() {
                    return id;
                },
                getOutOfPage: function getOutOfPage() {
                    return false;
                },
                getResponseInformation: function getResponseInformation() {
                    return response;
                },
                getServices: function getServices() {
                    return Array.from(services);
                },
                getSizes: function getSizes() {
                    return sizes;
                },
                getSlotElementId: function getSlotElementId() {
                    return optDiv;
                },
                getSlotId: function getSlotId() {
                    return slot;
                },
                getTargeting: function getTargeting(k) {
                    return targeting.get(k) || gTargeting.get(k) || [];
                },
                getTargetingKeys: function getTargetingKeys() {
                    return Array.from(new Set(Array.of(...gTargeting.keys(), ...targeting.keys())));
                },
                getTargetingMap: function getTargetingMap() {
                    return Object.assign(Object.fromEntries(gTargeting.entries()), Object.fromEntries(targeting.entries()));
                },
                set(k, v) {
                    attributes.set(k, v);
                    return slot;
                },
                setCategoryExclusion(e) {
                    exclusions.add(e);
                    return slot;
                },
                setClickUrl(u) {
                    clickUrl = u;
                    return slot;
                },
                setCollapseEmptyDiv(v) {
                    collapseEmptyDiv = !!v;
                    return slot;
                },
                setSafeFrameConfig: noopThis,
                setTagForChildDirectedTreatment: noopThis,
                setTargeting(k, v) {
                    targeting.set(k, getTargetingValue(v));
                    return slot;
                },
                toString: function toString() {
                    return id;
                },
                updateTargetingFromMap(map) {
                    updateTargeting(targeting, map);
                    return slot;
                }
            };
            slots.set(adUnitPath, slot);
            slotsById.set(optDiv, slot);
            slotCreatives.set(optDiv, creatives);
            return slot;
        };
        var pubAdsService = {
            addEventListener: addEventListener,
            removeEventListener: removeEventListener,
            clear: noopFunc,
            clearCategoryExclusions: noopThis,
            clearTagForChildDirectedTreatment: noopThis,
            clearTargeting(k) {
                if (k === undefined) {
                    gTargeting.clear();
                } else {
                    gTargeting.delete(k);
                }
            },
            collapseEmptyDivs: noopFunc,
            defineOutOfPagePassback() {
                return new PassbackSlot;
            },
            definePassback() {
                return new PassbackSlot;
            },
            disableInitialLoad: noopFunc,
            display: noopFunc,
            enableAsyncRendering: noopFunc,
            enableLazyLoad: noopFunc,
            enableSingleRequest: noopFunc,
            enableSyncRendering: noopFunc,
            enableVideoAds: noopFunc,
            get: noopNull,
            getAttributeKeys: noopArray,
            getTargeting: noopArray,
            getTargetingKeys: noopArray,
            getSlots: noopArray,
            isInitialLoadDisabled: trueFunc,
            refresh: noopFunc,
            set: noopThis,
            setCategoryExclusion: noopThis,
            setCentering: noopFunc,
            setCookieOptions: noopThis,
            setForceSafeFrame: noopThis,
            setLocation: noopThis,
            setPrivacySettings: noopThis,
            setPublisherProvidedId: noopThis,
            setRequestNonPersonalizedAds: noopThis,
            setSafeFrameConfig: noopThis,
            setTagForChildDirectedTreatment: noopThis,
            setTargeting: noopThis,
            setVideoContent: noopThis,
            updateCorrelator: noopFunc
        };
        var {googletag: googletag = {}} = window;
        var {cmd: cmd = []} = googletag;
        googletag.apiReady = true;
        googletag.cmd = [];
        googletag.cmd.push = function(a) {
            try {
                a();
            } catch (ex) {}
            return 1;
        };
        googletag.companionAds = function() {
            return companionAdsService;
        };
        googletag.content = function() {
            return contentService;
        };
        googletag.defineOutOfPageSlot = defineSlot;
        googletag.defineSlot = defineSlot;
        googletag.destroySlots = function() {
            slots.clear();
            slotsById.clear();
        };
        googletag.disablePublisherConsole = noopFunc;
        googletag.display = function(arg) {
            var id;
            if (arg !== null && arg !== void 0 && arg.getSlotElementId) {
                id = arg.getSlotElementId();
            } else if (arg !== null && arg !== void 0 && arg.nodeType) {
                id = arg.id;
            } else {
                id = String(arg);
            }
            displaySlot(slotsById.get(id));
        };
        googletag.enableServices = noopFunc;
        googletag.getVersion = noopStr;
        googletag.pubads = function() {
            return pubAdsService;
        };
        googletag.pubadsReady = true;
        googletag.setAdIframeTitle = noopFunc;
        googletag.sizeMapping = function() {
            return new SizeMappingBuilder;
        };
        window.googletag = googletag;
        while (cmd.length !== 0) {
            googletag.cmd.push(cmd.shift());
        }
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopFunc() {}
    function noopThis() {
        return this;
    }
    function noopNull() {
        return null;
    }
    function noopArray() {
        return [];
    }
    function noopStr() {
        return "";
    }
    function trueFunc() {
        return true;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        GoogleTagServicesGpt.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function Matomo(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function Matomo(source) {
        var Tracker = function Tracker() {};
        Tracker.prototype.setDoNotTrack = noopFunc;
        Tracker.prototype.setDomains = noopFunc;
        Tracker.prototype.setCustomDimension = noopFunc;
        Tracker.prototype.trackPageView = noopFunc;
        var AsyncTracker = function AsyncTracker() {};
        AsyncTracker.prototype.addListener = noopFunc;
        var matomoWrapper = {
            getTracker: Tracker,
            getAsyncTracker: AsyncTracker
        };
        window.Piwik = matomoWrapper;
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopFunc() {}
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        Matomo.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function NaverWcslog(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function NaverWcslog(source) {
        window.wcs_add = {};
        window.wcs_do = noopFunc;
        window.wcs = {
            inflow: noopFunc
        };
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopFunc() {}
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        NaverWcslog.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function Pardot(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function Pardot(source) {
        window.piVersion = "1.0.2";
        window.piScriptNum = 0;
        window.piScriptObj = [];
        window.checkNamespace = noopFunc;
        window.getPardotUrl = noopStr;
        window.piGetParameter = noopNull;
        window.piSetCookie = noopFunc;
        window.piGetCookie = noopStr;
        function piTracker() {
            window.pi = {
                tracker: {
                    visitor_id: "",
                    visitor_id_sign: "",
                    pi_opt_in: "",
                    campaign_id: ""
                }
            };
            window.piScriptNum += 1;
        }
        window.piResponse = noopFunc;
        window.piTracker = piTracker;
        piTracker();
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopFunc() {}
    function noopStr() {
        return "";
    }
    function noopNull() {
        return null;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        Pardot.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function Prebid(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function Prebid(source) {
        var pushFunction = function pushFunction(arg) {
            if (typeof arg === "function") {
                try {
                    arg.call();
                } catch (ex) {}
            }
        };
        var pbjsWrapper = {
            addAdUnits() {},
            adServers: {
                dfp: {
                    buildVideoUrl: noopStr
                }
            },
            adUnits: [],
            aliasBidder() {},
            cmd: [],
            enableAnalytics() {},
            getHighestCpmBids: noopArray,
            libLoaded: true,
            que: [],
            requestBids(arg) {
                if (arg instanceof Object && arg.bidsBackHandler) {
                    try {
                        arg.bidsBackHandler.call();
                    } catch (ex) {}
                }
            },
            removeAdUnit() {},
            setBidderConfig() {},
            setConfig() {},
            setTargetingForGPTAsync() {}
        };
        pbjsWrapper.cmd.push = pushFunction;
        pbjsWrapper.que.push = pushFunction;
        window.pbjs = pbjsWrapper;
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopStr() {
        return "";
    }
    function noopArray() {
        return [];
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        Prebid.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function ScoreCardResearchBeacon(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function ScoreCardResearchBeacon(source) {
        window.COMSCORE = {
            purge() {
                window._comscore = [];
            },
            beacon() {}
        };
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        ScoreCardResearchBeacon.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function abortCurrentInlineScript(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function abortCurrentInlineScript(source, property, search) {
        var searchRegexp = toRegExp(search);
        var rid = randomId();
        var SRC_DATA_MARKER = "data:text/javascript;base64,";
        var getCurrentScript = function getCurrentScript() {
            if ("currentScript" in document) {
                return document.currentScript;
            }
            var scripts = document.getElementsByTagName("script");
            return scripts[scripts.length - 1];
        };
        var ourScript = getCurrentScript();
        var abort = function abort() {
            var _scriptEl$src;
            var scriptEl = getCurrentScript();
            if (!scriptEl) {
                return;
            }
            var content = scriptEl.textContent;
            try {
                var textContentGetter = Object.getOwnPropertyDescriptor(Node.prototype, "textContent").get;
                content = textContentGetter.call(scriptEl);
            } catch (e) {}
            if (content.length === 0 && typeof scriptEl.src !== "undefined" && (_scriptEl$src = scriptEl.src) !== null && _scriptEl$src !== void 0 && _scriptEl$src.startsWith(SRC_DATA_MARKER)) {
                var encodedContent = scriptEl.src.slice(SRC_DATA_MARKER.length);
                content = window.atob(encodedContent);
            }
            if (scriptEl instanceof HTMLScriptElement && content.length > 0 && scriptEl !== ourScript && searchRegexp.test(content)) {
                hit(source);
                throw new ReferenceError(rid);
            }
        };
        var _setChainPropAccess = function setChainPropAccess(owner, property) {
            var chainInfo = getPropertyInChain(owner, property);
            var {base: base} = chainInfo;
            var {prop: prop, chain: chain} = chainInfo;
            if (base instanceof Object === false && base === null) {
                var props = property.split(".");
                var propIndex = props.indexOf(prop);
                var baseName = props[propIndex - 1];
                var message = `The scriptlet had been executed before the ${baseName} was loaded.`;
                logMessage(source, message);
                return;
            }
            if (chain) {
                var setter = function setter(a) {
                    base = a;
                    if (a instanceof Object) {
                        _setChainPropAccess(a, chain);
                    }
                };
                Object.defineProperty(owner, prop, {
                    get: function get() {
                        return base;
                    },
                    set: setter
                });
                return;
            }
            var currentValue = base[prop];
            var origDescriptor = Object.getOwnPropertyDescriptor(base, prop);
            if (origDescriptor instanceof Object === false || origDescriptor.get instanceof Function === false) {
                currentValue = base[prop];
                origDescriptor = undefined;
            }
            var descriptorWrapper = Object.assign(getDescriptorAddon(), {
                currentValue: currentValue,
                get() {
                    if (!this.isAbortingSuspended) {
                        this.isolateCallback(abort);
                    }
                    if (origDescriptor instanceof Object) {
                        return origDescriptor.get.call(base);
                    }
                    return this.currentValue;
                },
                set(newValue) {
                    if (!this.isAbortingSuspended) {
                        this.isolateCallback(abort);
                    }
                    if (origDescriptor instanceof Object) {
                        origDescriptor.set.call(base, newValue);
                    } else {
                        this.currentValue = newValue;
                    }
                }
            });
            setPropertyAccess(base, prop, {
                get() {
                    return descriptorWrapper.get.call(descriptorWrapper);
                },
                set(newValue) {
                    descriptorWrapper.set.call(descriptorWrapper, newValue);
                }
            });
        };
        _setChainPropAccess(window, property);
        window.onerror = createOnErrorHandler(rid).bind();
    }
    function randomId() {
        return Math.random().toString(36).slice(2, 9);
    }
    function setPropertyAccess(object, property, descriptor) {
        var currentDescriptor = Object.getOwnPropertyDescriptor(object, property);
        if (currentDescriptor && !currentDescriptor.configurable) {
            return false;
        }
        Object.defineProperty(object, property, descriptor);
        return true;
    }
    function getPropertyInChain(base, chain) {
        var pos = chain.indexOf(".");
        if (pos === -1) {
            return {
                base: base,
                prop: chain
            };
        }
        var prop = chain.slice(0, pos);
        if (base === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        var nextBase = base[prop];
        chain = chain.slice(pos + 1);
        if ((base instanceof Object || typeof base === "object") && isEmptyObject(base)) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase !== undefined) {
            return getPropertyInChain(nextBase, chain);
        }
        Object.defineProperty(base, prop, {
            configurable: true
        });
        return {
            base: base,
            prop: prop,
            chain: chain
        };
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function createOnErrorHandler(rid) {
        var nativeOnError = window.onerror;
        return function onError(error) {
            if (typeof error === "string" && error.includes(rid)) {
                return true;
            }
            if (nativeOnError instanceof Function) {
                for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                    args[_key - 1] = arguments[_key];
                }
                return nativeOnError.apply(window, [ error, ...args ]);
            }
            return false;
        };
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function isEmptyObject(obj) {
        return Object.keys(obj).length === 0 && !obj.prototype;
    }
    function getDescriptorAddon() {
        return {
            isAbortingSuspended: false,
            isolateCallback(cb) {
                this.isAbortingSuspended = true;
                try {
                    for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                        args[_key - 1] = arguments[_key];
                    }
                    var result = cb(...args);
                    this.isAbortingSuspended = false;
                    return result;
                } catch (_unused) {
                    var rid = randomId();
                    this.isAbortingSuspended = false;
                    throw new ReferenceError(rid);
                }
            }
        };
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        abortCurrentInlineScript.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function abortOnPropertyRead(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function abortOnPropertyRead(source, property) {
        if (!property) {
            return;
        }
        var rid = randomId();
        var abort = function abort() {
            hit(source);
            throw new ReferenceError(rid);
        };
        var _setChainPropAccess = function setChainPropAccess(owner, property) {
            var chainInfo = getPropertyInChain(owner, property);
            var {base: base} = chainInfo;
            var {prop: prop, chain: chain} = chainInfo;
            if (chain) {
                var setter = function setter(a) {
                    base = a;
                    if (a instanceof Object) {
                        _setChainPropAccess(a, chain);
                    }
                };
                Object.defineProperty(owner, prop, {
                    get: function get() {
                        return base;
                    },
                    set: setter
                });
                return;
            }
            setPropertyAccess(base, prop, {
                get: abort,
                set: function set() {}
            });
        };
        _setChainPropAccess(window, property);
        window.onerror = createOnErrorHandler(rid).bind();
    }
    function randomId() {
        return Math.random().toString(36).slice(2, 9);
    }
    function setPropertyAccess(object, property, descriptor) {
        var currentDescriptor = Object.getOwnPropertyDescriptor(object, property);
        if (currentDescriptor && !currentDescriptor.configurable) {
            return false;
        }
        Object.defineProperty(object, property, descriptor);
        return true;
    }
    function getPropertyInChain(base, chain) {
        var pos = chain.indexOf(".");
        if (pos === -1) {
            return {
                base: base,
                prop: chain
            };
        }
        var prop = chain.slice(0, pos);
        if (base === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        var nextBase = base[prop];
        chain = chain.slice(pos + 1);
        if ((base instanceof Object || typeof base === "object") && isEmptyObject(base)) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase !== undefined) {
            return getPropertyInChain(nextBase, chain);
        }
        Object.defineProperty(base, prop, {
            configurable: true
        });
        return {
            base: base,
            prop: prop,
            chain: chain
        };
    }
    function createOnErrorHandler(rid) {
        var nativeOnError = window.onerror;
        return function onError(error) {
            if (typeof error === "string" && error.includes(rid)) {
                return true;
            }
            if (nativeOnError instanceof Function) {
                for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                    args[_key - 1] = arguments[_key];
                }
                return nativeOnError.apply(window, [ error, ...args ]);
            }
            return false;
        };
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function isEmptyObject(obj) {
        return Object.keys(obj).length === 0 && !obj.prototype;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        abortOnPropertyRead.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function abortOnPropertyWrite(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function abortOnPropertyWrite(source, property) {
        if (!property) {
            return;
        }
        var rid = randomId();
        var abort = function abort() {
            hit(source);
            throw new ReferenceError(rid);
        };
        var _setChainPropAccess = function setChainPropAccess(owner, property) {
            var chainInfo = getPropertyInChain(owner, property);
            var {base: base} = chainInfo;
            var {prop: prop, chain: chain} = chainInfo;
            if (chain) {
                var setter = function setter(a) {
                    base = a;
                    if (a instanceof Object) {
                        _setChainPropAccess(a, chain);
                    }
                };
                Object.defineProperty(owner, prop, {
                    get: function get() {
                        return base;
                    },
                    set: setter
                });
                return;
            }
            setPropertyAccess(base, prop, {
                set: abort
            });
        };
        _setChainPropAccess(window, property);
        window.onerror = createOnErrorHandler(rid).bind();
    }
    function randomId() {
        return Math.random().toString(36).slice(2, 9);
    }
    function setPropertyAccess(object, property, descriptor) {
        var currentDescriptor = Object.getOwnPropertyDescriptor(object, property);
        if (currentDescriptor && !currentDescriptor.configurable) {
            return false;
        }
        Object.defineProperty(object, property, descriptor);
        return true;
    }
    function getPropertyInChain(base, chain) {
        var pos = chain.indexOf(".");
        if (pos === -1) {
            return {
                base: base,
                prop: chain
            };
        }
        var prop = chain.slice(0, pos);
        if (base === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        var nextBase = base[prop];
        chain = chain.slice(pos + 1);
        if ((base instanceof Object || typeof base === "object") && isEmptyObject(base)) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase !== undefined) {
            return getPropertyInChain(nextBase, chain);
        }
        Object.defineProperty(base, prop, {
            configurable: true
        });
        return {
            base: base,
            prop: prop,
            chain: chain
        };
    }
    function createOnErrorHandler(rid) {
        var nativeOnError = window.onerror;
        return function onError(error) {
            if (typeof error === "string" && error.includes(rid)) {
                return true;
            }
            if (nativeOnError instanceof Function) {
                for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                    args[_key - 1] = arguments[_key];
                }
                return nativeOnError.apply(window, [ error, ...args ]);
            }
            return false;
        };
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function isEmptyObject(obj) {
        return Object.keys(obj).length === 0 && !obj.prototype;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        abortOnPropertyWrite.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function abortOnStackTrace(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function abortOnStackTrace(source, property, stack) {
        if (!property || !stack) {
            return;
        }
        var rid = randomId();
        var abort = function abort() {
            hit(source);
            throw new ReferenceError(rid);
        };
        var _setChainPropAccess = function setChainPropAccess(owner, property) {
            var chainInfo = getPropertyInChain(owner, property);
            var {base: base} = chainInfo;
            var {prop: prop, chain: chain} = chainInfo;
            if (chain) {
                var setter = function setter(a) {
                    base = a;
                    if (a instanceof Object) {
                        _setChainPropAccess(a, chain);
                    }
                };
                Object.defineProperty(owner, prop, {
                    get: function get() {
                        return base;
                    },
                    set: setter
                });
                return;
            }
            if (!stack.match(/^(inlineScript|injectedScript)$/) && !isValidStrPattern(stack)) {
                logMessage(source, `Invalid parameter: ${stack}`);
                return;
            }
            var descriptorWrapper = Object.assign(getDescriptorAddon(), {
                value: base[prop],
                get() {
                    if (!this.isAbortingSuspended && this.isolateCallback(matchStackTrace, stack, (new Error).stack)) {
                        abort();
                    }
                    return this.value;
                },
                set(newValue) {
                    if (!this.isAbortingSuspended && this.isolateCallback(matchStackTrace, stack, (new Error).stack)) {
                        abort();
                    }
                    this.value = newValue;
                }
            });
            setPropertyAccess(base, prop, {
                get() {
                    return descriptorWrapper.get.call(descriptorWrapper);
                },
                set(newValue) {
                    descriptorWrapper.set.call(descriptorWrapper, newValue);
                }
            });
        };
        _setChainPropAccess(window, property);
        window.onerror = createOnErrorHandler(rid).bind();
    }
    function randomId() {
        return Math.random().toString(36).slice(2, 9);
    }
    function setPropertyAccess(object, property, descriptor) {
        var currentDescriptor = Object.getOwnPropertyDescriptor(object, property);
        if (currentDescriptor && !currentDescriptor.configurable) {
            return false;
        }
        Object.defineProperty(object, property, descriptor);
        return true;
    }
    function getPropertyInChain(base, chain) {
        var pos = chain.indexOf(".");
        if (pos === -1) {
            return {
                base: base,
                prop: chain
            };
        }
        var prop = chain.slice(0, pos);
        if (base === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        var nextBase = base[prop];
        chain = chain.slice(pos + 1);
        if ((base instanceof Object || typeof base === "object") && isEmptyObject(base)) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase !== undefined) {
            return getPropertyInChain(nextBase, chain);
        }
        Object.defineProperty(base, prop, {
            configurable: true
        });
        return {
            base: base,
            prop: prop,
            chain: chain
        };
    }
    function createOnErrorHandler(rid) {
        var nativeOnError = window.onerror;
        return function onError(error) {
            if (typeof error === "string" && error.includes(rid)) {
                return true;
            }
            if (nativeOnError instanceof Function) {
                for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                    args[_key - 1] = arguments[_key];
                }
                return nativeOnError.apply(window, [ error, ...args ]);
            }
            return false;
        };
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function isValidStrPattern(input) {
        var FORWARD_SLASH = "/";
        var str = escapeRegExp(input);
        if (input[0] === FORWARD_SLASH && input[input.length - 1] === FORWARD_SLASH) {
            str = input.slice(1, -1);
        }
        var isValid;
        try {
            isValid = new RegExp(str);
            isValid = true;
        } catch (e) {
            isValid = false;
        }
        return isValid;
    }
    function escapeRegExp(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    function matchStackTrace(stackMatch, stackTrace) {
        if (!stackMatch || stackMatch === "") {
            return true;
        }
        var regExpValues = backupRegExpValues();
        if (shouldAbortInlineOrInjectedScript(stackMatch, stackTrace)) {
            if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
                restoreRegExpValues(regExpValues);
            }
            return true;
        }
        var stackRegexp = toRegExp(stackMatch);
        var refinedStackTrace = stackTrace.split("\n").slice(2).map((function(line) {
            return line.trim();
        })).join("\n");
        if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
            restoreRegExpValues(regExpValues);
        }
        return getNativeRegexpTest().call(stackRegexp, refinedStackTrace);
    }
    function getDescriptorAddon() {
        return {
            isAbortingSuspended: false,
            isolateCallback(cb) {
                this.isAbortingSuspended = true;
                try {
                    for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                        args[_key - 1] = arguments[_key];
                    }
                    var result = cb(...args);
                    this.isAbortingSuspended = false;
                    return result;
                } catch (_unused) {
                    var rid = randomId();
                    this.isAbortingSuspended = false;
                    throw new ReferenceError(rid);
                }
            }
        };
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function isEmptyObject(obj) {
        return Object.keys(obj).length === 0 && !obj.prototype;
    }
    function getNativeRegexpTest() {
        var descriptor = Object.getOwnPropertyDescriptor(RegExp.prototype, "test");
        var nativeRegexTest = descriptor === null || descriptor === void 0 ? void 0 : descriptor.value;
        if (descriptor && typeof descriptor.value === "function") {
            return nativeRegexTest;
        }
        throw new Error("RegExp.prototype.test is not a function");
    }
    function shouldAbortInlineOrInjectedScript(stackMatch, stackTrace) {
        var INLINE_SCRIPT_STRING = "inlineScript";
        var INJECTED_SCRIPT_STRING = "injectedScript";
        var INJECTED_SCRIPT_MARKER = "<anonymous>";
        var isInlineScript = function isInlineScript(match) {
            return match.includes(INLINE_SCRIPT_STRING);
        };
        var isInjectedScript = function isInjectedScript(match) {
            return match.includes(INJECTED_SCRIPT_STRING);
        };
        if (!(isInlineScript(stackMatch) || isInjectedScript(stackMatch))) {
            return false;
        }
        var documentURL = window.location.href;
        var pos = documentURL.indexOf("#");
        if (pos !== -1) {
            documentURL = documentURL.slice(0, pos);
        }
        var stackSteps = stackTrace.split("\n").slice(2).map((function(line) {
            return line.trim();
        }));
        var stackLines = stackSteps.map((function(line) {
            var stack;
            var getStackTraceValues = /(.*?@)?(\S+)(:\d+)(:\d+)\)?$/.exec(line);
            if (getStackTraceValues) {
                var _stackURL, _stackURL2;
                var stackURL = getStackTraceValues[2];
                var stackLine = getStackTraceValues[3];
                var stackCol = getStackTraceValues[4];
                if ((_stackURL = stackURL) !== null && _stackURL !== void 0 && _stackURL.startsWith("(")) {
                    stackURL = stackURL.slice(1);
                }
                if ((_stackURL2 = stackURL) !== null && _stackURL2 !== void 0 && _stackURL2.startsWith(INJECTED_SCRIPT_MARKER)) {
                    var _stackFunction;
                    stackURL = INJECTED_SCRIPT_STRING;
                    var stackFunction = getStackTraceValues[1] !== undefined ? getStackTraceValues[1].slice(0, -1) : line.slice(0, getStackTraceValues.index).trim();
                    if ((_stackFunction = stackFunction) !== null && _stackFunction !== void 0 && _stackFunction.startsWith("at")) {
                        stackFunction = stackFunction.slice(2).trim();
                    }
                    stack = `${stackFunction} ${stackURL}${stackLine}${stackCol}`.trim();
                } else if (stackURL === documentURL) {
                    stack = `${INLINE_SCRIPT_STRING}${stackLine}${stackCol}`.trim();
                } else {
                    stack = `${stackURL}${stackLine}${stackCol}`.trim();
                }
            } else {
                stack = line;
            }
            return stack;
        }));
        if (stackLines) {
            for (var index = 0; index < stackLines.length; index += 1) {
                if (isInlineScript(stackMatch) && stackLines[index].startsWith(INLINE_SCRIPT_STRING) && stackLines[index].match(toRegExp(stackMatch))) {
                    return true;
                }
                if (isInjectedScript(stackMatch) && stackLines[index].startsWith(INJECTED_SCRIPT_STRING) && stackLines[index].match(toRegExp(stackMatch))) {
                    return true;
                }
            }
        }
        return false;
    }
    function backupRegExpValues() {
        try {
            var arrayOfRegexpValues = [];
            for (var index = 1; index < 10; index += 1) {
                var value = `$${index}`;
                if (!RegExp[value]) {
                    break;
                }
                arrayOfRegexpValues.push(RegExp[value]);
            }
            return arrayOfRegexpValues;
        } catch (error) {
            return [];
        }
    }
    function restoreRegExpValues(array) {
        if (!array.length) {
            return;
        }
        try {
            var stringPattern = "";
            if (array.length === 1) {
                stringPattern = `(${array[0]})`;
            } else {
                stringPattern = array.reduce((function(accumulator, currentValue, currentIndex) {
                    if (currentIndex === 1) {
                        return `(${accumulator}),(${currentValue})`;
                    }
                    return `${accumulator},(${currentValue})`;
                }));
            }
            var regExpGroup = new RegExp(stringPattern);
            array.toString().replace(regExpGroup, "");
        } catch (error) {
            var message = `Failed to restore RegExp values: ${error}`;
            console.log(message);
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        abortOnStackTrace.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function adjustSetInterval(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function adjustSetInterval(source, matchCallback, matchDelay, boost) {
        var nativeSetInterval = window.setInterval;
        var matchRegexp = toRegExp(matchCallback);
        var intervalWrapper = function intervalWrapper(callback, delay) {
            if (!isValidCallback(callback)) {
                var message = `Scriptlet can't be applied because of invalid callback: '${String(callback)}'`;
                logMessage(source, message);
            } else if (matchRegexp.test(callback.toString()) && isDelayMatched(matchDelay, delay)) {
                delay *= getBoostMultiplier(boost);
                hit(source);
            }
            for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
                args[_key - 2] = arguments[_key];
            }
            return nativeSetInterval.apply(window, [ callback, delay, ...args ]);
        };
        window.setInterval = intervalWrapper;
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function isValidCallback(callback) {
        return callback instanceof Function || typeof callback === "string";
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function getBoostMultiplier(boost) {
        var DEFAULT_MULTIPLIER = .05;
        var MIN_MULTIPLIER = .001;
        var MAX_MULTIPLIER = 50;
        var parsedBoost = parseFloat(boost);
        var boostMultiplier = nativeIsNaN(parsedBoost) || !nativeIsFinite(parsedBoost) ? DEFAULT_MULTIPLIER : parsedBoost;
        if (boostMultiplier < MIN_MULTIPLIER) {
            boostMultiplier = MIN_MULTIPLIER;
        }
        if (boostMultiplier > MAX_MULTIPLIER) {
            boostMultiplier = MAX_MULTIPLIER;
        }
        return boostMultiplier;
    }
    function isDelayMatched(inputDelay, realDelay) {
        return shouldMatchAnyDelay(inputDelay) || realDelay === getMatchDelay(inputDelay);
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function nativeIsNaN(num) {
        var native = Number.isNaN || window.isNaN;
        return native(num);
    }
    function nativeIsFinite(num) {
        var native = Number.isFinite || window.isFinite;
        return native(num);
    }
    function getMatchDelay(delay) {
        var DEFAULT_DELAY = 1e3;
        var parsedDelay = parseInt(delay, 10);
        var delayMatch = nativeIsNaN(parsedDelay) ? DEFAULT_DELAY : parsedDelay;
        return delayMatch;
    }
    function shouldMatchAnyDelay(delay) {
        return delay === "*";
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        adjustSetInterval.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function adjustSetTimeout(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function adjustSetTimeout(source, matchCallback, matchDelay, boost) {
        var nativeSetTimeout = window.setTimeout;
        var matchRegexp = toRegExp(matchCallback);
        var timeoutWrapper = function timeoutWrapper(callback, delay) {
            if (!isValidCallback(callback)) {
                var message = `Scriptlet can't be applied because of invalid callback: '${String(callback)}'`;
                logMessage(source, message);
            } else if (matchRegexp.test(callback.toString()) && isDelayMatched(matchDelay, delay)) {
                delay *= getBoostMultiplier(boost);
                hit(source);
            }
            for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
                args[_key - 2] = arguments[_key];
            }
            return nativeSetTimeout.apply(window, [ callback, delay, ...args ]);
        };
        window.setTimeout = timeoutWrapper;
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function isValidCallback(callback) {
        return callback instanceof Function || typeof callback === "string";
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function getBoostMultiplier(boost) {
        var DEFAULT_MULTIPLIER = .05;
        var MIN_MULTIPLIER = .001;
        var MAX_MULTIPLIER = 50;
        var parsedBoost = parseFloat(boost);
        var boostMultiplier = nativeIsNaN(parsedBoost) || !nativeIsFinite(parsedBoost) ? DEFAULT_MULTIPLIER : parsedBoost;
        if (boostMultiplier < MIN_MULTIPLIER) {
            boostMultiplier = MIN_MULTIPLIER;
        }
        if (boostMultiplier > MAX_MULTIPLIER) {
            boostMultiplier = MAX_MULTIPLIER;
        }
        return boostMultiplier;
    }
    function isDelayMatched(inputDelay, realDelay) {
        return shouldMatchAnyDelay(inputDelay) || realDelay === getMatchDelay(inputDelay);
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function nativeIsNaN(num) {
        var native = Number.isNaN || window.isNaN;
        return native(num);
    }
    function nativeIsFinite(num) {
        var native = Number.isFinite || window.isFinite;
        return native(num);
    }
    function getMatchDelay(delay) {
        var DEFAULT_DELAY = 1e3;
        var parsedDelay = parseInt(delay, 10);
        var delayMatch = nativeIsNaN(parsedDelay) ? DEFAULT_DELAY : parsedDelay;
        return delayMatch;
    }
    function shouldMatchAnyDelay(delay) {
        return delay === "*";
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        adjustSetTimeout.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function callNoThrow(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function callNoThrow(source, functionName) {
        if (!functionName) {
            return;
        }
        var {base: base, prop: prop} = getPropertyInChain(window, functionName);
        if (!base || !prop || typeof base[prop] !== "function") {
            var message = `${functionName} is not a function`;
            logMessage(source, message);
            return;
        }
        var objectWrapper = function objectWrapper() {
            var result;
            try {
                result = Reflect.apply(...arguments);
            } catch (e) {
                var _message = `Error calling ${functionName}: ${e.message}`;
                logMessage(source, _message);
            }
            hit(source);
            return result;
        };
        var objectHandler = {
            apply: objectWrapper
        };
        base[prop] = new Proxy(base[prop], objectHandler);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function getPropertyInChain(base, chain) {
        var pos = chain.indexOf(".");
        if (pos === -1) {
            return {
                base: base,
                prop: chain
            };
        }
        var prop = chain.slice(0, pos);
        if (base === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        var nextBase = base[prop];
        chain = chain.slice(pos + 1);
        if ((base instanceof Object || typeof base === "object") && isEmptyObject(base)) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase !== undefined) {
            return getPropertyInChain(nextBase, chain);
        }
        Object.defineProperty(base, prop, {
            configurable: true
        });
        return {
            base: base,
            prop: prop,
            chain: chain
        };
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function isEmptyObject(obj) {
        return Object.keys(obj).length === 0 && !obj.prototype;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        callNoThrow.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function debugCurrentInlineScript(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function debugCurrentInlineScript(source, property, search) {
        var searchRegexp = toRegExp(search);
        var rid = randomId();
        var getCurrentScript = function getCurrentScript() {
            if ("currentScript" in document) {
                return document.currentScript;
            }
            var scripts = document.getElementsByTagName("script");
            return scripts[scripts.length - 1];
        };
        var ourScript = getCurrentScript();
        var abort = function abort() {
            var scriptEl = getCurrentScript();
            if (!scriptEl) {
                return;
            }
            var content = scriptEl.textContent;
            try {
                var textContentGetter = Object.getOwnPropertyDescriptor(Node.prototype, "textContent").get;
                content = textContentGetter.call(scriptEl);
            } catch (e) {}
            if (scriptEl instanceof HTMLScriptElement && content.length > 0 && scriptEl !== ourScript && searchRegexp.test(content)) {
                hit(source);
                debugger;
            }
        };
        var _setChainPropAccess = function setChainPropAccess(owner, property) {
            var chainInfo = getPropertyInChain(owner, property);
            var {base: base} = chainInfo;
            var {prop: prop, chain: chain} = chainInfo;
            if (base instanceof Object === false && base === null) {
                var props = property.split(".");
                var propIndex = props.indexOf(prop);
                var baseName = props[propIndex - 1];
                var message = `The scriptlet had been executed before the ${baseName} was loaded.`;
                logMessage(message, source.verbose);
                return;
            }
            if (chain) {
                var setter = function setter(a) {
                    base = a;
                    if (a instanceof Object) {
                        _setChainPropAccess(a, chain);
                    }
                };
                Object.defineProperty(owner, prop, {
                    get: function get() {
                        return base;
                    },
                    set: setter
                });
                return;
            }
            var currentValue = base[prop];
            setPropertyAccess(base, prop, {
                set: function set(value) {
                    abort();
                    currentValue = value;
                },
                get: function get() {
                    abort();
                    return currentValue;
                }
            });
        };
        _setChainPropAccess(window, property);
        window.onerror = createOnErrorHandler(rid).bind();
    }
    function randomId() {
        return Math.random().toString(36).slice(2, 9);
    }
    function setPropertyAccess(object, property, descriptor) {
        var currentDescriptor = Object.getOwnPropertyDescriptor(object, property);
        if (currentDescriptor && !currentDescriptor.configurable) {
            return false;
        }
        Object.defineProperty(object, property, descriptor);
        return true;
    }
    function getPropertyInChain(base, chain) {
        var pos = chain.indexOf(".");
        if (pos === -1) {
            return {
                base: base,
                prop: chain
            };
        }
        var prop = chain.slice(0, pos);
        if (base === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        var nextBase = base[prop];
        chain = chain.slice(pos + 1);
        if ((base instanceof Object || typeof base === "object") && isEmptyObject(base)) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase !== undefined) {
            return getPropertyInChain(nextBase, chain);
        }
        Object.defineProperty(base, prop, {
            configurable: true
        });
        return {
            base: base,
            prop: prop,
            chain: chain
        };
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function createOnErrorHandler(rid) {
        var nativeOnError = window.onerror;
        return function onError(error) {
            if (typeof error === "string" && error.includes(rid)) {
                return true;
            }
            if (nativeOnError instanceof Function) {
                for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                    args[_key - 1] = arguments[_key];
                }
                return nativeOnError.apply(window, [ error, ...args ]);
            }
            return false;
        };
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function isEmptyObject(obj) {
        return Object.keys(obj).length === 0 && !obj.prototype;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        debugCurrentInlineScript.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function debugOnPropertyRead(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function debugOnPropertyRead(source, property) {
        if (!property) {
            return;
        }
        var rid = randomId();
        var abort = function abort() {
            hit(source);
            debugger;
        };
        var _setChainPropAccess = function setChainPropAccess(owner, property) {
            var chainInfo = getPropertyInChain(owner, property);
            var {base: base} = chainInfo;
            var {prop: prop, chain: chain} = chainInfo;
            if (chain) {
                var setter = function setter(a) {
                    base = a;
                    if (a instanceof Object) {
                        _setChainPropAccess(a, chain);
                    }
                };
                Object.defineProperty(owner, prop, {
                    get: function get() {
                        return base;
                    },
                    set: setter
                });
                return;
            }
            setPropertyAccess(base, prop, {
                get: abort,
                set: noopFunc
            });
        };
        _setChainPropAccess(window, property);
        window.onerror = createOnErrorHandler(rid).bind();
    }
    function randomId() {
        return Math.random().toString(36).slice(2, 9);
    }
    function setPropertyAccess(object, property, descriptor) {
        var currentDescriptor = Object.getOwnPropertyDescriptor(object, property);
        if (currentDescriptor && !currentDescriptor.configurable) {
            return false;
        }
        Object.defineProperty(object, property, descriptor);
        return true;
    }
    function getPropertyInChain(base, chain) {
        var pos = chain.indexOf(".");
        if (pos === -1) {
            return {
                base: base,
                prop: chain
            };
        }
        var prop = chain.slice(0, pos);
        if (base === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        var nextBase = base[prop];
        chain = chain.slice(pos + 1);
        if ((base instanceof Object || typeof base === "object") && isEmptyObject(base)) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase !== undefined) {
            return getPropertyInChain(nextBase, chain);
        }
        Object.defineProperty(base, prop, {
            configurable: true
        });
        return {
            base: base,
            prop: prop,
            chain: chain
        };
    }
    function createOnErrorHandler(rid) {
        var nativeOnError = window.onerror;
        return function onError(error) {
            if (typeof error === "string" && error.includes(rid)) {
                return true;
            }
            if (nativeOnError instanceof Function) {
                for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                    args[_key - 1] = arguments[_key];
                }
                return nativeOnError.apply(window, [ error, ...args ]);
            }
            return false;
        };
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopFunc() {}
    function isEmptyObject(obj) {
        return Object.keys(obj).length === 0 && !obj.prototype;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        debugOnPropertyRead.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function debugOnPropertyWrite(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function debugOnPropertyWrite(source, property) {
        if (!property) {
            return;
        }
        var rid = randomId();
        var abort = function abort() {
            hit(source);
            debugger;
        };
        var _setChainPropAccess = function setChainPropAccess(owner, property) {
            var chainInfo = getPropertyInChain(owner, property);
            var {base: base} = chainInfo;
            var {prop: prop, chain: chain} = chainInfo;
            if (chain) {
                var setter = function setter(a) {
                    base = a;
                    if (a instanceof Object) {
                        _setChainPropAccess(a, chain);
                    }
                };
                Object.defineProperty(owner, prop, {
                    get: function get() {
                        return base;
                    },
                    set: setter
                });
                return;
            }
            setPropertyAccess(base, prop, {
                set: abort
            });
        };
        _setChainPropAccess(window, property);
        window.onerror = createOnErrorHandler(rid).bind();
    }
    function randomId() {
        return Math.random().toString(36).slice(2, 9);
    }
    function setPropertyAccess(object, property, descriptor) {
        var currentDescriptor = Object.getOwnPropertyDescriptor(object, property);
        if (currentDescriptor && !currentDescriptor.configurable) {
            return false;
        }
        Object.defineProperty(object, property, descriptor);
        return true;
    }
    function getPropertyInChain(base, chain) {
        var pos = chain.indexOf(".");
        if (pos === -1) {
            return {
                base: base,
                prop: chain
            };
        }
        var prop = chain.slice(0, pos);
        if (base === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        var nextBase = base[prop];
        chain = chain.slice(pos + 1);
        if ((base instanceof Object || typeof base === "object") && isEmptyObject(base)) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase !== undefined) {
            return getPropertyInChain(nextBase, chain);
        }
        Object.defineProperty(base, prop, {
            configurable: true
        });
        return {
            base: base,
            prop: prop,
            chain: chain
        };
    }
    function createOnErrorHandler(rid) {
        var nativeOnError = window.onerror;
        return function onError(error) {
            if (typeof error === "string" && error.includes(rid)) {
                return true;
            }
            if (nativeOnError instanceof Function) {
                for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                    args[_key - 1] = arguments[_key];
                }
                return nativeOnError.apply(window, [ error, ...args ]);
            }
            return false;
        };
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function isEmptyObject(obj) {
        return Object.keys(obj).length === 0 && !obj.prototype;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        debugOnPropertyWrite.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function dirString(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function dirString(source, times) {
        var {dir: dir} = console;
        function dirWrapper(object) {
            if (typeof dir === "function") {
                dir.call(this, object);
            }
            hit(source);
        }
        console.dir = dirWrapper;
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        dirString.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function disableNewtabLinks(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function disableNewtabLinks(source) {
        document.addEventListener("click", (function(ev) {
            var {target: target} = ev;
            while (target !== null) {
                if (target.localName === "a" && target.hasAttribute("target")) {
                    ev.stopPropagation();
                    ev.preventDefault();
                    hit(source);
                    break;
                }
                target = target.parentNode;
            }
        }));
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        disableNewtabLinks.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function evalDataPrune(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function evalDataPrune(source, propsToRemove, requiredInitialProps, stack) {
        var prunePaths = getPrunePath(propsToRemove);
        var requiredPaths = getPrunePath(requiredInitialProps);
        var nativeObjects = {
            nativeStringify: window.JSON.stringify
        };
        var evalWrapper = function evalWrapper(target, thisArg, args) {
            var data = Reflect.apply(target, thisArg, args);
            if (typeof data === "object") {
                data = jsonPruner(source, data, prunePaths, requiredPaths, stack, nativeObjects);
            }
            return data;
        };
        var evalHandler = {
            apply: evalWrapper
        };
        window.eval = new Proxy(window.eval, evalHandler);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function matchStackTrace(stackMatch, stackTrace) {
        if (!stackMatch || stackMatch === "") {
            return true;
        }
        var regExpValues = backupRegExpValues();
        if (shouldAbortInlineOrInjectedScript(stackMatch, stackTrace)) {
            if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
                restoreRegExpValues(regExpValues);
            }
            return true;
        }
        var stackRegexp = toRegExp(stackMatch);
        var refinedStackTrace = stackTrace.split("\n").slice(2).map((function(line) {
            return line.trim();
        })).join("\n");
        if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
            restoreRegExpValues(regExpValues);
        }
        return getNativeRegexpTest().call(stackRegexp, refinedStackTrace);
    }
    function getWildcardPropertyInChain(base, chain) {
        var lookThrough = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var output = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
        var valueToCheck = arguments.length > 4 ? arguments[4] : undefined;
        var pos = chain.indexOf(".");
        if (pos === -1) {
            if (chain === "*" || chain === "[]") {
                for (var key in base) {
                    if (Object.prototype.hasOwnProperty.call(base, key)) {
                        if (valueToCheck !== undefined) {
                            var objectValue = base[key];
                            if (typeof objectValue === "string" && valueToCheck instanceof RegExp) {
                                if (valueToCheck.test(objectValue)) {
                                    output.push({
                                        base: base,
                                        prop: key
                                    });
                                }
                            } else if (objectValue === valueToCheck) {
                                output.push({
                                    base: base,
                                    prop: key
                                });
                            }
                        } else {
                            output.push({
                                base: base,
                                prop: key
                            });
                        }
                    }
                }
            } else if (valueToCheck !== undefined) {
                var _objectValue = base[chain];
                if (typeof _objectValue === "string" && valueToCheck instanceof RegExp) {
                    if (valueToCheck.test(_objectValue)) {
                        output.push({
                            base: base,
                            prop: chain
                        });
                    }
                } else if (base[chain] === valueToCheck) {
                    output.push({
                        base: base,
                        prop: chain
                    });
                }
            } else {
                output.push({
                    base: base,
                    prop: chain
                });
            }
            return output;
        }
        var prop = chain.slice(0, pos);
        var shouldLookThrough = prop === "[]" && Array.isArray(base) || prop === "*" && base instanceof Object || prop === "[-]" && Array.isArray(base) || prop === "{-}" && base instanceof Object;
        if (shouldLookThrough) {
            var nextProp = chain.slice(pos + 1);
            var baseKeys = Object.keys(base);
            if (prop === "{-}" || prop === "[-]") {
                var type = Array.isArray(base) ? "array" : "object";
                var shouldRemove = !!(prop === "{-}" && type === "object") || !!(prop === "[-]" && type === "array");
                if (!shouldRemove) {
                    return output;
                }
                baseKeys.forEach((function(key) {
                    var item = base[key];
                    if (isKeyInObject(item, nextProp, valueToCheck)) {
                        output.push({
                            base: base,
                            prop: key
                        });
                    }
                }));
                return output;
            }
            baseKeys.forEach((function(key) {
                var item = base[key];
                getWildcardPropertyInChain(item, nextProp, lookThrough, output, valueToCheck);
            }));
        }
        if (Array.isArray(base)) {
            base.forEach((function(key) {
                var nextBase = key;
                if (nextBase !== undefined) {
                    getWildcardPropertyInChain(nextBase, chain, lookThrough, output, valueToCheck);
                }
            }));
        }
        var nextBase = base[prop];
        chain = chain.slice(pos + 1);
        if (nextBase !== undefined) {
            getWildcardPropertyInChain(nextBase, chain, lookThrough, output, valueToCheck);
        }
        return output;
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function isPruningNeeded(source, root, prunePaths, requiredPaths, stack, nativeObjects) {
        if (!root) {
            return false;
        }
        var {nativeStringify: nativeStringify} = nativeObjects;
        var shouldProcess;
        var prunePathsToCheck = prunePaths.map((function(obj) {
            return obj.path;
        }));
        var requiredPathsToCheck = requiredPaths.map((function(obj) {
            return obj.path;
        }));
        if (prunePathsToCheck.length === 0 && requiredPathsToCheck.length > 0) {
            var rootString = nativeStringify(root);
            var matchRegex = toRegExp(requiredPathsToCheck.join(""));
            var shouldLog = matchRegex.test(rootString);
            if (shouldLog) {
                logMessage(source, `${window.location.hostname}\n${nativeStringify(root, null, 2)}\nStack trace:\n${(new Error).stack}`, true);
                if (root && typeof root === "object") {
                    logMessage(source, root, true, false);
                }
                shouldProcess = false;
                return shouldProcess;
            }
        }
        if (stack && !matchStackTrace(stack, (new Error).stack || "")) {
            shouldProcess = false;
            return shouldProcess;
        }
        var wildcardSymbols = [ ".*.", "*.", ".*", ".[].", "[].", ".[]" ];
        var _loop = function _loop() {
            var requiredPath = requiredPathsToCheck[i];
            var lastNestedPropName = requiredPath.split(".").pop();
            var hasWildcard = wildcardSymbols.some((function(symbol) {
                return requiredPath.includes(symbol);
            }));
            var details = getWildcardPropertyInChain(root, requiredPath, hasWildcard);
            if (!details.length) {
                shouldProcess = false;
                return {
                    v: shouldProcess
                };
            }
            shouldProcess = !hasWildcard;
            for (var j = 0; j < details.length; j += 1) {
                var hasRequiredProp = typeof lastNestedPropName === "string" && details[j].base[lastNestedPropName] !== undefined;
                if (hasWildcard) {
                    shouldProcess = hasRequiredProp || shouldProcess;
                } else {
                    shouldProcess = hasRequiredProp && shouldProcess;
                }
            }
        }, _ret;
        for (var i = 0; i < requiredPathsToCheck.length; i += 1) {
            _ret = _loop();
            if (_ret) return _ret.v;
        }
        return shouldProcess;
    }
    function jsonPruner(source, root, prunePaths, requiredPaths, stack, nativeObjects) {
        var {nativeStringify: nativeStringify} = nativeObjects;
        if (prunePaths.length === 0 && requiredPaths.length === 0) {
            logMessage(source, `${window.location.hostname}\n${nativeStringify(root, null, 2)}\nStack trace:\n${(new Error).stack}`, true);
            if (root && typeof root === "object") {
                logMessage(source, root, true, false);
            }
            return root;
        }
        try {
            if (isPruningNeeded(source, root, prunePaths, requiredPaths, stack, nativeObjects) === false) {
                return root;
            }
            prunePaths.forEach((function(path) {
                var pathToCheck = path.path;
                var valueToCheck = path.value;
                var ownerObjArr = getWildcardPropertyInChain(root, pathToCheck, true, [], valueToCheck);
                for (var i = ownerObjArr.length - 1; i >= 0; i -= 1) {
                    var ownerObj = ownerObjArr[i];
                    if (ownerObj === undefined || !ownerObj.base) {
                        continue;
                    }
                    hit(source);
                    if (!Array.isArray(ownerObj.base)) {
                        delete ownerObj.base[ownerObj.prop];
                        continue;
                    }
                    try {
                        var index = Number(ownerObj.prop);
                        if (Number.isNaN(index)) {
                            continue;
                        }
                        ownerObj.base.splice(index, 1);
                    } catch (error) {
                        console.error("Error while deleting array element", error);
                    }
                }
            }));
        } catch (e) {
            logMessage(source, e);
        }
        return root;
    }
    function getPrunePath(props) {
        var VALUE_MARKER = ".[=].";
        var REGEXP_START_MARKER = "/";
        var validPropsString = typeof props === "string" && props !== undefined && props !== "";
        if (validPropsString) {
            var splitRegexp = /(?<!\.\[=\]\.\/(?:[^/]|\\.)*)\s+/;
            var parts = props.split(splitRegexp).map((function(part) {
                var splitPart = part.split(VALUE_MARKER);
                var path = splitPart[0];
                var value = splitPart[1];
                if (value !== undefined) {
                    if (value === "true") {
                        value = true;
                    } else if (value === "false") {
                        value = false;
                    } else if (value.startsWith(REGEXP_START_MARKER)) {
                        value = toRegExp(value);
                    } else if (typeof value === "string" && /^\d+$/.test(value)) {
                        value = parseFloat(value);
                    }
                    return {
                        path: path,
                        value: value
                    };
                }
                return {
                    path: path
                };
            }));
            return parts;
        }
        return [];
    }
    function getNativeRegexpTest() {
        var descriptor = Object.getOwnPropertyDescriptor(RegExp.prototype, "test");
        var nativeRegexTest = descriptor === null || descriptor === void 0 ? void 0 : descriptor.value;
        if (descriptor && typeof descriptor.value === "function") {
            return nativeRegexTest;
        }
        throw new Error("RegExp.prototype.test is not a function");
    }
    function shouldAbortInlineOrInjectedScript(stackMatch, stackTrace) {
        var INLINE_SCRIPT_STRING = "inlineScript";
        var INJECTED_SCRIPT_STRING = "injectedScript";
        var INJECTED_SCRIPT_MARKER = "<anonymous>";
        var isInlineScript = function isInlineScript(match) {
            return match.includes(INLINE_SCRIPT_STRING);
        };
        var isInjectedScript = function isInjectedScript(match) {
            return match.includes(INJECTED_SCRIPT_STRING);
        };
        if (!(isInlineScript(stackMatch) || isInjectedScript(stackMatch))) {
            return false;
        }
        var documentURL = window.location.href;
        var pos = documentURL.indexOf("#");
        if (pos !== -1) {
            documentURL = documentURL.slice(0, pos);
        }
        var stackSteps = stackTrace.split("\n").slice(2).map((function(line) {
            return line.trim();
        }));
        var stackLines = stackSteps.map((function(line) {
            var stack;
            var getStackTraceValues = /(.*?@)?(\S+)(:\d+)(:\d+)\)?$/.exec(line);
            if (getStackTraceValues) {
                var _stackURL, _stackURL2;
                var stackURL = getStackTraceValues[2];
                var stackLine = getStackTraceValues[3];
                var stackCol = getStackTraceValues[4];
                if ((_stackURL = stackURL) !== null && _stackURL !== void 0 && _stackURL.startsWith("(")) {
                    stackURL = stackURL.slice(1);
                }
                if ((_stackURL2 = stackURL) !== null && _stackURL2 !== void 0 && _stackURL2.startsWith(INJECTED_SCRIPT_MARKER)) {
                    var _stackFunction;
                    stackURL = INJECTED_SCRIPT_STRING;
                    var stackFunction = getStackTraceValues[1] !== undefined ? getStackTraceValues[1].slice(0, -1) : line.slice(0, getStackTraceValues.index).trim();
                    if ((_stackFunction = stackFunction) !== null && _stackFunction !== void 0 && _stackFunction.startsWith("at")) {
                        stackFunction = stackFunction.slice(2).trim();
                    }
                    stack = `${stackFunction} ${stackURL}${stackLine}${stackCol}`.trim();
                } else if (stackURL === documentURL) {
                    stack = `${INLINE_SCRIPT_STRING}${stackLine}${stackCol}`.trim();
                } else {
                    stack = `${stackURL}${stackLine}${stackCol}`.trim();
                }
            } else {
                stack = line;
            }
            return stack;
        }));
        if (stackLines) {
            for (var index = 0; index < stackLines.length; index += 1) {
                if (isInlineScript(stackMatch) && stackLines[index].startsWith(INLINE_SCRIPT_STRING) && stackLines[index].match(toRegExp(stackMatch))) {
                    return true;
                }
                if (isInjectedScript(stackMatch) && stackLines[index].startsWith(INJECTED_SCRIPT_STRING) && stackLines[index].match(toRegExp(stackMatch))) {
                    return true;
                }
            }
        }
        return false;
    }
    function backupRegExpValues() {
        try {
            var arrayOfRegexpValues = [];
            for (var index = 1; index < 10; index += 1) {
                var value = `$${index}`;
                if (!RegExp[value]) {
                    break;
                }
                arrayOfRegexpValues.push(RegExp[value]);
            }
            return arrayOfRegexpValues;
        } catch (error) {
            return [];
        }
    }
    function restoreRegExpValues(array) {
        if (!array.length) {
            return;
        }
        try {
            var stringPattern = "";
            if (array.length === 1) {
                stringPattern = `(${array[0]})`;
            } else {
                stringPattern = array.reduce((function(accumulator, currentValue, currentIndex) {
                    if (currentIndex === 1) {
                        return `(${accumulator}),(${currentValue})`;
                    }
                    return `${accumulator},(${currentValue})`;
                }));
            }
            var regExpGroup = new RegExp(stringPattern);
            array.toString().replace(regExpGroup, "");
        } catch (error) {
            var message = `Failed to restore RegExp values: ${error}`;
            console.log(message);
        }
    }
    function isKeyInObject(baseObj, path, valueToCheck) {
        var parts = path.split(".");
        var _check = function check(targetObject, pathSegments) {
            if (pathSegments.length === 0) {
                if (valueToCheck !== undefined) {
                    if (typeof targetObject === "string" && valueToCheck instanceof RegExp) {
                        return valueToCheck.test(targetObject);
                    }
                    return targetObject === valueToCheck;
                }
                return true;
            }
            var current = pathSegments[0];
            var rest = pathSegments.slice(1);
            if (current === "*" || current === "[]") {
                if (Array.isArray(targetObject)) {
                    return targetObject.some((function(item) {
                        return _check(item, rest);
                    }));
                }
                if (typeof targetObject === "object" && targetObject !== null) {
                    return Object.keys(targetObject).some((function(key) {
                        return _check(targetObject[key], rest);
                    }));
                }
            }
            if (Object.prototype.hasOwnProperty.call(targetObject, current)) {
                return _check(targetObject[current], rest);
            }
            return false;
        };
        return _check(baseObj, parts);
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        evalDataPrune.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function forceWindowClose(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function forceWindowClose(source) {
        var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
        if (typeof window.close !== "function") {
            var message = "window.close() is not a function so 'close-window' scriptlet is unavailable";
            logMessage(source, message);
            return;
        }
        var closeImmediately = function closeImmediately() {
            try {
                hit(source);
                window.close();
            } catch (e) {
                logMessage(source, e);
            }
        };
        var closeByExtension = function closeByExtension() {
            var extCall = function extCall() {
                dispatchEvent(new Event("adguard:scriptlet-close-window"));
            };
            window.addEventListener("adguard:subscribed-to-close-window", extCall, {
                once: true
            });
            setTimeout((function() {
                window.removeEventListener("adguard:subscribed-to-close-window", extCall, {
                    once: true
                });
            }), 5e3);
        };
        var shouldClose = function shouldClose() {
            if (path === "") {
                return true;
            }
            var pathRegexp = toRegExp(path);
            var currentPath = `${window.location.pathname}${window.location.search}`;
            return pathRegexp.test(currentPath);
        };
        if (shouldClose()) {
            closeImmediately();
            if (navigator.userAgent.includes("Chrome")) {
                closeByExtension();
            }
        }
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        forceWindowClose.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function hideInShadowDom(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function hideInShadowDom(source, selector, baseSelector) {
        if (!Element.prototype.attachShadow) {
            return;
        }
        var hideElement = function hideElement(targetElement) {
            var DISPLAY_NONE_CSS = "display:none!important;";
            targetElement.style.cssText = DISPLAY_NONE_CSS;
        };
        var hideHandler = function hideHandler() {
            var hostElements = !baseSelector ? findHostElements(document.documentElement) : document.querySelectorAll(baseSelector);
            var _loop = function _loop() {
                var isHidden = false;
                var {targets: targets, innerHosts: innerHosts} = pierceShadowDom(selector, hostElements);
                targets.forEach((function(targetEl) {
                    hideElement(targetEl);
                    isHidden = true;
                }));
                if (isHidden) {
                    hit(source);
                }
                hostElements = innerHosts;
            };
            while (hostElements.length !== 0) {
                _loop();
            }
        };
        hideHandler();
        observeDOMChanges(hideHandler, true);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function observeDOMChanges(callback) {
        var observeAttrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
        var attrsToObserve = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
        var THROTTLE_DELAY_MS = 20;
        var observer = new MutationObserver(throttle(callbackWrapper, THROTTLE_DELAY_MS));
        var connect = function connect() {
            if (attrsToObserve.length > 0) {
                observer.observe(document.documentElement, {
                    childList: true,
                    subtree: true,
                    attributes: observeAttrs,
                    attributeFilter: attrsToObserve
                });
            } else {
                observer.observe(document.documentElement, {
                    childList: true,
                    subtree: true,
                    attributes: observeAttrs
                });
            }
        };
        var disconnect = function disconnect() {
            observer.disconnect();
        };
        function callbackWrapper() {
            disconnect();
            callback();
            connect();
        }
        connect();
    }
    function findHostElements(rootElement) {
        var hosts = [];
        if (rootElement) {
            var domElems = rootElement.querySelectorAll("*");
            domElems.forEach((function(el) {
                if (el.shadowRoot) {
                    hosts.push(el);
                }
            }));
        }
        return hosts;
    }
    function pierceShadowDom(selector, hostElements) {
        var targets = [];
        var innerHostsAcc = [];
        hostElements.forEach((function(host) {
            var simpleElems = host.querySelectorAll(selector);
            targets = targets.concat([].slice.call(simpleElems));
            var shadowRootElem = host.shadowRoot;
            var shadowChildren = shadowRootElem.querySelectorAll(selector);
            targets = targets.concat([].slice.call(shadowChildren));
            innerHostsAcc.push(findHostElements(shadowRootElem));
        }));
        var innerHosts = flatten(innerHostsAcc);
        return {
            targets: targets,
            innerHosts: innerHosts
        };
    }
    function flatten(input) {
        var stack = [];
        input.forEach((function(el) {
            return stack.push(el);
        }));
        var res = [];
        while (stack.length) {
            var next = stack.pop();
            if (Array.isArray(next)) {
                next.forEach((function(el) {
                    return stack.push(el);
                }));
            } else {
                res.push(next);
            }
        }
        return res.reverse();
    }
    function throttle(cb, delay) {
        var wait = false;
        var savedArgs;
        var _wrapper = function wrapper() {
            for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                args[_key] = arguments[_key];
            }
            if (wait) {
                savedArgs = args;
                return;
            }
            cb(...args);
            wait = true;
            setTimeout((function() {
                wait = false;
                if (savedArgs) {
                    _wrapper(...savedArgs);
                    savedArgs = null;
                }
            }), delay);
        };
        return _wrapper;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        hideInShadowDom.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function hrefSanitizer(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function hrefSanitizer(source, selector) {
        var attribute = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "text";
        var transform = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "";
        if (!selector) {
            logMessage(source, "Selector is required.");
            return;
        }
        var BASE64_DECODE_TRANSFORM_MARKER = "base64decode";
        var REMOVE_HASH_TRANSFORM_MARKER = "removeHash";
        var REMOVE_PARAM_TRANSFORM_MARKER = "removeParam";
        var MARKER_SEPARATOR = ":";
        var COMMA = ",";
        var regexpNotValidAtStart = /^[^!-~\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CD\uA7D0\uA7D1\uA7D3\uA7D5-\uA7DC\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{10300}-\u{1031F}\u{1032D}-\u{10340}\u{10342}-\u{10349}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{103A0}-\u{103C3}\u{103C8}-\u{103CF}\u{10400}-\u{1049D}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{10570}-\u{1057A}\u{1057C}-\u{1058A}\u{1058C}-\u{10592}\u{10594}\u{10595}\u{10597}-\u{105A1}\u{105A3}-\u{105B1}\u{105B3}-\u{105B9}\u{105BB}\u{105BC}\u{105C0}-\u{105F3}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{10780}-\u{10785}\u{10787}-\u{107B0}\u{107B2}-\u{107BA}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10860}-\u{10876}\u{10880}-\u{1089E}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{10900}-\u{10915}\u{10920}-\u{10939}\u{10980}-\u{109B7}\u{109BE}\u{109BF}\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A60}-\u{10A7C}\u{10A80}-\u{10A9C}\u{10AC0}-\u{10AC7}\u{10AC9}-\u{10AE4}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B60}-\u{10B72}\u{10B80}-\u{10B91}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10D00}-\u{10D23}\u{10D4A}-\u{10D65}\u{10D6F}-\u{10D85}\u{10E80}-\u{10EA9}\u{10EB0}\u{10EB1}\u{10EC2}-\u{10EC4}\u{10F00}-\u{10F1C}\u{10F27}\u{10F30}-\u{10F45}\u{10F70}-\u{10F81}\u{10FB0}-\u{10FC4}\u{10FE0}-\u{10FF6}\u{11003}-\u{11037}\u{11071}\u{11072}\u{11075}\u{11083}-\u{110AF}\u{110D0}-\u{110E8}\u{11103}-\u{11126}\u{11144}\u{11147}\u{11150}-\u{11172}\u{11176}\u{11183}-\u{111B2}\u{111C1}-\u{111C4}\u{111DA}\u{111DC}\u{11200}-\u{11211}\u{11213}-\u{1122B}\u{1123F}\u{11240}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A8}\u{112B0}-\u{112DE}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}\u{11350}\u{1135D}-\u{11361}\u{11380}-\u{11389}\u{1138B}\u{1138E}\u{11390}-\u{113B5}\u{113B7}\u{113D1}\u{113D3}\u{11400}-\u{11434}\u{11447}-\u{1144A}\u{1145F}-\u{11461}\u{11480}-\u{114AF}\u{114C4}\u{114C5}\u{114C7}\u{11580}-\u{115AE}\u{115D8}-\u{115DB}\u{11600}-\u{1162F}\u{11644}\u{11680}-\u{116AA}\u{116B8}\u{11700}-\u{1171A}\u{11740}-\u{11746}\u{11800}-\u{1182B}\u{118A0}-\u{118DF}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{1192F}\u{1193F}\u{11941}\u{119A0}-\u{119A7}\u{119AA}-\u{119D0}\u{119E1}\u{119E3}\u{11A00}\u{11A0B}-\u{11A32}\u{11A3A}\u{11A50}\u{11A5C}-\u{11A89}\u{11A9D}\u{11AB0}-\u{11AF8}\u{11BC0}-\u{11BE0}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2E}\u{11C40}\u{11C72}-\u{11C8F}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D89}\u{11D98}\u{11EE0}-\u{11EF2}\u{11F02}\u{11F04}-\u{11F10}\u{11F12}-\u{11F33}\u{11FB0}\u{12000}-\u{12399}\u{12480}-\u{12543}\u{12F90}-\u{12FF0}\u{13000}-\u{1342F}\u{13441}-\u{13446}\u{13460}-\u{143FA}\u{14400}-\u{14646}\u{16100}-\u{1611D}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A70}-\u{16ABE}\u{16AD0}-\u{16AED}\u{16B00}-\u{16B2F}\u{16B40}-\u{16B43}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16D40}-\u{16D6C}\u{16E40}-\u{16E7F}\u{16F00}-\u{16F4A}\u{16F50}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{16FE3}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18CFF}-\u{18D08}\u{1AFF0}-\u{1AFF3}\u{1AFF5}-\u{1AFFB}\u{1AFFD}\u{1AFFE}\u{1B000}-\u{1B122}\u{1B132}\u{1B150}-\u{1B152}\u{1B155}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6C0}\u{1D6C2}-\u{1D6DA}\u{1D6DC}-\u{1D6FA}\u{1D6FC}-\u{1D714}\u{1D716}-\u{1D734}\u{1D736}-\u{1D74E}\u{1D750}-\u{1D76E}\u{1D770}-\u{1D788}\u{1D78A}-\u{1D7A8}\u{1D7AA}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1DF00}-\u{1DF1E}\u{1DF25}-\u{1DF2A}\u{1E030}-\u{1E06D}\u{1E100}-\u{1E12C}\u{1E137}-\u{1E13D}\u{1E14E}\u{1E290}-\u{1E2AD}\u{1E2C0}-\u{1E2EB}\u{1E4D0}-\u{1E4EB}\u{1E5D0}-\u{1E5ED}\u{1E5F0}\u{1E7E0}-\u{1E7E6}\u{1E7E8}-\u{1E7EB}\u{1E7ED}\u{1E7EE}\u{1E7F0}-\u{1E7FE}\u{1E800}-\u{1E8C4}\u{1E900}-\u{1E943}\u{1E94B}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}\u{20000}-\u{2A6DF}\u{2A700}-\u{2B739}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2EBF0}-\u{2EE5D}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{31350}-\u{323AF}]+/u;
        var regexpNotValidAtEnd = /[^!-~\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CD\uA7D0\uA7D1\uA7D3\uA7D5-\uA7DC\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{10300}-\u{1031F}\u{1032D}-\u{10340}\u{10342}-\u{10349}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{103A0}-\u{103C3}\u{103C8}-\u{103CF}\u{10400}-\u{1049D}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{10570}-\u{1057A}\u{1057C}-\u{1058A}\u{1058C}-\u{10592}\u{10594}\u{10595}\u{10597}-\u{105A1}\u{105A3}-\u{105B1}\u{105B3}-\u{105B9}\u{105BB}\u{105BC}\u{105C0}-\u{105F3}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{10780}-\u{10785}\u{10787}-\u{107B0}\u{107B2}-\u{107BA}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10860}-\u{10876}\u{10880}-\u{1089E}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{10900}-\u{10915}\u{10920}-\u{10939}\u{10980}-\u{109B7}\u{109BE}\u{109BF}\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A60}-\u{10A7C}\u{10A80}-\u{10A9C}\u{10AC0}-\u{10AC7}\u{10AC9}-\u{10AE4}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B60}-\u{10B72}\u{10B80}-\u{10B91}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10D00}-\u{10D23}\u{10D4A}-\u{10D65}\u{10D6F}-\u{10D85}\u{10E80}-\u{10EA9}\u{10EB0}\u{10EB1}\u{10EC2}-\u{10EC4}\u{10F00}-\u{10F1C}\u{10F27}\u{10F30}-\u{10F45}\u{10F70}-\u{10F81}\u{10FB0}-\u{10FC4}\u{10FE0}-\u{10FF6}\u{11003}-\u{11037}\u{11071}\u{11072}\u{11075}\u{11083}-\u{110AF}\u{110D0}-\u{110E8}\u{11103}-\u{11126}\u{11144}\u{11147}\u{11150}-\u{11172}\u{11176}\u{11183}-\u{111B2}\u{111C1}-\u{111C4}\u{111DA}\u{111DC}\u{11200}-\u{11211}\u{11213}-\u{1122B}\u{1123F}\u{11240}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A8}\u{112B0}-\u{112DE}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}\u{11350}\u{1135D}-\u{11361}\u{11380}-\u{11389}\u{1138B}\u{1138E}\u{11390}-\u{113B5}\u{113B7}\u{113D1}\u{113D3}\u{11400}-\u{11434}\u{11447}-\u{1144A}\u{1145F}-\u{11461}\u{11480}-\u{114AF}\u{114C4}\u{114C5}\u{114C7}\u{11580}-\u{115AE}\u{115D8}-\u{115DB}\u{11600}-\u{1162F}\u{11644}\u{11680}-\u{116AA}\u{116B8}\u{11700}-\u{1171A}\u{11740}-\u{11746}\u{11800}-\u{1182B}\u{118A0}-\u{118DF}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{1192F}\u{1193F}\u{11941}\u{119A0}-\u{119A7}\u{119AA}-\u{119D0}\u{119E1}\u{119E3}\u{11A00}\u{11A0B}-\u{11A32}\u{11A3A}\u{11A50}\u{11A5C}-\u{11A89}\u{11A9D}\u{11AB0}-\u{11AF8}\u{11BC0}-\u{11BE0}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2E}\u{11C40}\u{11C72}-\u{11C8F}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D89}\u{11D98}\u{11EE0}-\u{11EF2}\u{11F02}\u{11F04}-\u{11F10}\u{11F12}-\u{11F33}\u{11FB0}\u{12000}-\u{12399}\u{12480}-\u{12543}\u{12F90}-\u{12FF0}\u{13000}-\u{1342F}\u{13441}-\u{13446}\u{13460}-\u{143FA}\u{14400}-\u{14646}\u{16100}-\u{1611D}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A70}-\u{16ABE}\u{16AD0}-\u{16AED}\u{16B00}-\u{16B2F}\u{16B40}-\u{16B43}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16D40}-\u{16D6C}\u{16E40}-\u{16E7F}\u{16F00}-\u{16F4A}\u{16F50}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{16FE3}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18CFF}-\u{18D08}\u{1AFF0}-\u{1AFF3}\u{1AFF5}-\u{1AFFB}\u{1AFFD}\u{1AFFE}\u{1B000}-\u{1B122}\u{1B132}\u{1B150}-\u{1B152}\u{1B155}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6C0}\u{1D6C2}-\u{1D6DA}\u{1D6DC}-\u{1D6FA}\u{1D6FC}-\u{1D714}\u{1D716}-\u{1D734}\u{1D736}-\u{1D74E}\u{1D750}-\u{1D76E}\u{1D770}-\u{1D788}\u{1D78A}-\u{1D7A8}\u{1D7AA}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1DF00}-\u{1DF1E}\u{1DF25}-\u{1DF2A}\u{1E030}-\u{1E06D}\u{1E100}-\u{1E12C}\u{1E137}-\u{1E13D}\u{1E14E}\u{1E290}-\u{1E2AD}\u{1E2C0}-\u{1E2EB}\u{1E4D0}-\u{1E4EB}\u{1E5D0}-\u{1E5ED}\u{1E5F0}\u{1E7E0}-\u{1E7E6}\u{1E7E8}-\u{1E7EB}\u{1E7ED}\u{1E7EE}\u{1E7F0}-\u{1E7FE}\u{1E800}-\u{1E8C4}\u{1E900}-\u{1E943}\u{1E94B}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}\u{20000}-\u{2A6DF}\u{2A700}-\u{2B739}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2EBF0}-\u{2EE5D}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{31350}-\u{323AF}]+$/u;
        var extractNewHref = function extractNewHref(anchor, attr) {
            if (attr === "text") {
                if (!anchor.textContent) {
                    return "";
                }
                return anchor.textContent.replace(regexpNotValidAtStart, "").replace(regexpNotValidAtEnd, "");
            }
            if (attr.startsWith("?")) {
                try {
                    var url = new URL(anchor.href, document.location.href);
                    return url.searchParams.get(attr.slice(1)) || "";
                } catch (ex) {
                    logMessage(source, `Cannot retrieve the parameter '${attr.slice(1)}' from the URL '${anchor.href}`);
                    return "";
                }
            }
            if (attr.startsWith("[") && attr.endsWith("]")) {
                return anchor.getAttribute(attr.slice(1, -1)) || "";
            }
            return "";
        };
        var isValidURL = function isValidURL(url) {
            try {
                new URL(url);
                return true;
            } catch (_unused) {
                return false;
            }
        };
        var getValidURL = function getValidURL(text) {
            if (!text) {
                return null;
            }
            try {
                var {href: href, protocol: protocol} = new URL(text, document.location.href);
                if (protocol !== "http:" && protocol !== "https:") {
                    logMessage(source, `Protocol not allowed: "${protocol}", from URL: "${href}"`);
                    return null;
                }
                return href;
            } catch (_unused2) {
                return null;
            }
        };
        var isSanitizableAnchor = function isSanitizableAnchor(element) {
            return element.nodeName.toLowerCase() === "a" && element.hasAttribute("href");
        };
        var _extractURLFromObject = function extractURLFromObject(obj) {
            for (var key in obj) {
                if (!Object.prototype.hasOwnProperty.call(obj, key)) {
                    continue;
                }
                var value = obj[key];
                if (typeof value === "string" && isValidURL(value)) {
                    return value;
                }
                if (typeof value === "object" && value !== null) {
                    var result = _extractURLFromObject(value);
                    if (result) {
                        return result;
                    }
                }
            }
            return null;
        };
        var isStringifiedObject = function isStringifiedObject(content) {
            return content.startsWith("{") && content.endsWith("}");
        };
        var decodeBase64SeveralTimes = function decodeBase64SeveralTimes(text, times) {
            var result = text;
            for (var i = 0; i < times; i += 1) {
                try {
                    result = atob(result);
                } catch (e) {
                    if (result === text) {
                        return "";
                    }
                }
            }
            if (isValidURL(result)) {
                return result;
            }
            if (isStringifiedObject(result)) {
                try {
                    var parsedResult = JSON.parse(result);
                    return _extractURLFromObject(parsedResult);
                } catch (ex) {
                    return "";
                }
            }
            logMessage(source, `Failed to decode base64 string: ${text}`);
            return "";
        };
        var SEARCH_QUERY_MARKER = "?";
        var SEARCH_PARAMS_MARKER = "&";
        var HASHBANG_MARKER = "#!";
        var ANCHOR_MARKER = "#";
        var DECODE_ATTEMPTS_NUMBER = 10;
        var decodeSearchString = function decodeSearchString(search) {
            var searchString = search.replace(SEARCH_QUERY_MARKER, "");
            var decodedParam;
            var validEncodedParam;
            if (searchString.includes(SEARCH_PARAMS_MARKER)) {
                var searchParamsArray = searchString.split(SEARCH_PARAMS_MARKER);
                searchParamsArray.forEach((function(param) {
                    decodedParam = decodeBase64SeveralTimes(param, DECODE_ATTEMPTS_NUMBER);
                    if (decodedParam && decodedParam.length > 0) {
                        validEncodedParam = decodedParam;
                    }
                }));
                return validEncodedParam;
            }
            return decodeBase64SeveralTimes(searchString, DECODE_ATTEMPTS_NUMBER);
        };
        var decodeHashString = function decodeHashString(hash) {
            var validEncodedHash = "";
            if (hash.includes(HASHBANG_MARKER)) {
                validEncodedHash = hash.replace(HASHBANG_MARKER, "");
            } else if (hash.includes(ANCHOR_MARKER)) {
                validEncodedHash = hash.replace(ANCHOR_MARKER, "");
            }
            return validEncodedHash ? decodeBase64SeveralTimes(validEncodedHash, DECODE_ATTEMPTS_NUMBER) : "";
        };
        var removeHash = function removeHash(url) {
            var urlObj = new URL(url, window.location.origin);
            if (!urlObj.hash) {
                return "";
            }
            urlObj.hash = "";
            return urlObj.toString();
        };
        var removeParam = function removeParam(url, transformValue) {
            var urlObj = new URL(url, window.location.origin);
            var paramNamesToRemoveStr = transformValue.split(MARKER_SEPARATOR)[1];
            if (!paramNamesToRemoveStr) {
                urlObj.search = "";
                return urlObj.toString();
            }
            var initSearchParamsLength = urlObj.searchParams.toString().length;
            var removeParams = paramNamesToRemoveStr.split(COMMA);
            removeParams.forEach((function(param) {
                if (urlObj.searchParams.has(param)) {
                    urlObj.searchParams.delete(param);
                }
            }));
            if (initSearchParamsLength === urlObj.searchParams.toString().length) {
                return "";
            }
            return urlObj.toString();
        };
        var decodeBase64URL = function decodeBase64URL(url) {
            var {search: search, hash: hash} = new URL(url, document.location.href);
            if (search.length > 0) {
                return decodeSearchString(search);
            }
            if (hash.length > 0) {
                return decodeHashString(hash);
            }
            logMessage(source, `Failed to execute base64 from URL: ${url}`);
            return null;
        };
        var base64Decode = function base64Decode(href) {
            if (isValidURL(href)) {
                return decodeBase64URL(href) || "";
            }
            return decodeBase64SeveralTimes(href, DECODE_ATTEMPTS_NUMBER) || "";
        };
        var sanitize = function sanitize(elementSelector) {
            var elements;
            try {
                elements = document.querySelectorAll(elementSelector);
            } catch (e) {
                logMessage(source, `Invalid selector "${elementSelector}"`);
                return;
            }
            elements.forEach((function(elem) {
                try {
                    if (!isSanitizableAnchor(elem)) {
                        logMessage(source, `${elem} is not a valid element to sanitize`);
                        return;
                    }
                    var newHref = extractNewHref(elem, attribute);
                    if (transform) {
                        switch (true) {
                          case transform === BASE64_DECODE_TRANSFORM_MARKER:
                            newHref = base64Decode(newHref);
                            break;

                          case transform === REMOVE_HASH_TRANSFORM_MARKER:
                            newHref = removeHash(newHref);
                            break;

                          case transform.startsWith(REMOVE_PARAM_TRANSFORM_MARKER):
                            {
                                newHref = removeParam(newHref, transform);
                                break;
                            }

                          default:
                            logMessage(source, `Invalid transform option: "${transform}"`);
                            return;
                        }
                    }
                    var newValidHref = getValidURL(newHref);
                    if (!newValidHref) {
                        logMessage(source, `Invalid URL: ${newHref}`);
                        return;
                    }
                    var oldHref = elem.href;
                    elem.setAttribute("href", newValidHref);
                    if (newValidHref !== oldHref) {
                        logMessage(source, `Sanitized "${oldHref}" to "${newValidHref}".`);
                    }
                } catch (ex) {
                    logMessage(source, `Failed to sanitize ${elem}.`);
                }
            }));
            hit(source);
        };
        var run = function run() {
            sanitize(selector);
            observeDOMChanges((function() {
                return sanitize(selector);
            }), true);
        };
        if (document.readyState === "loading") {
            window.addEventListener("DOMContentLoaded", run, {
                once: true
            });
        } else {
            run();
        }
    }
    function observeDOMChanges(callback) {
        var observeAttrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
        var attrsToObserve = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
        var THROTTLE_DELAY_MS = 20;
        var observer = new MutationObserver(throttle(callbackWrapper, THROTTLE_DELAY_MS));
        var connect = function connect() {
            if (attrsToObserve.length > 0) {
                observer.observe(document.documentElement, {
                    childList: true,
                    subtree: true,
                    attributes: observeAttrs,
                    attributeFilter: attrsToObserve
                });
            } else {
                observer.observe(document.documentElement, {
                    childList: true,
                    subtree: true,
                    attributes: observeAttrs
                });
            }
        };
        var disconnect = function disconnect() {
            observer.disconnect();
        };
        function callbackWrapper() {
            disconnect();
            callback();
            connect();
        }
        connect();
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function throttle(cb, delay) {
        var wait = false;
        var savedArgs;
        var _wrapper = function wrapper() {
            for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                args[_key] = arguments[_key];
            }
            if (wait) {
                savedArgs = args;
                return;
            }
            cb(...args);
            wait = true;
            setTimeout((function() {
                wait = false;
                if (savedArgs) {
                    _wrapper(...savedArgs);
                    savedArgs = null;
                }
            }), delay);
        };
        return _wrapper;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        hrefSanitizer.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function injectCssInShadowDom(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function injectCssInShadowDom(source, cssRule) {
        var hostSelector = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
        if (!Element.prototype.attachShadow || typeof Proxy === "undefined" || typeof Reflect === "undefined") {
            return;
        }
        if (cssRule.match(/(url|image-set)\(.*\)/i)) {
            logMessage(source, '"url()" function is not allowed for css rules');
            return;
        }
        var callback = function callback(shadowRoot) {
            try {
                var stylesheet = new CSSStyleSheet;
                try {
                    stylesheet.insertRule(cssRule);
                } catch (e) {
                    logMessage(source, `Unable to apply the rule '${cssRule}' due to: \n'${e.message}'`);
                    return;
                }
                shadowRoot.adoptedStyleSheets = [ ...shadowRoot.adoptedStyleSheets, stylesheet ];
            } catch (_unused) {
                var styleTag = document.createElement("style");
                styleTag.innerText = cssRule;
                shadowRoot.appendChild(styleTag);
            }
            hit(source);
        };
        hijackAttachShadow(window, hostSelector, callback);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function hijackAttachShadow(context, hostSelector, callback) {
        var handlerWrapper = function handlerWrapper(target, thisArg, args) {
            var shadowRoot = Reflect.apply(target, thisArg, args);
            if (thisArg && thisArg.matches(hostSelector || "*")) {
                callback(shadowRoot);
            }
            return shadowRoot;
        };
        var attachShadowHandler = {
            apply: handlerWrapper
        };
        context.Element.prototype.attachShadow = new Proxy(context.Element.prototype.attachShadow, attachShadowHandler);
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        injectCssInShadowDom.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function jsonPrune(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function jsonPrune(source, propsToRemove, requiredInitialProps) {
        var stack = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "";
        var prunePaths = getPrunePath(propsToRemove);
        var requiredPaths = getPrunePath(requiredInitialProps);
        var nativeObjects = {
            nativeStringify: window.JSON.stringify
        };
        var nativeJSONParse = JSON.parse;
        var jsonParseWrapper = function jsonParseWrapper() {
            for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                args[_key] = arguments[_key];
            }
            var root = nativeJSONParse.apply(JSON, args);
            return jsonPruner(source, root, prunePaths, requiredPaths, stack, nativeObjects);
        };
        jsonParseWrapper.toString = nativeJSONParse.toString.bind(nativeJSONParse);
        JSON.parse = jsonParseWrapper;
        var nativeResponseJson = Response.prototype.json;
        var responseJsonWrapper = function responseJsonWrapper() {
            var promise = nativeResponseJson.apply(this);
            return promise.then((function(obj) {
                return jsonPruner(source, obj, prunePaths, requiredPaths, stack, nativeObjects);
            }));
        };
        if (typeof Response === "undefined") {
            return;
        }
        Response.prototype.json = responseJsonWrapper;
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function matchStackTrace(stackMatch, stackTrace) {
        if (!stackMatch || stackMatch === "") {
            return true;
        }
        var regExpValues = backupRegExpValues();
        if (shouldAbortInlineOrInjectedScript(stackMatch, stackTrace)) {
            if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
                restoreRegExpValues(regExpValues);
            }
            return true;
        }
        var stackRegexp = toRegExp(stackMatch);
        var refinedStackTrace = stackTrace.split("\n").slice(2).map((function(line) {
            return line.trim();
        })).join("\n");
        if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
            restoreRegExpValues(regExpValues);
        }
        return getNativeRegexpTest().call(stackRegexp, refinedStackTrace);
    }
    function getWildcardPropertyInChain(base, chain) {
        var lookThrough = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var output = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
        var valueToCheck = arguments.length > 4 ? arguments[4] : undefined;
        var pos = chain.indexOf(".");
        if (pos === -1) {
            if (chain === "*" || chain === "[]") {
                for (var key in base) {
                    if (Object.prototype.hasOwnProperty.call(base, key)) {
                        if (valueToCheck !== undefined) {
                            var objectValue = base[key];
                            if (typeof objectValue === "string" && valueToCheck instanceof RegExp) {
                                if (valueToCheck.test(objectValue)) {
                                    output.push({
                                        base: base,
                                        prop: key
                                    });
                                }
                            } else if (objectValue === valueToCheck) {
                                output.push({
                                    base: base,
                                    prop: key
                                });
                            }
                        } else {
                            output.push({
                                base: base,
                                prop: key
                            });
                        }
                    }
                }
            } else if (valueToCheck !== undefined) {
                var _objectValue = base[chain];
                if (typeof _objectValue === "string" && valueToCheck instanceof RegExp) {
                    if (valueToCheck.test(_objectValue)) {
                        output.push({
                            base: base,
                            prop: chain
                        });
                    }
                } else if (base[chain] === valueToCheck) {
                    output.push({
                        base: base,
                        prop: chain
                    });
                }
            } else {
                output.push({
                    base: base,
                    prop: chain
                });
            }
            return output;
        }
        var prop = chain.slice(0, pos);
        var shouldLookThrough = prop === "[]" && Array.isArray(base) || prop === "*" && base instanceof Object || prop === "[-]" && Array.isArray(base) || prop === "{-}" && base instanceof Object;
        if (shouldLookThrough) {
            var nextProp = chain.slice(pos + 1);
            var baseKeys = Object.keys(base);
            if (prop === "{-}" || prop === "[-]") {
                var type = Array.isArray(base) ? "array" : "object";
                var shouldRemove = !!(prop === "{-}" && type === "object") || !!(prop === "[-]" && type === "array");
                if (!shouldRemove) {
                    return output;
                }
                baseKeys.forEach((function(key) {
                    var item = base[key];
                    if (isKeyInObject(item, nextProp, valueToCheck)) {
                        output.push({
                            base: base,
                            prop: key
                        });
                    }
                }));
                return output;
            }
            baseKeys.forEach((function(key) {
                var item = base[key];
                getWildcardPropertyInChain(item, nextProp, lookThrough, output, valueToCheck);
            }));
        }
        if (Array.isArray(base)) {
            base.forEach((function(key) {
                var nextBase = key;
                if (nextBase !== undefined) {
                    getWildcardPropertyInChain(nextBase, chain, lookThrough, output, valueToCheck);
                }
            }));
        }
        var nextBase = base[prop];
        chain = chain.slice(pos + 1);
        if (nextBase !== undefined) {
            getWildcardPropertyInChain(nextBase, chain, lookThrough, output, valueToCheck);
        }
        return output;
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function isPruningNeeded(source, root, prunePaths, requiredPaths, stack, nativeObjects) {
        if (!root) {
            return false;
        }
        var {nativeStringify: nativeStringify} = nativeObjects;
        var shouldProcess;
        var prunePathsToCheck = prunePaths.map((function(obj) {
            return obj.path;
        }));
        var requiredPathsToCheck = requiredPaths.map((function(obj) {
            return obj.path;
        }));
        if (prunePathsToCheck.length === 0 && requiredPathsToCheck.length > 0) {
            var rootString = nativeStringify(root);
            var matchRegex = toRegExp(requiredPathsToCheck.join(""));
            var shouldLog = matchRegex.test(rootString);
            if (shouldLog) {
                logMessage(source, `${window.location.hostname}\n${nativeStringify(root, null, 2)}\nStack trace:\n${(new Error).stack}`, true);
                if (root && typeof root === "object") {
                    logMessage(source, root, true, false);
                }
                shouldProcess = false;
                return shouldProcess;
            }
        }
        if (stack && !matchStackTrace(stack, (new Error).stack || "")) {
            shouldProcess = false;
            return shouldProcess;
        }
        var wildcardSymbols = [ ".*.", "*.", ".*", ".[].", "[].", ".[]" ];
        var _loop = function _loop() {
            var requiredPath = requiredPathsToCheck[i];
            var lastNestedPropName = requiredPath.split(".").pop();
            var hasWildcard = wildcardSymbols.some((function(symbol) {
                return requiredPath.includes(symbol);
            }));
            var details = getWildcardPropertyInChain(root, requiredPath, hasWildcard);
            if (!details.length) {
                shouldProcess = false;
                return {
                    v: shouldProcess
                };
            }
            shouldProcess = !hasWildcard;
            for (var j = 0; j < details.length; j += 1) {
                var hasRequiredProp = typeof lastNestedPropName === "string" && details[j].base[lastNestedPropName] !== undefined;
                if (hasWildcard) {
                    shouldProcess = hasRequiredProp || shouldProcess;
                } else {
                    shouldProcess = hasRequiredProp && shouldProcess;
                }
            }
        }, _ret;
        for (var i = 0; i < requiredPathsToCheck.length; i += 1) {
            _ret = _loop();
            if (_ret) return _ret.v;
        }
        return shouldProcess;
    }
    function jsonPruner(source, root, prunePaths, requiredPaths, stack, nativeObjects) {
        var {nativeStringify: nativeStringify} = nativeObjects;
        if (prunePaths.length === 0 && requiredPaths.length === 0) {
            logMessage(source, `${window.location.hostname}\n${nativeStringify(root, null, 2)}\nStack trace:\n${(new Error).stack}`, true);
            if (root && typeof root === "object") {
                logMessage(source, root, true, false);
            }
            return root;
        }
        try {
            if (isPruningNeeded(source, root, prunePaths, requiredPaths, stack, nativeObjects) === false) {
                return root;
            }
            prunePaths.forEach((function(path) {
                var pathToCheck = path.path;
                var valueToCheck = path.value;
                var ownerObjArr = getWildcardPropertyInChain(root, pathToCheck, true, [], valueToCheck);
                for (var i = ownerObjArr.length - 1; i >= 0; i -= 1) {
                    var ownerObj = ownerObjArr[i];
                    if (ownerObj === undefined || !ownerObj.base) {
                        continue;
                    }
                    hit(source);
                    if (!Array.isArray(ownerObj.base)) {
                        delete ownerObj.base[ownerObj.prop];
                        continue;
                    }
                    try {
                        var index = Number(ownerObj.prop);
                        if (Number.isNaN(index)) {
                            continue;
                        }
                        ownerObj.base.splice(index, 1);
                    } catch (error) {
                        console.error("Error while deleting array element", error);
                    }
                }
            }));
        } catch (e) {
            logMessage(source, e);
        }
        return root;
    }
    function getPrunePath(props) {
        var VALUE_MARKER = ".[=].";
        var REGEXP_START_MARKER = "/";
        var validPropsString = typeof props === "string" && props !== undefined && props !== "";
        if (validPropsString) {
            var splitRegexp = /(?<!\.\[=\]\.\/(?:[^/]|\\.)*)\s+/;
            var parts = props.split(splitRegexp).map((function(part) {
                var splitPart = part.split(VALUE_MARKER);
                var path = splitPart[0];
                var value = splitPart[1];
                if (value !== undefined) {
                    if (value === "true") {
                        value = true;
                    } else if (value === "false") {
                        value = false;
                    } else if (value.startsWith(REGEXP_START_MARKER)) {
                        value = toRegExp(value);
                    } else if (typeof value === "string" && /^\d+$/.test(value)) {
                        value = parseFloat(value);
                    }
                    return {
                        path: path,
                        value: value
                    };
                }
                return {
                    path: path
                };
            }));
            return parts;
        }
        return [];
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function getNativeRegexpTest() {
        var descriptor = Object.getOwnPropertyDescriptor(RegExp.prototype, "test");
        var nativeRegexTest = descriptor === null || descriptor === void 0 ? void 0 : descriptor.value;
        if (descriptor && typeof descriptor.value === "function") {
            return nativeRegexTest;
        }
        throw new Error("RegExp.prototype.test is not a function");
    }
    function shouldAbortInlineOrInjectedScript(stackMatch, stackTrace) {
        var INLINE_SCRIPT_STRING = "inlineScript";
        var INJECTED_SCRIPT_STRING = "injectedScript";
        var INJECTED_SCRIPT_MARKER = "<anonymous>";
        var isInlineScript = function isInlineScript(match) {
            return match.includes(INLINE_SCRIPT_STRING);
        };
        var isInjectedScript = function isInjectedScript(match) {
            return match.includes(INJECTED_SCRIPT_STRING);
        };
        if (!(isInlineScript(stackMatch) || isInjectedScript(stackMatch))) {
            return false;
        }
        var documentURL = window.location.href;
        var pos = documentURL.indexOf("#");
        if (pos !== -1) {
            documentURL = documentURL.slice(0, pos);
        }
        var stackSteps = stackTrace.split("\n").slice(2).map((function(line) {
            return line.trim();
        }));
        var stackLines = stackSteps.map((function(line) {
            var stack;
            var getStackTraceValues = /(.*?@)?(\S+)(:\d+)(:\d+)\)?$/.exec(line);
            if (getStackTraceValues) {
                var _stackURL, _stackURL2;
                var stackURL = getStackTraceValues[2];
                var stackLine = getStackTraceValues[3];
                var stackCol = getStackTraceValues[4];
                if ((_stackURL = stackURL) !== null && _stackURL !== void 0 && _stackURL.startsWith("(")) {
                    stackURL = stackURL.slice(1);
                }
                if ((_stackURL2 = stackURL) !== null && _stackURL2 !== void 0 && _stackURL2.startsWith(INJECTED_SCRIPT_MARKER)) {
                    var _stackFunction;
                    stackURL = INJECTED_SCRIPT_STRING;
                    var stackFunction = getStackTraceValues[1] !== undefined ? getStackTraceValues[1].slice(0, -1) : line.slice(0, getStackTraceValues.index).trim();
                    if ((_stackFunction = stackFunction) !== null && _stackFunction !== void 0 && _stackFunction.startsWith("at")) {
                        stackFunction = stackFunction.slice(2).trim();
                    }
                    stack = `${stackFunction} ${stackURL}${stackLine}${stackCol}`.trim();
                } else if (stackURL === documentURL) {
                    stack = `${INLINE_SCRIPT_STRING}${stackLine}${stackCol}`.trim();
                } else {
                    stack = `${stackURL}${stackLine}${stackCol}`.trim();
                }
            } else {
                stack = line;
            }
            return stack;
        }));
        if (stackLines) {
            for (var index = 0; index < stackLines.length; index += 1) {
                if (isInlineScript(stackMatch) && stackLines[index].startsWith(INLINE_SCRIPT_STRING) && stackLines[index].match(toRegExp(stackMatch))) {
                    return true;
                }
                if (isInjectedScript(stackMatch) && stackLines[index].startsWith(INJECTED_SCRIPT_STRING) && stackLines[index].match(toRegExp(stackMatch))) {
                    return true;
                }
            }
        }
        return false;
    }
    function backupRegExpValues() {
        try {
            var arrayOfRegexpValues = [];
            for (var index = 1; index < 10; index += 1) {
                var value = `$${index}`;
                if (!RegExp[value]) {
                    break;
                }
                arrayOfRegexpValues.push(RegExp[value]);
            }
            return arrayOfRegexpValues;
        } catch (error) {
            return [];
        }
    }
    function restoreRegExpValues(array) {
        if (!array.length) {
            return;
        }
        try {
            var stringPattern = "";
            if (array.length === 1) {
                stringPattern = `(${array[0]})`;
            } else {
                stringPattern = array.reduce((function(accumulator, currentValue, currentIndex) {
                    if (currentIndex === 1) {
                        return `(${accumulator}),(${currentValue})`;
                    }
                    return `${accumulator},(${currentValue})`;
                }));
            }
            var regExpGroup = new RegExp(stringPattern);
            array.toString().replace(regExpGroup, "");
        } catch (error) {
            var message = `Failed to restore RegExp values: ${error}`;
            console.log(message);
        }
    }
    function isKeyInObject(baseObj, path, valueToCheck) {
        var parts = path.split(".");
        var _check = function check(targetObject, pathSegments) {
            if (pathSegments.length === 0) {
                if (valueToCheck !== undefined) {
                    if (typeof targetObject === "string" && valueToCheck instanceof RegExp) {
                        return valueToCheck.test(targetObject);
                    }
                    return targetObject === valueToCheck;
                }
                return true;
            }
            var current = pathSegments[0];
            var rest = pathSegments.slice(1);
            if (current === "*" || current === "[]") {
                if (Array.isArray(targetObject)) {
                    return targetObject.some((function(item) {
                        return _check(item, rest);
                    }));
                }
                if (typeof targetObject === "object" && targetObject !== null) {
                    return Object.keys(targetObject).some((function(key) {
                        return _check(targetObject[key], rest);
                    }));
                }
            }
            if (Object.prototype.hasOwnProperty.call(targetObject, current)) {
                return _check(targetObject[current], rest);
            }
            return false;
        };
        return _check(baseObj, parts);
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        jsonPrune.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function jsonPruneFetchResponse(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function jsonPruneFetchResponse(source, propsToRemove, obligatoryProps) {
        var propsToMatch = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "";
        var stack = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : "";
        if (typeof fetch === "undefined" || typeof Proxy === "undefined" || typeof Response === "undefined") {
            return;
        }
        var prunePaths = getPrunePath(propsToRemove);
        var requiredPaths = getPrunePath(obligatoryProps);
        var nativeStringify = window.JSON.stringify;
        var nativeRequestClone = window.Request.prototype.clone;
        var nativeResponseClone = window.Response.prototype.clone;
        var nativeFetch = window.fetch;
        var fetchHandlerWrapper = async function fetchHandlerWrapper(target, thisArg, args) {
            var fetchData = getFetchData(args, nativeRequestClone);
            if (!matchRequestProps(source, propsToMatch, fetchData)) {
                return Reflect.apply(target, thisArg, args);
            }
            var originalResponse;
            var clonedResponse;
            try {
                originalResponse = await nativeFetch.apply(null, args);
                clonedResponse = nativeResponseClone.call(originalResponse);
            } catch (_unused) {
                logMessage(source, `Could not make an original fetch request: ${fetchData.url}`);
                return Reflect.apply(target, thisArg, args);
            }
            var json;
            try {
                json = await originalResponse.json();
            } catch (e) {
                var message = `Response body can't be converted to json: ${objectToString(fetchData)}`;
                logMessage(source, message);
                return clonedResponse;
            }
            var modifiedJson = jsonPruner(source, json, prunePaths, requiredPaths, stack, {
                nativeStringify: nativeStringify,
                nativeRequestClone: nativeRequestClone,
                nativeResponseClone: nativeResponseClone,
                nativeFetch: nativeFetch
            });
            var forgedResponse = forgeResponse(originalResponse, nativeStringify(modifiedJson));
            hit(source);
            return forgedResponse;
        };
        var fetchHandler = {
            apply: fetchHandlerWrapper
        };
        window.fetch = new Proxy(window.fetch, fetchHandler);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function getFetchData(args, nativeRequestClone) {
        var fetchPropsObj = {};
        var resource = args[0];
        var fetchUrl;
        var fetchInit;
        if (resource instanceof Request) {
            var realData = nativeRequestClone.call(resource);
            var requestData = getRequestData(realData);
            fetchUrl = requestData.url;
            fetchInit = requestData;
        } else {
            fetchUrl = resource;
            fetchInit = args[1];
        }
        fetchPropsObj.url = fetchUrl;
        if (fetchInit instanceof Object) {
            var props = Object.keys(fetchInit);
            props.forEach((function(prop) {
                fetchPropsObj[prop] = fetchInit[prop];
            }));
        }
        return fetchPropsObj;
    }
    function objectToString(obj) {
        if (!obj || typeof obj !== "object") {
            return String(obj);
        }
        if (isEmptyObject(obj)) {
            return "{}";
        }
        return Object.entries(obj).map((function(pair) {
            var key = pair[0];
            var value = pair[1];
            var recordValueStr = value;
            if (value instanceof Object) {
                recordValueStr = `{ ${objectToString(value)} }`;
            }
            return `${key}:"${recordValueStr}"`;
        })).join(" ");
    }
    function matchRequestProps(source, propsToMatch, requestData) {
        if (propsToMatch === "" || propsToMatch === "*") {
            return true;
        }
        var isMatched;
        var parsedData = parseMatchProps(propsToMatch);
        if (!isValidParsedData(parsedData)) {
            logMessage(source, `Invalid parameter: ${propsToMatch}`);
            isMatched = false;
        } else {
            var matchData = getMatchPropsData(parsedData);
            var matchKeys = Object.keys(matchData);
            isMatched = matchKeys.every((function(matchKey) {
                var matchValue = matchData[matchKey];
                var dataValue = requestData[matchKey];
                return Object.prototype.hasOwnProperty.call(requestData, matchKey) && typeof dataValue === "string" && (matchValue === null || matchValue === void 0 ? void 0 : matchValue.test(dataValue));
            }));
        }
        return isMatched;
    }
    function jsonPruner(source, root, prunePaths, requiredPaths, stack, nativeObjects) {
        var {nativeStringify: nativeStringify} = nativeObjects;
        if (prunePaths.length === 0 && requiredPaths.length === 0) {
            logMessage(source, `${window.location.hostname}\n${nativeStringify(root, null, 2)}\nStack trace:\n${(new Error).stack}`, true);
            if (root && typeof root === "object") {
                logMessage(source, root, true, false);
            }
            return root;
        }
        try {
            if (isPruningNeeded(source, root, prunePaths, requiredPaths, stack, nativeObjects) === false) {
                return root;
            }
            prunePaths.forEach((function(path) {
                var pathToCheck = path.path;
                var valueToCheck = path.value;
                var ownerObjArr = getWildcardPropertyInChain(root, pathToCheck, true, [], valueToCheck);
                for (var i = ownerObjArr.length - 1; i >= 0; i -= 1) {
                    var ownerObj = ownerObjArr[i];
                    if (ownerObj === undefined || !ownerObj.base) {
                        continue;
                    }
                    hit(source);
                    if (!Array.isArray(ownerObj.base)) {
                        delete ownerObj.base[ownerObj.prop];
                        continue;
                    }
                    try {
                        var index = Number(ownerObj.prop);
                        if (Number.isNaN(index)) {
                            continue;
                        }
                        ownerObj.base.splice(index, 1);
                    } catch (error) {
                        console.error("Error while deleting array element", error);
                    }
                }
            }));
        } catch (e) {
            logMessage(source, e);
        }
        return root;
    }
    function getPrunePath(props) {
        var VALUE_MARKER = ".[=].";
        var REGEXP_START_MARKER = "/";
        var validPropsString = typeof props === "string" && props !== undefined && props !== "";
        if (validPropsString) {
            var splitRegexp = /(?<!\.\[=\]\.\/(?:[^/]|\\.)*)\s+/;
            var parts = props.split(splitRegexp).map((function(part) {
                var splitPart = part.split(VALUE_MARKER);
                var path = splitPart[0];
                var value = splitPart[1];
                if (value !== undefined) {
                    if (value === "true") {
                        value = true;
                    } else if (value === "false") {
                        value = false;
                    } else if (value.startsWith(REGEXP_START_MARKER)) {
                        value = toRegExp(value);
                    } else if (typeof value === "string" && /^\d+$/.test(value)) {
                        value = parseFloat(value);
                    }
                    return {
                        path: path,
                        value: value
                    };
                }
                return {
                    path: path
                };
            }));
            return parts;
        }
        return [];
    }
    function forgeResponse(response, textContent) {
        var {bodyUsed: bodyUsed, headers: headers, ok: ok, redirected: redirected, status: status, statusText: statusText, type: type, url: url} = response;
        var forgedResponse = new Response(textContent, {
            status: status,
            statusText: statusText,
            headers: headers
        });
        Object.defineProperties(forgedResponse, {
            url: {
                value: url
            },
            type: {
                value: type
            },
            ok: {
                value: ok
            },
            bodyUsed: {
                value: bodyUsed
            },
            redirected: {
                value: redirected
            }
        });
        return forgedResponse;
    }
    function isPruningNeeded(source, root, prunePaths, requiredPaths, stack, nativeObjects) {
        if (!root) {
            return false;
        }
        var {nativeStringify: nativeStringify} = nativeObjects;
        var shouldProcess;
        var prunePathsToCheck = prunePaths.map((function(obj) {
            return obj.path;
        }));
        var requiredPathsToCheck = requiredPaths.map((function(obj) {
            return obj.path;
        }));
        if (prunePathsToCheck.length === 0 && requiredPathsToCheck.length > 0) {
            var rootString = nativeStringify(root);
            var matchRegex = toRegExp(requiredPathsToCheck.join(""));
            var shouldLog = matchRegex.test(rootString);
            if (shouldLog) {
                logMessage(source, `${window.location.hostname}\n${nativeStringify(root, null, 2)}\nStack trace:\n${(new Error).stack}`, true);
                if (root && typeof root === "object") {
                    logMessage(source, root, true, false);
                }
                shouldProcess = false;
                return shouldProcess;
            }
        }
        if (stack && !matchStackTrace(stack, (new Error).stack || "")) {
            shouldProcess = false;
            return shouldProcess;
        }
        var wildcardSymbols = [ ".*.", "*.", ".*", ".[].", "[].", ".[]" ];
        var _loop = function _loop() {
            var requiredPath = requiredPathsToCheck[i];
            var lastNestedPropName = requiredPath.split(".").pop();
            var hasWildcard = wildcardSymbols.some((function(symbol) {
                return requiredPath.includes(symbol);
            }));
            var details = getWildcardPropertyInChain(root, requiredPath, hasWildcard);
            if (!details.length) {
                shouldProcess = false;
                return {
                    v: shouldProcess
                };
            }
            shouldProcess = !hasWildcard;
            for (var j = 0; j < details.length; j += 1) {
                var hasRequiredProp = typeof lastNestedPropName === "string" && details[j].base[lastNestedPropName] !== undefined;
                if (hasWildcard) {
                    shouldProcess = hasRequiredProp || shouldProcess;
                } else {
                    shouldProcess = hasRequiredProp && shouldProcess;
                }
            }
        }, _ret;
        for (var i = 0; i < requiredPathsToCheck.length; i += 1) {
            _ret = _loop();
            if (_ret) return _ret.v;
        }
        return shouldProcess;
    }
    function matchStackTrace(stackMatch, stackTrace) {
        if (!stackMatch || stackMatch === "") {
            return true;
        }
        var regExpValues = backupRegExpValues();
        if (shouldAbortInlineOrInjectedScript(stackMatch, stackTrace)) {
            if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
                restoreRegExpValues(regExpValues);
            }
            return true;
        }
        var stackRegexp = toRegExp(stackMatch);
        var refinedStackTrace = stackTrace.split("\n").slice(2).map((function(line) {
            return line.trim();
        })).join("\n");
        if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
            restoreRegExpValues(regExpValues);
        }
        return getNativeRegexpTest().call(stackRegexp, refinedStackTrace);
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function isValidStrPattern(input) {
        var FORWARD_SLASH = "/";
        var str = escapeRegExp(input);
        if (input[0] === FORWARD_SLASH && input[input.length - 1] === FORWARD_SLASH) {
            str = input.slice(1, -1);
        }
        var isValid;
        try {
            isValid = new RegExp(str);
            isValid = true;
        } catch (e) {
            isValid = false;
        }
        return isValid;
    }
    function escapeRegExp(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    function isEmptyObject(obj) {
        return Object.keys(obj).length === 0 && !obj.prototype;
    }
    function getRequestData(request) {
        var requestInitOptions = getRequestProps();
        var entries = requestInitOptions.map((function(key) {
            var value = request[key];
            return [ key, value ];
        }));
        return Object.fromEntries(entries);
    }
    function getRequestProps() {
        return [ "url", "method", "headers", "body", "credentials", "cache", "redirect", "referrer", "referrerPolicy", "integrity", "keepalive", "signal", "mode" ];
    }
    function parseMatchProps(propsToMatchStr) {
        var PROPS_DIVIDER = " ";
        var PAIRS_MARKER = ":";
        var isRequestProp = function isRequestProp(prop) {
            return getRequestProps().includes(prop);
        };
        var propsObj = {};
        var props = propsToMatchStr.split(PROPS_DIVIDER);
        props.forEach((function(prop) {
            var dividerInd = prop.indexOf(PAIRS_MARKER);
            var key = prop.slice(0, dividerInd);
            if (isRequestProp(key)) {
                var value = prop.slice(dividerInd + 1);
                propsObj[key] = value;
            } else {
                propsObj.url = prop;
            }
        }));
        return propsObj;
    }
    function isValidParsedData(data) {
        return Object.values(data).every((function(value) {
            return isValidStrPattern(value);
        }));
    }
    function getMatchPropsData(data) {
        var matchData = {};
        var dataKeys = Object.keys(data);
        dataKeys.forEach((function(key) {
            matchData[key] = toRegExp(data[key]);
        }));
        return matchData;
    }
    function getWildcardPropertyInChain(base, chain) {
        var lookThrough = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var output = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
        var valueToCheck = arguments.length > 4 ? arguments[4] : undefined;
        var pos = chain.indexOf(".");
        if (pos === -1) {
            if (chain === "*" || chain === "[]") {
                for (var key in base) {
                    if (Object.prototype.hasOwnProperty.call(base, key)) {
                        if (valueToCheck !== undefined) {
                            var objectValue = base[key];
                            if (typeof objectValue === "string" && valueToCheck instanceof RegExp) {
                                if (valueToCheck.test(objectValue)) {
                                    output.push({
                                        base: base,
                                        prop: key
                                    });
                                }
                            } else if (objectValue === valueToCheck) {
                                output.push({
                                    base: base,
                                    prop: key
                                });
                            }
                        } else {
                            output.push({
                                base: base,
                                prop: key
                            });
                        }
                    }
                }
            } else if (valueToCheck !== undefined) {
                var _objectValue = base[chain];
                if (typeof _objectValue === "string" && valueToCheck instanceof RegExp) {
                    if (valueToCheck.test(_objectValue)) {
                        output.push({
                            base: base,
                            prop: chain
                        });
                    }
                } else if (base[chain] === valueToCheck) {
                    output.push({
                        base: base,
                        prop: chain
                    });
                }
            } else {
                output.push({
                    base: base,
                    prop: chain
                });
            }
            return output;
        }
        var prop = chain.slice(0, pos);
        var shouldLookThrough = prop === "[]" && Array.isArray(base) || prop === "*" && base instanceof Object || prop === "[-]" && Array.isArray(base) || prop === "{-}" && base instanceof Object;
        if (shouldLookThrough) {
            var nextProp = chain.slice(pos + 1);
            var baseKeys = Object.keys(base);
            if (prop === "{-}" || prop === "[-]") {
                var type = Array.isArray(base) ? "array" : "object";
                var shouldRemove = !!(prop === "{-}" && type === "object") || !!(prop === "[-]" && type === "array");
                if (!shouldRemove) {
                    return output;
                }
                baseKeys.forEach((function(key) {
                    var item = base[key];
                    if (isKeyInObject(item, nextProp, valueToCheck)) {
                        output.push({
                            base: base,
                            prop: key
                        });
                    }
                }));
                return output;
            }
            baseKeys.forEach((function(key) {
                var item = base[key];
                getWildcardPropertyInChain(item, nextProp, lookThrough, output, valueToCheck);
            }));
        }
        if (Array.isArray(base)) {
            base.forEach((function(key) {
                var nextBase = key;
                if (nextBase !== undefined) {
                    getWildcardPropertyInChain(nextBase, chain, lookThrough, output, valueToCheck);
                }
            }));
        }
        var nextBase = base[prop];
        chain = chain.slice(pos + 1);
        if (nextBase !== undefined) {
            getWildcardPropertyInChain(nextBase, chain, lookThrough, output, valueToCheck);
        }
        return output;
    }
    function shouldAbortInlineOrInjectedScript(stackMatch, stackTrace) {
        var INLINE_SCRIPT_STRING = "inlineScript";
        var INJECTED_SCRIPT_STRING = "injectedScript";
        var INJECTED_SCRIPT_MARKER = "<anonymous>";
        var isInlineScript = function isInlineScript(match) {
            return match.includes(INLINE_SCRIPT_STRING);
        };
        var isInjectedScript = function isInjectedScript(match) {
            return match.includes(INJECTED_SCRIPT_STRING);
        };
        if (!(isInlineScript(stackMatch) || isInjectedScript(stackMatch))) {
            return false;
        }
        var documentURL = window.location.href;
        var pos = documentURL.indexOf("#");
        if (pos !== -1) {
            documentURL = documentURL.slice(0, pos);
        }
        var stackSteps = stackTrace.split("\n").slice(2).map((function(line) {
            return line.trim();
        }));
        var stackLines = stackSteps.map((function(line) {
            var stack;
            var getStackTraceValues = /(.*?@)?(\S+)(:\d+)(:\d+)\)?$/.exec(line);
            if (getStackTraceValues) {
                var _stackURL, _stackURL2;
                var stackURL = getStackTraceValues[2];
                var stackLine = getStackTraceValues[3];
                var stackCol = getStackTraceValues[4];
                if ((_stackURL = stackURL) !== null && _stackURL !== void 0 && _stackURL.startsWith("(")) {
                    stackURL = stackURL.slice(1);
                }
                if ((_stackURL2 = stackURL) !== null && _stackURL2 !== void 0 && _stackURL2.startsWith(INJECTED_SCRIPT_MARKER)) {
                    var _stackFunction;
                    stackURL = INJECTED_SCRIPT_STRING;
                    var stackFunction = getStackTraceValues[1] !== undefined ? getStackTraceValues[1].slice(0, -1) : line.slice(0, getStackTraceValues.index).trim();
                    if ((_stackFunction = stackFunction) !== null && _stackFunction !== void 0 && _stackFunction.startsWith("at")) {
                        stackFunction = stackFunction.slice(2).trim();
                    }
                    stack = `${stackFunction} ${stackURL}${stackLine}${stackCol}`.trim();
                } else if (stackURL === documentURL) {
                    stack = `${INLINE_SCRIPT_STRING}${stackLine}${stackCol}`.trim();
                } else {
                    stack = `${stackURL}${stackLine}${stackCol}`.trim();
                }
            } else {
                stack = line;
            }
            return stack;
        }));
        if (stackLines) {
            for (var index = 0; index < stackLines.length; index += 1) {
                if (isInlineScript(stackMatch) && stackLines[index].startsWith(INLINE_SCRIPT_STRING) && stackLines[index].match(toRegExp(stackMatch))) {
                    return true;
                }
                if (isInjectedScript(stackMatch) && stackLines[index].startsWith(INJECTED_SCRIPT_STRING) && stackLines[index].match(toRegExp(stackMatch))) {
                    return true;
                }
            }
        }
        return false;
    }
    function getNativeRegexpTest() {
        var descriptor = Object.getOwnPropertyDescriptor(RegExp.prototype, "test");
        var nativeRegexTest = descriptor === null || descriptor === void 0 ? void 0 : descriptor.value;
        if (descriptor && typeof descriptor.value === "function") {
            return nativeRegexTest;
        }
        throw new Error("RegExp.prototype.test is not a function");
    }
    function backupRegExpValues() {
        try {
            var arrayOfRegexpValues = [];
            for (var index = 1; index < 10; index += 1) {
                var value = `$${index}`;
                if (!RegExp[value]) {
                    break;
                }
                arrayOfRegexpValues.push(RegExp[value]);
            }
            return arrayOfRegexpValues;
        } catch (error) {
            return [];
        }
    }
    function restoreRegExpValues(array) {
        if (!array.length) {
            return;
        }
        try {
            var stringPattern = "";
            if (array.length === 1) {
                stringPattern = `(${array[0]})`;
            } else {
                stringPattern = array.reduce((function(accumulator, currentValue, currentIndex) {
                    if (currentIndex === 1) {
                        return `(${accumulator}),(${currentValue})`;
                    }
                    return `${accumulator},(${currentValue})`;
                }));
            }
            var regExpGroup = new RegExp(stringPattern);
            array.toString().replace(regExpGroup, "");
        } catch (error) {
            var message = `Failed to restore RegExp values: ${error}`;
            console.log(message);
        }
    }
    function isKeyInObject(baseObj, path, valueToCheck) {
        var parts = path.split(".");
        var _check = function check(targetObject, pathSegments) {
            if (pathSegments.length === 0) {
                if (valueToCheck !== undefined) {
                    if (typeof targetObject === "string" && valueToCheck instanceof RegExp) {
                        return valueToCheck.test(targetObject);
                    }
                    return targetObject === valueToCheck;
                }
                return true;
            }
            var current = pathSegments[0];
            var rest = pathSegments.slice(1);
            if (current === "*" || current === "[]") {
                if (Array.isArray(targetObject)) {
                    return targetObject.some((function(item) {
                        return _check(item, rest);
                    }));
                }
                if (typeof targetObject === "object" && targetObject !== null) {
                    return Object.keys(targetObject).some((function(key) {
                        return _check(targetObject[key], rest);
                    }));
                }
            }
            if (Object.prototype.hasOwnProperty.call(targetObject, current)) {
                return _check(targetObject[current], rest);
            }
            return false;
        };
        return _check(baseObj, parts);
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        jsonPruneFetchResponse.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function jsonPruneXhrResponse(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function jsonPruneXhrResponse(source, propsToRemove, obligatoryProps) {
        var propsToMatch = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "";
        var stack = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : "";
        if (typeof Proxy === "undefined") {
            return;
        }
        var shouldLog = !propsToRemove && !obligatoryProps;
        var prunePaths = getPrunePath(propsToRemove);
        var requiredPaths = getPrunePath(obligatoryProps);
        var nativeParse = window.JSON.parse;
        var nativeStringify = window.JSON.stringify;
        var nativeOpen = window.XMLHttpRequest.prototype.open;
        var nativeSend = window.XMLHttpRequest.prototype.send;
        var setRequestHeaderWrapper = function setRequestHeaderWrapper(setRequestHeader, thisArgument, argsList) {
            thisArgument.collectedHeaders.push(argsList);
            return Reflect.apply(setRequestHeader, thisArgument, argsList);
        };
        var setRequestHeaderHandler = {
            apply: setRequestHeaderWrapper
        };
        var xhrData;
        var openWrapper = function openWrapper(target, thisArg, args) {
            xhrData = getXhrData.apply(null, args);
            if (matchRequestProps(source, propsToMatch, xhrData) || shouldLog) {
                thisArg.xhrShouldBePruned = true;
                thisArg.headersReceived = !!thisArg.headersReceived;
            }
            if (thisArg.xhrShouldBePruned && !thisArg.headersReceived) {
                thisArg.headersReceived = true;
                thisArg.collectedHeaders = [];
                thisArg.setRequestHeader = new Proxy(thisArg.setRequestHeader, setRequestHeaderHandler);
            }
            return Reflect.apply(target, thisArg, args);
        };
        var sendWrapper = function sendWrapper(target, thisArg, args) {
            var stackTrace = (new Error).stack || "";
            if (!thisArg.xhrShouldBePruned || stack && !matchStackTrace(stack, stackTrace)) {
                return Reflect.apply(target, thisArg, args);
            }
            var forgedRequest = new XMLHttpRequest;
            forgedRequest.addEventListener("readystatechange", (function() {
                if (forgedRequest.readyState !== 4) {
                    return;
                }
                var {readyState: readyState, response: response, responseText: responseText, responseURL: responseURL, responseXML: responseXML, status: status, statusText: statusText} = forgedRequest;
                var content = responseText || response;
                if (typeof content !== "string" && typeof content !== "object") {
                    return;
                }
                var modifiedContent;
                if (typeof content === "string") {
                    try {
                        var jsonContent = nativeParse(content);
                        if (shouldLog) {
                            logMessage(source, `${window.location.hostname}\n${nativeStringify(jsonContent, null, 2)}\nStack trace:\n${stackTrace}`, true);
                            logMessage(source, jsonContent, true, false);
                            modifiedContent = content;
                        } else {
                            modifiedContent = jsonPruner(source, jsonContent, prunePaths, requiredPaths, stack = "", {
                                nativeStringify: nativeStringify
                            });
                            try {
                                var {responseType: responseType} = thisArg;
                                switch (responseType) {
                                  case "":
                                  case "text":
                                    modifiedContent = nativeStringify(modifiedContent);
                                    break;

                                  case "arraybuffer":
                                    modifiedContent = (new TextEncoder).encode(nativeStringify(modifiedContent)).buffer;
                                    break;

                                  case "blob":
                                    modifiedContent = new Blob([ nativeStringify(modifiedContent) ]);
                                    break;

                                  default:
                                    break;
                                }
                            } catch (error) {
                                var message = `Response body cannot be converted to reponse type: '${content}'`;
                                logMessage(source, message);
                                modifiedContent = content;
                            }
                        }
                    } catch (error) {
                        var _message = `Response body cannot be converted to json: '${content}'`;
                        logMessage(source, _message);
                        modifiedContent = content;
                    }
                }
                Object.defineProperties(thisArg, {
                    readyState: {
                        value: readyState,
                        writable: false
                    },
                    responseURL: {
                        value: responseURL,
                        writable: false
                    },
                    responseXML: {
                        value: responseXML,
                        writable: false
                    },
                    status: {
                        value: status,
                        writable: false
                    },
                    statusText: {
                        value: statusText,
                        writable: false
                    },
                    response: {
                        value: modifiedContent,
                        writable: false
                    },
                    responseText: {
                        value: modifiedContent,
                        writable: false
                    }
                });
                setTimeout((function() {
                    var stateEvent = new Event("readystatechange");
                    thisArg.dispatchEvent(stateEvent);
                    var loadEvent = new Event("load");
                    thisArg.dispatchEvent(loadEvent);
                    var loadEndEvent = new Event("loadend");
                    thisArg.dispatchEvent(loadEndEvent);
                }), 1);
                hit(source);
            }));
            nativeOpen.apply(forgedRequest, [ xhrData.method, xhrData.url, Boolean(xhrData.async) ]);
            thisArg.collectedHeaders.forEach((function(header) {
                forgedRequest.setRequestHeader(header[0], header[1]);
            }));
            thisArg.collectedHeaders = [];
            try {
                nativeSend.call(forgedRequest, args);
            } catch (_unused) {
                return Reflect.apply(target, thisArg, args);
            }
            return undefined;
        };
        var openHandler = {
            apply: openWrapper
        };
        var sendHandler = {
            apply: sendWrapper
        };
        XMLHttpRequest.prototype.open = new Proxy(XMLHttpRequest.prototype.open, openHandler);
        XMLHttpRequest.prototype.send = new Proxy(XMLHttpRequest.prototype.send, sendHandler);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function jsonPruner(source, root, prunePaths, requiredPaths, stack, nativeObjects) {
        var {nativeStringify: nativeStringify} = nativeObjects;
        if (prunePaths.length === 0 && requiredPaths.length === 0) {
            logMessage(source, `${window.location.hostname}\n${nativeStringify(root, null, 2)}\nStack trace:\n${(new Error).stack}`, true);
            if (root && typeof root === "object") {
                logMessage(source, root, true, false);
            }
            return root;
        }
        try {
            if (isPruningNeeded(source, root, prunePaths, requiredPaths, stack, nativeObjects) === false) {
                return root;
            }
            prunePaths.forEach((function(path) {
                var pathToCheck = path.path;
                var valueToCheck = path.value;
                var ownerObjArr = getWildcardPropertyInChain(root, pathToCheck, true, [], valueToCheck);
                for (var i = ownerObjArr.length - 1; i >= 0; i -= 1) {
                    var ownerObj = ownerObjArr[i];
                    if (ownerObj === undefined || !ownerObj.base) {
                        continue;
                    }
                    hit(source);
                    if (!Array.isArray(ownerObj.base)) {
                        delete ownerObj.base[ownerObj.prop];
                        continue;
                    }
                    try {
                        var index = Number(ownerObj.prop);
                        if (Number.isNaN(index)) {
                            continue;
                        }
                        ownerObj.base.splice(index, 1);
                    } catch (error) {
                        console.error("Error while deleting array element", error);
                    }
                }
            }));
        } catch (e) {
            logMessage(source, e);
        }
        return root;
    }
    function getPrunePath(props) {
        var VALUE_MARKER = ".[=].";
        var REGEXP_START_MARKER = "/";
        var validPropsString = typeof props === "string" && props !== undefined && props !== "";
        if (validPropsString) {
            var splitRegexp = /(?<!\.\[=\]\.\/(?:[^/]|\\.)*)\s+/;
            var parts = props.split(splitRegexp).map((function(part) {
                var splitPart = part.split(VALUE_MARKER);
                var path = splitPart[0];
                var value = splitPart[1];
                if (value !== undefined) {
                    if (value === "true") {
                        value = true;
                    } else if (value === "false") {
                        value = false;
                    } else if (value.startsWith(REGEXP_START_MARKER)) {
                        value = toRegExp(value);
                    } else if (typeof value === "string" && /^\d+$/.test(value)) {
                        value = parseFloat(value);
                    }
                    return {
                        path: path,
                        value: value
                    };
                }
                return {
                    path: path
                };
            }));
            return parts;
        }
        return [];
    }
    function matchRequestProps(source, propsToMatch, requestData) {
        if (propsToMatch === "" || propsToMatch === "*") {
            return true;
        }
        var isMatched;
        var parsedData = parseMatchProps(propsToMatch);
        if (!isValidParsedData(parsedData)) {
            logMessage(source, `Invalid parameter: ${propsToMatch}`);
            isMatched = false;
        } else {
            var matchData = getMatchPropsData(parsedData);
            var matchKeys = Object.keys(matchData);
            isMatched = matchKeys.every((function(matchKey) {
                var matchValue = matchData[matchKey];
                var dataValue = requestData[matchKey];
                return Object.prototype.hasOwnProperty.call(requestData, matchKey) && typeof dataValue === "string" && (matchValue === null || matchValue === void 0 ? void 0 : matchValue.test(dataValue));
            }));
        }
        return isMatched;
    }
    function getXhrData(method, url, async, user, password) {
        return {
            method: method,
            url: url,
            async: async,
            user: user,
            password: password
        };
    }
    function isPruningNeeded(source, root, prunePaths, requiredPaths, stack, nativeObjects) {
        if (!root) {
            return false;
        }
        var {nativeStringify: nativeStringify} = nativeObjects;
        var shouldProcess;
        var prunePathsToCheck = prunePaths.map((function(obj) {
            return obj.path;
        }));
        var requiredPathsToCheck = requiredPaths.map((function(obj) {
            return obj.path;
        }));
        if (prunePathsToCheck.length === 0 && requiredPathsToCheck.length > 0) {
            var rootString = nativeStringify(root);
            var matchRegex = toRegExp(requiredPathsToCheck.join(""));
            var shouldLog = matchRegex.test(rootString);
            if (shouldLog) {
                logMessage(source, `${window.location.hostname}\n${nativeStringify(root, null, 2)}\nStack trace:\n${(new Error).stack}`, true);
                if (root && typeof root === "object") {
                    logMessage(source, root, true, false);
                }
                shouldProcess = false;
                return shouldProcess;
            }
        }
        if (stack && !matchStackTrace(stack, (new Error).stack || "")) {
            shouldProcess = false;
            return shouldProcess;
        }
        var wildcardSymbols = [ ".*.", "*.", ".*", ".[].", "[].", ".[]" ];
        var _loop = function _loop() {
            var requiredPath = requiredPathsToCheck[i];
            var lastNestedPropName = requiredPath.split(".").pop();
            var hasWildcard = wildcardSymbols.some((function(symbol) {
                return requiredPath.includes(symbol);
            }));
            var details = getWildcardPropertyInChain(root, requiredPath, hasWildcard);
            if (!details.length) {
                shouldProcess = false;
                return {
                    v: shouldProcess
                };
            }
            shouldProcess = !hasWildcard;
            for (var j = 0; j < details.length; j += 1) {
                var hasRequiredProp = typeof lastNestedPropName === "string" && details[j].base[lastNestedPropName] !== undefined;
                if (hasWildcard) {
                    shouldProcess = hasRequiredProp || shouldProcess;
                } else {
                    shouldProcess = hasRequiredProp && shouldProcess;
                }
            }
        }, _ret;
        for (var i = 0; i < requiredPathsToCheck.length; i += 1) {
            _ret = _loop();
            if (_ret) return _ret.v;
        }
        return shouldProcess;
    }
    function matchStackTrace(stackMatch, stackTrace) {
        if (!stackMatch || stackMatch === "") {
            return true;
        }
        var regExpValues = backupRegExpValues();
        if (shouldAbortInlineOrInjectedScript(stackMatch, stackTrace)) {
            if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
                restoreRegExpValues(regExpValues);
            }
            return true;
        }
        var stackRegexp = toRegExp(stackMatch);
        var refinedStackTrace = stackTrace.split("\n").slice(2).map((function(line) {
            return line.trim();
        })).join("\n");
        if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
            restoreRegExpValues(regExpValues);
        }
        return getNativeRegexpTest().call(stackRegexp, refinedStackTrace);
    }
    function getMatchPropsData(data) {
        var matchData = {};
        var dataKeys = Object.keys(data);
        dataKeys.forEach((function(key) {
            matchData[key] = toRegExp(data[key]);
        }));
        return matchData;
    }
    function getRequestProps() {
        return [ "url", "method", "headers", "body", "credentials", "cache", "redirect", "referrer", "referrerPolicy", "integrity", "keepalive", "signal", "mode" ];
    }
    function isValidParsedData(data) {
        return Object.values(data).every((function(value) {
            return isValidStrPattern(value);
        }));
    }
    function parseMatchProps(propsToMatchStr) {
        var PROPS_DIVIDER = " ";
        var PAIRS_MARKER = ":";
        var isRequestProp = function isRequestProp(prop) {
            return getRequestProps().includes(prop);
        };
        var propsObj = {};
        var props = propsToMatchStr.split(PROPS_DIVIDER);
        props.forEach((function(prop) {
            var dividerInd = prop.indexOf(PAIRS_MARKER);
            var key = prop.slice(0, dividerInd);
            if (isRequestProp(key)) {
                var value = prop.slice(dividerInd + 1);
                propsObj[key] = value;
            } else {
                propsObj.url = prop;
            }
        }));
        return propsObj;
    }
    function isValidStrPattern(input) {
        var FORWARD_SLASH = "/";
        var str = escapeRegExp(input);
        if (input[0] === FORWARD_SLASH && input[input.length - 1] === FORWARD_SLASH) {
            str = input.slice(1, -1);
        }
        var isValid;
        try {
            isValid = new RegExp(str);
            isValid = true;
        } catch (e) {
            isValid = false;
        }
        return isValid;
    }
    function escapeRegExp(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    function getWildcardPropertyInChain(base, chain) {
        var lookThrough = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var output = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
        var valueToCheck = arguments.length > 4 ? arguments[4] : undefined;
        var pos = chain.indexOf(".");
        if (pos === -1) {
            if (chain === "*" || chain === "[]") {
                for (var key in base) {
                    if (Object.prototype.hasOwnProperty.call(base, key)) {
                        if (valueToCheck !== undefined) {
                            var objectValue = base[key];
                            if (typeof objectValue === "string" && valueToCheck instanceof RegExp) {
                                if (valueToCheck.test(objectValue)) {
                                    output.push({
                                        base: base,
                                        prop: key
                                    });
                                }
                            } else if (objectValue === valueToCheck) {
                                output.push({
                                    base: base,
                                    prop: key
                                });
                            }
                        } else {
                            output.push({
                                base: base,
                                prop: key
                            });
                        }
                    }
                }
            } else if (valueToCheck !== undefined) {
                var _objectValue = base[chain];
                if (typeof _objectValue === "string" && valueToCheck instanceof RegExp) {
                    if (valueToCheck.test(_objectValue)) {
                        output.push({
                            base: base,
                            prop: chain
                        });
                    }
                } else if (base[chain] === valueToCheck) {
                    output.push({
                        base: base,
                        prop: chain
                    });
                }
            } else {
                output.push({
                    base: base,
                    prop: chain
                });
            }
            return output;
        }
        var prop = chain.slice(0, pos);
        var shouldLookThrough = prop === "[]" && Array.isArray(base) || prop === "*" && base instanceof Object || prop === "[-]" && Array.isArray(base) || prop === "{-}" && base instanceof Object;
        if (shouldLookThrough) {
            var nextProp = chain.slice(pos + 1);
            var baseKeys = Object.keys(base);
            if (prop === "{-}" || prop === "[-]") {
                var type = Array.isArray(base) ? "array" : "object";
                var shouldRemove = !!(prop === "{-}" && type === "object") || !!(prop === "[-]" && type === "array");
                if (!shouldRemove) {
                    return output;
                }
                baseKeys.forEach((function(key) {
                    var item = base[key];
                    if (isKeyInObject(item, nextProp, valueToCheck)) {
                        output.push({
                            base: base,
                            prop: key
                        });
                    }
                }));
                return output;
            }
            baseKeys.forEach((function(key) {
                var item = base[key];
                getWildcardPropertyInChain(item, nextProp, lookThrough, output, valueToCheck);
            }));
        }
        if (Array.isArray(base)) {
            base.forEach((function(key) {
                var nextBase = key;
                if (nextBase !== undefined) {
                    getWildcardPropertyInChain(nextBase, chain, lookThrough, output, valueToCheck);
                }
            }));
        }
        var nextBase = base[prop];
        chain = chain.slice(pos + 1);
        if (nextBase !== undefined) {
            getWildcardPropertyInChain(nextBase, chain, lookThrough, output, valueToCheck);
        }
        return output;
    }
    function shouldAbortInlineOrInjectedScript(stackMatch, stackTrace) {
        var INLINE_SCRIPT_STRING = "inlineScript";
        var INJECTED_SCRIPT_STRING = "injectedScript";
        var INJECTED_SCRIPT_MARKER = "<anonymous>";
        var isInlineScript = function isInlineScript(match) {
            return match.includes(INLINE_SCRIPT_STRING);
        };
        var isInjectedScript = function isInjectedScript(match) {
            return match.includes(INJECTED_SCRIPT_STRING);
        };
        if (!(isInlineScript(stackMatch) || isInjectedScript(stackMatch))) {
            return false;
        }
        var documentURL = window.location.href;
        var pos = documentURL.indexOf("#");
        if (pos !== -1) {
            documentURL = documentURL.slice(0, pos);
        }
        var stackSteps = stackTrace.split("\n").slice(2).map((function(line) {
            return line.trim();
        }));
        var stackLines = stackSteps.map((function(line) {
            var stack;
            var getStackTraceValues = /(.*?@)?(\S+)(:\d+)(:\d+)\)?$/.exec(line);
            if (getStackTraceValues) {
                var _stackURL, _stackURL2;
                var stackURL = getStackTraceValues[2];
                var stackLine = getStackTraceValues[3];
                var stackCol = getStackTraceValues[4];
                if ((_stackURL = stackURL) !== null && _stackURL !== void 0 && _stackURL.startsWith("(")) {
                    stackURL = stackURL.slice(1);
                }
                if ((_stackURL2 = stackURL) !== null && _stackURL2 !== void 0 && _stackURL2.startsWith(INJECTED_SCRIPT_MARKER)) {
                    var _stackFunction;
                    stackURL = INJECTED_SCRIPT_STRING;
                    var stackFunction = getStackTraceValues[1] !== undefined ? getStackTraceValues[1].slice(0, -1) : line.slice(0, getStackTraceValues.index).trim();
                    if ((_stackFunction = stackFunction) !== null && _stackFunction !== void 0 && _stackFunction.startsWith("at")) {
                        stackFunction = stackFunction.slice(2).trim();
                    }
                    stack = `${stackFunction} ${stackURL}${stackLine}${stackCol}`.trim();
                } else if (stackURL === documentURL) {
                    stack = `${INLINE_SCRIPT_STRING}${stackLine}${stackCol}`.trim();
                } else {
                    stack = `${stackURL}${stackLine}${stackCol}`.trim();
                }
            } else {
                stack = line;
            }
            return stack;
        }));
        if (stackLines) {
            for (var index = 0; index < stackLines.length; index += 1) {
                if (isInlineScript(stackMatch) && stackLines[index].startsWith(INLINE_SCRIPT_STRING) && stackLines[index].match(toRegExp(stackMatch))) {
                    return true;
                }
                if (isInjectedScript(stackMatch) && stackLines[index].startsWith(INJECTED_SCRIPT_STRING) && stackLines[index].match(toRegExp(stackMatch))) {
                    return true;
                }
            }
        }
        return false;
    }
    function getNativeRegexpTest() {
        var descriptor = Object.getOwnPropertyDescriptor(RegExp.prototype, "test");
        var nativeRegexTest = descriptor === null || descriptor === void 0 ? void 0 : descriptor.value;
        if (descriptor && typeof descriptor.value === "function") {
            return nativeRegexTest;
        }
        throw new Error("RegExp.prototype.test is not a function");
    }
    function backupRegExpValues() {
        try {
            var arrayOfRegexpValues = [];
            for (var index = 1; index < 10; index += 1) {
                var value = `$${index}`;
                if (!RegExp[value]) {
                    break;
                }
                arrayOfRegexpValues.push(RegExp[value]);
            }
            return arrayOfRegexpValues;
        } catch (error) {
            return [];
        }
    }
    function restoreRegExpValues(array) {
        if (!array.length) {
            return;
        }
        try {
            var stringPattern = "";
            if (array.length === 1) {
                stringPattern = `(${array[0]})`;
            } else {
                stringPattern = array.reduce((function(accumulator, currentValue, currentIndex) {
                    if (currentIndex === 1) {
                        return `(${accumulator}),(${currentValue})`;
                    }
                    return `${accumulator},(${currentValue})`;
                }));
            }
            var regExpGroup = new RegExp(stringPattern);
            array.toString().replace(regExpGroup, "");
        } catch (error) {
            var message = `Failed to restore RegExp values: ${error}`;
            console.log(message);
        }
    }
    function isKeyInObject(baseObj, path, valueToCheck) {
        var parts = path.split(".");
        var _check = function check(targetObject, pathSegments) {
            if (pathSegments.length === 0) {
                if (valueToCheck !== undefined) {
                    if (typeof targetObject === "string" && valueToCheck instanceof RegExp) {
                        return valueToCheck.test(targetObject);
                    }
                    return targetObject === valueToCheck;
                }
                return true;
            }
            var current = pathSegments[0];
            var rest = pathSegments.slice(1);
            if (current === "*" || current === "[]") {
                if (Array.isArray(targetObject)) {
                    return targetObject.some((function(item) {
                        return _check(item, rest);
                    }));
                }
                if (typeof targetObject === "object" && targetObject !== null) {
                    return Object.keys(targetObject).some((function(key) {
                        return _check(targetObject[key], rest);
                    }));
                }
            }
            if (Object.prototype.hasOwnProperty.call(targetObject, current)) {
                return _check(targetObject[current], rest);
            }
            return false;
        };
        return _check(baseObj, parts);
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        jsonPruneXhrResponse.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function log(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function log() {
        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
        }
        console.log(args);
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        log.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function logAddEventListener(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function logAddEventListener(source) {
        var nativeAddEventListener = window.EventTarget.prototype.addEventListener;
        function addEventListenerWrapper(type, listener) {
            var _this$constructor;
            if (validateType(type) && validateListener(listener)) {
                var message = `addEventListener("${type}", ${listenerToString(listener)})`;
                logMessage(source, message, true);
                hit(source);
            } else {
                var _message = `Invalid event type or listener passed to addEventListener:\n        type: ${convertTypeToString(type)}\n        listener: ${convertTypeToString(listener)}`;
                logMessage(source, _message, true);
            }
            var context = this;
            if (this && ((_this$constructor = this.constructor) === null || _this$constructor === void 0 ? void 0 : _this$constructor.name) === "Window" && this !== window) {
                context = window;
            }
            for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
                args[_key - 2] = arguments[_key];
            }
            return nativeAddEventListener.apply(context, [ type, listener, ...args ]);
        }
        var descriptor = {
            configurable: true,
            set: function set() {},
            get: function get() {
                return addEventListenerWrapper;
            }
        };
        Object.defineProperty(window.EventTarget.prototype, "addEventListener", descriptor);
        Object.defineProperty(window, "addEventListener", descriptor);
        Object.defineProperty(document, "addEventListener", descriptor);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function validateType(type) {
        return typeof type !== "undefined";
    }
    function validateListener(listener) {
        return typeof listener !== "undefined" && (typeof listener === "function" || typeof listener === "object" && listener !== null && "handleEvent" in listener && typeof listener.handleEvent === "function");
    }
    function listenerToString(listener) {
        return typeof listener === "function" ? listener.toString() : listener.handleEvent.toString();
    }
    function convertTypeToString(value) {
        var output;
        if (typeof value === "undefined") {
            output = "undefined";
        } else if (typeof value === "object") {
            if (value === null) {
                output = "null";
            } else {
                output = objectToString(value);
            }
        } else {
            output = String(value);
        }
        return output;
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function objectToString(obj) {
        if (!obj || typeof obj !== "object") {
            return String(obj);
        }
        if (isEmptyObject(obj)) {
            return "{}";
        }
        return Object.entries(obj).map((function(pair) {
            var key = pair[0];
            var value = pair[1];
            var recordValueStr = value;
            if (value instanceof Object) {
                recordValueStr = `{ ${objectToString(value)} }`;
            }
            return `${key}:"${recordValueStr}"`;
        })).join(" ");
    }
    function isEmptyObject(obj) {
        return Object.keys(obj).length === 0 && !obj.prototype;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        logAddEventListener.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function logEval(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function logEval(source) {
        var nativeEval = window.eval;
        function evalWrapper(str) {
            hit(source);
            logMessage(source, `eval("${str}")`, true);
            return nativeEval(str);
        }
        window.eval = evalWrapper;
        var nativeFunction = window.Function;
        function FunctionWrapper() {
            hit(source);
            for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                args[_key] = arguments[_key];
            }
            logMessage(source, `new Function(${args.join(", ")})`, true);
            return nativeFunction.apply(this, [ ...args ]);
        }
        FunctionWrapper.prototype = Object.create(nativeFunction.prototype);
        FunctionWrapper.prototype.constructor = FunctionWrapper;
        window.Function = FunctionWrapper;
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        logEval.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function logOnStackTrace(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function logOnStackTrace(source, property) {
        if (!property) {
            return;
        }
        var refineStackTrace = function refineStackTrace(stackString) {
            var regExpValues = backupRegExpValues();
            var stackSteps = stackString.split("\n").slice(2).map((function(line) {
                return line.replace(/ {4}at /, "");
            }));
            var logInfoArray = stackSteps.map((function(line) {
                var funcName;
                var funcFullPath;
                var reg = /\(([^\)]+)\)/;
                var regFirefox = /(.*?@)(\S+)(:\d+):\d+\)?$/;
                if (line.match(reg)) {
                    funcName = line.split(" ").slice(0, -1).join(" ");
                    funcFullPath = line.match(reg)[1];
                } else if (line.match(regFirefox)) {
                    funcName = line.split("@").slice(0, -1).join(" ");
                    funcFullPath = line.match(regFirefox)[2];
                } else {
                    funcName = "function name is not available";
                    funcFullPath = line;
                }
                return [ funcName, funcFullPath ];
            }));
            var logInfoObject = {};
            logInfoArray.forEach((function(pair) {
                logInfoObject[pair[0]] = pair[1];
            }));
            if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
                restoreRegExpValues(regExpValues);
            }
            return logInfoObject;
        };
        var _setChainPropAccess = function setChainPropAccess(owner, property) {
            var chainInfo = getPropertyInChain(owner, property);
            var {base: base} = chainInfo;
            var {prop: prop, chain: chain} = chainInfo;
            if (chain) {
                var setter = function setter(a) {
                    base = a;
                    if (a instanceof Object) {
                        _setChainPropAccess(a, chain);
                    }
                };
                Object.defineProperty(owner, prop, {
                    get: function get() {
                        return base;
                    },
                    set: setter
                });
                return;
            }
            var value = base[prop];
            setPropertyAccess(base, prop, {
                get() {
                    hit(source);
                    logMessage(source, `Get ${prop}`, true);
                    console.table(refineStackTrace((new Error).stack));
                    return value;
                },
                set(newValue) {
                    hit(source);
                    logMessage(source, `Set ${prop}`, true);
                    console.table(refineStackTrace((new Error).stack));
                    value = newValue;
                }
            });
        };
        _setChainPropAccess(window, property);
    }
    function getPropertyInChain(base, chain) {
        var pos = chain.indexOf(".");
        if (pos === -1) {
            return {
                base: base,
                prop: chain
            };
        }
        var prop = chain.slice(0, pos);
        if (base === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        var nextBase = base[prop];
        chain = chain.slice(pos + 1);
        if ((base instanceof Object || typeof base === "object") && isEmptyObject(base)) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase !== undefined) {
            return getPropertyInChain(nextBase, chain);
        }
        Object.defineProperty(base, prop, {
            configurable: true
        });
        return {
            base: base,
            prop: prop,
            chain: chain
        };
    }
    function setPropertyAccess(object, property, descriptor) {
        var currentDescriptor = Object.getOwnPropertyDescriptor(object, property);
        if (currentDescriptor && !currentDescriptor.configurable) {
            return false;
        }
        Object.defineProperty(object, property, descriptor);
        return true;
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function isEmptyObject(obj) {
        return Object.keys(obj).length === 0 && !obj.prototype;
    }
    function backupRegExpValues() {
        try {
            var arrayOfRegexpValues = [];
            for (var index = 1; index < 10; index += 1) {
                var value = `$${index}`;
                if (!RegExp[value]) {
                    break;
                }
                arrayOfRegexpValues.push(RegExp[value]);
            }
            return arrayOfRegexpValues;
        } catch (error) {
            return [];
        }
    }
    function restoreRegExpValues(array) {
        if (!array.length) {
            return;
        }
        try {
            var stringPattern = "";
            if (array.length === 1) {
                stringPattern = `(${array[0]})`;
            } else {
                stringPattern = array.reduce((function(accumulator, currentValue, currentIndex) {
                    if (currentIndex === 1) {
                        return `(${accumulator}),(${currentValue})`;
                    }
                    return `${accumulator},(${currentValue})`;
                }));
            }
            var regExpGroup = new RegExp(stringPattern);
            array.toString().replace(regExpGroup, "");
        } catch (error) {
            var message = `Failed to restore RegExp values: ${error}`;
            console.log(message);
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        logOnStackTrace.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function m3uPrune(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function m3uPrune(source, propsToRemove) {
        var urlToMatch = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
        var verbose = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
        if (typeof Reflect === "undefined" || typeof fetch === "undefined" || typeof Proxy === "undefined" || typeof Response === "undefined") {
            return;
        }
        var shouldPruneResponse = false;
        var shouldLogContent = verbose === "true";
        var urlMatchRegexp = toRegExp(urlToMatch);
        var SEGMENT_MARKER = "#";
        var AD_MARKER = {
            ASSET: "#EXT-X-ASSET:",
            CUE: "#EXT-X-CUE:",
            CUE_IN: "#EXT-X-CUE-IN",
            DISCONTINUITY: "#EXT-X-DISCONTINUITY",
            EXTINF: "#EXTINF",
            EXTM3U: "#EXTM3U",
            SCTE35: "#EXT-X-SCTE35:"
        };
        var COMCAST_AD_MARKER = {
            AD: "-AD-",
            VAST: "-VAST-",
            VMAP_AD: "-VMAP-AD-",
            VMAP_AD_BREAK: "#EXT-X-VMAP-AD-BREAK:"
        };
        var TAGS_ALLOWLIST = [ "#EXT-X-TARGETDURATION", "#EXT-X-MEDIA-SEQUENCE", "#EXT-X-DISCONTINUITY-SEQUENCE", "#EXT-X-ENDLIST", "#EXT-X-PLAYLIST-TYPE", "#EXT-X-I-FRAMES-ONLY", "#EXT-X-MEDIA", "#EXT-X-STREAM-INF", "#EXT-X-I-FRAME-STREAM-INF", "#EXT-X-SESSION-DATA", "#EXT-X-SESSION-KEY", "#EXT-X-INDEPENDENT-SEGMENTS", "#EXT-X-START" ];
        var isAllowedTag = function isAllowedTag(str) {
            return TAGS_ALLOWLIST.some((function(el) {
                return str.startsWith(el);
            }));
        };
        var _pruneExtinfFromVmapBlock = function pruneExtinfFromVmapBlock(lines, i) {
            var array = lines.slice();
            var index = i;
            if (array[index].includes(AD_MARKER.EXTINF)) {
                array[index] = undefined;
                index += 1;
                if (array[index].includes(AD_MARKER.DISCONTINUITY)) {
                    array[index] = undefined;
                    index += 1;
                    var prunedExtinf = _pruneExtinfFromVmapBlock(array, index);
                    array = prunedExtinf.array;
                    index = prunedExtinf.index;
                }
            }
            return {
                array: array,
                index: index
            };
        };
        var pruneVmapBlock = function pruneVmapBlock(lines) {
            var array = lines.slice();
            for (var i = 0; i < array.length - 1; i += 1) {
                if (array[i].includes(COMCAST_AD_MARKER.VMAP_AD) || array[i].includes(COMCAST_AD_MARKER.VAST) || array[i].includes(COMCAST_AD_MARKER.AD)) {
                    array[i] = undefined;
                    if (array[i + 1].includes(AD_MARKER.EXTINF)) {
                        i += 1;
                        var prunedExtinf = _pruneExtinfFromVmapBlock(array, i);
                        array = prunedExtinf.array;
                        i = prunedExtinf.index - 1;
                    }
                }
            }
            return array;
        };
        var pruneSpliceoutBlock = function pruneSpliceoutBlock(line, index, array) {
            if (!line.startsWith(AD_MARKER.CUE)) {
                return line;
            }
            line = undefined;
            index += 1;
            if (array[index].startsWith(AD_MARKER.ASSET)) {
                array[index] = undefined;
                index += 1;
            }
            if (array[index].startsWith(AD_MARKER.SCTE35)) {
                array[index] = undefined;
                index += 1;
            }
            if (array[index].startsWith(AD_MARKER.CUE_IN)) {
                array[index] = undefined;
                index += 1;
            }
            if (array[index].startsWith(AD_MARKER.SCTE35)) {
                array[index] = undefined;
            }
            return line;
        };
        var removeM3ULineRegexp = toRegExp(propsToRemove);
        var pruneInfBlock = function pruneInfBlock(line, index, array) {
            if (!line.startsWith(AD_MARKER.EXTINF)) {
                return line;
            }
            if (!removeM3ULineRegexp.test(array[index + 1])) {
                return line;
            }
            if (!isAllowedTag(array[index])) {
                array[index] = undefined;
            }
            index += 1;
            if (!isAllowedTag(array[index])) {
                array[index] = undefined;
            }
            index += 1;
            if (array[index].startsWith(AD_MARKER.DISCONTINUITY)) {
                array[index] = undefined;
            }
            return line;
        };
        var pruneSegments = function pruneSegments(lines) {
            for (var i = 0; i < lines.length - 1; i += 1) {
                var _lines$i;
                if ((_lines$i = lines[i]) !== null && _lines$i !== void 0 && _lines$i.startsWith(SEGMENT_MARKER) && removeM3ULineRegexp.test(lines[i])) {
                    var segmentName = lines[i].substring(0, lines[i].indexOf(":"));
                    if (!segmentName) {
                        return lines;
                    }
                    lines[i] = undefined;
                    i += 1;
                    for (var j = i; j < lines.length; j += 1) {
                        if (!lines[j].includes(segmentName) && !isAllowedTag(lines[j])) {
                            lines[j] = undefined;
                        } else {
                            i = j - 1;
                            break;
                        }
                    }
                }
            }
            return lines;
        };
        var isM3U = function isM3U(text) {
            if (typeof text === "string") {
                var trimmedText = text.trim();
                return trimmedText.startsWith(AD_MARKER.EXTM3U) || trimmedText.startsWith(COMCAST_AD_MARKER.VMAP_AD_BREAK);
            }
            return false;
        };
        var isPruningNeeded = function isPruningNeeded(text, regexp) {
            return isM3U(text) && regexp.test(text);
        };
        var pruneM3U = function pruneM3U(text) {
            if (shouldLogContent) {
                logMessage(source, `Original M3U content:\n${text}`);
            }
            var lines = text.split(/\r?\n/);
            if (text.includes(COMCAST_AD_MARKER.VMAP_AD_BREAK)) {
                lines = pruneVmapBlock(lines);
                lines = lines.filter((function(l) {
                    return !!l;
                })).join("\n");
                if (shouldLogContent) {
                    logMessage(source, `Modified M3U content:\n${lines}`);
                }
                return lines;
            }
            lines = pruneSegments(lines);
            lines = lines.map((function(line, index, array) {
                if (typeof line === "undefined") {
                    return line;
                }
                line = pruneSpliceoutBlock(line, index, array);
                if (typeof line !== "undefined") {
                    line = pruneInfBlock(line, index, array);
                }
                return line;
            })).filter((function(l) {
                return !!l;
            })).join("\n");
            if (shouldLogContent) {
                logMessage(source, `Modified M3U content:\n${lines}`);
            }
            return lines;
        };
        var nativeOpen = window.XMLHttpRequest.prototype.open;
        var nativeSend = window.XMLHttpRequest.prototype.send;
        var xhrData;
        var openWrapper = function openWrapper(target, thisArg, args) {
            xhrData = getXhrData.apply(null, args);
            if (matchRequestProps(source, urlToMatch, xhrData)) {
                thisArg.shouldBePruned = true;
            }
            if (thisArg.shouldBePruned) {
                thisArg.collectedHeaders = [];
                var setRequestHeaderWrapper = function setRequestHeaderWrapper(target, thisArg, args) {
                    thisArg.collectedHeaders.push(args);
                    return Reflect.apply(target, thisArg, args);
                };
                var setRequestHeaderHandler = {
                    apply: setRequestHeaderWrapper
                };
                thisArg.setRequestHeader = new Proxy(thisArg.setRequestHeader, setRequestHeaderHandler);
            }
            return Reflect.apply(target, thisArg, args);
        };
        var sendWrapper = function sendWrapper(target, thisArg, args) {
            var allowedResponseTypeValues = [ "", "text" ];
            if (!thisArg.shouldBePruned || !allowedResponseTypeValues.includes(thisArg.responseType)) {
                return Reflect.apply(target, thisArg, args);
            }
            var forgedRequest = new XMLHttpRequest;
            forgedRequest.addEventListener("readystatechange", (function() {
                if (forgedRequest.readyState !== 4) {
                    return;
                }
                var {readyState: readyState, response: response, responseText: responseText, responseURL: responseURL, responseXML: responseXML, status: status, statusText: statusText} = forgedRequest;
                var content = responseText || response;
                if (typeof content !== "string") {
                    return;
                }
                if (!propsToRemove) {
                    if (isM3U(response)) {
                        var message = `XMLHttpRequest.open() URL: ${responseURL}\nresponse: ${response}`;
                        logMessage(source, message);
                    }
                } else {
                    shouldPruneResponse = isPruningNeeded(response, removeM3ULineRegexp);
                }
                var responseContent = shouldPruneResponse ? pruneM3U(response) : response;
                Object.defineProperties(thisArg, {
                    readyState: {
                        value: readyState,
                        writable: false
                    },
                    responseURL: {
                        value: responseURL,
                        writable: false
                    },
                    responseXML: {
                        value: responseXML,
                        writable: false
                    },
                    status: {
                        value: status,
                        writable: false
                    },
                    statusText: {
                        value: statusText,
                        writable: false
                    },
                    response: {
                        value: responseContent,
                        writable: false
                    },
                    responseText: {
                        value: responseContent,
                        writable: false
                    }
                });
                setTimeout((function() {
                    var stateEvent = new Event("readystatechange");
                    thisArg.dispatchEvent(stateEvent);
                    var loadEvent = new Event("load");
                    thisArg.dispatchEvent(loadEvent);
                    var loadEndEvent = new Event("loadend");
                    thisArg.dispatchEvent(loadEndEvent);
                }), 1);
                hit(source);
            }));
            nativeOpen.apply(forgedRequest, [ xhrData.method, xhrData.url ]);
            thisArg.collectedHeaders.forEach((function(header) {
                var name = header[0];
                var value = header[1];
                forgedRequest.setRequestHeader(name, value);
            }));
            thisArg.collectedHeaders = [];
            try {
                nativeSend.call(forgedRequest, args);
            } catch (_unused) {
                return Reflect.apply(target, thisArg, args);
            }
            return undefined;
        };
        var openHandler = {
            apply: openWrapper
        };
        var sendHandler = {
            apply: sendWrapper
        };
        XMLHttpRequest.prototype.open = new Proxy(XMLHttpRequest.prototype.open, openHandler);
        XMLHttpRequest.prototype.send = new Proxy(XMLHttpRequest.prototype.send, sendHandler);
        var nativeFetch = window.fetch;
        var fetchWrapper = async function fetchWrapper(target, thisArg, args) {
            var fetchURL = args[0] instanceof Request ? args[0].url : args[0];
            if (typeof fetchURL !== "string" || fetchURL.length === 0) {
                return Reflect.apply(target, thisArg, args);
            }
            if (urlMatchRegexp.test(fetchURL)) {
                var response = await nativeFetch(...args);
                var clonedResponse = response.clone();
                var responseText = await response.text();
                if (!propsToRemove && isM3U(responseText)) {
                    var message = `fetch URL: ${fetchURL}\nresponse text: ${responseText}`;
                    logMessage(source, message);
                    return clonedResponse;
                }
                if (isPruningNeeded(responseText, removeM3ULineRegexp)) {
                    var prunedText = pruneM3U(responseText);
                    hit(source);
                    return new Response(prunedText, {
                        status: response.status,
                        statusText: response.statusText,
                        headers: response.headers
                    });
                }
                return clonedResponse;
            }
            return Reflect.apply(target, thisArg, args);
        };
        var fetchHandler = {
            apply: fetchWrapper
        };
        window.fetch = new Proxy(window.fetch, fetchHandler);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function getXhrData(method, url, async, user, password) {
        return {
            method: method,
            url: url,
            async: async,
            user: user,
            password: password
        };
    }
    function matchRequestProps(source, propsToMatch, requestData) {
        if (propsToMatch === "" || propsToMatch === "*") {
            return true;
        }
        var isMatched;
        var parsedData = parseMatchProps(propsToMatch);
        if (!isValidParsedData(parsedData)) {
            logMessage(source, `Invalid parameter: ${propsToMatch}`);
            isMatched = false;
        } else {
            var matchData = getMatchPropsData(parsedData);
            var matchKeys = Object.keys(matchData);
            isMatched = matchKeys.every((function(matchKey) {
                var matchValue = matchData[matchKey];
                var dataValue = requestData[matchKey];
                return Object.prototype.hasOwnProperty.call(requestData, matchKey) && typeof dataValue === "string" && (matchValue === null || matchValue === void 0 ? void 0 : matchValue.test(dataValue));
            }));
        }
        return isMatched;
    }
    function getMatchPropsData(data) {
        var matchData = {};
        var dataKeys = Object.keys(data);
        dataKeys.forEach((function(key) {
            matchData[key] = toRegExp(data[key]);
        }));
        return matchData;
    }
    function getRequestProps() {
        return [ "url", "method", "headers", "body", "credentials", "cache", "redirect", "referrer", "referrerPolicy", "integrity", "keepalive", "signal", "mode" ];
    }
    function isValidParsedData(data) {
        return Object.values(data).every((function(value) {
            return isValidStrPattern(value);
        }));
    }
    function parseMatchProps(propsToMatchStr) {
        var PROPS_DIVIDER = " ";
        var PAIRS_MARKER = ":";
        var isRequestProp = function isRequestProp(prop) {
            return getRequestProps().includes(prop);
        };
        var propsObj = {};
        var props = propsToMatchStr.split(PROPS_DIVIDER);
        props.forEach((function(prop) {
            var dividerInd = prop.indexOf(PAIRS_MARKER);
            var key = prop.slice(0, dividerInd);
            if (isRequestProp(key)) {
                var value = prop.slice(dividerInd + 1);
                propsObj[key] = value;
            } else {
                propsObj.url = prop;
            }
        }));
        return propsObj;
    }
    function isValidStrPattern(input) {
        var FORWARD_SLASH = "/";
        var str = escapeRegExp(input);
        if (input[0] === FORWARD_SLASH && input[input.length - 1] === FORWARD_SLASH) {
            str = input.slice(1, -1);
        }
        var isValid;
        try {
            isValid = new RegExp(str);
            isValid = true;
        } catch (e) {
            isValid = false;
        }
        return isValid;
    }
    function escapeRegExp(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        m3uPrune.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function metrikaYandexTag(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function metrikaYandexTag(source) {
        var asyncCallbackFromOptions = function asyncCallbackFromOptions(id, param) {
            var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
            var {callback: callback} = options;
            var {ctx: ctx} = options;
            if (typeof callback === "function") {
                callback = ctx !== undefined ? callback.bind(ctx) : callback;
                setTimeout((function() {
                    return callback();
                }));
            }
        };
        var addFileExtension = noopFunc;
        var extLink = asyncCallbackFromOptions;
        var file = asyncCallbackFromOptions;
        var getClientID = function getClientID(id, cb) {
            if (!cb) {
                return;
            }
            setTimeout(cb(null));
        };
        var hitFunc = asyncCallbackFromOptions;
        var notBounce = asyncCallbackFromOptions;
        var params = noopFunc;
        var reachGoal = function reachGoal(id, target, params, callback, ctx) {
            asyncCallbackFromOptions(null, null, {
                callback: callback,
                ctx: ctx
            });
        };
        var setUserID = noopFunc;
        var userParams = noopFunc;
        var destruct = noopFunc;
        var api = {
            addFileExtension: addFileExtension,
            extLink: extLink,
            file: file,
            getClientID: getClientID,
            hit: hitFunc,
            notBounce: notBounce,
            params: params,
            reachGoal: reachGoal,
            setUserID: setUserID,
            userParams: userParams,
            destruct: destruct
        };
        function init(id) {
            window[`yaCounter${id}`] = api;
            document.dispatchEvent(new Event(`yacounter${id}inited`));
        }
        function ym(id, funcName) {
            if (funcName === "init") {
                return init(id);
            }
            for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
                args[_key - 2] = arguments[_key];
            }
            return api[funcName] && api[funcName](id, ...args);
        }
        if (typeof window.ym === "undefined") {
            window.ym = ym;
            ym.a = [];
        } else if (window.ym && window.ym.a) {
            ym.a = window.ym.a;
            window.ym = ym;
            window.ym.a.forEach((function(params) {
                var id = params[0];
                init(id);
            }));
        }
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopFunc() {}
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        metrikaYandexTag.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function metrikaYandexWatch(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function metrikaYandexWatch(source) {
        var cbName = "yandex_metrika_callbacks";
        var asyncCallbackFromOptions = function asyncCallbackFromOptions() {
            var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
            var {callback: callback} = options;
            var {ctx: ctx} = options;
            if (typeof callback === "function") {
                callback = ctx !== undefined ? callback.bind(ctx) : callback;
                setTimeout((function() {
                    return callback();
                }));
            }
        };
        function Metrika() {}
        Metrika.counters = noopArray;
        Metrika.prototype.addFileExtension = noopFunc;
        Metrika.prototype.getClientID = noopFunc;
        Metrika.prototype.setUserID = noopFunc;
        Metrika.prototype.userParams = noopFunc;
        Metrika.prototype.params = noopFunc;
        Metrika.prototype.counters = noopArray;
        Metrika.prototype.extLink = function(url, options) {
            asyncCallbackFromOptions(options);
        };
        Metrika.prototype.file = function(url, options) {
            asyncCallbackFromOptions(options);
        };
        Metrika.prototype.hit = function(url, options) {
            asyncCallbackFromOptions(options);
        };
        Metrika.prototype.reachGoal = function(target, params, cb, ctx) {
            asyncCallbackFromOptions({
                callback: cb,
                ctx: ctx
            });
        };
        Metrika.prototype.notBounce = asyncCallbackFromOptions;
        if (window.Ya) {
            window.Ya.Metrika = Metrika;
        } else {
            window.Ya = {
                Metrika: Metrika
            };
        }
        if (window[cbName] && Array.isArray(window[cbName])) {
            window[cbName].forEach((function(func) {
                if (typeof func === "function") {
                    func();
                }
            }));
        }
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopFunc() {}
    function noopArray() {
        return [];
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        metrikaYandexWatch.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function noProtectedAudience(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function noProtectedAudience(source) {
        if (Document instanceof Object === false) {
            return;
        }
        var protectedAudienceMethods = {
            joinAdInterestGroup: noopResolveVoid,
            runAdAuction: noopResolveNull,
            leaveAdInterestGroup: noopResolveVoid,
            clearOriginJoinedAdInterestGroups: noopResolveVoid,
            createAuctionNonce: noopStr,
            updateAdInterestGroups: noopFunc
        };
        for (var _i = 0, _Object$keys = Object.keys(protectedAudienceMethods); _i < _Object$keys.length; _i++) {
            var key = _Object$keys[_i];
            var methodName = key;
            var prototype = Navigator.prototype;
            if (!Object.prototype.hasOwnProperty.call(prototype, methodName) || prototype[methodName] instanceof Function === false) {
                continue;
            }
            prototype[methodName] = protectedAudienceMethods[methodName];
        }
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopStr() {
        return "";
    }
    function noopFunc() {}
    function noopResolveVoid() {
        return Promise.resolve(undefined);
    }
    function noopResolveNull() {
        return Promise.resolve(null);
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        noProtectedAudience.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function noTopics(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function noTopics(source) {
        var TOPICS_PROPERTY_NAME = "browsingTopics";
        if (Document instanceof Object === false) {
            return;
        }
        if (!Object.prototype.hasOwnProperty.call(Document.prototype, TOPICS_PROPERTY_NAME) || Document.prototype[TOPICS_PROPERTY_NAME] instanceof Function === false) {
            return;
        }
        Document.prototype[TOPICS_PROPERTY_NAME] = function() {
            return noopPromiseResolve("[]");
        };
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopPromiseResolve() {
        var responseBody = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "{}";
        var responseUrl = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
        var responseType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "basic";
        if (typeof Response === "undefined") {
            return;
        }
        var response = new Response(responseBody, {
            status: 200,
            statusText: "OK"
        });
        if (responseType === "opaque") {
            Object.defineProperties(response, {
                body: {
                    value: null
                },
                status: {
                    value: 0
                },
                ok: {
                    value: false
                },
                statusText: {
                    value: ""
                },
                url: {
                    value: ""
                },
                type: {
                    value: responseType
                }
            });
        } else {
            Object.defineProperties(response, {
                url: {
                    value: responseUrl
                },
                type: {
                    value: responseType
                }
            });
        }
        return Promise.resolve(response);
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        noTopics.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function noeval(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function noeval(source) {
        window.eval = function evalWrapper(s) {
            hit(source);
            logMessage(source, `AdGuard has prevented eval:\n${s}`, true);
        }.bind();
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        noeval.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function nowebrtc(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function nowebrtc(source) {
        var propertyName = "";
        if (window.RTCPeerConnection) {
            propertyName = "RTCPeerConnection";
        } else if (window.webkitRTCPeerConnection) {
            propertyName = "webkitRTCPeerConnection";
        }
        if (propertyName === "") {
            return;
        }
        var rtcReplacement = function rtcReplacement(config) {
            var message = `Document tried to create an RTCPeerConnection: ${convertRtcConfigToString(config)}`;
            logMessage(source, message);
            hit(source);
        };
        rtcReplacement.prototype = {
            close: noopFunc,
            createDataChannel: noopFunc,
            createOffer: noopFunc,
            setRemoteDescription: noopFunc
        };
        var rtc = window[propertyName];
        window[propertyName] = rtcReplacement;
        if (rtc.prototype) {
            rtc.prototype.createDataChannel = function(a, b) {
                return {
                    close: noopFunc,
                    send: noopFunc
                };
            }.bind(null);
        }
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopFunc() {}
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function convertRtcConfigToString(config) {
        var UNDEF_STR = "undefined";
        var str = UNDEF_STR;
        if (config === null) {
            str = "null";
        } else if (config instanceof Object) {
            var SERVERS_PROP_NAME = "iceServers";
            var URLS_PROP_NAME = "urls";
            if (Object.prototype.hasOwnProperty.call(config, SERVERS_PROP_NAME) && config[SERVERS_PROP_NAME] && Object.prototype.hasOwnProperty.call(config[SERVERS_PROP_NAME][0], URLS_PROP_NAME) && !!config[SERVERS_PROP_NAME][0][URLS_PROP_NAME]) {
                str = config[SERVERS_PROP_NAME][0][URLS_PROP_NAME].toString();
            }
        }
        return str;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        nowebrtc.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function preventAddEventListener(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function preventAddEventListener(source, typeSearch, listenerSearch) {
        var typeSearchRegexp = toRegExp(typeSearch);
        var listenerSearchRegexp = toRegExp(listenerSearch);
        var nativeAddEventListener = window.EventTarget.prototype.addEventListener;
        function addEventListenerWrapper(type, listener) {
            var _this$constructor;
            var shouldPrevent = false;
            if (validateType(type) && validateListener(listener)) {
                shouldPrevent = typeSearchRegexp.test(type.toString()) && listenerSearchRegexp.test(listenerToString(listener));
            }
            if (shouldPrevent) {
                hit(source);
                return undefined;
            }
            var context = this;
            if (this && ((_this$constructor = this.constructor) === null || _this$constructor === void 0 ? void 0 : _this$constructor.name) === "Window" && this !== window) {
                context = window;
            }
            for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
                args[_key - 2] = arguments[_key];
            }
            return nativeAddEventListener.apply(context, [ type, listener, ...args ]);
        }
        var descriptor = {
            configurable: true,
            set: function set() {},
            get: function get() {
                return addEventListenerWrapper;
            }
        };
        Object.defineProperty(window.EventTarget.prototype, "addEventListener", descriptor);
        Object.defineProperty(window, "addEventListener", descriptor);
        Object.defineProperty(document, "addEventListener", descriptor);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function validateType(type) {
        return typeof type !== "undefined";
    }
    function validateListener(listener) {
        return typeof listener !== "undefined" && (typeof listener === "function" || typeof listener === "object" && listener !== null && "handleEvent" in listener && typeof listener.handleEvent === "function");
    }
    function listenerToString(listener) {
        return typeof listener === "function" ? listener.toString() : listener.handleEvent.toString();
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        preventAddEventListener.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function preventAdfly(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function preventAdfly(source) {
        var isDigit = function isDigit(data) {
            return /^\d$/.test(data);
        };
        var handler = function handler(encodedURL) {
            var evenChars = "";
            var oddChars = "";
            for (var i = 0; i < encodedURL.length; i += 1) {
                if (i % 2 === 0) {
                    evenChars += encodedURL.charAt(i);
                } else {
                    oddChars = encodedURL.charAt(i) + oddChars;
                }
            }
            var data = (evenChars + oddChars).split("");
            for (var _i = 0; _i < data.length; _i += 1) {
                if (isDigit(data[_i])) {
                    for (var ii = _i + 1; ii < data.length; ii += 1) {
                        if (isDigit(data[ii])) {
                            var temp = parseInt(data[_i], 10) ^ parseInt(data[ii], 10);
                            if (temp < 10) {
                                data[_i] = temp.toString();
                            }
                            _i = ii;
                            break;
                        }
                    }
                }
            }
            data = data.join("");
            var decodedURL = window.atob(data).slice(16, -16);
            if (window.stop) {
                window.stop();
            }
            window.onbeforeunload = null;
            window.location.href = decodedURL;
        };
        var val;
        var applyHandler = true;
        var result = setPropertyAccess(window, "ysmm", {
            configurable: false,
            set: function set(value) {
                if (applyHandler) {
                    applyHandler = false;
                    try {
                        if (typeof value === "string") {
                            handler(value);
                        }
                    } catch (err) {}
                }
                val = value;
            },
            get: function get() {
                return val;
            }
        });
        if (result) {
            hit(source);
        } else {
            logMessage(source, "Failed to set up prevent-adfly scriptlet");
        }
    }
    function setPropertyAccess(object, property, descriptor) {
        var currentDescriptor = Object.getOwnPropertyDescriptor(object, property);
        if (currentDescriptor && !currentDescriptor.configurable) {
            return false;
        }
        Object.defineProperty(object, property, descriptor);
        return true;
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        preventAdfly.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function preventBab(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function preventBab(source) {
        var nativeSetTimeout = window.setTimeout;
        var babRegex = /\.bab_elementid.$/;
        var timeoutWrapper = function timeoutWrapper(callback) {
            if (typeof callback !== "string" || !babRegex.test(callback)) {
                for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                    args[_key - 1] = arguments[_key];
                }
                return nativeSetTimeout.apply(window, [ callback, ...args ]);
            }
            hit(source);
        };
        window.setTimeout = timeoutWrapper;
        var signatures = [ [ "blockadblock" ], [ "babasbm" ], [ /getItem\('babn'\)/ ], [ "getElementById", "String.fromCharCode", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "charAt", "DOMContentLoaded", "AdBlock", "addEventListener", "doScroll", "fromCharCode", "<<2|r>>4", "sessionStorage", "clientWidth", "localStorage", "Math", "random" ] ];
        var check = function check(str) {
            if (typeof str !== "string") {
                return false;
            }
            for (var i = 0; i < signatures.length; i += 1) {
                var tokens = signatures[i];
                var match = 0;
                for (var j = 0; j < tokens.length; j += 1) {
                    var token = tokens[j];
                    var found = token instanceof RegExp ? token.test(str) : str.includes(token);
                    if (found) {
                        match += 1;
                    }
                }
                if (match / tokens.length >= .8) {
                    return true;
                }
            }
            return false;
        };
        var nativeEval = window.eval;
        var evalWrapper = function evalWrapper(str) {
            if (!check(str)) {
                return nativeEval(str);
            }
            hit(source);
            var bodyEl = document.body;
            if (bodyEl) {
                bodyEl.style.removeProperty("visibility");
            }
            var el = document.getElementById("babasbmsgx");
            if (el) {
                el.parentNode.removeChild(el);
            }
        };
        window.eval = evalWrapper.bind(window);
        window.eval.toString = nativeEval.toString.bind(nativeEval);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        preventBab.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function preventCanvas(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function preventCanvas(source, contextType) {
        var handlerWrapper = function handlerWrapper(target, thisArg, argumentsList) {
            var type = argumentsList[0];
            var shouldPrevent = false;
            if (!contextType) {
                shouldPrevent = true;
            } else if (isValidMatchStr(contextType)) {
                var {isInvertedMatch: isInvertedMatch, matchRegexp: matchRegexp} = parseMatchArg(contextType);
                shouldPrevent = matchRegexp.test(type) !== isInvertedMatch;
            } else {
                logMessage(source, `Invalid contextType parameter: ${contextType}`);
                shouldPrevent = false;
            }
            if (shouldPrevent) {
                hit(source);
                return null;
            }
            return Reflect.apply(target, thisArg, argumentsList);
        };
        var canvasHandler = {
            apply: handlerWrapper
        };
        window.HTMLCanvasElement.prototype.getContext = new Proxy(window.HTMLCanvasElement.prototype.getContext, canvasHandler);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function parseMatchArg(match) {
        var INVERT_MARKER = "!";
        var isInvertedMatch = match ? match === null || match === void 0 ? void 0 : match.startsWith(INVERT_MARKER) : false;
        var matchValue = isInvertedMatch ? match.slice(1) : match;
        var matchRegexp = toRegExp(matchValue);
        return {
            isInvertedMatch: isInvertedMatch,
            matchRegexp: matchRegexp,
            matchValue: matchValue
        };
    }
    function isValidMatchStr(match) {
        var INVERT_MARKER = "!";
        var str = match;
        if (match !== null && match !== void 0 && match.startsWith(INVERT_MARKER)) {
            str = match.slice(1);
        }
        return isValidStrPattern(str);
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function escapeRegExp(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    function isValidStrPattern(input) {
        var FORWARD_SLASH = "/";
        var str = escapeRegExp(input);
        if (input[0] === FORWARD_SLASH && input[input.length - 1] === FORWARD_SLASH) {
            str = input.slice(1, -1);
        }
        var isValid;
        try {
            isValid = new RegExp(str);
            isValid = true;
        } catch (e) {
            isValid = false;
        }
        return isValid;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        preventCanvas.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function preventElementSrcLoading(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function preventElementSrcLoading(source, tagName, match) {
        if (typeof Proxy === "undefined" || typeof Reflect === "undefined") {
            return;
        }
        var srcMockData = {
            script: "data:text/javascript;base64,KCk9Pnt9",
            img: "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",
            iframe: "data:text/html;base64, PGRpdj48L2Rpdj4=",
            link: "data:text/plain;base64,"
        };
        var instance;
        if (tagName === "script") {
            instance = HTMLScriptElement;
        } else if (tagName === "img") {
            instance = HTMLImageElement;
        } else if (tagName === "iframe") {
            instance = HTMLIFrameElement;
        } else if (tagName === "link") {
            instance = HTMLLinkElement;
        } else {
            return;
        }
        var hasTrustedTypes = window.trustedTypes && typeof window.trustedTypes.createPolicy === "function";
        var policy;
        if (hasTrustedTypes) {
            policy = window.trustedTypes.createPolicy("AGPolicy", {
                createScriptURL: function createScriptURL(arg) {
                    return arg;
                }
            });
        }
        var SOURCE_PROPERTY_NAME = tagName === "link" ? "href" : "src";
        var ONERROR_PROPERTY_NAME = "onerror";
        var searchRegexp = toRegExp(match);
        var setMatchedAttribute = function setMatchedAttribute(elem) {
            return elem.setAttribute(source.name, "matched");
        };
        var setAttributeWrapper = function setAttributeWrapper(target, thisArg, args) {
            if (!args[0] || !args[1]) {
                return Reflect.apply(target, thisArg, args);
            }
            var nodeName = thisArg.nodeName.toLowerCase();
            var attrName = args[0].toLowerCase();
            var attrValue = args[1];
            var isMatched = attrName === SOURCE_PROPERTY_NAME && tagName.toLowerCase() === nodeName && srcMockData[nodeName] && searchRegexp.test(attrValue);
            if (!isMatched) {
                return Reflect.apply(target, thisArg, args);
            }
            hit(source);
            setMatchedAttribute(thisArg);
            return Reflect.apply(target, thisArg, [ attrName, srcMockData[nodeName] ]);
        };
        var setAttributeHandler = {
            apply: setAttributeWrapper
        };
        instance.prototype.setAttribute = new Proxy(Element.prototype.setAttribute, setAttributeHandler);
        var origSrcDescriptor = safeGetDescriptor(instance.prototype, SOURCE_PROPERTY_NAME);
        if (!origSrcDescriptor) {
            return;
        }
        Object.defineProperty(instance.prototype, SOURCE_PROPERTY_NAME, {
            enumerable: true,
            configurable: true,
            get() {
                return origSrcDescriptor.get.call(this);
            },
            set(urlValue) {
                var nodeName = this.nodeName.toLowerCase();
                var isMatched = tagName.toLowerCase() === nodeName && srcMockData[nodeName] && searchRegexp.test(urlValue);
                if (!isMatched) {
                    origSrcDescriptor.set.call(this, urlValue);
                    return true;
                }
                if (policy && urlValue instanceof TrustedScriptURL) {
                    var trustedSrc = policy.createScriptURL(urlValue);
                    origSrcDescriptor.set.call(this, trustedSrc);
                    hit(source);
                    return;
                }
                setMatchedAttribute(this);
                origSrcDescriptor.set.call(this, srcMockData[nodeName]);
                hit(source);
            }
        });
        var origOnerrorDescriptor = safeGetDescriptor(HTMLElement.prototype, ONERROR_PROPERTY_NAME);
        if (!origOnerrorDescriptor) {
            return;
        }
        Object.defineProperty(HTMLElement.prototype, ONERROR_PROPERTY_NAME, {
            enumerable: true,
            configurable: true,
            get() {
                return origOnerrorDescriptor.get.call(this);
            },
            set(cb) {
                var isMatched = this.getAttribute(source.name) === "matched";
                if (!isMatched) {
                    origOnerrorDescriptor.set.call(this, cb);
                    return true;
                }
                origOnerrorDescriptor.set.call(this, noopFunc);
                return true;
            }
        });
        var addEventListenerWrapper = function addEventListenerWrapper(target, thisArg, args) {
            if (!args[0] || !args[1] || !thisArg) {
                return Reflect.apply(target, thisArg, args);
            }
            var eventName = args[0];
            var isMatched = typeof thisArg.getAttribute === "function" && thisArg.getAttribute(source.name) === "matched" && eventName === "error";
            if (isMatched) {
                return Reflect.apply(target, thisArg, [ eventName, noopFunc ]);
            }
            return Reflect.apply(target, thisArg, args);
        };
        var addEventListenerHandler = {
            apply: addEventListenerWrapper
        };
        EventTarget.prototype.addEventListener = new Proxy(EventTarget.prototype.addEventListener, addEventListenerHandler);
        var preventInlineOnerror = function preventInlineOnerror(tagName, src) {
            window.addEventListener("error", (function(event) {
                if (!event.target || !event.target.nodeName || event.target.nodeName.toLowerCase() !== tagName || !event.target.src || !src.test(event.target.src)) {
                    return;
                }
                hit(source);
                if (typeof event.target.onload === "function") {
                    event.target.onerror = event.target.onload;
                    return;
                }
                event.target.onerror = noopFunc;
            }), true);
        };
        preventInlineOnerror(tagName, searchRegexp);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function safeGetDescriptor(obj, prop) {
        var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
        if (descriptor && descriptor.configurable) {
            return descriptor;
        }
        return null;
    }
    function noopFunc() {}
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        preventElementSrcLoading.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function preventEvalIf(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function preventEvalIf(source, search) {
        var searchRegexp = toRegExp(search);
        var nativeEval = window.eval;
        window.eval = function(payload) {
            if (!searchRegexp.test(payload.toString())) {
                return nativeEval.call(window, payload);
            }
            hit(source);
            return undefined;
        }.bind(window);
        window.eval.toString = nativeEval.toString.bind(nativeEval);
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        preventEvalIf.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function preventFab(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function preventFab(source) {
        hit(source);
        var Fab = function Fab() {};
        Fab.prototype.check = noopFunc;
        Fab.prototype.clearEvent = noopFunc;
        Fab.prototype.emitEvent = noopFunc;
        Fab.prototype.on = function(a, b) {
            if (!a) {
                b();
            }
            return this;
        };
        Fab.prototype.onDetected = noopThis;
        Fab.prototype.onNotDetected = function(a) {
            a();
            return this;
        };
        Fab.prototype.setOption = noopFunc;
        Fab.prototype.options = {
            set: noopFunc,
            get: noopFunc
        };
        var fab = new Fab;
        var getSetFab = {
            get() {
                return Fab;
            },
            set() {}
        };
        var getsetfab = {
            get() {
                return fab;
            },
            set() {}
        };
        if (Object.prototype.hasOwnProperty.call(window, "FuckAdBlock")) {
            window.FuckAdBlock = Fab;
        } else {
            Object.defineProperty(window, "FuckAdBlock", getSetFab);
        }
        if (Object.prototype.hasOwnProperty.call(window, "BlockAdBlock")) {
            window.BlockAdBlock = Fab;
        } else {
            Object.defineProperty(window, "BlockAdBlock", getSetFab);
        }
        if (Object.prototype.hasOwnProperty.call(window, "SniffAdBlock")) {
            window.SniffAdBlock = Fab;
        } else {
            Object.defineProperty(window, "SniffAdBlock", getSetFab);
        }
        if (Object.prototype.hasOwnProperty.call(window, "fuckAdBlock")) {
            window.fuckAdBlock = fab;
        } else {
            Object.defineProperty(window, "fuckAdBlock", getsetfab);
        }
        if (Object.prototype.hasOwnProperty.call(window, "blockAdBlock")) {
            window.blockAdBlock = fab;
        } else {
            Object.defineProperty(window, "blockAdBlock", getsetfab);
        }
        if (Object.prototype.hasOwnProperty.call(window, "sniffAdBlock")) {
            window.sniffAdBlock = fab;
        } else {
            Object.defineProperty(window, "sniffAdBlock", getsetfab);
        }
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopFunc() {}
    function noopThis() {
        return this;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        preventFab.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function preventFetch(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function preventFetch(source, propsToMatch) {
        var responseBody = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "emptyObj";
        var responseType = arguments.length > 3 ? arguments[3] : undefined;
        if (typeof fetch === "undefined" || typeof Proxy === "undefined" || typeof Response === "undefined") {
            return;
        }
        var nativeRequestClone = Request.prototype.clone;
        var strResponseBody;
        if (responseBody === "" || responseBody === "emptyObj") {
            strResponseBody = "{}";
        } else if (responseBody === "emptyArr") {
            strResponseBody = "[]";
        } else if (responseBody === "emptyStr") {
            strResponseBody = "";
        } else {
            logMessage(source, `Invalid responseBody parameter: '${responseBody}'`);
            return;
        }
        var isResponseTypeSpecified = typeof responseType !== "undefined";
        var isResponseTypeSupported = function isResponseTypeSupported(responseType) {
            var SUPPORTED_TYPES = [ "basic", "cors", "opaque" ];
            return SUPPORTED_TYPES.includes(responseType);
        };
        if (isResponseTypeSpecified && !isResponseTypeSupported(responseType)) {
            logMessage(source, `Invalid responseType parameter: '${responseType}'`);
            return;
        }
        var getResponseType = function getResponseType(request) {
            try {
                var {mode: mode} = request;
                if (mode === undefined || mode === "cors" || mode === "no-cors") {
                    var fetchURL = new URL(request.url);
                    if (fetchURL.origin === document.location.origin) {
                        return "basic";
                    }
                    return mode === "no-cors" ? "opaque" : "cors";
                }
            } catch (error) {
                logMessage(source, `Could not determine response type: ${error}`);
            }
            return undefined;
        };
        var handlerWrapper = async function handlerWrapper(target, thisArg, args) {
            var shouldPrevent = false;
            var fetchData = getFetchData(args, nativeRequestClone);
            if (typeof propsToMatch === "undefined") {
                logMessage(source, `fetch( ${objectToString(fetchData)} )`, true);
                hit(source);
                return Reflect.apply(target, thisArg, args);
            }
            shouldPrevent = matchRequestProps(source, propsToMatch, fetchData);
            if (shouldPrevent) {
                hit(source);
                var finalResponseType;
                try {
                    finalResponseType = responseType || getResponseType(fetchData);
                    var origResponse = await Reflect.apply(target, thisArg, args);
                    if (!origResponse.ok) {
                        return noopPromiseResolve(strResponseBody, fetchData.url, finalResponseType);
                    }
                    return modifyResponse(origResponse, {
                        body: strResponseBody,
                        type: finalResponseType
                    });
                } catch (ex) {
                    return noopPromiseResolve(strResponseBody, fetchData.url, finalResponseType);
                }
            }
            return Reflect.apply(target, thisArg, args);
        };
        var fetchHandler = {
            apply: handlerWrapper
        };
        fetch = new Proxy(fetch, fetchHandler);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function getFetchData(args, nativeRequestClone) {
        var fetchPropsObj = {};
        var resource = args[0];
        var fetchUrl;
        var fetchInit;
        if (resource instanceof Request) {
            var realData = nativeRequestClone.call(resource);
            var requestData = getRequestData(realData);
            fetchUrl = requestData.url;
            fetchInit = requestData;
        } else {
            fetchUrl = resource;
            fetchInit = args[1];
        }
        fetchPropsObj.url = fetchUrl;
        if (fetchInit instanceof Object) {
            var props = Object.keys(fetchInit);
            props.forEach((function(prop) {
                fetchPropsObj[prop] = fetchInit[prop];
            }));
        }
        return fetchPropsObj;
    }
    function objectToString(obj) {
        if (!obj || typeof obj !== "object") {
            return String(obj);
        }
        if (isEmptyObject(obj)) {
            return "{}";
        }
        return Object.entries(obj).map((function(pair) {
            var key = pair[0];
            var value = pair[1];
            var recordValueStr = value;
            if (value instanceof Object) {
                recordValueStr = `{ ${objectToString(value)} }`;
            }
            return `${key}:"${recordValueStr}"`;
        })).join(" ");
    }
    function matchRequestProps(source, propsToMatch, requestData) {
        if (propsToMatch === "" || propsToMatch === "*") {
            return true;
        }
        var isMatched;
        var parsedData = parseMatchProps(propsToMatch);
        if (!isValidParsedData(parsedData)) {
            logMessage(source, `Invalid parameter: ${propsToMatch}`);
            isMatched = false;
        } else {
            var matchData = getMatchPropsData(parsedData);
            var matchKeys = Object.keys(matchData);
            isMatched = matchKeys.every((function(matchKey) {
                var matchValue = matchData[matchKey];
                var dataValue = requestData[matchKey];
                return Object.prototype.hasOwnProperty.call(requestData, matchKey) && typeof dataValue === "string" && (matchValue === null || matchValue === void 0 ? void 0 : matchValue.test(dataValue));
            }));
        }
        return isMatched;
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function noopPromiseResolve() {
        var responseBody = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "{}";
        var responseUrl = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
        var responseType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "basic";
        if (typeof Response === "undefined") {
            return;
        }
        var response = new Response(responseBody, {
            status: 200,
            statusText: "OK"
        });
        if (responseType === "opaque") {
            Object.defineProperties(response, {
                body: {
                    value: null
                },
                status: {
                    value: 0
                },
                ok: {
                    value: false
                },
                statusText: {
                    value: ""
                },
                url: {
                    value: ""
                },
                type: {
                    value: responseType
                }
            });
        } else {
            Object.defineProperties(response, {
                url: {
                    value: responseUrl
                },
                type: {
                    value: responseType
                }
            });
        }
        return Promise.resolve(response);
    }
    function modifyResponse(origResponse) {
        var _origResponse$headers;
        var replacement = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
            body: "{}"
        };
        var headers = {};
        origResponse === null || origResponse === void 0 || (_origResponse$headers = origResponse.headers) === null || _origResponse$headers === void 0 || _origResponse$headers.forEach((function(value, key) {
            headers[key] = value;
        }));
        var modifiedResponse = new Response(replacement.body, {
            status: origResponse.status,
            statusText: origResponse.statusText,
            headers: headers
        });
        Object.defineProperties(modifiedResponse, {
            url: {
                value: origResponse.url
            },
            type: {
                value: replacement.type || origResponse.type
            }
        });
        return modifiedResponse;
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function isValidStrPattern(input) {
        var FORWARD_SLASH = "/";
        var str = escapeRegExp(input);
        if (input[0] === FORWARD_SLASH && input[input.length - 1] === FORWARD_SLASH) {
            str = input.slice(1, -1);
        }
        var isValid;
        try {
            isValid = new RegExp(str);
            isValid = true;
        } catch (e) {
            isValid = false;
        }
        return isValid;
    }
    function escapeRegExp(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    function isEmptyObject(obj) {
        return Object.keys(obj).length === 0 && !obj.prototype;
    }
    function getRequestData(request) {
        var requestInitOptions = getRequestProps();
        var entries = requestInitOptions.map((function(key) {
            var value = request[key];
            return [ key, value ];
        }));
        return Object.fromEntries(entries);
    }
    function getRequestProps() {
        return [ "url", "method", "headers", "body", "credentials", "cache", "redirect", "referrer", "referrerPolicy", "integrity", "keepalive", "signal", "mode" ];
    }
    function parseMatchProps(propsToMatchStr) {
        var PROPS_DIVIDER = " ";
        var PAIRS_MARKER = ":";
        var isRequestProp = function isRequestProp(prop) {
            return getRequestProps().includes(prop);
        };
        var propsObj = {};
        var props = propsToMatchStr.split(PROPS_DIVIDER);
        props.forEach((function(prop) {
            var dividerInd = prop.indexOf(PAIRS_MARKER);
            var key = prop.slice(0, dividerInd);
            if (isRequestProp(key)) {
                var value = prop.slice(dividerInd + 1);
                propsObj[key] = value;
            } else {
                propsObj.url = prop;
            }
        }));
        return propsObj;
    }
    function isValidParsedData(data) {
        return Object.values(data).every((function(value) {
            return isValidStrPattern(value);
        }));
    }
    function getMatchPropsData(data) {
        var matchData = {};
        var dataKeys = Object.keys(data);
        dataKeys.forEach((function(key) {
            matchData[key] = toRegExp(data[key]);
        }));
        return matchData;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        preventFetch.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function preventPopadsNet(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function preventPopadsNet(source) {
        var rid = randomId();
        var throwError = function throwError() {
            throw new ReferenceError(rid);
        };
        delete window.PopAds;
        delete window.popns;
        Object.defineProperties(window, {
            PopAds: {
                set: throwError
            },
            popns: {
                set: throwError
            }
        });
        window.onerror = createOnErrorHandler(rid).bind();
        hit(source);
    }
    function createOnErrorHandler(rid) {
        var nativeOnError = window.onerror;
        return function onError(error) {
            if (typeof error === "string" && error.includes(rid)) {
                return true;
            }
            if (nativeOnError instanceof Function) {
                for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                    args[_key - 1] = arguments[_key];
                }
                return nativeOnError.apply(window, [ error, ...args ]);
            }
            return false;
        };
    }
    function randomId() {
        return Math.random().toString(36).slice(2, 9);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        preventPopadsNet.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function preventRefresh(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function preventRefresh(source, delaySec) {
        var getMetaElements = function getMetaElements() {
            var metaNodes = [];
            try {
                metaNodes = document.querySelectorAll('meta[http-equiv="refresh" i][content]');
            } catch (e) {
                try {
                    metaNodes = document.querySelectorAll('meta[http-equiv="refresh"][content]');
                } catch (e) {
                    logMessage(source, e);
                }
            }
            return Array.from(metaNodes);
        };
        var getMetaContentDelay = function getMetaContentDelay(metaElements) {
            var delays = metaElements.map((function(meta) {
                var contentString = meta.getAttribute("content");
                if (contentString.length === 0) {
                    return null;
                }
                var contentDelay;
                var limiterIndex = contentString.indexOf(";");
                if (limiterIndex !== -1) {
                    var delaySubstring = contentString.substring(0, limiterIndex);
                    contentDelay = getNumberFromString(delaySubstring);
                } else {
                    contentDelay = getNumberFromString(contentString);
                }
                return contentDelay;
            })).filter((function(delay) {
                return delay !== null;
            }));
            if (!delays.length) {
                return null;
            }
            var minDelay = delays.reduce((function(a, b) {
                return Math.min(a, b);
            }));
            return minDelay;
        };
        var stop = function stop() {
            var metaElements = getMetaElements();
            if (metaElements.length === 0) {
                return;
            }
            var secondsToRun = getNumberFromString(delaySec);
            if (secondsToRun === null) {
                secondsToRun = getMetaContentDelay(metaElements);
            }
            if (secondsToRun === null) {
                return;
            }
            var delayMs = secondsToRun * 1e3;
            setTimeout((function() {
                window.stop();
                hit(source);
            }), delayMs);
        };
        if (document.readyState === "loading") {
            document.addEventListener("DOMContentLoaded", stop, {
                once: true
            });
        } else {
            stop();
        }
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function getNumberFromString(rawString) {
        var parsedDelay = parseInt(rawString, 10);
        var validDelay = nativeIsNaN(parsedDelay) ? null : parsedDelay;
        return validDelay;
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function nativeIsNaN(num) {
        var native = Number.isNaN || window.isNaN;
        return native(num);
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        preventRefresh.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function preventRequestAnimationFrame(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function preventRequestAnimationFrame(source, match) {
        var nativeRequestAnimationFrame = window.requestAnimationFrame;
        var shouldLog = typeof match === "undefined";
        var {isInvertedMatch: isInvertedMatch, matchRegexp: matchRegexp} = parseMatchArg(match);
        var rafWrapper = function rafWrapper(callback) {
            var shouldPrevent = false;
            if (shouldLog) {
                hit(source);
                logMessage(source, `requestAnimationFrame(${String(callback)})`, true);
            } else if (isValidCallback(callback) && isValidStrPattern(match)) {
                shouldPrevent = matchRegexp.test(callback.toString()) !== isInvertedMatch;
            }
            if (shouldPrevent) {
                hit(source);
                return nativeRequestAnimationFrame(noopFunc);
            }
            for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                args[_key - 1] = arguments[_key];
            }
            return nativeRequestAnimationFrame.apply(window, [ callback, ...args ]);
        };
        window.requestAnimationFrame = rafWrapper;
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopFunc() {}
    function parseMatchArg(match) {
        var INVERT_MARKER = "!";
        var isInvertedMatch = match ? match === null || match === void 0 ? void 0 : match.startsWith(INVERT_MARKER) : false;
        var matchValue = isInvertedMatch ? match.slice(1) : match;
        var matchRegexp = toRegExp(matchValue);
        return {
            isInvertedMatch: isInvertedMatch,
            matchRegexp: matchRegexp,
            matchValue: matchValue
        };
    }
    function isValidStrPattern(input) {
        var FORWARD_SLASH = "/";
        var str = escapeRegExp(input);
        if (input[0] === FORWARD_SLASH && input[input.length - 1] === FORWARD_SLASH) {
            str = input.slice(1, -1);
        }
        var isValid;
        try {
            isValid = new RegExp(str);
            isValid = true;
        } catch (e) {
            isValid = false;
        }
        return isValid;
    }
    function isValidCallback(callback) {
        return callback instanceof Function || typeof callback === "string";
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function escapeRegExp(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        preventRequestAnimationFrame.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function preventSetInterval(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function preventSetInterval(source, matchCallback, matchDelay) {
        var shouldLog = typeof matchCallback === "undefined" && typeof matchDelay === "undefined";
        var handlerWrapper = function handlerWrapper(target, thisArg, args) {
            var callback = args[0];
            var delay = args[1];
            var shouldPrevent = false;
            if (shouldLog) {
                hit(source);
                logMessage(source, `setInterval(${String(callback)}, ${delay})`, true);
            } else {
                shouldPrevent = isPreventionNeeded({
                    callback: callback,
                    delay: delay,
                    matchCallback: matchCallback,
                    matchDelay: matchDelay
                });
            }
            if (shouldPrevent) {
                hit(source);
                args[0] = noopFunc;
            }
            return target.apply(thisArg, args);
        };
        var setIntervalHandler = {
            apply: handlerWrapper
        };
        window.setInterval = new Proxy(window.setInterval, setIntervalHandler);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopFunc() {}
    function isPreventionNeeded(_ref) {
        var {callback: callback, delay: delay, matchCallback: matchCallback, matchDelay: matchDelay} = _ref;
        if (!isValidCallback(callback)) {
            return false;
        }
        if (!isValidMatchStr(matchCallback) || matchDelay && !isValidMatchNumber(matchDelay)) {
            return false;
        }
        var {isInvertedMatch: isInvertedMatch, matchRegexp: matchRegexp} = parseMatchArg(matchCallback);
        var {isInvertedDelayMatch: isInvertedDelayMatch, delayMatch: delayMatch} = parseDelayArg(matchDelay);
        var parsedDelay = parseRawDelay(delay);
        var shouldPrevent = false;
        var callbackStr = String(callback);
        if (delayMatch === null) {
            shouldPrevent = matchRegexp.test(callbackStr) !== isInvertedMatch;
        } else if (!matchCallback) {
            shouldPrevent = parsedDelay === delayMatch !== isInvertedDelayMatch;
        } else {
            shouldPrevent = matchRegexp.test(callbackStr) !== isInvertedMatch && parsedDelay === delayMatch !== isInvertedDelayMatch;
        }
        return shouldPrevent;
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function nativeIsNaN(num) {
        var native = Number.isNaN || window.isNaN;
        return native(num);
    }
    function parseMatchArg(match) {
        var INVERT_MARKER = "!";
        var isInvertedMatch = match ? match === null || match === void 0 ? void 0 : match.startsWith(INVERT_MARKER) : false;
        var matchValue = isInvertedMatch ? match.slice(1) : match;
        var matchRegexp = toRegExp(matchValue);
        return {
            isInvertedMatch: isInvertedMatch,
            matchRegexp: matchRegexp,
            matchValue: matchValue
        };
    }
    function parseDelayArg(delay) {
        var INVERT_MARKER = "!";
        var isInvertedDelayMatch = delay === null || delay === void 0 ? void 0 : delay.startsWith(INVERT_MARKER);
        var delayValue = isInvertedDelayMatch ? delay.slice(1) : delay;
        var parsedDelay = parseInt(delayValue, 10);
        var delayMatch = nativeIsNaN(parsedDelay) ? null : parsedDelay;
        return {
            isInvertedDelayMatch: isInvertedDelayMatch,
            delayMatch: delayMatch
        };
    }
    function isValidCallback(callback) {
        return callback instanceof Function || typeof callback === "string";
    }
    function isValidMatchStr(match) {
        var INVERT_MARKER = "!";
        var str = match;
        if (match !== null && match !== void 0 && match.startsWith(INVERT_MARKER)) {
            str = match.slice(1);
        }
        return isValidStrPattern(str);
    }
    function isValidStrPattern(input) {
        var FORWARD_SLASH = "/";
        var str = escapeRegExp(input);
        if (input[0] === FORWARD_SLASH && input[input.length - 1] === FORWARD_SLASH) {
            str = input.slice(1, -1);
        }
        var isValid;
        try {
            isValid = new RegExp(str);
            isValid = true;
        } catch (e) {
            isValid = false;
        }
        return isValid;
    }
    function escapeRegExp(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    function nativeIsFinite(num) {
        var native = Number.isFinite || window.isFinite;
        return native(num);
    }
    function isValidMatchNumber(match) {
        var INVERT_MARKER = "!";
        var str = match;
        if (match !== null && match !== void 0 && match.startsWith(INVERT_MARKER)) {
            str = match.slice(1);
        }
        var num = parseFloat(str);
        return !nativeIsNaN(num) && nativeIsFinite(num);
    }
    function parseRawDelay(delay) {
        var parsedDelay = Math.floor(parseInt(delay, 10));
        return typeof parsedDelay === "number" && !nativeIsNaN(parsedDelay) ? parsedDelay : delay;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        preventSetInterval.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function preventSetTimeout(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function preventSetTimeout(source, matchCallback, matchDelay) {
        var shouldLog = typeof matchCallback === "undefined" && typeof matchDelay === "undefined";
        var handlerWrapper = function handlerWrapper(target, thisArg, args) {
            var callback = args[0];
            var delay = args[1];
            var shouldPrevent = false;
            if (shouldLog) {
                hit(source);
                logMessage(source, `setTimeout(${String(callback)}, ${delay})`, true);
            } else {
                shouldPrevent = isPreventionNeeded({
                    callback: callback,
                    delay: delay,
                    matchCallback: matchCallback,
                    matchDelay: matchDelay
                });
            }
            if (shouldPrevent) {
                hit(source);
                args[0] = noopFunc;
            }
            return target.apply(thisArg, args);
        };
        var setTimeoutHandler = {
            apply: handlerWrapper
        };
        window.setTimeout = new Proxy(window.setTimeout, setTimeoutHandler);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function noopFunc() {}
    function isPreventionNeeded(_ref) {
        var {callback: callback, delay: delay, matchCallback: matchCallback, matchDelay: matchDelay} = _ref;
        if (!isValidCallback(callback)) {
            return false;
        }
        if (!isValidMatchStr(matchCallback) || matchDelay && !isValidMatchNumber(matchDelay)) {
            return false;
        }
        var {isInvertedMatch: isInvertedMatch, matchRegexp: matchRegexp} = parseMatchArg(matchCallback);
        var {isInvertedDelayMatch: isInvertedDelayMatch, delayMatch: delayMatch} = parseDelayArg(matchDelay);
        var parsedDelay = parseRawDelay(delay);
        var shouldPrevent = false;
        var callbackStr = String(callback);
        if (delayMatch === null) {
            shouldPrevent = matchRegexp.test(callbackStr) !== isInvertedMatch;
        } else if (!matchCallback) {
            shouldPrevent = parsedDelay === delayMatch !== isInvertedDelayMatch;
        } else {
            shouldPrevent = matchRegexp.test(callbackStr) !== isInvertedMatch && parsedDelay === delayMatch !== isInvertedDelayMatch;
        }
        return shouldPrevent;
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function parseMatchArg(match) {
        var INVERT_MARKER = "!";
        var isInvertedMatch = match ? match === null || match === void 0 ? void 0 : match.startsWith(INVERT_MARKER) : false;
        var matchValue = isInvertedMatch ? match.slice(1) : match;
        var matchRegexp = toRegExp(matchValue);
        return {
            isInvertedMatch: isInvertedMatch,
            matchRegexp: matchRegexp,
            matchValue: matchValue
        };
    }
    function parseDelayArg(delay) {
        var INVERT_MARKER = "!";
        var isInvertedDelayMatch = delay === null || delay === void 0 ? void 0 : delay.startsWith(INVERT_MARKER);
        var delayValue = isInvertedDelayMatch ? delay.slice(1) : delay;
        var parsedDelay = parseInt(delayValue, 10);
        var delayMatch = nativeIsNaN(parsedDelay) ? null : parsedDelay;
        return {
            isInvertedDelayMatch: isInvertedDelayMatch,
            delayMatch: delayMatch
        };
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function nativeIsNaN(num) {
        var native = Number.isNaN || window.isNaN;
        return native(num);
    }
    function isValidCallback(callback) {
        return callback instanceof Function || typeof callback === "string";
    }
    function isValidMatchStr(match) {
        var INVERT_MARKER = "!";
        var str = match;
        if (match !== null && match !== void 0 && match.startsWith(INVERT_MARKER)) {
            str = match.slice(1);
        }
        return isValidStrPattern(str);
    }
    function escapeRegExp(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    function isValidStrPattern(input) {
        var FORWARD_SLASH = "/";
        var str = escapeRegExp(input);
        if (input[0] === FORWARD_SLASH && input[input.length - 1] === FORWARD_SLASH) {
            str = input.slice(1, -1);
        }
        var isValid;
        try {
            isValid = new RegExp(str);
            isValid = true;
        } catch (e) {
            isValid = false;
        }
        return isValid;
    }
    function nativeIsFinite(num) {
        var native = Number.isFinite || window.isFinite;
        return native(num);
    }
    function isValidMatchNumber(match) {
        var INVERT_MARKER = "!";
        var str = match;
        if (match !== null && match !== void 0 && match.startsWith(INVERT_MARKER)) {
            str = match.slice(1);
        }
        var num = parseFloat(str);
        return !nativeIsNaN(num) && nativeIsFinite(num);
    }
    function parseRawDelay(delay) {
        var parsedDelay = Math.floor(parseInt(delay, 10));
        return typeof parsedDelay === "number" && !nativeIsNaN(parsedDelay) ? parsedDelay : delay;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        preventSetTimeout.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function preventWindowOpen(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function preventWindowOpen(source) {
        var match = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "*";
        var delay = arguments.length > 2 ? arguments[2] : undefined;
        var replacement = arguments.length > 3 ? arguments[3] : undefined;
        var nativeOpen = window.open;
        var isNewSyntax = match !== "0" && match !== "1";
        var oldOpenWrapper = function oldOpenWrapper(str) {
            match = Number(match) > 0;
            for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                args[_key - 1] = arguments[_key];
            }
            if (!isValidStrPattern(delay)) {
                logMessage(source, `Invalid parameter: ${delay}`);
                return nativeOpen.apply(window, [ str, ...args ]);
            }
            var searchRegexp = toRegExp(delay);
            if (match !== searchRegexp.test(str)) {
                return nativeOpen.apply(window, [ str, ...args ]);
            }
            hit(source);
            return handleOldReplacement(replacement);
        };
        var newOpenWrapper = function newOpenWrapper(url) {
            var shouldLog = replacement && replacement.includes("log");
            for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
                args[_key2 - 1] = arguments[_key2];
            }
            if (shouldLog) {
                var argsStr = args && args.length > 0 ? `, ${args.join(", ")}` : "";
                var message = `${url}${argsStr}`;
                logMessage(source, message, true);
                hit(source);
            }
            var shouldPrevent = false;
            if (match === "*") {
                shouldPrevent = true;
            } else if (isValidMatchStr(match)) {
                var {isInvertedMatch: isInvertedMatch, matchRegexp: matchRegexp} = parseMatchArg(match);
                shouldPrevent = matchRegexp.test(url) !== isInvertedMatch;
            } else {
                logMessage(source, `Invalid parameter: ${match}`);
                shouldPrevent = false;
            }
            if (shouldPrevent) {
                var parsedDelay = parseInt(delay, 10);
                var result;
                if (nativeIsNaN(parsedDelay)) {
                    result = noopNull();
                } else {
                    var decoyArgs = {
                        replacement: replacement,
                        url: url,
                        delay: parsedDelay
                    };
                    var decoy = createDecoy(decoyArgs);
                    var popup = decoy.contentWindow;
                    if (typeof popup === "object" && popup !== null) {
                        Object.defineProperty(popup, "closed", {
                            value: false
                        });
                        Object.defineProperty(popup, "opener", {
                            value: window
                        });
                        Object.defineProperty(popup, "frameElement", {
                            value: null
                        });
                    } else {
                        var nativeGetter = decoy.contentWindow && decoy.contentWindow.get;
                        Object.defineProperty(decoy, "contentWindow", {
                            get: getPreventGetter(nativeGetter)
                        });
                        popup = decoy.contentWindow;
                    }
                    result = popup;
                }
                hit(source);
                return result;
            }
            return nativeOpen.apply(window, [ url, ...args ]);
        };
        window.open = isNewSyntax ? newOpenWrapper : oldOpenWrapper;
        window.open.toString = nativeOpen.toString.bind(nativeOpen);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function isValidStrPattern(input) {
        var FORWARD_SLASH = "/";
        var str = escapeRegExp(input);
        if (input[0] === FORWARD_SLASH && input[input.length - 1] === FORWARD_SLASH) {
            str = input.slice(1, -1);
        }
        var isValid;
        try {
            isValid = new RegExp(str);
            isValid = true;
        } catch (e) {
            isValid = false;
        }
        return isValid;
    }
    function escapeRegExp(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    function isValidMatchStr(match) {
        var INVERT_MARKER = "!";
        var str = match;
        if (match !== null && match !== void 0 && match.startsWith(INVERT_MARKER)) {
            str = match.slice(1);
        }
        return isValidStrPattern(str);
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function nativeIsNaN(num) {
        var native = Number.isNaN || window.isNaN;
        return native(num);
    }
    function parseMatchArg(match) {
        var INVERT_MARKER = "!";
        var isInvertedMatch = match ? match === null || match === void 0 ? void 0 : match.startsWith(INVERT_MARKER) : false;
        var matchValue = isInvertedMatch ? match.slice(1) : match;
        var matchRegexp = toRegExp(matchValue);
        return {
            isInvertedMatch: isInvertedMatch,
            matchRegexp: matchRegexp,
            matchValue: matchValue
        };
    }
    function handleOldReplacement(replacement) {
        var result;
        if (!replacement) {
            result = noopFunc;
        } else if (replacement === "trueFunc") {
            result = trueFunc;
        } else if (replacement.includes("=")) {
            var isProp = replacement.startsWith("{") && replacement.endsWith("}");
            if (isProp) {
                var propertyPart = replacement.slice(1, -1);
                var propertyName = substringBefore(propertyPart, "=");
                var propertyValue = substringAfter(propertyPart, "=");
                if (propertyValue === "noopFunc") {
                    result = {};
                    result[propertyName] = noopFunc;
                }
            }
        }
        return result;
    }
    function createDecoy(args) {
        var UrlPropNameOf = function(UrlPropNameOf) {
            UrlPropNameOf["Object"] = "data";
            UrlPropNameOf["Iframe"] = "src";
            return UrlPropNameOf;
        }({});
        var {replacement: replacement, url: url, delay: delay} = args;
        var tag;
        if (replacement === "obj") {
            tag = "object";
        } else {
            tag = "iframe";
        }
        var decoy = document.createElement(tag);
        if (decoy instanceof HTMLObjectElement) {
            decoy[UrlPropNameOf.Object] = url;
        } else if (decoy instanceof HTMLIFrameElement) {
            decoy[UrlPropNameOf.Iframe] = url;
        }
        decoy.style.setProperty("height", "1px", "important");
        decoy.style.setProperty("position", "fixed", "important");
        decoy.style.setProperty("top", "-1px", "important");
        decoy.style.setProperty("width", "1px", "important");
        document.body.appendChild(decoy);
        setTimeout((function() {
            return decoy.remove();
        }), delay * 1e3);
        return decoy;
    }
    function getPreventGetter(nativeGetter) {
        var preventGetter = function preventGetter(target, prop) {
            if (prop && prop === "closed") {
                return false;
            }
            if (typeof nativeGetter === "function") {
                return noopFunc;
            }
            return prop && target[prop];
        };
        return preventGetter;
    }
    function noopNull() {
        return null;
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function noopFunc() {}
    function trueFunc() {
        return true;
    }
    function substringBefore(str, separator) {
        if (!str || !separator) {
            return str;
        }
        var index = str.indexOf(separator);
        return index < 0 ? str : str.substring(0, index);
    }
    function substringAfter(str, separator) {
        if (!str) {
            return str;
        }
        var index = str.indexOf(separator);
        return index < 0 ? "" : str.substring(index + separator.length);
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        preventWindowOpen.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function preventXHR(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function preventXHR(source, propsToMatch, customResponseText) {
        if (typeof Proxy === "undefined") {
            return;
        }
        var nativeOpen = window.XMLHttpRequest.prototype.open;
        var nativeGetResponseHeader = window.XMLHttpRequest.prototype.getResponseHeader;
        var nativeGetAllResponseHeaders = window.XMLHttpRequest.prototype.getAllResponseHeaders;
        var xhrData;
        var modifiedResponse = "";
        var modifiedResponseText = "";
        var openWrapper = function openWrapper(target, thisArg, args) {
            xhrData = getXhrData.apply(null, args);
            if (typeof propsToMatch === "undefined") {
                logMessage(source, `xhr( ${objectToString(xhrData)} )`, true);
                hit(source);
            } else if (matchRequestProps(source, propsToMatch, xhrData)) {
                thisArg.shouldBePrevented = true;
                thisArg.xhrData = xhrData;
            }
            if (thisArg.shouldBePrevented) {
                thisArg.collectedHeaders = [];
                var setRequestHeaderWrapper = function setRequestHeaderWrapper(target, thisArg, args) {
                    thisArg.collectedHeaders.push(args);
                    return Reflect.apply(target, thisArg, args);
                };
                var setRequestHeaderHandler = {
                    apply: setRequestHeaderWrapper
                };
                thisArg.setRequestHeader = new Proxy(thisArg.setRequestHeader, setRequestHeaderHandler);
            }
            return Reflect.apply(target, thisArg, args);
        };
        var sendWrapper = function sendWrapper(target, thisArg, args) {
            if (!thisArg.shouldBePrevented) {
                return Reflect.apply(target, thisArg, args);
            }
            if (thisArg.responseType === "blob") {
                modifiedResponse = new Blob;
            }
            if (thisArg.responseType === "arraybuffer") {
                modifiedResponse = new ArrayBuffer;
            }
            if (customResponseText) {
                var randomText = generateRandomResponse(customResponseText);
                if (randomText) {
                    modifiedResponse = randomText;
                    modifiedResponseText = randomText;
                } else {
                    logMessage(source, `Invalid randomize parameter: '${customResponseText}'`);
                }
            }
            var forgedRequest = new XMLHttpRequest;
            var transitionReadyState = function transitionReadyState(state) {
                if (state === 4) {
                    var {responseURL: responseURL, responseXML: responseXML} = forgedRequest;
                    Object.defineProperties(thisArg, {
                        readyState: {
                            value: 4,
                            writable: false
                        },
                        statusText: {
                            value: "OK",
                            writable: false
                        },
                        responseURL: {
                            value: responseURL || thisArg.xhrData.url,
                            writable: false
                        },
                        responseXML: {
                            value: responseXML,
                            writable: false
                        },
                        status: {
                            value: 200,
                            writable: false
                        },
                        response: {
                            value: modifiedResponse,
                            writable: false
                        },
                        responseText: {
                            value: modifiedResponseText,
                            writable: false
                        }
                    });
                    hit(source);
                } else {
                    Object.defineProperty(thisArg, "readyState", {
                        value: state,
                        writable: true,
                        configurable: true
                    });
                }
                var stateEvent = new Event("readystatechange");
                thisArg.dispatchEvent(stateEvent);
            };
            forgedRequest.addEventListener("readystatechange", (function() {
                transitionReadyState(1);
                var loadStartEvent = new ProgressEvent("loadstart");
                thisArg.dispatchEvent(loadStartEvent);
                transitionReadyState(2);
                transitionReadyState(3);
                var progressEvent = new ProgressEvent("progress");
                thisArg.dispatchEvent(progressEvent);
                transitionReadyState(4);
            }));
            setTimeout((function() {
                var loadEvent = new ProgressEvent("load");
                thisArg.dispatchEvent(loadEvent);
                var loadEndEvent = new ProgressEvent("loadend");
                thisArg.dispatchEvent(loadEndEvent);
            }), 1);
            nativeOpen.apply(forgedRequest, [ thisArg.xhrData.method, thisArg.xhrData.url ]);
            thisArg.collectedHeaders.forEach((function(header) {
                var name = header[0];
                var value = header[1];
                forgedRequest.setRequestHeader(name, value);
            }));
            return undefined;
        };
        var getHeaderWrapper = function getHeaderWrapper(target, thisArg, args) {
            if (!thisArg.shouldBePrevented) {
                return nativeGetResponseHeader.apply(thisArg, args);
            }
            if (!thisArg.collectedHeaders.length) {
                return null;
            }
            var searchHeaderName = args[0].toLowerCase();
            var matchedHeader = thisArg.collectedHeaders.find((function(header) {
                var headerName = header[0].toLowerCase();
                return headerName === searchHeaderName;
            }));
            return matchedHeader ? matchedHeader[1] : null;
        };
        var getAllHeadersWrapper = function getAllHeadersWrapper(target, thisArg) {
            if (!thisArg.shouldBePrevented) {
                return nativeGetAllResponseHeaders.call(thisArg);
            }
            if (!thisArg.collectedHeaders.length) {
                return "";
            }
            var allHeadersStr = thisArg.collectedHeaders.map((function(header) {
                var headerName = header[0];
                var headerValue = header[1];
                return `${headerName.toLowerCase()}: ${headerValue}`;
            })).join("\r\n");
            return allHeadersStr;
        };
        var openHandler = {
            apply: openWrapper
        };
        var sendHandler = {
            apply: sendWrapper
        };
        var getHeaderHandler = {
            apply: getHeaderWrapper
        };
        var getAllHeadersHandler = {
            apply: getAllHeadersWrapper
        };
        XMLHttpRequest.prototype.open = new Proxy(XMLHttpRequest.prototype.open, openHandler);
        XMLHttpRequest.prototype.send = new Proxy(XMLHttpRequest.prototype.send, sendHandler);
        XMLHttpRequest.prototype.getResponseHeader = new Proxy(XMLHttpRequest.prototype.getResponseHeader, getHeaderHandler);
        XMLHttpRequest.prototype.getAllResponseHeaders = new Proxy(XMLHttpRequest.prototype.getAllResponseHeaders, getAllHeadersHandler);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function objectToString(obj) {
        if (!obj || typeof obj !== "object") {
            return String(obj);
        }
        if (isEmptyObject(obj)) {
            return "{}";
        }
        return Object.entries(obj).map((function(pair) {
            var key = pair[0];
            var value = pair[1];
            var recordValueStr = value;
            if (value instanceof Object) {
                recordValueStr = `{ ${objectToString(value)} }`;
            }
            return `${key}:"${recordValueStr}"`;
        })).join(" ");
    }
    function generateRandomResponse(customResponseText) {
        var customResponse = customResponseText;
        if (customResponse === "true") {
            customResponse = Math.random().toString(36).slice(-10);
            return customResponse;
        }
        customResponse = customResponse.replace("length:", "");
        var rangeRegex = /^\d+-\d+$/;
        if (!rangeRegex.test(customResponse)) {
            return null;
        }
        var rangeMin = getNumberFromString(customResponse.split("-")[0]);
        var rangeMax = getNumberFromString(customResponse.split("-")[1]);
        if (!nativeIsFinite(rangeMin) || !nativeIsFinite(rangeMax)) {
            return null;
        }
        if (rangeMin > rangeMax) {
            var temp = rangeMin;
            rangeMin = rangeMax;
            rangeMax = temp;
        }
        var LENGTH_RANGE_LIMIT = 500 * 1e3;
        if (rangeMax > LENGTH_RANGE_LIMIT) {
            return null;
        }
        var length = getRandomIntInclusive(rangeMin, rangeMax);
        customResponse = getRandomStrByLength(length);
        return customResponse;
    }
    function matchRequestProps(source, propsToMatch, requestData) {
        if (propsToMatch === "" || propsToMatch === "*") {
            return true;
        }
        var isMatched;
        var parsedData = parseMatchProps(propsToMatch);
        if (!isValidParsedData(parsedData)) {
            logMessage(source, `Invalid parameter: ${propsToMatch}`);
            isMatched = false;
        } else {
            var matchData = getMatchPropsData(parsedData);
            var matchKeys = Object.keys(matchData);
            isMatched = matchKeys.every((function(matchKey) {
                var matchValue = matchData[matchKey];
                var dataValue = requestData[matchKey];
                return Object.prototype.hasOwnProperty.call(requestData, matchKey) && typeof dataValue === "string" && (matchValue === null || matchValue === void 0 ? void 0 : matchValue.test(dataValue));
            }));
        }
        return isMatched;
    }
    function getXhrData(method, url, async, user, password) {
        return {
            method: method,
            url: url,
            async: async,
            user: user,
            password: password
        };
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function isValidStrPattern(input) {
        var FORWARD_SLASH = "/";
        var str = escapeRegExp(input);
        if (input[0] === FORWARD_SLASH && input[input.length - 1] === FORWARD_SLASH) {
            str = input.slice(1, -1);
        }
        var isValid;
        try {
            isValid = new RegExp(str);
            isValid = true;
        } catch (e) {
            isValid = false;
        }
        return isValid;
    }
    function escapeRegExp(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    function isEmptyObject(obj) {
        return Object.keys(obj).length === 0 && !obj.prototype;
    }
    function getNumberFromString(rawString) {
        var parsedDelay = parseInt(rawString, 10);
        var validDelay = nativeIsNaN(parsedDelay) ? null : parsedDelay;
        return validDelay;
    }
    function nativeIsFinite(num) {
        var native = Number.isFinite || window.isFinite;
        return native(num);
    }
    function nativeIsNaN(num) {
        var native = Number.isNaN || window.isNaN;
        return native(num);
    }
    function parseMatchProps(propsToMatchStr) {
        var PROPS_DIVIDER = " ";
        var PAIRS_MARKER = ":";
        var isRequestProp = function isRequestProp(prop) {
            return getRequestProps().includes(prop);
        };
        var propsObj = {};
        var props = propsToMatchStr.split(PROPS_DIVIDER);
        props.forEach((function(prop) {
            var dividerInd = prop.indexOf(PAIRS_MARKER);
            var key = prop.slice(0, dividerInd);
            if (isRequestProp(key)) {
                var value = prop.slice(dividerInd + 1);
                propsObj[key] = value;
            } else {
                propsObj.url = prop;
            }
        }));
        return propsObj;
    }
    function isValidParsedData(data) {
        return Object.values(data).every((function(value) {
            return isValidStrPattern(value);
        }));
    }
    function getMatchPropsData(data) {
        var matchData = {};
        var dataKeys = Object.keys(data);
        dataKeys.forEach((function(key) {
            matchData[key] = toRegExp(data[key]);
        }));
        return matchData;
    }
    function getRequestProps() {
        return [ "url", "method", "headers", "body", "credentials", "cache", "redirect", "referrer", "referrerPolicy", "integrity", "keepalive", "signal", "mode" ];
    }
    function getRandomIntInclusive(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min + 1) + min);
    }
    function getRandomStrByLength(length) {
        var result = "";
        var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+=~";
        var charactersLength = characters.length;
        for (var i = 0; i < length; i += 1) {
            result += characters.charAt(Math.floor(Math.random() * charactersLength));
        }
        return result;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        preventXHR.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function removeAttr(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function removeAttr(source, attrs, selector) {
        var applying = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "asap stay";
        if (!attrs) {
            return;
        }
        attrs = attrs.split(/\s*\|\s*/);
        if (!selector) {
            selector = `[${attrs.join("],[")}]`;
        }
        var rmattr = function rmattr() {
            var nodes = [];
            try {
                nodes = [].slice.call(document.querySelectorAll(selector));
            } catch (e) {
                logMessage(source, `Invalid selector arg: '${selector}'`);
            }
            var removed = false;
            nodes.forEach((function(node) {
                attrs.forEach((function(attr) {
                    node.removeAttribute(attr);
                    removed = true;
                }));
            }));
            if (removed) {
                hit(source);
            }
        };
        var flags = parseFlags(applying);
        var run = function run() {
            rmattr();
            if (!flags.hasFlag(flags.STAY)) {
                return;
            }
            observeDOMChanges(rmattr, true);
        };
        if (flags.hasFlag(flags.ASAP)) {
            if (document.readyState === "loading") {
                window.addEventListener("DOMContentLoaded", rmattr, {
                    once: true
                });
            } else {
                rmattr();
            }
        }
        if (document.readyState !== "complete" && flags.hasFlag(flags.COMPLETE)) {
            window.addEventListener("load", run, {
                once: true
            });
        } else if (flags.hasFlag(flags.STAY)) {
            if (!applying.includes(" ")) {
                rmattr();
            }
            observeDOMChanges(rmattr, true);
        }
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function observeDOMChanges(callback) {
        var observeAttrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
        var attrsToObserve = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
        var THROTTLE_DELAY_MS = 20;
        var observer = new MutationObserver(throttle(callbackWrapper, THROTTLE_DELAY_MS));
        var connect = function connect() {
            if (attrsToObserve.length > 0) {
                observer.observe(document.documentElement, {
                    childList: true,
                    subtree: true,
                    attributes: observeAttrs,
                    attributeFilter: attrsToObserve
                });
            } else {
                observer.observe(document.documentElement, {
                    childList: true,
                    subtree: true,
                    attributes: observeAttrs
                });
            }
        };
        var disconnect = function disconnect() {
            observer.disconnect();
        };
        function callbackWrapper() {
            disconnect();
            callback();
            connect();
        }
        connect();
    }
    function parseFlags(flags) {
        var FLAGS_DIVIDER = " ";
        var ASAP_FLAG = "asap";
        var COMPLETE_FLAG = "complete";
        var STAY_FLAG = "stay";
        var VALID_FLAGS = new Set([ ASAP_FLAG, COMPLETE_FLAG, STAY_FLAG ]);
        var passedFlags = new Set(flags.trim().split(FLAGS_DIVIDER).filter((function(flag) {
            return VALID_FLAGS.has(flag);
        })));
        return {
            ASAP: ASAP_FLAG,
            COMPLETE: COMPLETE_FLAG,
            STAY: STAY_FLAG,
            hasFlag: function hasFlag(flag) {
                return passedFlags.has(flag);
            }
        };
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function throttle(cb, delay) {
        var wait = false;
        var savedArgs;
        var _wrapper = function wrapper() {
            for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                args[_key] = arguments[_key];
            }
            if (wait) {
                savedArgs = args;
                return;
            }
            cb(...args);
            wait = true;
            setTimeout((function() {
                wait = false;
                if (savedArgs) {
                    _wrapper(...savedArgs);
                    savedArgs = null;
                }
            }), delay);
        };
        return _wrapper;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        removeAttr.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function removeClass(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function removeClass(source, classNames, selector) {
        var applying = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "asap stay";
        if (!classNames) {
            return;
        }
        classNames = classNames.split(/\s*\|\s*/);
        var selectors = [];
        if (!selector) {
            selectors = classNames.map((function(className) {
                return `.${className}`;
            }));
        }
        var removeClassHandler = function removeClassHandler() {
            var nodes = new Set;
            if (selector) {
                var foundNodes = [];
                try {
                    foundNodes = [].slice.call(document.querySelectorAll(selector));
                } catch (e) {
                    logMessage(source, `Invalid selector arg: '${selector}'`);
                }
                foundNodes.forEach((function(n) {
                    return nodes.add(n);
                }));
            } else if (selectors.length > 0) {
                selectors.forEach((function(s) {
                    var elements = document.querySelectorAll(s);
                    for (var i = 0; i < elements.length; i += 1) {
                        var element = elements[i];
                        nodes.add(element);
                    }
                }));
            }
            var removed = false;
            nodes.forEach((function(node) {
                classNames.forEach((function(className) {
                    if (node.classList.contains(className)) {
                        node.classList.remove(className);
                        removed = true;
                    }
                }));
            }));
            if (removed) {
                hit(source);
            }
        };
        var CLASS_ATTR_NAME = [ "class" ];
        var flags = parseFlags(applying);
        var run = function run() {
            removeClassHandler();
            if (!flags.hasFlag(flags.STAY)) {
                return;
            }
            observeDOMChanges(removeClassHandler, true, CLASS_ATTR_NAME);
        };
        if (flags.hasFlag(flags.ASAP)) {
            if (document.readyState === "loading") {
                window.addEventListener("DOMContentLoaded", removeClassHandler, {
                    once: true
                });
            } else {
                removeClassHandler();
            }
        }
        if (document.readyState !== "complete" && flags.hasFlag(flags.COMPLETE)) {
            window.addEventListener("load", run, {
                once: true
            });
        } else if (flags.hasFlag(flags.STAY)) {
            if (!applying.includes(" ")) {
                removeClassHandler();
            }
            observeDOMChanges(removeClassHandler, true, CLASS_ATTR_NAME);
        }
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function observeDOMChanges(callback) {
        var observeAttrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
        var attrsToObserve = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
        var THROTTLE_DELAY_MS = 20;
        var observer = new MutationObserver(throttle(callbackWrapper, THROTTLE_DELAY_MS));
        var connect = function connect() {
            if (attrsToObserve.length > 0) {
                observer.observe(document.documentElement, {
                    childList: true,
                    subtree: true,
                    attributes: observeAttrs,
                    attributeFilter: attrsToObserve
                });
            } else {
                observer.observe(document.documentElement, {
                    childList: true,
                    subtree: true,
                    attributes: observeAttrs
                });
            }
        };
        var disconnect = function disconnect() {
            observer.disconnect();
        };
        function callbackWrapper() {
            disconnect();
            callback();
            connect();
        }
        connect();
    }
    function parseFlags(flags) {
        var FLAGS_DIVIDER = " ";
        var ASAP_FLAG = "asap";
        var COMPLETE_FLAG = "complete";
        var STAY_FLAG = "stay";
        var VALID_FLAGS = new Set([ ASAP_FLAG, COMPLETE_FLAG, STAY_FLAG ]);
        var passedFlags = new Set(flags.trim().split(FLAGS_DIVIDER).filter((function(flag) {
            return VALID_FLAGS.has(flag);
        })));
        return {
            ASAP: ASAP_FLAG,
            COMPLETE: COMPLETE_FLAG,
            STAY: STAY_FLAG,
            hasFlag: function hasFlag(flag) {
                return passedFlags.has(flag);
            }
        };
    }
    function throttle(cb, delay) {
        var wait = false;
        var savedArgs;
        var _wrapper = function wrapper() {
            for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                args[_key] = arguments[_key];
            }
            if (wait) {
                savedArgs = args;
                return;
            }
            cb(...args);
            wait = true;
            setTimeout((function() {
                wait = false;
                if (savedArgs) {
                    _wrapper(...savedArgs);
                    savedArgs = null;
                }
            }), delay);
        };
        return _wrapper;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        removeClass.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function removeCookie(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function removeCookie(source, match) {
        var matchRegexp = toRegExp(match);
        var removeCookieFromHost = function removeCookieFromHost(cookieName, hostName) {
            var cookieSpec = `${cookieName}=`;
            var domain1 = `; domain=${hostName}`;
            var domain2 = `; domain=.${hostName}`;
            var path = "; path=/";
            var expiration = "; expires=Thu, 01 Jan 1970 00:00:00 GMT";
            document.cookie = cookieSpec + expiration;
            document.cookie = cookieSpec + domain1 + expiration;
            document.cookie = cookieSpec + domain2 + expiration;
            document.cookie = cookieSpec + path + expiration;
            document.cookie = cookieSpec + domain1 + path + expiration;
            document.cookie = cookieSpec + domain2 + path + expiration;
            hit(source);
        };
        var rmCookie = function rmCookie() {
            document.cookie.split(";").forEach((function(cookieStr) {
                var pos = cookieStr.indexOf("=");
                if (pos === -1) {
                    return;
                }
                var cookieName = cookieStr.slice(0, pos).trim();
                if (!matchRegexp.test(cookieName)) {
                    return;
                }
                var hostParts = document.location.hostname.split(".");
                for (var i = 0; i <= hostParts.length - 1; i += 1) {
                    var hostName = hostParts.slice(i).join(".");
                    if (hostName) {
                        removeCookieFromHost(cookieName, hostName);
                    }
                }
            }));
        };
        rmCookie();
        window.addEventListener("beforeunload", rmCookie);
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        removeCookie.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function removeInShadowDom(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function removeInShadowDom(source, selector, baseSelector) {
        if (!Element.prototype.attachShadow) {
            return;
        }
        var removeElement = function removeElement(targetElement) {
            targetElement.remove();
        };
        var removeHandler = function removeHandler() {
            var hostElements = !baseSelector ? findHostElements(document.documentElement) : document.querySelectorAll(baseSelector);
            var _loop = function _loop() {
                var isRemoved = false;
                var {targets: targets, innerHosts: innerHosts} = pierceShadowDom(selector, hostElements);
                targets.forEach((function(targetEl) {
                    removeElement(targetEl);
                    isRemoved = true;
                }));
                if (isRemoved) {
                    hit(source);
                }
                hostElements = innerHosts;
            };
            while (hostElements.length !== 0) {
                _loop();
            }
        };
        removeHandler();
        observeDOMChanges(removeHandler, true);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function observeDOMChanges(callback) {
        var observeAttrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
        var attrsToObserve = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
        var THROTTLE_DELAY_MS = 20;
        var observer = new MutationObserver(throttle(callbackWrapper, THROTTLE_DELAY_MS));
        var connect = function connect() {
            if (attrsToObserve.length > 0) {
                observer.observe(document.documentElement, {
                    childList: true,
                    subtree: true,
                    attributes: observeAttrs,
                    attributeFilter: attrsToObserve
                });
            } else {
                observer.observe(document.documentElement, {
                    childList: true,
                    subtree: true,
                    attributes: observeAttrs
                });
            }
        };
        var disconnect = function disconnect() {
            observer.disconnect();
        };
        function callbackWrapper() {
            disconnect();
            callback();
            connect();
        }
        connect();
    }
    function findHostElements(rootElement) {
        var hosts = [];
        if (rootElement) {
            var domElems = rootElement.querySelectorAll("*");
            domElems.forEach((function(el) {
                if (el.shadowRoot) {
                    hosts.push(el);
                }
            }));
        }
        return hosts;
    }
    function pierceShadowDom(selector, hostElements) {
        var targets = [];
        var innerHostsAcc = [];
        hostElements.forEach((function(host) {
            var simpleElems = host.querySelectorAll(selector);
            targets = targets.concat([].slice.call(simpleElems));
            var shadowRootElem = host.shadowRoot;
            var shadowChildren = shadowRootElem.querySelectorAll(selector);
            targets = targets.concat([].slice.call(shadowChildren));
            innerHostsAcc.push(findHostElements(shadowRootElem));
        }));
        var innerHosts = flatten(innerHostsAcc);
        return {
            targets: targets,
            innerHosts: innerHosts
        };
    }
    function flatten(input) {
        var stack = [];
        input.forEach((function(el) {
            return stack.push(el);
        }));
        var res = [];
        while (stack.length) {
            var next = stack.pop();
            if (Array.isArray(next)) {
                next.forEach((function(el) {
                    return stack.push(el);
                }));
            } else {
                res.push(next);
            }
        }
        return res.reverse();
    }
    function throttle(cb, delay) {
        var wait = false;
        var savedArgs;
        var _wrapper = function wrapper() {
            for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                args[_key] = arguments[_key];
            }
            if (wait) {
                savedArgs = args;
                return;
            }
            cb(...args);
            wait = true;
            setTimeout((function() {
                wait = false;
                if (savedArgs) {
                    _wrapper(...savedArgs);
                    savedArgs = null;
                }
            }), delay);
        };
        return _wrapper;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        removeInShadowDom.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function removeNodeText(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function removeNodeText(source, nodeName, textMatch, parentSelector) {
        var {selector: selector, nodeNameMatch: nodeNameMatch, textContentMatch: textContentMatch} = parseNodeTextParams(nodeName, textMatch);
        var handleNodes = function handleNodes(nodes) {
            return nodes.forEach((function(node) {
                var shouldReplace = isTargetNode(node, nodeNameMatch, textContentMatch);
                if (shouldReplace) {
                    var ALL_TEXT_PATTERN = /^[^]*$/;
                    var REPLACEMENT = "";
                    replaceNodeText(source, node, ALL_TEXT_PATTERN, REPLACEMENT);
                }
            }));
        };
        if (document.documentElement) {
            handleExistingNodes(selector, handleNodes, parentSelector);
        }
        observeDocumentWithTimeout((function(mutations) {
            return handleMutations(mutations, handleNodes, selector, parentSelector);
        }));
    }
    function observeDocumentWithTimeout(callback) {
        var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
            subtree: true,
            childList: true
        };
        var timeout = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1e4;
        var documentObserver = new MutationObserver((function(mutations, observer) {
            observer.disconnect();
            callback(mutations, observer);
            observer.observe(document.documentElement, options);
        }));
        documentObserver.observe(document.documentElement, options);
        if (typeof timeout === "number") {
            setTimeout((function() {
                return documentObserver.disconnect();
            }), timeout);
        }
    }
    function handleExistingNodes(selector, handler, parentSelector) {
        var processNodes = function processNodes(parent) {
            if (selector === "#text") {
                var textNodes = nodeListToArray(parent.childNodes).filter((function(node) {
                    return node.nodeType === Node.TEXT_NODE;
                }));
                handler(textNodes);
            } else {
                var _nodes = nodeListToArray(parent.querySelectorAll(selector));
                handler(_nodes);
            }
        };
        var parents = parentSelector ? document.querySelectorAll(parentSelector) : [ document ];
        parents.forEach((function(parent) {
            return processNodes(parent);
        }));
    }
    function handleMutations(mutations, handler, selector, parentSelector) {
        var addedNodes = getAddedNodes(mutations);
        if (selector && parentSelector) {
            addedNodes.forEach((function() {
                handleExistingNodes(selector, handler, parentSelector);
            }));
        } else {
            handler(addedNodes);
        }
    }
    function replaceNodeText(source, node, pattern, replacement) {
        var {textContent: textContent} = node;
        if (textContent) {
            if (node.nodeName === "SCRIPT" && window.trustedTypes && window.trustedTypes.createPolicy) {
                var policy = window.trustedTypes.createPolicy("AGPolicy", {
                    createScript: function createScript(string) {
                        return string;
                    }
                });
                var modifiedText = textContent.replace(pattern, replacement);
                var trustedReplacement = policy.createScript(modifiedText);
                node.textContent = trustedReplacement;
            } else {
                node.textContent = textContent.replace(pattern, replacement);
            }
            hit(source);
        }
    }
    function isTargetNode(node, nodeNameMatch, textContentMatch) {
        var {nodeName: nodeName, textContent: textContent} = node;
        var nodeNameLowerCase = nodeName.toLowerCase();
        return textContent !== null && textContent !== "" && (nodeNameMatch instanceof RegExp ? nodeNameMatch.test(nodeNameLowerCase) : nodeNameMatch === nodeNameLowerCase) && (textContentMatch instanceof RegExp ? textContentMatch.test(textContent) : textContent.includes(textContentMatch));
    }
    function parseNodeTextParams(nodeName, textMatch) {
        var pattern = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
        var REGEXP_START_MARKER = "/";
        var isStringNameMatch = !(nodeName.startsWith(REGEXP_START_MARKER) && nodeName.endsWith(REGEXP_START_MARKER));
        var selector = isStringNameMatch ? nodeName : "*";
        var nodeNameMatch = isStringNameMatch ? nodeName : toRegExp(nodeName);
        var textContentMatch = !textMatch.startsWith(REGEXP_START_MARKER) ? textMatch : toRegExp(textMatch);
        var patternMatch;
        if (pattern) {
            patternMatch = !pattern.startsWith(REGEXP_START_MARKER) ? pattern : toRegExp(pattern);
        }
        return {
            selector: selector,
            nodeNameMatch: nodeNameMatch,
            textContentMatch: textContentMatch,
            patternMatch: patternMatch
        };
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function nodeListToArray(nodeList) {
        var nodes = [];
        for (var i = 0; i < nodeList.length; i += 1) {
            nodes.push(nodeList[i]);
        }
        return nodes;
    }
    function getAddedNodes(mutations) {
        var nodes = [];
        for (var i = 0; i < mutations.length; i += 1) {
            var {addedNodes: addedNodes} = mutations[i];
            for (var j = 0; j < addedNodes.length; j += 1) {
                nodes.push(addedNodes[j]);
            }
        }
        return nodes;
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        removeNodeText.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function setAttr(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function setAttr(source, selector, attr) {
        var value = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "";
        if (!selector || !attr) {
            return;
        }
        var allowedValues = [ "true", "false" ];
        var shouldCopyValue = value.startsWith("[") && value.endsWith("]");
        var isValidValue = value.length === 0 || !nativeIsNaN(parseInt(value, 10)) && parseInt(value, 10) >= 0 && parseInt(value, 10) <= 32767 || allowedValues.includes(value.toLowerCase());
        if (!shouldCopyValue && !isValidValue) {
            logMessage(source, `Invalid attribute value provided: '${convertTypeToString(value)}'`);
            return;
        }
        var attributeHandler;
        if (shouldCopyValue) {
            attributeHandler = function attributeHandler(elem, attr, value) {
                var valueToCopy = elem.getAttribute(value.slice(1, -1));
                if (valueToCopy === null) {
                    logMessage(source, `No element attribute found to copy value from: ${value}`);
                }
                elem.setAttribute(attr, valueToCopy);
            };
        }
        setAttributeBySelector(source, selector, attr, value, attributeHandler);
        observeDOMChanges((function() {
            return setAttributeBySelector(source, selector, attr, value, attributeHandler);
        }), true);
    }
    function setAttributeBySelector(source, selector, attribute, value) {
        var attributeSetter = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : defaultAttributeSetter;
        var elements;
        try {
            elements = document.querySelectorAll(selector);
        } catch (_unused) {
            logMessage(source, `Failed to find elements matching selector "${selector}"`);
            return;
        }
        if (!elements || elements.length === 0) {
            return;
        }
        try {
            elements.forEach((function(elem) {
                return attributeSetter(elem, attribute, value);
            }));
            hit(source);
        } catch (_unused2) {
            logMessage(source, `Failed to set [${attribute}="${value}"] to each of selected elements.`);
        }
    }
    function observeDOMChanges(callback) {
        var observeAttrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
        var attrsToObserve = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
        var THROTTLE_DELAY_MS = 20;
        var observer = new MutationObserver(throttle(callbackWrapper, THROTTLE_DELAY_MS));
        var connect = function connect() {
            if (attrsToObserve.length > 0) {
                observer.observe(document.documentElement, {
                    childList: true,
                    subtree: true,
                    attributes: observeAttrs,
                    attributeFilter: attrsToObserve
                });
            } else {
                observer.observe(document.documentElement, {
                    childList: true,
                    subtree: true,
                    attributes: observeAttrs
                });
            }
        };
        var disconnect = function disconnect() {
            observer.disconnect();
        };
        function callbackWrapper() {
            disconnect();
            callback();
            connect();
        }
        connect();
    }
    function nativeIsNaN(num) {
        var native = Number.isNaN || window.isNaN;
        return native(num);
    }
    function convertTypeToString(value) {
        var output;
        if (typeof value === "undefined") {
            output = "undefined";
        } else if (typeof value === "object") {
            if (value === null) {
                output = "null";
            } else {
                output = objectToString(value);
            }
        } else {
            output = String(value);
        }
        return output;
    }
    function defaultAttributeSetter(elem, attribute, value) {
        return elem.setAttribute(attribute, value);
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function throttle(cb, delay) {
        var wait = false;
        var savedArgs;
        var _wrapper = function wrapper() {
            for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                args[_key] = arguments[_key];
            }
            if (wait) {
                savedArgs = args;
                return;
            }
            cb(...args);
            wait = true;
            setTimeout((function() {
                wait = false;
                if (savedArgs) {
                    _wrapper(...savedArgs);
                    savedArgs = null;
                }
            }), delay);
        };
        return _wrapper;
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        setAttr.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function setConstant(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function setConstant(source, property, value) {
        var stack = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "";
        var valueWrapper = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : "";
        var setProxyTrap = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
        var uboAliases = [ "set-constant.js", "ubo-set-constant.js", "set.js", "ubo-set.js", "ubo-set-constant", "ubo-set" ];
        if (uboAliases.includes(source.name)) {
            if (stack.length !== 1 && !getNumberFromString(stack)) {
                valueWrapper = stack;
            }
            stack = undefined;
        }
        if (!property || !matchStackTrace(stack, (new Error).stack)) {
            return;
        }
        var isProxyTrapSet = false;
        var emptyArr = noopArray();
        var emptyObj = noopObject();
        var constantValue;
        if (value === "undefined") {
            constantValue = undefined;
        } else if (value === "false") {
            constantValue = false;
        } else if (value === "true") {
            constantValue = true;
        } else if (value === "null") {
            constantValue = null;
        } else if (value === "emptyArr") {
            constantValue = emptyArr;
        } else if (value === "emptyObj") {
            constantValue = emptyObj;
        } else if (value === "noopFunc") {
            constantValue = noopFunc;
        } else if (value === "noopCallbackFunc") {
            constantValue = noopCallbackFunc;
        } else if (value === "trueFunc") {
            constantValue = trueFunc;
        } else if (value === "falseFunc") {
            constantValue = falseFunc;
        } else if (value === "throwFunc") {
            constantValue = throwFunc;
        } else if (value === "noopPromiseResolve") {
            constantValue = noopPromiseResolve;
        } else if (value === "noopPromiseReject") {
            constantValue = noopPromiseReject;
        } else if (/^\d+$/.test(value)) {
            constantValue = parseFloat(value);
            if (nativeIsNaN(constantValue)) {
                return;
            }
            if (Math.abs(constantValue) > 32767) {
                return;
            }
        } else if (value === "-1") {
            constantValue = -1;
        } else if (value === "") {
            constantValue = "";
        } else if (value === "yes") {
            constantValue = "yes";
        } else if (value === "no") {
            constantValue = "no";
        } else {
            return;
        }
        var valueWrapperNames = [ "asFunction", "asCallback", "asResolved", "asRejected" ];
        if (valueWrapperNames.includes(valueWrapper)) {
            var valueWrappersMap = {
                asFunction(v) {
                    return function() {
                        return v;
                    };
                },
                asCallback(v) {
                    return function() {
                        return function() {
                            return v;
                        };
                    };
                },
                asResolved(v) {
                    return Promise.resolve(v);
                },
                asRejected(v) {
                    return Promise.reject(v);
                }
            };
            constantValue = valueWrappersMap[valueWrapper](constantValue);
        }
        var canceled = false;
        var mustCancel = function mustCancel(value) {
            if (canceled) {
                return canceled;
            }
            canceled = value !== undefined && constantValue !== undefined && typeof value !== typeof constantValue && value !== null;
            return canceled;
        };
        var trapProp = function trapProp(base, prop, configurable, handler) {
            if (!handler.init(base[prop])) {
                return false;
            }
            var origDescriptor = Object.getOwnPropertyDescriptor(base, prop);
            var prevSetter;
            if (origDescriptor instanceof Object) {
                if (!origDescriptor.configurable) {
                    var message = `Property '${prop}' is not configurable`;
                    logMessage(source, message);
                    return false;
                }
                if (base[prop]) {
                    base[prop] = constantValue;
                }
                if (origDescriptor.set instanceof Function) {
                    prevSetter = origDescriptor.set;
                }
            }
            Object.defineProperty(base, prop, {
                configurable: configurable,
                get() {
                    return handler.get();
                },
                set(a) {
                    if (prevSetter !== undefined) {
                        prevSetter(a);
                    }
                    if (a instanceof Object) {
                        var propertiesToCheck = property.split(".").slice(1);
                        if (setProxyTrap && !isProxyTrapSet) {
                            isProxyTrapSet = true;
                            a = new Proxy(a, {
                                get: function get(target, propertyKey, val) {
                                    propertiesToCheck.reduce((function(object, currentProp, index, array) {
                                        var currentObj = object === null || object === void 0 ? void 0 : object[currentProp];
                                        if (index === array.length - 1 && currentObj !== constantValue) {
                                            object[currentProp] = constantValue;
                                        }
                                        return currentObj || object;
                                    }), target);
                                    return Reflect.get(target, propertyKey, val);
                                }
                            });
                        }
                    }
                    handler.set(a);
                }
            });
            return true;
        };
        var _setChainPropAccess = function setChainPropAccess(owner, property) {
            var chainInfo = getPropertyInChain(owner, property);
            var {base: base} = chainInfo;
            var {prop: prop, chain: chain} = chainInfo;
            var inChainPropHandler = {
                factValue: undefined,
                init(a) {
                    this.factValue = a;
                    return true;
                },
                get() {
                    return this.factValue;
                },
                set(a) {
                    if (this.factValue === a) {
                        return;
                    }
                    this.factValue = a;
                    if (a instanceof Object) {
                        _setChainPropAccess(a, chain);
                    }
                }
            };
            var endPropHandler = {
                init(a) {
                    if (mustCancel(a)) {
                        return false;
                    }
                    return true;
                },
                get() {
                    return constantValue;
                },
                set(a) {
                    if (!mustCancel(a)) {
                        return;
                    }
                    constantValue = a;
                }
            };
            if (!chain) {
                var isTrapped = trapProp(base, prop, false, endPropHandler);
                if (isTrapped) {
                    hit(source);
                }
                return;
            }
            if (base !== undefined && base[prop] === null) {
                trapProp(base, prop, true, inChainPropHandler);
                return;
            }
            if ((base instanceof Object || typeof base === "object") && isEmptyObject(base)) {
                trapProp(base, prop, true, inChainPropHandler);
            }
            var propValue = owner[prop];
            if (propValue instanceof Object || typeof propValue === "object" && propValue !== null) {
                _setChainPropAccess(propValue, chain);
            }
            trapProp(base, prop, true, inChainPropHandler);
        };
        _setChainPropAccess(window, property);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function getNumberFromString(rawString) {
        var parsedDelay = parseInt(rawString, 10);
        var validDelay = nativeIsNaN(parsedDelay) ? null : parsedDelay;
        return validDelay;
    }
    function noopArray() {
        return [];
    }
    function noopObject() {
        return {};
    }
    function noopFunc() {}
    function noopCallbackFunc() {
        return noopFunc;
    }
    function trueFunc() {
        return true;
    }
    function falseFunc() {
        return false;
    }
    function throwFunc() {
        throw new Error;
    }
    function noopPromiseReject() {
        return Promise.reject();
    }
    function noopPromiseResolve() {
        var responseBody = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "{}";
        var responseUrl = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
        var responseType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "basic";
        if (typeof Response === "undefined") {
            return;
        }
        var response = new Response(responseBody, {
            status: 200,
            statusText: "OK"
        });
        if (responseType === "opaque") {
            Object.defineProperties(response, {
                body: {
                    value: null
                },
                status: {
                    value: 0
                },
                ok: {
                    value: false
                },
                statusText: {
                    value: ""
                },
                url: {
                    value: ""
                },
                type: {
                    value: responseType
                }
            });
        } else {
            Object.defineProperties(response, {
                url: {
                    value: responseUrl
                },
                type: {
                    value: responseType
                }
            });
        }
        return Promise.resolve(response);
    }
    function getPropertyInChain(base, chain) {
        var pos = chain.indexOf(".");
        if (pos === -1) {
            return {
                base: base,
                prop: chain
            };
        }
        var prop = chain.slice(0, pos);
        if (base === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        var nextBase = base[prop];
        chain = chain.slice(pos + 1);
        if ((base instanceof Object || typeof base === "object") && isEmptyObject(base)) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase !== undefined) {
            return getPropertyInChain(nextBase, chain);
        }
        Object.defineProperty(base, prop, {
            configurable: true
        });
        return {
            base: base,
            prop: prop,
            chain: chain
        };
    }
    function matchStackTrace(stackMatch, stackTrace) {
        if (!stackMatch || stackMatch === "") {
            return true;
        }
        var regExpValues = backupRegExpValues();
        if (shouldAbortInlineOrInjectedScript(stackMatch, stackTrace)) {
            if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
                restoreRegExpValues(regExpValues);
            }
            return true;
        }
        var stackRegexp = toRegExp(stackMatch);
        var refinedStackTrace = stackTrace.split("\n").slice(2).map((function(line) {
            return line.trim();
        })).join("\n");
        if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
            restoreRegExpValues(regExpValues);
        }
        return getNativeRegexpTest().call(stackRegexp, refinedStackTrace);
    }
    function nativeIsNaN(num) {
        var native = Number.isNaN || window.isNaN;
        return native(num);
    }
    function isEmptyObject(obj) {
        return Object.keys(obj).length === 0 && !obj.prototype;
    }
    function shouldAbortInlineOrInjectedScript(stackMatch, stackTrace) {
        var INLINE_SCRIPT_STRING = "inlineScript";
        var INJECTED_SCRIPT_STRING = "injectedScript";
        var INJECTED_SCRIPT_MARKER = "<anonymous>";
        var isInlineScript = function isInlineScript(match) {
            return match.includes(INLINE_SCRIPT_STRING);
        };
        var isInjectedScript = function isInjectedScript(match) {
            return match.includes(INJECTED_SCRIPT_STRING);
        };
        if (!(isInlineScript(stackMatch) || isInjectedScript(stackMatch))) {
            return false;
        }
        var documentURL = window.location.href;
        var pos = documentURL.indexOf("#");
        if (pos !== -1) {
            documentURL = documentURL.slice(0, pos);
        }
        var stackSteps = stackTrace.split("\n").slice(2).map((function(line) {
            return line.trim();
        }));
        var stackLines = stackSteps.map((function(line) {
            var stack;
            var getStackTraceValues = /(.*?@)?(\S+)(:\d+)(:\d+)\)?$/.exec(line);
            if (getStackTraceValues) {
                var _stackURL, _stackURL2;
                var stackURL = getStackTraceValues[2];
                var stackLine = getStackTraceValues[3];
                var stackCol = getStackTraceValues[4];
                if ((_stackURL = stackURL) !== null && _stackURL !== void 0 && _stackURL.startsWith("(")) {
                    stackURL = stackURL.slice(1);
                }
                if ((_stackURL2 = stackURL) !== null && _stackURL2 !== void 0 && _stackURL2.startsWith(INJECTED_SCRIPT_MARKER)) {
                    var _stackFunction;
                    stackURL = INJECTED_SCRIPT_STRING;
                    var stackFunction = getStackTraceValues[1] !== undefined ? getStackTraceValues[1].slice(0, -1) : line.slice(0, getStackTraceValues.index).trim();
                    if ((_stackFunction = stackFunction) !== null && _stackFunction !== void 0 && _stackFunction.startsWith("at")) {
                        stackFunction = stackFunction.slice(2).trim();
                    }
                    stack = `${stackFunction} ${stackURL}${stackLine}${stackCol}`.trim();
                } else if (stackURL === documentURL) {
                    stack = `${INLINE_SCRIPT_STRING}${stackLine}${stackCol}`.trim();
                } else {
                    stack = `${stackURL}${stackLine}${stackCol}`.trim();
                }
            } else {
                stack = line;
            }
            return stack;
        }));
        if (stackLines) {
            for (var index = 0; index < stackLines.length; index += 1) {
                if (isInlineScript(stackMatch) && stackLines[index].startsWith(INLINE_SCRIPT_STRING) && stackLines[index].match(toRegExp(stackMatch))) {
                    return true;
                }
                if (isInjectedScript(stackMatch) && stackLines[index].startsWith(INJECTED_SCRIPT_STRING) && stackLines[index].match(toRegExp(stackMatch))) {
                    return true;
                }
            }
        }
        return false;
    }
    function getNativeRegexpTest() {
        var descriptor = Object.getOwnPropertyDescriptor(RegExp.prototype, "test");
        var nativeRegexTest = descriptor === null || descriptor === void 0 ? void 0 : descriptor.value;
        if (descriptor && typeof descriptor.value === "function") {
            return nativeRegexTest;
        }
        throw new Error("RegExp.prototype.test is not a function");
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function backupRegExpValues() {
        try {
            var arrayOfRegexpValues = [];
            for (var index = 1; index < 10; index += 1) {
                var value = `$${index}`;
                if (!RegExp[value]) {
                    break;
                }
                arrayOfRegexpValues.push(RegExp[value]);
            }
            return arrayOfRegexpValues;
        } catch (error) {
            return [];
        }
    }
    function restoreRegExpValues(array) {
        if (!array.length) {
            return;
        }
        try {
            var stringPattern = "";
            if (array.length === 1) {
                stringPattern = `(${array[0]})`;
            } else {
                stringPattern = array.reduce((function(accumulator, currentValue, currentIndex) {
                    if (currentIndex === 1) {
                        return `(${accumulator}),(${currentValue})`;
                    }
                    return `${accumulator},(${currentValue})`;
                }));
            }
            var regExpGroup = new RegExp(stringPattern);
            array.toString().replace(regExpGroup, "");
        } catch (error) {
            var message = `Failed to restore RegExp values: ${error}`;
            console.log(message);
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        setConstant.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function setCookie(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function setCookie(source, name, value) {
        var path = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "/";
        var domain = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : "";
        var validValue = getLimitedCookieValue(value);
        if (validValue === null) {
            logMessage(source, `Invalid cookie value: '${validValue}'`);
            return;
        }
        if (!isValidCookiePath(path)) {
            logMessage(source, `Invalid cookie path: '${path}'`);
            return;
        }
        if (!document.location.origin.includes(domain)) {
            logMessage(source, `Cookie domain not matched by origin: '${domain}'`);
            return;
        }
        var cookieToSet = serializeCookie(name, validValue, path, domain);
        if (!cookieToSet) {
            logMessage(source, "Invalid cookie name or value");
            return;
        }
        hit(source);
        document.cookie = cookieToSet;
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function nativeIsNaN(num) {
        var native = Number.isNaN || window.isNaN;
        return native(num);
    }
    function getLimitedCookieValue(value) {
        if (!value) {
            return null;
        }
        var allowedCookieValues = new Set([ "true", "t", "false", "f", "yes", "y", "no", "n", "ok", "on", "off", "accept", "accepted", "notaccepted", "reject", "rejected", "allow", "allowed", "disallow", "deny", "enable", "enabled", "disable", "disabled", "necessary", "required", "hide", "hidden", "essential", "nonessential", "checked", "unchecked", "forbidden", "forever" ]);
        var validValue;
        if (allowedCookieValues.has(value.toLowerCase())) {
            validValue = value;
        } else if (/^\d+$/.test(value)) {
            validValue = parseFloat(value);
            if (nativeIsNaN(validValue)) {
                return null;
            }
            if (Math.abs(validValue) < 0 || Math.abs(validValue) > 32767) {
                return null;
            }
        } else {
            return null;
        }
        return validValue;
    }
    function serializeCookie(name, rawValue, rawPath) {
        var domainValue = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "";
        var shouldEncodeValue = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
        var HOST_PREFIX = "__Host-";
        var SECURE_PREFIX = "__Secure-";
        var COOKIE_BREAKER = ";";
        if (!shouldEncodeValue && `${rawValue}`.includes(COOKIE_BREAKER) || name.includes(COOKIE_BREAKER)) {
            return null;
        }
        var value = shouldEncodeValue ? encodeURIComponent(rawValue) : rawValue;
        var resultCookie = `${name}=${value}`;
        if (name.startsWith(HOST_PREFIX)) {
            resultCookie += "; path=/; secure";
            if (domainValue) {
                console.debug(`Domain value: "${domainValue}" has been ignored, because is not allowed for __Host- prefixed cookies`);
            }
            return resultCookie;
        }
        var path = getCookiePath(rawPath);
        if (path) {
            resultCookie += `; ${path}`;
        }
        if (name.startsWith(SECURE_PREFIX)) {
            resultCookie += "; secure";
        }
        if (domainValue) {
            resultCookie += `; domain=${domainValue}`;
        }
        return resultCookie;
    }
    function isValidCookiePath(rawPath) {
        return rawPath === "/" || rawPath === "none";
    }
    function getCookiePath(rawPath) {
        if (rawPath === "/") {
            return "path=/";
        }
        return "";
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        setCookie.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function setCookieReload(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function setCookieReload(source, name, value) {
        var path = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "/";
        var domain = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : "";
        if (isCookieSetWithValue(document.cookie, name, value)) {
            return;
        }
        var validValue = getLimitedCookieValue(value);
        if (validValue === null) {
            logMessage(source, `Invalid cookie value: '${value}'`);
            return;
        }
        if (!isValidCookiePath(path)) {
            logMessage(source, `Invalid cookie path: '${path}'`);
            return;
        }
        if (!document.location.origin.includes(domain)) {
            logMessage(source, `Cookie domain not matched by origin: '${domain}'`);
            return;
        }
        var cookieToSet = serializeCookie(name, validValue, path, domain);
        if (!cookieToSet) {
            logMessage(source, "Invalid cookie name or value");
            return;
        }
        document.cookie = cookieToSet;
        hit(source);
        if (isCookieSetWithValue(document.cookie, name, value)) {
            window.location.reload();
        }
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function nativeIsNaN(num) {
        var native = Number.isNaN || window.isNaN;
        return native(num);
    }
    function isCookieSetWithValue(cookieString, name, value) {
        return cookieString.split(";").some((function(cookieStr) {
            var pos = cookieStr.indexOf("=");
            if (pos === -1) {
                return false;
            }
            var cookieName = cookieStr.slice(0, pos).trim();
            var cookieValue = cookieStr.slice(pos + 1).trim();
            return name === cookieName && value === cookieValue;
        }));
    }
    function getLimitedCookieValue(value) {
        if (!value) {
            return null;
        }
        var allowedCookieValues = new Set([ "true", "t", "false", "f", "yes", "y", "no", "n", "ok", "on", "off", "accept", "accepted", "notaccepted", "reject", "rejected", "allow", "allowed", "disallow", "deny", "enable", "enabled", "disable", "disabled", "necessary", "required", "hide", "hidden", "essential", "nonessential", "checked", "unchecked", "forbidden", "forever" ]);
        var validValue;
        if (allowedCookieValues.has(value.toLowerCase())) {
            validValue = value;
        } else if (/^\d+$/.test(value)) {
            validValue = parseFloat(value);
            if (nativeIsNaN(validValue)) {
                return null;
            }
            if (Math.abs(validValue) < 0 || Math.abs(validValue) > 32767) {
                return null;
            }
        } else {
            return null;
        }
        return validValue;
    }
    function serializeCookie(name, rawValue, rawPath) {
        var domainValue = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "";
        var shouldEncodeValue = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
        var HOST_PREFIX = "__Host-";
        var SECURE_PREFIX = "__Secure-";
        var COOKIE_BREAKER = ";";
        if (!shouldEncodeValue && `${rawValue}`.includes(COOKIE_BREAKER) || name.includes(COOKIE_BREAKER)) {
            return null;
        }
        var value = shouldEncodeValue ? encodeURIComponent(rawValue) : rawValue;
        var resultCookie = `${name}=${value}`;
        if (name.startsWith(HOST_PREFIX)) {
            resultCookie += "; path=/; secure";
            if (domainValue) {
                console.debug(`Domain value: "${domainValue}" has been ignored, because is not allowed for __Host- prefixed cookies`);
            }
            return resultCookie;
        }
        var path = getCookiePath(rawPath);
        if (path) {
            resultCookie += `; ${path}`;
        }
        if (name.startsWith(SECURE_PREFIX)) {
            resultCookie += "; secure";
        }
        if (domainValue) {
            resultCookie += `; domain=${domainValue}`;
        }
        return resultCookie;
    }
    function isValidCookiePath(rawPath) {
        return rawPath === "/" || rawPath === "none";
    }
    function getCookiePath(rawPath) {
        if (rawPath === "/") {
            return "path=/";
        }
        return "";
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        setCookieReload.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function setLocalStorageItem(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function setLocalStorageItem(source, key, value) {
        if (typeof key === "undefined") {
            logMessage(source, "Item key should be specified.");
            return;
        }
        var validValue;
        try {
            validValue = getLimitedStorageItemValue(value);
        } catch (_unused) {
            logMessage(source, `Invalid storage item value: '${value}'`);
            return;
        }
        var {localStorage: localStorage} = window;
        if (validValue === "$remove$") {
            removeStorageItem(source, localStorage, key);
        } else {
            setStorageItem(source, localStorage, key, validValue);
        }
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function nativeIsNaN(num) {
        var native = Number.isNaN || window.isNaN;
        return native(num);
    }
    function setStorageItem(source, storage, key, value) {
        try {
            storage.setItem(key, value);
        } catch (e) {
            var message = `Unable to set storage item due to: ${e.message}`;
            logMessage(source, message);
        }
    }
    function removeStorageItem(source, storage, key) {
        try {
            if (key.startsWith("/") && (key.endsWith("/") || key.endsWith("/i")) && isValidStrPattern(key)) {
                var regExpKey = toRegExp(key);
                var storageKeys = Object.keys(storage);
                storageKeys.forEach((function(storageKey) {
                    if (regExpKey.test(storageKey)) {
                        storage.removeItem(storageKey);
                    }
                }));
            } else {
                storage.removeItem(key);
            }
        } catch (e) {
            var message = `Unable to remove storage item due to: ${e.message}`;
            logMessage(source, message);
        }
    }
    function getLimitedStorageItemValue(value) {
        if (typeof value !== "string") {
            throw new Error("Invalid value");
        }
        var allowedStorageValues = new Set([ "undefined", "false", "true", "null", "", "yes", "no", "on", "off", "accept", "accepted", "reject", "rejected", "allowed", "denied", "forbidden", "forever" ]);
        var validValue;
        if (allowedStorageValues.has(value.toLowerCase())) {
            validValue = value;
        } else if (value === "emptyArr") {
            validValue = "[]";
        } else if (value === "emptyObj") {
            validValue = "{}";
        } else if (/^\d+$/.test(value)) {
            validValue = parseFloat(value);
            if (nativeIsNaN(validValue)) {
                throw new Error("Invalid value");
            }
            if (Math.abs(validValue) > 32767) {
                throw new Error("Invalid value");
            }
        } else if (value === "$remove$") {
            validValue = "$remove$";
        } else {
            throw new Error("Invalid value");
        }
        return validValue;
    }
    function isValidStrPattern(input) {
        var FORWARD_SLASH = "/";
        var str = escapeRegExp(input);
        if (input[0] === FORWARD_SLASH && input[input.length - 1] === FORWARD_SLASH) {
            str = input.slice(1, -1);
        }
        var isValid;
        try {
            isValid = new RegExp(str);
            isValid = true;
        } catch (e) {
            isValid = false;
        }
        return isValid;
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function escapeRegExp(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        setLocalStorageItem.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function setPopadsDummy(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function setPopadsDummy(source) {
        delete window.PopAds;
        delete window.popns;
        Object.defineProperties(window, {
            PopAds: {
                get: function get() {
                    hit(source);
                    return {};
                }
            },
            popns: {
                get: function get() {
                    hit(source);
                    return {};
                }
            }
        });
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        setPopadsDummy.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function setSessionStorageItem(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function setSessionStorageItem(source, key, value) {
        if (typeof key === "undefined") {
            logMessage(source, "Item key should be specified.");
            return;
        }
        var validValue;
        try {
            validValue = getLimitedStorageItemValue(value);
        } catch (_unused) {
            logMessage(source, `Invalid storage item value: '${value}'`);
            return;
        }
        var {sessionStorage: sessionStorage} = window;
        if (validValue === "$remove$") {
            removeStorageItem(source, sessionStorage, key);
        } else {
            setStorageItem(source, sessionStorage, key, validValue);
        }
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function nativeIsNaN(num) {
        var native = Number.isNaN || window.isNaN;
        return native(num);
    }
    function setStorageItem(source, storage, key, value) {
        try {
            storage.setItem(key, value);
        } catch (e) {
            var message = `Unable to set storage item due to: ${e.message}`;
            logMessage(source, message);
        }
    }
    function removeStorageItem(source, storage, key) {
        try {
            if (key.startsWith("/") && (key.endsWith("/") || key.endsWith("/i")) && isValidStrPattern(key)) {
                var regExpKey = toRegExp(key);
                var storageKeys = Object.keys(storage);
                storageKeys.forEach((function(storageKey) {
                    if (regExpKey.test(storageKey)) {
                        storage.removeItem(storageKey);
                    }
                }));
            } else {
                storage.removeItem(key);
            }
        } catch (e) {
            var message = `Unable to remove storage item due to: ${e.message}`;
            logMessage(source, message);
        }
    }
    function getLimitedStorageItemValue(value) {
        if (typeof value !== "string") {
            throw new Error("Invalid value");
        }
        var allowedStorageValues = new Set([ "undefined", "false", "true", "null", "", "yes", "no", "on", "off", "accept", "accepted", "reject", "rejected", "allowed", "denied", "forbidden", "forever" ]);
        var validValue;
        if (allowedStorageValues.has(value.toLowerCase())) {
            validValue = value;
        } else if (value === "emptyArr") {
            validValue = "[]";
        } else if (value === "emptyObj") {
            validValue = "{}";
        } else if (/^\d+$/.test(value)) {
            validValue = parseFloat(value);
            if (nativeIsNaN(validValue)) {
                throw new Error("Invalid value");
            }
            if (Math.abs(validValue) > 32767) {
                throw new Error("Invalid value");
            }
        } else if (value === "$remove$") {
            validValue = "$remove$";
        } else {
            throw new Error("Invalid value");
        }
        return validValue;
    }
    function isValidStrPattern(input) {
        var FORWARD_SLASH = "/";
        var str = escapeRegExp(input);
        if (input[0] === FORWARD_SLASH && input[input.length - 1] === FORWARD_SLASH) {
            str = input.slice(1, -1);
        }
        var isValid;
        try {
            isValid = new RegExp(str);
            isValid = true;
        } catch (e) {
            isValid = false;
        }
        return isValid;
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function escapeRegExp(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        setSessionStorageItem.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function spoofCSS(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function spoofCSS(source, selectors, cssPropertyName, cssPropertyValue) {
        if (!selectors) {
            return;
        }
        var uboAliases = [ "spoof-css.js", "ubo-spoof-css.js", "ubo-spoof-css" ];
        function convertToCamelCase(cssProperty) {
            if (!cssProperty.includes("-")) {
                return cssProperty;
            }
            var splittedProperty = cssProperty.split("-");
            var firstPart = splittedProperty[0];
            var secondPart = splittedProperty[1];
            return `${firstPart}${secondPart[0].toUpperCase()}${secondPart.slice(1)}`;
        }
        var shouldDebug = !!(cssPropertyName === "debug" && cssPropertyValue);
        var propToValueMap = new Map;
        if (uboAliases.includes(source.name)) {
            var {args: args} = source;
            var arrayOfProperties = [];
            var isDebug = args.at(-2);
            if (isDebug === "debug") {
                arrayOfProperties = args.slice(1, -2);
            } else {
                arrayOfProperties = args.slice(1);
            }
            for (var i = 0; i < arrayOfProperties.length; i += 2) {
                if (arrayOfProperties[i] === "") {
                    break;
                }
                propToValueMap.set(convertToCamelCase(arrayOfProperties[i]), arrayOfProperties[i + 1]);
            }
        } else if (cssPropertyName && cssPropertyValue && !shouldDebug) {
            propToValueMap.set(convertToCamelCase(cssPropertyName), cssPropertyValue);
        }
        var spoofStyle = function spoofStyle(cssProperty, realCssValue) {
            return propToValueMap.has(cssProperty) ? propToValueMap.get(cssProperty) : realCssValue;
        };
        var setRectValue = function setRectValue(rect, prop, value) {
            Object.defineProperty(rect, prop, {
                value: parseFloat(value)
            });
        };
        var getter = function getter(target, prop, receiver) {
            hit(source);
            if (prop === "toString") {
                return target.toString.bind(target);
            }
            return Reflect.get(target, prop, receiver);
        };
        var getComputedStyleWrapper = function getComputedStyleWrapper(target, thisArg, args) {
            if (shouldDebug) {
                debugger;
            }
            var style = Reflect.apply(target, thisArg, args);
            if (!args[0].matches(selectors)) {
                return style;
            }
            var proxiedStyle = new Proxy(style, {
                get(target, prop) {
                    var CSSStyleProp = target[prop];
                    if (typeof CSSStyleProp !== "function") {
                        return spoofStyle(prop, CSSStyleProp || "");
                    }
                    if (prop !== "getPropertyValue") {
                        return CSSStyleProp.bind(target);
                    }
                    var getPropertyValueFunc = new Proxy(CSSStyleProp, {
                        apply(target, thisArg, args) {
                            var cssName = args[0];
                            var cssValue = thisArg[cssName];
                            return spoofStyle(cssName, cssValue);
                        },
                        get: getter
                    });
                    return getPropertyValueFunc;
                },
                getOwnPropertyDescriptor(target, prop) {
                    if (propToValueMap.has(prop)) {
                        return {
                            configurable: true,
                            enumerable: true,
                            value: propToValueMap.get(prop),
                            writable: true
                        };
                    }
                    return Reflect.getOwnPropertyDescriptor(target, prop);
                }
            });
            hit(source);
            return proxiedStyle;
        };
        var getComputedStyleHandler = {
            apply: getComputedStyleWrapper,
            get: getter
        };
        window.getComputedStyle = new Proxy(window.getComputedStyle, getComputedStyleHandler);
        var getBoundingClientRectWrapper = function getBoundingClientRectWrapper(target, thisArg, args) {
            if (shouldDebug) {
                debugger;
            }
            var rect = Reflect.apply(target, thisArg, args);
            if (!thisArg.matches(selectors)) {
                return rect;
            }
            var {top: top, bottom: bottom, height: height, width: width, left: left, right: right} = rect;
            var newDOMRect = new window.DOMRect(rect.x, rect.y, top, bottom, width, height, left, right);
            if (propToValueMap.has("top")) {
                setRectValue(newDOMRect, "top", propToValueMap.get("top"));
            }
            if (propToValueMap.has("bottom")) {
                setRectValue(newDOMRect, "bottom", propToValueMap.get("bottom"));
            }
            if (propToValueMap.has("left")) {
                setRectValue(newDOMRect, "left", propToValueMap.get("left"));
            }
            if (propToValueMap.has("right")) {
                setRectValue(newDOMRect, "right", propToValueMap.get("right"));
            }
            if (propToValueMap.has("height")) {
                setRectValue(newDOMRect, "height", propToValueMap.get("height"));
            }
            if (propToValueMap.has("width")) {
                setRectValue(newDOMRect, "width", propToValueMap.get("width"));
            }
            hit(source);
            return newDOMRect;
        };
        var getBoundingClientRectHandler = {
            apply: getBoundingClientRectWrapper,
            get: getter
        };
        window.Element.prototype.getBoundingClientRect = new Proxy(window.Element.prototype.getBoundingClientRect, getBoundingClientRectHandler);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        spoofCSS.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function trustedClickElement(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function trustedClickElement(source, selectors) {
        var extraMatch = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
        var delay = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : NaN;
        var reload = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : "";
        if (!selectors) {
            return;
        }
        var SHADOW_COMBINATOR = " >>> ";
        var OBSERVER_TIMEOUT_MS = 1e4;
        var THROTTLE_DELAY_MS = 20;
        var STATIC_CLICK_DELAY_MS = 150;
        var STATIC_RELOAD_DELAY_MS = 500;
        var COOKIE_MATCH_MARKER = "cookie:";
        var LOCAL_STORAGE_MATCH_MARKER = "localStorage:";
        var TEXT_MATCH_MARKER = "containsText:";
        var RELOAD_ON_FINAL_CLICK_MARKER = "reloadAfterClick";
        var SELECTORS_DELIMITER = ",";
        var COOKIE_STRING_DELIMITER = ";";
        var COLON = ":";
        var EXTRA_MATCH_DELIMITER = /(,\s*){1}(?=!?cookie:|!?localStorage:|containsText:)/;
        var sleep = function sleep(delayMs) {
            return new Promise((function(resolve) {
                setTimeout(resolve, delayMs);
            }));
        };
        if (selectors.includes(SHADOW_COMBINATOR)) {
            var attachShadowWrapper = function attachShadowWrapper(target, thisArg, argumentsList) {
                var _argumentsList$;
                var mode = (_argumentsList$ = argumentsList[0]) === null || _argumentsList$ === void 0 ? void 0 : _argumentsList$.mode;
                if (mode === "closed") {
                    argumentsList[0].mode = "open";
                }
                return Reflect.apply(target, thisArg, argumentsList);
            };
            var attachShadowHandler = {
                apply: attachShadowWrapper
            };
            window.Element.prototype.attachShadow = new Proxy(window.Element.prototype.attachShadow, attachShadowHandler);
        }
        var parsedDelay;
        if (delay) {
            parsedDelay = parseInt(String(delay), 10);
            var isValidDelay = !Number.isNaN(parsedDelay) || parsedDelay < OBSERVER_TIMEOUT_MS;
            if (!isValidDelay) {
                var message = `Passed delay '${delay}' is invalid or bigger than ${OBSERVER_TIMEOUT_MS} ms`;
                logMessage(source, message);
                return;
            }
        }
        var canClick = !parsedDelay;
        var cookieMatches = [];
        var localStorageMatches = [];
        var textMatches = "";
        var isInvertedMatchCookie = false;
        var isInvertedMatchLocalStorage = false;
        if (extraMatch) {
            var parsedExtraMatch = extraMatch.split(EXTRA_MATCH_DELIMITER).map((function(matchStr) {
                return matchStr.trim();
            }));
            parsedExtraMatch.forEach((function(matchStr) {
                if (matchStr.includes(COOKIE_MATCH_MARKER)) {
                    var {isInvertedMatch: isInvertedMatch, matchValue: matchValue} = parseMatchArg(matchStr);
                    isInvertedMatchCookie = isInvertedMatch;
                    var cookieMatch = matchValue.replace(COOKIE_MATCH_MARKER, "");
                    cookieMatches.push(cookieMatch);
                }
                if (matchStr.includes(LOCAL_STORAGE_MATCH_MARKER)) {
                    var {isInvertedMatch: _isInvertedMatch, matchValue: _matchValue} = parseMatchArg(matchStr);
                    isInvertedMatchLocalStorage = _isInvertedMatch;
                    var localStorageMatch = _matchValue.replace(LOCAL_STORAGE_MATCH_MARKER, "");
                    localStorageMatches.push(localStorageMatch);
                }
                if (matchStr.includes(TEXT_MATCH_MARKER)) {
                    var {matchValue: _matchValue2} = parseMatchArg(matchStr);
                    var textMatch = _matchValue2.replace(TEXT_MATCH_MARKER, "");
                    textMatches = textMatch;
                }
            }));
        }
        if (cookieMatches.length > 0) {
            var parsedCookieMatches = parseCookieString(cookieMatches.join(COOKIE_STRING_DELIMITER));
            var parsedCookies = parseCookieString(document.cookie);
            var cookieKeys = Object.keys(parsedCookies);
            if (cookieKeys.length === 0) {
                return;
            }
            var cookiesMatched = Object.keys(parsedCookieMatches).every((function(key) {
                var valueMatch = parsedCookieMatches[key] ? toRegExp(parsedCookieMatches[key]) : null;
                var keyMatch = toRegExp(key);
                return cookieKeys.some((function(cookieKey) {
                    var keysMatched = keyMatch.test(cookieKey);
                    if (!keysMatched) {
                        return false;
                    }
                    if (!valueMatch) {
                        return true;
                    }
                    var parsedCookieValue = parsedCookies[cookieKey];
                    if (!parsedCookieValue) {
                        return false;
                    }
                    return valueMatch.test(parsedCookieValue);
                }));
            }));
            var shouldRun = cookiesMatched !== isInvertedMatchCookie;
            if (!shouldRun) {
                return;
            }
        }
        if (localStorageMatches.length > 0) {
            var localStorageMatched = localStorageMatches.every((function(str) {
                var itemValue = window.localStorage.getItem(str);
                return itemValue || itemValue === "";
            }));
            var _shouldRun = localStorageMatched !== isInvertedMatchLocalStorage;
            if (!_shouldRun) {
                return;
            }
        }
        var textMatchRegexp = textMatches ? toRegExp(textMatches) : null;
        var selectorsSequence = selectors.split(SELECTORS_DELIMITER).map((function(selector) {
            return selector.trim();
        }));
        var createElementObj = function createElementObj(element, selector) {
            return {
                element: element || null,
                clicked: false,
                selectorText: selector || null
            };
        };
        var elementsSequence = Array(selectorsSequence.length).fill(createElementObj(null));
        var findAndClickElement = function findAndClickElement(elementObj) {
            try {
                if (!elementObj.selectorText) {
                    return;
                }
                var element = queryShadowSelector(elementObj.selectorText);
                if (!element) {
                    logMessage(source, `Could not find element: '${elementObj.selectorText}'`);
                    return;
                }
                element.click();
                elementObj.clicked = true;
            } catch (error) {
                logMessage(source, `Could not click element: '${elementObj.selectorText}'`);
            }
        };
        var shouldReloadAfterClick = false;
        var reloadDelayMs = STATIC_RELOAD_DELAY_MS;
        if (reload) {
            var reloadSplit = reload.split(COLON);
            var reloadMarker = reloadSplit[0];
            var reloadValue = reloadSplit[1];
            if (reloadMarker !== RELOAD_ON_FINAL_CLICK_MARKER) {
                logMessage(source, `Passed reload option '${reload}' is invalid`);
                return;
            }
            if (reloadValue) {
                var passedReload = Number(reloadValue);
                if (Number.isNaN(passedReload)) {
                    logMessage(source, `Passed reload delay value '${passedReload}' is invalid`);
                    return;
                }
                if (passedReload > OBSERVER_TIMEOUT_MS) {
                    logMessage(source, `Passed reload delay value '${passedReload}' is bigger than maximum ${OBSERVER_TIMEOUT_MS} ms`);
                    return;
                }
                reloadDelayMs = passedReload;
            }
            shouldReloadAfterClick = true;
        }
        var canReload = true;
        var clickElementsBySequence = async function clickElementsBySequence() {
            for (var i = 0; i < elementsSequence.length; i += 1) {
                var elementObj = elementsSequence[i];
                if (i >= 1) {
                    await sleep(STATIC_CLICK_DELAY_MS);
                }
                if (!elementObj.element) {
                    break;
                }
                if (!elementObj.clicked) {
                    if (elementObj.element.isConnected) {
                        elementObj.element.click();
                        elementObj.clicked = true;
                    } else {
                        findAndClickElement(elementObj);
                    }
                }
            }
            var allElementsClicked = elementsSequence.every((function(elementObj) {
                return elementObj.clicked === true;
            }));
            if (allElementsClicked) {
                if (shouldReloadAfterClick && canReload) {
                    canReload = false;
                    setTimeout((function() {
                        window.location.reload();
                    }), reloadDelayMs);
                }
                hit(source);
            }
        };
        var handleElement = function handleElement(element, i, selector) {
            var elementObj = createElementObj(element, selector);
            elementsSequence[i] = elementObj;
            if (canClick) {
                clickElementsBySequence();
            }
        };
        var fulfillAndHandleSelectors = function fulfillAndHandleSelectors() {
            var fulfilledSelectors = [];
            selectorsSequence.forEach((function(selector, i) {
                if (!selector) {
                    return;
                }
                var element = queryShadowSelector(selector, document.documentElement, textMatchRegexp);
                if (!element) {
                    return;
                }
                handleElement(element, i, selector);
                fulfilledSelectors.push(selector);
            }));
            selectorsSequence = selectorsSequence.map((function(selector) {
                return selector && fulfilledSelectors.includes(selector) ? null : selector;
            }));
            return selectorsSequence;
        };
        var findElements = function findElements(mutations, observer) {
            selectorsSequence = fulfillAndHandleSelectors();
            var allSelectorsFulfilled = selectorsSequence.every((function(selector) {
                return selector === null;
            }));
            if (allSelectorsFulfilled) {
                observer.disconnect();
            }
        };
        var initializeMutationObserver = function initializeMutationObserver() {
            var observer = new MutationObserver(throttle(findElements, THROTTLE_DELAY_MS));
            observer.observe(document.documentElement, {
                attributes: true,
                childList: true,
                subtree: true
            });
            setTimeout((function() {
                return observer.disconnect();
            }), OBSERVER_TIMEOUT_MS);
        };
        var checkInitialElements = function checkInitialElements() {
            var foundElements = selectorsSequence.every((function(selector) {
                if (!selector) {
                    return false;
                }
                var element = queryShadowSelector(selector, document.documentElement, textMatchRegexp);
                return !!element;
            }));
            if (foundElements) {
                fulfillAndHandleSelectors();
            } else {
                initializeMutationObserver();
            }
        };
        checkInitialElements();
        if (parsedDelay) {
            setTimeout((function() {
                clickElementsBySequence();
                canClick = true;
            }), parsedDelay);
        }
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function parseCookieString(cookieString) {
        var COOKIE_DELIMITER = "=";
        var COOKIE_PAIRS_DELIMITER = ";";
        var cookieChunks = cookieString.split(COOKIE_PAIRS_DELIMITER);
        var cookieData = {};
        cookieChunks.forEach((function(singleCookie) {
            var cookieKey;
            var cookieValue = "";
            var delimiterIndex = singleCookie.indexOf(COOKIE_DELIMITER);
            if (delimiterIndex === -1) {
                cookieKey = singleCookie.trim();
            } else {
                cookieKey = singleCookie.slice(0, delimiterIndex).trim();
                cookieValue = singleCookie.slice(delimiterIndex + 1);
            }
            cookieData[cookieKey] = cookieValue || null;
        }));
        return cookieData;
    }
    function throttle(cb, delay) {
        var wait = false;
        var savedArgs;
        var _wrapper = function wrapper() {
            for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                args[_key] = arguments[_key];
            }
            if (wait) {
                savedArgs = args;
                return;
            }
            cb(...args);
            wait = true;
            setTimeout((function() {
                wait = false;
                if (savedArgs) {
                    _wrapper(...savedArgs);
                    savedArgs = null;
                }
            }), delay);
        };
        return _wrapper;
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function parseMatchArg(match) {
        var INVERT_MARKER = "!";
        var isInvertedMatch = match ? match === null || match === void 0 ? void 0 : match.startsWith(INVERT_MARKER) : false;
        var matchValue = isInvertedMatch ? match.slice(1) : match;
        var matchRegexp = toRegExp(matchValue);
        return {
            isInvertedMatch: isInvertedMatch,
            matchRegexp: matchRegexp,
            matchValue: matchValue
        };
    }
    function queryShadowSelector(selector) {
        var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document.documentElement;
        var textContent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
        var SHADOW_COMBINATOR = " >>> ";
        var pos = selector.indexOf(SHADOW_COMBINATOR);
        if (pos === -1) {
            if (textContent) {
                return findElementWithText(context, selector, textContent);
            }
            return context.querySelector(selector);
        }
        var shadowHostSelector = selector.slice(0, pos).trim();
        var elem = context.querySelector(shadowHostSelector);
        if (!elem || !elem.shadowRoot) {
            return null;
        }
        var shadowRootSelector = selector.slice(pos + SHADOW_COMBINATOR.length).trim();
        return queryShadowSelector(shadowRootSelector, elem.shadowRoot, textContent);
    }
    function doesElementContainText(element, matchRegexp) {
        var {textContent: textContent} = element;
        if (!textContent) {
            return false;
        }
        return matchRegexp.test(textContent);
    }
    function findElementWithText(rootElement, selector, matchRegexp) {
        var elements = rootElement.querySelectorAll(selector);
        for (var i = 0; i < elements.length; i += 1) {
            if (doesElementContainText(elements[i], matchRegexp)) {
                return elements[i];
            }
        }
        return null;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        trustedClickElement.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function trustedCreateElement(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function trustedCreateElement(source, parentSelector, tagName) {
        var attributePairs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "";
        var textContent = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : "";
        var cleanupDelayMs = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : NaN;
        if (!parentSelector || !tagName) {
            return;
        }
        var IFRAME_WINDOW_NAME = "trusted-create-element-window";
        if (window.name === IFRAME_WINDOW_NAME) {
            return;
        }
        var logError = function logError(prefix, error) {
            logMessage(source, `${prefix} due to ${getErrorMessage(error)}`);
        };
        var element;
        try {
            element = document.createElement(tagName);
            element.textContent = textContent;
        } catch (e) {
            logError(`Cannot create element with tag name '${tagName}'`, e);
            return;
        }
        var attributes = [];
        try {
            attributes = parseAttributePairs(attributePairs);
        } catch (e) {
            logError(`Cannot parse attributePairs param: '${attributePairs}'`, e);
            return;
        }
        attributes.forEach((function(attr) {
            try {
                element.setAttribute(attr.name, attr.value);
            } catch (e) {
                logError(`Cannot set attribute '${attr.name}' with value '${attr.value}'`, e);
            }
        }));
        var timerId;
        var elementCreated = false;
        var elementRemoved = false;
        var findParentAndAppendEl = function findParentAndAppendEl(parentElSelector, el, removeElDelayMs) {
            var parentEl;
            try {
                parentEl = document.querySelector(parentElSelector);
            } catch (e) {
                logError(`Cannot find parent element by selector '${parentElSelector}'`, e);
                return false;
            }
            if (!parentEl) {
                logMessage(source, `No parent element found by selector: '${parentElSelector}'`);
                return false;
            }
            try {
                if (!parentEl.contains(el)) {
                    parentEl.append(el);
                }
                if (el instanceof HTMLIFrameElement && el.contentWindow) {
                    el.contentWindow.name = IFRAME_WINDOW_NAME;
                }
                elementCreated = true;
                hit(source);
            } catch (e) {
                logError(`Cannot append child to parent by selector '${parentElSelector}'`, e);
                return false;
            }
            if (!nativeIsNaN(removeElDelayMs)) {
                timerId = setTimeout((function() {
                    el.remove();
                    elementRemoved = true;
                    clearTimeout(timerId);
                }), removeElDelayMs);
            }
            return true;
        };
        if (!findParentAndAppendEl(parentSelector, element, cleanupDelayMs)) {
            observeDocumentWithTimeout((function(mutations, observer) {
                if (elementRemoved || elementCreated || findParentAndAppendEl(parentSelector, element, cleanupDelayMs)) {
                    observer.disconnect();
                }
            }));
        }
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function observeDocumentWithTimeout(callback) {
        var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
            subtree: true,
            childList: true
        };
        var timeout = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1e4;
        var documentObserver = new MutationObserver((function(mutations, observer) {
            observer.disconnect();
            callback(mutations, observer);
            observer.observe(document.documentElement, options);
        }));
        documentObserver.observe(document.documentElement, options);
        if (typeof timeout === "number") {
            setTimeout((function() {
                return documentObserver.disconnect();
            }), timeout);
        }
    }
    function nativeIsNaN(num) {
        var native = Number.isNaN || window.isNaN;
        return native(num);
    }
    function parseAttributePairs(input) {
        if (!input) {
            return [];
        }
        var NAME_VALUE_SEPARATOR = "=";
        var PAIRS_SEPARATOR = " ";
        var SINGLE_QUOTE = "'";
        var DOUBLE_QUOTE = '"';
        var BACKSLASH = "\\";
        var pairs = [];
        for (var i = 0; i < input.length; i += 1) {
            var name = "";
            var value = "";
            while (i < input.length && input[i] !== NAME_VALUE_SEPARATOR && input[i] !== PAIRS_SEPARATOR) {
                name += input[i];
                i += 1;
            }
            if (i < input.length && input[i] === NAME_VALUE_SEPARATOR) {
                i += 1;
                var quote = null;
                if (input[i] === SINGLE_QUOTE || input[i] === DOUBLE_QUOTE) {
                    quote = input[i];
                    i += 1;
                    for (;i < input.length; i += 1) {
                        if (input[i] === quote) {
                            if (input[i - 1] === BACKSLASH) {
                                value = `${value.slice(0, -1)}${quote}`;
                            } else {
                                i += 1;
                                quote = null;
                                break;
                            }
                        } else {
                            value += input[i];
                        }
                    }
                    if (quote !== null) {
                        throw new Error(`Unbalanced quote for attribute value: '${input}'`);
                    }
                } else {
                    throw new Error(`Attribute value should be quoted: "${input.slice(i)}"`);
                }
            }
            name = name.trim();
            value = value.trim();
            if (!name) {
                if (!value) {
                    continue;
                }
                throw new Error(`Attribute name before '=' should be specified: '${input}'`);
            }
            pairs.push({
                name: name,
                value: value
            });
            if (input[i] && input[i] !== PAIRS_SEPARATOR) {
                throw new Error(`No space before attribute: '${input.slice(i)}'`);
            }
        }
        return pairs;
    }
    function getErrorMessage(error) {
        var isErrorWithMessage = function isErrorWithMessage(e) {
            return typeof e === "object" && e !== null && "message" in e && typeof e.message === "string";
        };
        if (isErrorWithMessage(error)) {
            return error.message;
        }
        try {
            return new Error(JSON.stringify(error)).message;
        } catch (_unused) {
            return new Error(String(error)).message;
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        trustedCreateElement.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function trustedDispatchEvent(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function trustedDispatchEvent(source, event, target) {
        if (!event) {
            return;
        }
        var hasBeenDispatched = false;
        var eventTarget = document;
        if (target === "window") {
            eventTarget = window;
        }
        var events = new Set;
        var dispatch = function dispatch() {
            var customEvent = new Event(event);
            if (typeof target === "string" && target !== "window") {
                eventTarget = document.querySelector(target);
            }
            var isEventAdded = events.has(event);
            if (!hasBeenDispatched && isEventAdded && eventTarget) {
                hasBeenDispatched = true;
                hit(source);
                eventTarget.dispatchEvent(customEvent);
            }
        };
        var wrapper = function wrapper(eventListener, thisArg, args) {
            var eventName = args[0];
            if (thisArg && eventName) {
                events.add(eventName);
                setTimeout((function() {
                    dispatch();
                }), 1);
            }
            return Reflect.apply(eventListener, thisArg, args);
        };
        var handler = {
            apply: wrapper
        };
        EventTarget.prototype.addEventListener = new Proxy(EventTarget.prototype.addEventListener, handler);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        trustedDispatchEvent.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function trustedPruneInboundObject(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function trustedPruneInboundObject(source, functionName, propsToRemove, requiredInitialProps) {
        var stack = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : "";
        if (!functionName) {
            return;
        }
        var nativeObjects = {
            nativeStringify: window.JSON.stringify
        };
        var {base: base, prop: prop} = getPropertyInChain(window, functionName);
        if (!base || !prop || typeof base[prop] !== "function") {
            var message = `${functionName} is not a function`;
            logMessage(source, message);
            return;
        }
        var prunePaths = getPrunePath(propsToRemove);
        var requiredPaths = getPrunePath(requiredInitialProps);
        var objectWrapper = function objectWrapper(target, thisArg, args) {
            var data = args[0];
            if (typeof data === "object") {
                data = jsonPruner(source, data, prunePaths, requiredPaths, stack, nativeObjects);
                args[0] = data;
            }
            return Reflect.apply(target, thisArg, args);
        };
        var objectHandler = {
            apply: objectWrapper
        };
        base[prop] = new Proxy(base[prop], objectHandler);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function matchStackTrace(stackMatch, stackTrace) {
        if (!stackMatch || stackMatch === "") {
            return true;
        }
        var regExpValues = backupRegExpValues();
        if (shouldAbortInlineOrInjectedScript(stackMatch, stackTrace)) {
            if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
                restoreRegExpValues(regExpValues);
            }
            return true;
        }
        var stackRegexp = toRegExp(stackMatch);
        var refinedStackTrace = stackTrace.split("\n").slice(2).map((function(line) {
            return line.trim();
        })).join("\n");
        if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
            restoreRegExpValues(regExpValues);
        }
        return getNativeRegexpTest().call(stackRegexp, refinedStackTrace);
    }
    function getPropertyInChain(base, chain) {
        var pos = chain.indexOf(".");
        if (pos === -1) {
            return {
                base: base,
                prop: chain
            };
        }
        var prop = chain.slice(0, pos);
        if (base === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        var nextBase = base[prop];
        chain = chain.slice(pos + 1);
        if ((base instanceof Object || typeof base === "object") && isEmptyObject(base)) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase !== undefined) {
            return getPropertyInChain(nextBase, chain);
        }
        Object.defineProperty(base, prop, {
            configurable: true
        });
        return {
            base: base,
            prop: prop,
            chain: chain
        };
    }
    function getWildcardPropertyInChain(base, chain) {
        var lookThrough = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var output = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
        var valueToCheck = arguments.length > 4 ? arguments[4] : undefined;
        var pos = chain.indexOf(".");
        if (pos === -1) {
            if (chain === "*" || chain === "[]") {
                for (var key in base) {
                    if (Object.prototype.hasOwnProperty.call(base, key)) {
                        if (valueToCheck !== undefined) {
                            var objectValue = base[key];
                            if (typeof objectValue === "string" && valueToCheck instanceof RegExp) {
                                if (valueToCheck.test(objectValue)) {
                                    output.push({
                                        base: base,
                                        prop: key
                                    });
                                }
                            } else if (objectValue === valueToCheck) {
                                output.push({
                                    base: base,
                                    prop: key
                                });
                            }
                        } else {
                            output.push({
                                base: base,
                                prop: key
                            });
                        }
                    }
                }
            } else if (valueToCheck !== undefined) {
                var _objectValue = base[chain];
                if (typeof _objectValue === "string" && valueToCheck instanceof RegExp) {
                    if (valueToCheck.test(_objectValue)) {
                        output.push({
                            base: base,
                            prop: chain
                        });
                    }
                } else if (base[chain] === valueToCheck) {
                    output.push({
                        base: base,
                        prop: chain
                    });
                }
            } else {
                output.push({
                    base: base,
                    prop: chain
                });
            }
            return output;
        }
        var prop = chain.slice(0, pos);
        var shouldLookThrough = prop === "[]" && Array.isArray(base) || prop === "*" && base instanceof Object || prop === "[-]" && Array.isArray(base) || prop === "{-}" && base instanceof Object;
        if (shouldLookThrough) {
            var nextProp = chain.slice(pos + 1);
            var baseKeys = Object.keys(base);
            if (prop === "{-}" || prop === "[-]") {
                var type = Array.isArray(base) ? "array" : "object";
                var shouldRemove = !!(prop === "{-}" && type === "object") || !!(prop === "[-]" && type === "array");
                if (!shouldRemove) {
                    return output;
                }
                baseKeys.forEach((function(key) {
                    var item = base[key];
                    if (isKeyInObject(item, nextProp, valueToCheck)) {
                        output.push({
                            base: base,
                            prop: key
                        });
                    }
                }));
                return output;
            }
            baseKeys.forEach((function(key) {
                var item = base[key];
                getWildcardPropertyInChain(item, nextProp, lookThrough, output, valueToCheck);
            }));
        }
        if (Array.isArray(base)) {
            base.forEach((function(key) {
                var nextBase = key;
                if (nextBase !== undefined) {
                    getWildcardPropertyInChain(nextBase, chain, lookThrough, output, valueToCheck);
                }
            }));
        }
        var nextBase = base[prop];
        chain = chain.slice(pos + 1);
        if (nextBase !== undefined) {
            getWildcardPropertyInChain(nextBase, chain, lookThrough, output, valueToCheck);
        }
        return output;
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function isPruningNeeded(source, root, prunePaths, requiredPaths, stack, nativeObjects) {
        if (!root) {
            return false;
        }
        var {nativeStringify: nativeStringify} = nativeObjects;
        var shouldProcess;
        var prunePathsToCheck = prunePaths.map((function(obj) {
            return obj.path;
        }));
        var requiredPathsToCheck = requiredPaths.map((function(obj) {
            return obj.path;
        }));
        if (prunePathsToCheck.length === 0 && requiredPathsToCheck.length > 0) {
            var rootString = nativeStringify(root);
            var matchRegex = toRegExp(requiredPathsToCheck.join(""));
            var shouldLog = matchRegex.test(rootString);
            if (shouldLog) {
                logMessage(source, `${window.location.hostname}\n${nativeStringify(root, null, 2)}\nStack trace:\n${(new Error).stack}`, true);
                if (root && typeof root === "object") {
                    logMessage(source, root, true, false);
                }
                shouldProcess = false;
                return shouldProcess;
            }
        }
        if (stack && !matchStackTrace(stack, (new Error).stack || "")) {
            shouldProcess = false;
            return shouldProcess;
        }
        var wildcardSymbols = [ ".*.", "*.", ".*", ".[].", "[].", ".[]" ];
        var _loop = function _loop() {
            var requiredPath = requiredPathsToCheck[i];
            var lastNestedPropName = requiredPath.split(".").pop();
            var hasWildcard = wildcardSymbols.some((function(symbol) {
                return requiredPath.includes(symbol);
            }));
            var details = getWildcardPropertyInChain(root, requiredPath, hasWildcard);
            if (!details.length) {
                shouldProcess = false;
                return {
                    v: shouldProcess
                };
            }
            shouldProcess = !hasWildcard;
            for (var j = 0; j < details.length; j += 1) {
                var hasRequiredProp = typeof lastNestedPropName === "string" && details[j].base[lastNestedPropName] !== undefined;
                if (hasWildcard) {
                    shouldProcess = hasRequiredProp || shouldProcess;
                } else {
                    shouldProcess = hasRequiredProp && shouldProcess;
                }
            }
        }, _ret;
        for (var i = 0; i < requiredPathsToCheck.length; i += 1) {
            _ret = _loop();
            if (_ret) return _ret.v;
        }
        return shouldProcess;
    }
    function jsonPruner(source, root, prunePaths, requiredPaths, stack, nativeObjects) {
        var {nativeStringify: nativeStringify} = nativeObjects;
        if (prunePaths.length === 0 && requiredPaths.length === 0) {
            logMessage(source, `${window.location.hostname}\n${nativeStringify(root, null, 2)}\nStack trace:\n${(new Error).stack}`, true);
            if (root && typeof root === "object") {
                logMessage(source, root, true, false);
            }
            return root;
        }
        try {
            if (isPruningNeeded(source, root, prunePaths, requiredPaths, stack, nativeObjects) === false) {
                return root;
            }
            prunePaths.forEach((function(path) {
                var pathToCheck = path.path;
                var valueToCheck = path.value;
                var ownerObjArr = getWildcardPropertyInChain(root, pathToCheck, true, [], valueToCheck);
                for (var i = ownerObjArr.length - 1; i >= 0; i -= 1) {
                    var ownerObj = ownerObjArr[i];
                    if (ownerObj === undefined || !ownerObj.base) {
                        continue;
                    }
                    hit(source);
                    if (!Array.isArray(ownerObj.base)) {
                        delete ownerObj.base[ownerObj.prop];
                        continue;
                    }
                    try {
                        var index = Number(ownerObj.prop);
                        if (Number.isNaN(index)) {
                            continue;
                        }
                        ownerObj.base.splice(index, 1);
                    } catch (error) {
                        console.error("Error while deleting array element", error);
                    }
                }
            }));
        } catch (e) {
            logMessage(source, e);
        }
        return root;
    }
    function getPrunePath(props) {
        var VALUE_MARKER = ".[=].";
        var REGEXP_START_MARKER = "/";
        var validPropsString = typeof props === "string" && props !== undefined && props !== "";
        if (validPropsString) {
            var splitRegexp = /(?<!\.\[=\]\.\/(?:[^/]|\\.)*)\s+/;
            var parts = props.split(splitRegexp).map((function(part) {
                var splitPart = part.split(VALUE_MARKER);
                var path = splitPart[0];
                var value = splitPart[1];
                if (value !== undefined) {
                    if (value === "true") {
                        value = true;
                    } else if (value === "false") {
                        value = false;
                    } else if (value.startsWith(REGEXP_START_MARKER)) {
                        value = toRegExp(value);
                    } else if (typeof value === "string" && /^\d+$/.test(value)) {
                        value = parseFloat(value);
                    }
                    return {
                        path: path,
                        value: value
                    };
                }
                return {
                    path: path
                };
            }));
            return parts;
        }
        return [];
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function getNativeRegexpTest() {
        var descriptor = Object.getOwnPropertyDescriptor(RegExp.prototype, "test");
        var nativeRegexTest = descriptor === null || descriptor === void 0 ? void 0 : descriptor.value;
        if (descriptor && typeof descriptor.value === "function") {
            return nativeRegexTest;
        }
        throw new Error("RegExp.prototype.test is not a function");
    }
    function shouldAbortInlineOrInjectedScript(stackMatch, stackTrace) {
        var INLINE_SCRIPT_STRING = "inlineScript";
        var INJECTED_SCRIPT_STRING = "injectedScript";
        var INJECTED_SCRIPT_MARKER = "<anonymous>";
        var isInlineScript = function isInlineScript(match) {
            return match.includes(INLINE_SCRIPT_STRING);
        };
        var isInjectedScript = function isInjectedScript(match) {
            return match.includes(INJECTED_SCRIPT_STRING);
        };
        if (!(isInlineScript(stackMatch) || isInjectedScript(stackMatch))) {
            return false;
        }
        var documentURL = window.location.href;
        var pos = documentURL.indexOf("#");
        if (pos !== -1) {
            documentURL = documentURL.slice(0, pos);
        }
        var stackSteps = stackTrace.split("\n").slice(2).map((function(line) {
            return line.trim();
        }));
        var stackLines = stackSteps.map((function(line) {
            var stack;
            var getStackTraceValues = /(.*?@)?(\S+)(:\d+)(:\d+)\)?$/.exec(line);
            if (getStackTraceValues) {
                var _stackURL, _stackURL2;
                var stackURL = getStackTraceValues[2];
                var stackLine = getStackTraceValues[3];
                var stackCol = getStackTraceValues[4];
                if ((_stackURL = stackURL) !== null && _stackURL !== void 0 && _stackURL.startsWith("(")) {
                    stackURL = stackURL.slice(1);
                }
                if ((_stackURL2 = stackURL) !== null && _stackURL2 !== void 0 && _stackURL2.startsWith(INJECTED_SCRIPT_MARKER)) {
                    var _stackFunction;
                    stackURL = INJECTED_SCRIPT_STRING;
                    var stackFunction = getStackTraceValues[1] !== undefined ? getStackTraceValues[1].slice(0, -1) : line.slice(0, getStackTraceValues.index).trim();
                    if ((_stackFunction = stackFunction) !== null && _stackFunction !== void 0 && _stackFunction.startsWith("at")) {
                        stackFunction = stackFunction.slice(2).trim();
                    }
                    stack = `${stackFunction} ${stackURL}${stackLine}${stackCol}`.trim();
                } else if (stackURL === documentURL) {
                    stack = `${INLINE_SCRIPT_STRING}${stackLine}${stackCol}`.trim();
                } else {
                    stack = `${stackURL}${stackLine}${stackCol}`.trim();
                }
            } else {
                stack = line;
            }
            return stack;
        }));
        if (stackLines) {
            for (var index = 0; index < stackLines.length; index += 1) {
                if (isInlineScript(stackMatch) && stackLines[index].startsWith(INLINE_SCRIPT_STRING) && stackLines[index].match(toRegExp(stackMatch))) {
                    return true;
                }
                if (isInjectedScript(stackMatch) && stackLines[index].startsWith(INJECTED_SCRIPT_STRING) && stackLines[index].match(toRegExp(stackMatch))) {
                    return true;
                }
            }
        }
        return false;
    }
    function isEmptyObject(obj) {
        return Object.keys(obj).length === 0 && !obj.prototype;
    }
    function backupRegExpValues() {
        try {
            var arrayOfRegexpValues = [];
            for (var index = 1; index < 10; index += 1) {
                var value = `$${index}`;
                if (!RegExp[value]) {
                    break;
                }
                arrayOfRegexpValues.push(RegExp[value]);
            }
            return arrayOfRegexpValues;
        } catch (error) {
            return [];
        }
    }
    function restoreRegExpValues(array) {
        if (!array.length) {
            return;
        }
        try {
            var stringPattern = "";
            if (array.length === 1) {
                stringPattern = `(${array[0]})`;
            } else {
                stringPattern = array.reduce((function(accumulator, currentValue, currentIndex) {
                    if (currentIndex === 1) {
                        return `(${accumulator}),(${currentValue})`;
                    }
                    return `${accumulator},(${currentValue})`;
                }));
            }
            var regExpGroup = new RegExp(stringPattern);
            array.toString().replace(regExpGroup, "");
        } catch (error) {
            var message = `Failed to restore RegExp values: ${error}`;
            console.log(message);
        }
    }
    function isKeyInObject(baseObj, path, valueToCheck) {
        var parts = path.split(".");
        var _check = function check(targetObject, pathSegments) {
            if (pathSegments.length === 0) {
                if (valueToCheck !== undefined) {
                    if (typeof targetObject === "string" && valueToCheck instanceof RegExp) {
                        return valueToCheck.test(targetObject);
                    }
                    return targetObject === valueToCheck;
                }
                return true;
            }
            var current = pathSegments[0];
            var rest = pathSegments.slice(1);
            if (current === "*" || current === "[]") {
                if (Array.isArray(targetObject)) {
                    return targetObject.some((function(item) {
                        return _check(item, rest);
                    }));
                }
                if (typeof targetObject === "object" && targetObject !== null) {
                    return Object.keys(targetObject).some((function(key) {
                        return _check(targetObject[key], rest);
                    }));
                }
            }
            if (Object.prototype.hasOwnProperty.call(targetObject, current)) {
                return _check(targetObject[current], rest);
            }
            return false;
        };
        return _check(baseObj, parts);
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        trustedPruneInboundObject.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function trustedReplaceFetchResponse(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function trustedReplaceFetchResponse(source) {
        var pattern = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
        var replacement = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
        var propsToMatch = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "";
        var verbose = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
        if (typeof fetch === "undefined" || typeof Proxy === "undefined" || typeof Response === "undefined") {
            return;
        }
        if (pattern === "" && replacement !== "") {
            logMessage(source, "Pattern argument should not be empty string");
            return;
        }
        var shouldLog = pattern === "" && replacement === "";
        var shouldLogContent = verbose === "true";
        var nativeRequestClone = Request.prototype.clone;
        var nativeFetch = fetch;
        var shouldReplace = false;
        var fetchData;
        var handlerWrapper = function handlerWrapper(target, thisArg, args) {
            fetchData = getFetchData(args, nativeRequestClone);
            if (shouldLog) {
                logMessage(source, `fetch( ${objectToString(fetchData)} )`, true);
                hit(source);
                return Reflect.apply(target, thisArg, args);
            }
            shouldReplace = matchRequestProps(source, propsToMatch, fetchData);
            if (!shouldReplace) {
                return Reflect.apply(target, thisArg, args);
            }
            return nativeFetch.apply(null, args).then((function(response) {
                return response.text().then((function(bodyText) {
                    var patternRegexp = pattern === "*" ? /(\n|.)*/ : toRegExp(pattern);
                    if (shouldLogContent) {
                        logMessage(source, `Original text content: ${bodyText}`);
                    }
                    var modifiedTextContent = bodyText.replace(patternRegexp, replacement);
                    if (shouldLogContent) {
                        logMessage(source, `Modified text content: ${modifiedTextContent}`);
                    }
                    var forgedResponse = forgeResponse(response, modifiedTextContent);
                    hit(source);
                    return forgedResponse;
                })).catch((function() {
                    var fetchDataStr = objectToString(fetchData);
                    var message = `Response body can't be converted to text: ${fetchDataStr}`;
                    logMessage(source, message);
                    return Reflect.apply(target, thisArg, args);
                }));
            })).catch((function() {
                return Reflect.apply(target, thisArg, args);
            }));
        };
        var fetchHandler = {
            apply: handlerWrapper
        };
        fetch = new Proxy(fetch, fetchHandler);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function getFetchData(args, nativeRequestClone) {
        var fetchPropsObj = {};
        var resource = args[0];
        var fetchUrl;
        var fetchInit;
        if (resource instanceof Request) {
            var realData = nativeRequestClone.call(resource);
            var requestData = getRequestData(realData);
            fetchUrl = requestData.url;
            fetchInit = requestData;
        } else {
            fetchUrl = resource;
            fetchInit = args[1];
        }
        fetchPropsObj.url = fetchUrl;
        if (fetchInit instanceof Object) {
            var props = Object.keys(fetchInit);
            props.forEach((function(prop) {
                fetchPropsObj[prop] = fetchInit[prop];
            }));
        }
        return fetchPropsObj;
    }
    function objectToString(obj) {
        if (!obj || typeof obj !== "object") {
            return String(obj);
        }
        if (isEmptyObject(obj)) {
            return "{}";
        }
        return Object.entries(obj).map((function(pair) {
            var key = pair[0];
            var value = pair[1];
            var recordValueStr = value;
            if (value instanceof Object) {
                recordValueStr = `{ ${objectToString(value)} }`;
            }
            return `${key}:"${recordValueStr}"`;
        })).join(" ");
    }
    function matchRequestProps(source, propsToMatch, requestData) {
        if (propsToMatch === "" || propsToMatch === "*") {
            return true;
        }
        var isMatched;
        var parsedData = parseMatchProps(propsToMatch);
        if (!isValidParsedData(parsedData)) {
            logMessage(source, `Invalid parameter: ${propsToMatch}`);
            isMatched = false;
        } else {
            var matchData = getMatchPropsData(parsedData);
            var matchKeys = Object.keys(matchData);
            isMatched = matchKeys.every((function(matchKey) {
                var matchValue = matchData[matchKey];
                var dataValue = requestData[matchKey];
                return Object.prototype.hasOwnProperty.call(requestData, matchKey) && typeof dataValue === "string" && (matchValue === null || matchValue === void 0 ? void 0 : matchValue.test(dataValue));
            }));
        }
        return isMatched;
    }
    function forgeResponse(response, textContent) {
        var {bodyUsed: bodyUsed, headers: headers, ok: ok, redirected: redirected, status: status, statusText: statusText, type: type, url: url} = response;
        var forgedResponse = new Response(textContent, {
            status: status,
            statusText: statusText,
            headers: headers
        });
        Object.defineProperties(forgedResponse, {
            url: {
                value: url
            },
            type: {
                value: type
            },
            ok: {
                value: ok
            },
            bodyUsed: {
                value: bodyUsed
            },
            redirected: {
                value: redirected
            }
        });
        return forgedResponse;
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function isValidStrPattern(input) {
        var FORWARD_SLASH = "/";
        var str = escapeRegExp(input);
        if (input[0] === FORWARD_SLASH && input[input.length - 1] === FORWARD_SLASH) {
            str = input.slice(1, -1);
        }
        var isValid;
        try {
            isValid = new RegExp(str);
            isValid = true;
        } catch (e) {
            isValid = false;
        }
        return isValid;
    }
    function escapeRegExp(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    function isEmptyObject(obj) {
        return Object.keys(obj).length === 0 && !obj.prototype;
    }
    function getRequestData(request) {
        var requestInitOptions = getRequestProps();
        var entries = requestInitOptions.map((function(key) {
            var value = request[key];
            return [ key, value ];
        }));
        return Object.fromEntries(entries);
    }
    function getRequestProps() {
        return [ "url", "method", "headers", "body", "credentials", "cache", "redirect", "referrer", "referrerPolicy", "integrity", "keepalive", "signal", "mode" ];
    }
    function parseMatchProps(propsToMatchStr) {
        var PROPS_DIVIDER = " ";
        var PAIRS_MARKER = ":";
        var isRequestProp = function isRequestProp(prop) {
            return getRequestProps().includes(prop);
        };
        var propsObj = {};
        var props = propsToMatchStr.split(PROPS_DIVIDER);
        props.forEach((function(prop) {
            var dividerInd = prop.indexOf(PAIRS_MARKER);
            var key = prop.slice(0, dividerInd);
            if (isRequestProp(key)) {
                var value = prop.slice(dividerInd + 1);
                propsObj[key] = value;
            } else {
                propsObj.url = prop;
            }
        }));
        return propsObj;
    }
    function isValidParsedData(data) {
        return Object.values(data).every((function(value) {
            return isValidStrPattern(value);
        }));
    }
    function getMatchPropsData(data) {
        var matchData = {};
        var dataKeys = Object.keys(data);
        dataKeys.forEach((function(key) {
            matchData[key] = toRegExp(data[key]);
        }));
        return matchData;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        trustedReplaceFetchResponse.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function trustedReplaceNodeText(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function trustedReplaceNodeText(source, nodeName, textMatch, pattern, replacement) {
        var {selector: selector, nodeNameMatch: nodeNameMatch, textContentMatch: textContentMatch, patternMatch: patternMatch} = parseNodeTextParams(nodeName, textMatch, pattern);
        for (var _len = arguments.length, extraArgs = new Array(_len > 5 ? _len - 5 : 0), _key = 5; _key < _len; _key++) {
            extraArgs[_key - 5] = arguments[_key];
        }
        var shouldLog = extraArgs.includes("verbose");
        var handleNodes = function handleNodes(nodes) {
            return nodes.forEach((function(node) {
                var shouldReplace = isTargetNode(node, nodeNameMatch, textContentMatch);
                if (shouldReplace) {
                    if (shouldLog) {
                        var originalText = node.textContent;
                        if (originalText) {
                            logMessage(source, `Original text content: ${originalText}`);
                        }
                    }
                    replaceNodeText(source, node, patternMatch, replacement);
                    if (shouldLog) {
                        var modifiedText = node.textContent;
                        if (modifiedText) {
                            logMessage(source, `Modified text content: ${modifiedText}`);
                        }
                    }
                }
            }));
        };
        if (document.documentElement) {
            handleExistingNodes(selector, handleNodes);
        }
        observeDocumentWithTimeout((function(mutations) {
            return handleMutations(mutations, handleNodes);
        }));
    }
    function observeDocumentWithTimeout(callback) {
        var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
            subtree: true,
            childList: true
        };
        var timeout = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1e4;
        var documentObserver = new MutationObserver((function(mutations, observer) {
            observer.disconnect();
            callback(mutations, observer);
            observer.observe(document.documentElement, options);
        }));
        documentObserver.observe(document.documentElement, options);
        if (typeof timeout === "number") {
            setTimeout((function() {
                return documentObserver.disconnect();
            }), timeout);
        }
    }
    function handleExistingNodes(selector, handler, parentSelector) {
        var processNodes = function processNodes(parent) {
            if (selector === "#text") {
                var textNodes = nodeListToArray(parent.childNodes).filter((function(node) {
                    return node.nodeType === Node.TEXT_NODE;
                }));
                handler(textNodes);
            } else {
                var _nodes = nodeListToArray(parent.querySelectorAll(selector));
                handler(_nodes);
            }
        };
        var parents = [ document ];
        parents.forEach((function(parent) {
            return processNodes(parent);
        }));
    }
    function handleMutations(mutations, handler, selector, parentSelector) {
        var addedNodes = getAddedNodes(mutations);
        {
            handler(addedNodes);
        }
    }
    function replaceNodeText(source, node, pattern, replacement) {
        var {textContent: textContent} = node;
        if (textContent) {
            if (node.nodeName === "SCRIPT" && window.trustedTypes && window.trustedTypes.createPolicy) {
                var policy = window.trustedTypes.createPolicy("AGPolicy", {
                    createScript: function createScript(string) {
                        return string;
                    }
                });
                var modifiedText = textContent.replace(pattern, replacement);
                var trustedReplacement = policy.createScript(modifiedText);
                node.textContent = trustedReplacement;
            } else {
                node.textContent = textContent.replace(pattern, replacement);
            }
            hit(source);
        }
    }
    function isTargetNode(node, nodeNameMatch, textContentMatch) {
        var {nodeName: nodeName, textContent: textContent} = node;
        var nodeNameLowerCase = nodeName.toLowerCase();
        return textContent !== null && textContent !== "" && (nodeNameMatch instanceof RegExp ? nodeNameMatch.test(nodeNameLowerCase) : nodeNameMatch === nodeNameLowerCase) && (textContentMatch instanceof RegExp ? textContentMatch.test(textContent) : textContent.includes(textContentMatch));
    }
    function parseNodeTextParams(nodeName, textMatch) {
        var pattern = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
        var REGEXP_START_MARKER = "/";
        var isStringNameMatch = !(nodeName.startsWith(REGEXP_START_MARKER) && nodeName.endsWith(REGEXP_START_MARKER));
        var selector = isStringNameMatch ? nodeName : "*";
        var nodeNameMatch = isStringNameMatch ? nodeName : toRegExp(nodeName);
        var textContentMatch = !textMatch.startsWith(REGEXP_START_MARKER) ? textMatch : toRegExp(textMatch);
        var patternMatch;
        if (pattern) {
            patternMatch = !pattern.startsWith(REGEXP_START_MARKER) ? pattern : toRegExp(pattern);
        }
        return {
            selector: selector,
            nodeNameMatch: nodeNameMatch,
            textContentMatch: textContentMatch,
            patternMatch: patternMatch
        };
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function nodeListToArray(nodeList) {
        var nodes = [];
        for (var i = 0; i < nodeList.length; i += 1) {
            nodes.push(nodeList[i]);
        }
        return nodes;
    }
    function getAddedNodes(mutations) {
        var nodes = [];
        for (var i = 0; i < mutations.length; i += 1) {
            var {addedNodes: addedNodes} = mutations[i];
            for (var j = 0; j < addedNodes.length; j += 1) {
                nodes.push(addedNodes[j]);
            }
        }
        return nodes;
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        trustedReplaceNodeText.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function trustedReplaceOutboundText(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function trustedReplaceOutboundText(source, methodPath) {
        var textToReplace = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
        var replacement = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "";
        var decodeMethod = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : "";
        var stack = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : "";
        var logContent = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : "";
        if (!methodPath) {
            return;
        }
        var getPathParts = getPropertyInChain;
        var {base: base, chain: chain, prop: prop} = getPathParts(window, methodPath);
        if (typeof chain !== "undefined") {
            logMessage(source, `Could not reach the end of the prop chain: ${methodPath}`);
            return;
        }
        var nativeMethod = base[prop];
        if (!nativeMethod || typeof nativeMethod !== "function") {
            logMessage(source, `Could not retrieve the method: ${methodPath}`);
            return;
        }
        var isValidBase64 = function isValidBase64(str) {
            try {
                if (str === "") {
                    return false;
                }
                var decodedString = atob(str);
                var encodedString = btoa(decodedString);
                var stringWithoutPadding = str.replace(/=+$/, "");
                var encodedStringWithoutPadding = encodedString.replace(/=+$/, "");
                return encodedStringWithoutPadding === stringWithoutPadding;
            } catch (e) {
                return false;
            }
        };
        var decodeAndReplaceContent = function decodeAndReplaceContent(content, pattern, textReplacement, decode, log) {
            switch (decode) {
              case "base64":
                try {
                    if (!isValidBase64(content)) {
                        logMessage(source, `Text content is not a valid base64 encoded string: ${content}`);
                        return content;
                    }
                    var decodedContent = atob(content);
                    if (log) {
                        logMessage(source, `Decoded text content: ${decodedContent}`);
                    }
                    var modifiedContent = textToReplace ? decodedContent.replace(pattern, textReplacement) : decodedContent;
                    if (log) {
                        var message = modifiedContent !== decodedContent ? `Modified decoded text content: ${modifiedContent}` : "Decoded text content was not modified";
                        logMessage(source, message);
                    }
                    var encodedContent = btoa(modifiedContent);
                    return encodedContent;
                } catch (e) {
                    return content;
                }

              default:
                return content.replace(pattern, textReplacement);
            }
        };
        var logOriginalContent = !textToReplace || !!logContent;
        var logModifiedContent = !!logContent;
        var logDecodedContent = !!decodeMethod && !!logContent;
        var isMatchingSuspended = false;
        var objectWrapper = function objectWrapper(target, thisArg, argumentsList) {
            if (isMatchingSuspended) {
                return Reflect.apply(target, thisArg, argumentsList);
            }
            isMatchingSuspended = true;
            hit(source);
            var result = Reflect.apply(target, thisArg, argumentsList);
            if (stack && !matchStackTrace(stack, (new Error).stack || "")) {
                return result;
            }
            if (typeof result === "string") {
                if (logOriginalContent) {
                    logMessage(source, `Original text content: ${result}`);
                }
                var patternRegexp = toRegExp(textToReplace);
                var modifiedContent = textToReplace || logDecodedContent ? decodeAndReplaceContent(result, patternRegexp, replacement, decodeMethod, logContent) : result;
                if (logModifiedContent) {
                    var message = modifiedContent !== result ? `Modified text content: ${modifiedContent}` : "Text content was not modified";
                    logMessage(source, message);
                }
                isMatchingSuspended = false;
                return modifiedContent;
            }
            isMatchingSuspended = false;
            logMessage(source, "Content is not a string");
            return result;
        };
        var objectHandler = {
            apply: objectWrapper
        };
        base[prop] = new Proxy(nativeMethod, objectHandler);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function matchStackTrace(stackMatch, stackTrace) {
        if (!stackMatch || stackMatch === "") {
            return true;
        }
        var regExpValues = backupRegExpValues();
        if (shouldAbortInlineOrInjectedScript(stackMatch, stackTrace)) {
            if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
                restoreRegExpValues(regExpValues);
            }
            return true;
        }
        var stackRegexp = toRegExp(stackMatch);
        var refinedStackTrace = stackTrace.split("\n").slice(2).map((function(line) {
            return line.trim();
        })).join("\n");
        if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
            restoreRegExpValues(regExpValues);
        }
        return getNativeRegexpTest().call(stackRegexp, refinedStackTrace);
    }
    function getPropertyInChain(base, chain) {
        var pos = chain.indexOf(".");
        if (pos === -1) {
            return {
                base: base,
                prop: chain
            };
        }
        var prop = chain.slice(0, pos);
        if (base === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        var nextBase = base[prop];
        chain = chain.slice(pos + 1);
        if ((base instanceof Object || typeof base === "object") && isEmptyObject(base)) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase !== undefined) {
            return getPropertyInChain(nextBase, chain);
        }
        Object.defineProperty(base, prop, {
            configurable: true
        });
        return {
            base: base,
            prop: prop,
            chain: chain
        };
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function shouldAbortInlineOrInjectedScript(stackMatch, stackTrace) {
        var INLINE_SCRIPT_STRING = "inlineScript";
        var INJECTED_SCRIPT_STRING = "injectedScript";
        var INJECTED_SCRIPT_MARKER = "<anonymous>";
        var isInlineScript = function isInlineScript(match) {
            return match.includes(INLINE_SCRIPT_STRING);
        };
        var isInjectedScript = function isInjectedScript(match) {
            return match.includes(INJECTED_SCRIPT_STRING);
        };
        if (!(isInlineScript(stackMatch) || isInjectedScript(stackMatch))) {
            return false;
        }
        var documentURL = window.location.href;
        var pos = documentURL.indexOf("#");
        if (pos !== -1) {
            documentURL = documentURL.slice(0, pos);
        }
        var stackSteps = stackTrace.split("\n").slice(2).map((function(line) {
            return line.trim();
        }));
        var stackLines = stackSteps.map((function(line) {
            var stack;
            var getStackTraceValues = /(.*?@)?(\S+)(:\d+)(:\d+)\)?$/.exec(line);
            if (getStackTraceValues) {
                var _stackURL, _stackURL2;
                var stackURL = getStackTraceValues[2];
                var stackLine = getStackTraceValues[3];
                var stackCol = getStackTraceValues[4];
                if ((_stackURL = stackURL) !== null && _stackURL !== void 0 && _stackURL.startsWith("(")) {
                    stackURL = stackURL.slice(1);
                }
                if ((_stackURL2 = stackURL) !== null && _stackURL2 !== void 0 && _stackURL2.startsWith(INJECTED_SCRIPT_MARKER)) {
                    var _stackFunction;
                    stackURL = INJECTED_SCRIPT_STRING;
                    var stackFunction = getStackTraceValues[1] !== undefined ? getStackTraceValues[1].slice(0, -1) : line.slice(0, getStackTraceValues.index).trim();
                    if ((_stackFunction = stackFunction) !== null && _stackFunction !== void 0 && _stackFunction.startsWith("at")) {
                        stackFunction = stackFunction.slice(2).trim();
                    }
                    stack = `${stackFunction} ${stackURL}${stackLine}${stackCol}`.trim();
                } else if (stackURL === documentURL) {
                    stack = `${INLINE_SCRIPT_STRING}${stackLine}${stackCol}`.trim();
                } else {
                    stack = `${stackURL}${stackLine}${stackCol}`.trim();
                }
            } else {
                stack = line;
            }
            return stack;
        }));
        if (stackLines) {
            for (var index = 0; index < stackLines.length; index += 1) {
                if (isInlineScript(stackMatch) && stackLines[index].startsWith(INLINE_SCRIPT_STRING) && stackLines[index].match(toRegExp(stackMatch))) {
                    return true;
                }
                if (isInjectedScript(stackMatch) && stackLines[index].startsWith(INJECTED_SCRIPT_STRING) && stackLines[index].match(toRegExp(stackMatch))) {
                    return true;
                }
            }
        }
        return false;
    }
    function getNativeRegexpTest() {
        var descriptor = Object.getOwnPropertyDescriptor(RegExp.prototype, "test");
        var nativeRegexTest = descriptor === null || descriptor === void 0 ? void 0 : descriptor.value;
        if (descriptor && typeof descriptor.value === "function") {
            return nativeRegexTest;
        }
        throw new Error("RegExp.prototype.test is not a function");
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function isEmptyObject(obj) {
        return Object.keys(obj).length === 0 && !obj.prototype;
    }
    function backupRegExpValues() {
        try {
            var arrayOfRegexpValues = [];
            for (var index = 1; index < 10; index += 1) {
                var value = `$${index}`;
                if (!RegExp[value]) {
                    break;
                }
                arrayOfRegexpValues.push(RegExp[value]);
            }
            return arrayOfRegexpValues;
        } catch (error) {
            return [];
        }
    }
    function restoreRegExpValues(array) {
        if (!array.length) {
            return;
        }
        try {
            var stringPattern = "";
            if (array.length === 1) {
                stringPattern = `(${array[0]})`;
            } else {
                stringPattern = array.reduce((function(accumulator, currentValue, currentIndex) {
                    if (currentIndex === 1) {
                        return `(${accumulator}),(${currentValue})`;
                    }
                    return `${accumulator},(${currentValue})`;
                }));
            }
            var regExpGroup = new RegExp(stringPattern);
            array.toString().replace(regExpGroup, "");
        } catch (error) {
            var message = `Failed to restore RegExp values: ${error}`;
            console.log(message);
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        trustedReplaceOutboundText.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function trustedReplaceXhrResponse(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function trustedReplaceXhrResponse(source) {
        var pattern = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
        var replacement = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
        var propsToMatch = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "";
        var verbose = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
        if (typeof Proxy === "undefined") {
            return;
        }
        if (pattern === "" && replacement !== "") {
            var message = "Pattern argument should not be empty string.";
            logMessage(source, message);
            return;
        }
        var shouldLog = pattern === "" && replacement === "";
        var shouldLogContent = verbose === "true";
        var nativeOpen = window.XMLHttpRequest.prototype.open;
        var nativeSend = window.XMLHttpRequest.prototype.send;
        var xhrData;
        var openWrapper = function openWrapper(target, thisArg, args) {
            xhrData = getXhrData.apply(null, args);
            if (shouldLog) {
                var _message = `xhr( ${objectToString(xhrData)} )`;
                logMessage(source, _message, true);
                hit(source);
                return Reflect.apply(target, thisArg, args);
            }
            if (matchRequestProps(source, propsToMatch, xhrData)) {
                thisArg.shouldBePrevented = true;
                thisArg.headersReceived = !!thisArg.headersReceived;
            }
            if (thisArg.shouldBePrevented && !thisArg.headersReceived) {
                thisArg.headersReceived = true;
                thisArg.collectedHeaders = [];
                var setRequestHeaderWrapper = function setRequestHeaderWrapper(target, thisArg, args) {
                    thisArg.collectedHeaders.push(args);
                    return Reflect.apply(target, thisArg, args);
                };
                var setRequestHeaderHandler = {
                    apply: setRequestHeaderWrapper
                };
                thisArg.setRequestHeader = new Proxy(thisArg.setRequestHeader, setRequestHeaderHandler);
            }
            return Reflect.apply(target, thisArg, args);
        };
        var sendWrapper = function sendWrapper(target, thisArg, args) {
            if (!thisArg.shouldBePrevented) {
                return Reflect.apply(target, thisArg, args);
            }
            var forgedRequest = new XMLHttpRequest;
            forgedRequest.addEventListener("readystatechange", (function() {
                if (forgedRequest.readyState !== 4) {
                    return;
                }
                var {readyState: readyState, response: response, responseText: responseText, responseURL: responseURL, responseXML: responseXML, status: status, statusText: statusText} = forgedRequest;
                var content = responseText || response;
                if (typeof content !== "string") {
                    return;
                }
                var patternRegexp = pattern === "*" ? /(\n|.)*/ : toRegExp(pattern);
                if (shouldLogContent) {
                    logMessage(source, `Original text content: ${content}`);
                }
                var modifiedContent = content.replace(patternRegexp, replacement);
                if (shouldLogContent) {
                    logMessage(source, `Modified text content: ${modifiedContent}`);
                }
                Object.defineProperties(thisArg, {
                    readyState: {
                        value: readyState,
                        writable: false
                    },
                    responseURL: {
                        value: responseURL,
                        writable: false
                    },
                    responseXML: {
                        value: responseXML,
                        writable: false
                    },
                    status: {
                        value: status,
                        writable: false
                    },
                    statusText: {
                        value: statusText,
                        writable: false
                    },
                    response: {
                        value: modifiedContent,
                        writable: false
                    },
                    responseText: {
                        value: modifiedContent,
                        writable: false
                    }
                });
                setTimeout((function() {
                    var stateEvent = new Event("readystatechange");
                    thisArg.dispatchEvent(stateEvent);
                    var loadEvent = new Event("load");
                    thisArg.dispatchEvent(loadEvent);
                    var loadEndEvent = new Event("loadend");
                    thisArg.dispatchEvent(loadEndEvent);
                }), 1);
                hit(source);
            }));
            nativeOpen.apply(forgedRequest, [ xhrData.method, xhrData.url ]);
            thisArg.collectedHeaders.forEach((function(header) {
                var name = header[0];
                var value = header[1];
                forgedRequest.setRequestHeader(name, value);
            }));
            thisArg.collectedHeaders = [];
            try {
                nativeSend.call(forgedRequest, args);
            } catch (_unused) {
                return Reflect.apply(target, thisArg, args);
            }
            return undefined;
        };
        var openHandler = {
            apply: openWrapper
        };
        var sendHandler = {
            apply: sendWrapper
        };
        XMLHttpRequest.prototype.open = new Proxy(XMLHttpRequest.prototype.open, openHandler);
        XMLHttpRequest.prototype.send = new Proxy(XMLHttpRequest.prototype.send, sendHandler);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function objectToString(obj) {
        if (!obj || typeof obj !== "object") {
            return String(obj);
        }
        if (isEmptyObject(obj)) {
            return "{}";
        }
        return Object.entries(obj).map((function(pair) {
            var key = pair[0];
            var value = pair[1];
            var recordValueStr = value;
            if (value instanceof Object) {
                recordValueStr = `{ ${objectToString(value)} }`;
            }
            return `${key}:"${recordValueStr}"`;
        })).join(" ");
    }
    function matchRequestProps(source, propsToMatch, requestData) {
        if (propsToMatch === "" || propsToMatch === "*") {
            return true;
        }
        var isMatched;
        var parsedData = parseMatchProps(propsToMatch);
        if (!isValidParsedData(parsedData)) {
            logMessage(source, `Invalid parameter: ${propsToMatch}`);
            isMatched = false;
        } else {
            var matchData = getMatchPropsData(parsedData);
            var matchKeys = Object.keys(matchData);
            isMatched = matchKeys.every((function(matchKey) {
                var matchValue = matchData[matchKey];
                var dataValue = requestData[matchKey];
                return Object.prototype.hasOwnProperty.call(requestData, matchKey) && typeof dataValue === "string" && (matchValue === null || matchValue === void 0 ? void 0 : matchValue.test(dataValue));
            }));
        }
        return isMatched;
    }
    function getXhrData(method, url, async, user, password) {
        return {
            method: method,
            url: url,
            async: async,
            user: user,
            password: password
        };
    }
    function getMatchPropsData(data) {
        var matchData = {};
        var dataKeys = Object.keys(data);
        dataKeys.forEach((function(key) {
            matchData[key] = toRegExp(data[key]);
        }));
        return matchData;
    }
    function getRequestProps() {
        return [ "url", "method", "headers", "body", "credentials", "cache", "redirect", "referrer", "referrerPolicy", "integrity", "keepalive", "signal", "mode" ];
    }
    function isValidParsedData(data) {
        return Object.values(data).every((function(value) {
            return isValidStrPattern(value);
        }));
    }
    function parseMatchProps(propsToMatchStr) {
        var PROPS_DIVIDER = " ";
        var PAIRS_MARKER = ":";
        var isRequestProp = function isRequestProp(prop) {
            return getRequestProps().includes(prop);
        };
        var propsObj = {};
        var props = propsToMatchStr.split(PROPS_DIVIDER);
        props.forEach((function(prop) {
            var dividerInd = prop.indexOf(PAIRS_MARKER);
            var key = prop.slice(0, dividerInd);
            if (isRequestProp(key)) {
                var value = prop.slice(dividerInd + 1);
                propsObj[key] = value;
            } else {
                propsObj.url = prop;
            }
        }));
        return propsObj;
    }
    function isValidStrPattern(input) {
        var FORWARD_SLASH = "/";
        var str = escapeRegExp(input);
        if (input[0] === FORWARD_SLASH && input[input.length - 1] === FORWARD_SLASH) {
            str = input.slice(1, -1);
        }
        var isValid;
        try {
            isValid = new RegExp(str);
            isValid = true;
        } catch (e) {
            isValid = false;
        }
        return isValid;
    }
    function escapeRegExp(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    function isEmptyObject(obj) {
        return Object.keys(obj).length === 0 && !obj.prototype;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        trustedReplaceXhrResponse.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function trustedSetAttr(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function trustedSetAttr(source, selector, attr) {
        var value = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "";
        if (!selector || !attr) {
            return;
        }
        setAttributeBySelector(source, selector, attr, value);
        observeDOMChanges((function() {
            return setAttributeBySelector(source, selector, attr, value);
        }), true);
    }
    function setAttributeBySelector(source, selector, attribute, value) {
        var attributeSetter = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : defaultAttributeSetter;
        var elements;
        try {
            elements = document.querySelectorAll(selector);
        } catch (_unused) {
            logMessage(source, `Failed to find elements matching selector "${selector}"`);
            return;
        }
        if (!elements || elements.length === 0) {
            return;
        }
        try {
            elements.forEach((function(elem) {
                return attributeSetter(elem, attribute, value);
            }));
            hit(source);
        } catch (_unused2) {
            logMessage(source, `Failed to set [${attribute}="${value}"] to each of selected elements.`);
        }
    }
    function observeDOMChanges(callback) {
        var observeAttrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
        var attrsToObserve = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
        var THROTTLE_DELAY_MS = 20;
        var observer = new MutationObserver(throttle(callbackWrapper, THROTTLE_DELAY_MS));
        var connect = function connect() {
            if (attrsToObserve.length > 0) {
                observer.observe(document.documentElement, {
                    childList: true,
                    subtree: true,
                    attributes: observeAttrs,
                    attributeFilter: attrsToObserve
                });
            } else {
                observer.observe(document.documentElement, {
                    childList: true,
                    subtree: true,
                    attributes: observeAttrs
                });
            }
        };
        var disconnect = function disconnect() {
            observer.disconnect();
        };
        function callbackWrapper() {
            disconnect();
            callback();
            connect();
        }
        connect();
    }
    function defaultAttributeSetter(elem, attribute, value) {
        return elem.setAttribute(attribute, value);
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function throttle(cb, delay) {
        var wait = false;
        var savedArgs;
        var _wrapper = function wrapper() {
            for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                args[_key] = arguments[_key];
            }
            if (wait) {
                savedArgs = args;
                return;
            }
            cb(...args);
            wait = true;
            setTimeout((function() {
                wait = false;
                if (savedArgs) {
                    _wrapper(...savedArgs);
                    savedArgs = null;
                }
            }), delay);
        };
        return _wrapper;
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        trustedSetAttr.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function trustedSetConstant(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function trustedSetConstant(source, property, value, stack) {
        if (!property || !matchStackTrace(stack, (new Error).stack)) {
            return;
        }
        var constantValue;
        try {
            constantValue = inferValue(value);
        } catch (e) {
            logMessage(source, e);
            return;
        }
        var canceled = false;
        var mustCancel = function mustCancel(value) {
            if (canceled) {
                return canceled;
            }
            canceled = value !== undefined && constantValue !== undefined && typeof value !== typeof constantValue && value !== null;
            return canceled;
        };
        var trapProp = function trapProp(base, prop, configurable, handler) {
            if (!handler.init(base[prop])) {
                return false;
            }
            var origDescriptor = Object.getOwnPropertyDescriptor(base, prop);
            var prevSetter;
            if (origDescriptor instanceof Object) {
                if (!origDescriptor.configurable) {
                    var message = `Property '${prop}' is not configurable`;
                    logMessage(source, message);
                    return false;
                }
                base[prop] = constantValue;
                if (origDescriptor.set instanceof Function) {
                    prevSetter = origDescriptor.set;
                }
            }
            Object.defineProperty(base, prop, {
                configurable: configurable,
                get() {
                    return handler.get();
                },
                set(a) {
                    if (prevSetter !== undefined) {
                        prevSetter(a);
                    }
                    handler.set(a);
                }
            });
            return true;
        };
        var _setChainPropAccess = function setChainPropAccess(owner, property) {
            var chainInfo = getPropertyInChain(owner, property);
            var {base: base} = chainInfo;
            var {prop: prop, chain: chain} = chainInfo;
            var inChainPropHandler = {
                factValue: undefined,
                init(a) {
                    this.factValue = a;
                    return true;
                },
                get() {
                    return this.factValue;
                },
                set(a) {
                    if (this.factValue === a) {
                        return;
                    }
                    this.factValue = a;
                    if (a instanceof Object) {
                        _setChainPropAccess(a, chain);
                    }
                }
            };
            var endPropHandler = {
                init(a) {
                    if (mustCancel(a)) {
                        return false;
                    }
                    return true;
                },
                get() {
                    return constantValue;
                },
                set(a) {
                    if (!mustCancel(a)) {
                        return;
                    }
                    constantValue = a;
                }
            };
            if (!chain) {
                var isTrapped = trapProp(base, prop, false, endPropHandler);
                if (isTrapped) {
                    hit(source);
                }
                return;
            }
            if (base !== undefined && base[prop] === null) {
                trapProp(base, prop, true, inChainPropHandler);
                return;
            }
            if ((base instanceof Object || typeof base === "object") && isEmptyObject(base)) {
                trapProp(base, prop, true, inChainPropHandler);
            }
            var propValue = owner[prop];
            if (propValue instanceof Object || typeof propValue === "object" && propValue !== null) {
                _setChainPropAccess(propValue, chain);
            }
            trapProp(base, prop, true, inChainPropHandler);
        };
        _setChainPropAccess(window, property);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function inferValue(value) {
        if (value === "undefined") {
            return undefined;
        }
        if (value === "false") {
            return false;
        }
        if (value === "true") {
            return true;
        }
        if (value === "null") {
            return null;
        }
        if (value === "NaN") {
            return NaN;
        }
        if (value.startsWith("/") && value.endsWith("/")) {
            return toRegExp(value);
        }
        var MAX_ALLOWED_NUM = 32767;
        var numVal = Number(value);
        if (!nativeIsNaN(numVal)) {
            if (Math.abs(numVal) > MAX_ALLOWED_NUM) {
                throw new Error("number values bigger than 32767 are not allowed");
            }
            return numVal;
        }
        var errorMessage = `'${value}' value type can't be inferred`;
        try {
            var parsableVal = JSON.parse(value);
            if (parsableVal instanceof Object || typeof parsableVal === "string") {
                return parsableVal;
            }
        } catch (e) {
            errorMessage += `: ${e}`;
        }
        throw new TypeError(errorMessage);
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function getPropertyInChain(base, chain) {
        var pos = chain.indexOf(".");
        if (pos === -1) {
            return {
                base: base,
                prop: chain
            };
        }
        var prop = chain.slice(0, pos);
        if (base === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        var nextBase = base[prop];
        chain = chain.slice(pos + 1);
        if ((base instanceof Object || typeof base === "object") && isEmptyObject(base)) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase !== undefined) {
            return getPropertyInChain(nextBase, chain);
        }
        Object.defineProperty(base, prop, {
            configurable: true
        });
        return {
            base: base,
            prop: prop,
            chain: chain
        };
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function matchStackTrace(stackMatch, stackTrace) {
        if (!stackMatch || stackMatch === "") {
            return true;
        }
        var regExpValues = backupRegExpValues();
        if (shouldAbortInlineOrInjectedScript(stackMatch, stackTrace)) {
            if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
                restoreRegExpValues(regExpValues);
            }
            return true;
        }
        var stackRegexp = toRegExp(stackMatch);
        var refinedStackTrace = stackTrace.split("\n").slice(2).map((function(line) {
            return line.trim();
        })).join("\n");
        if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
            restoreRegExpValues(regExpValues);
        }
        return getNativeRegexpTest().call(stackRegexp, refinedStackTrace);
    }
    function nativeIsNaN(num) {
        var native = Number.isNaN || window.isNaN;
        return native(num);
    }
    function isEmptyObject(obj) {
        return Object.keys(obj).length === 0 && !obj.prototype;
    }
    function getNativeRegexpTest() {
        var descriptor = Object.getOwnPropertyDescriptor(RegExp.prototype, "test");
        var nativeRegexTest = descriptor === null || descriptor === void 0 ? void 0 : descriptor.value;
        if (descriptor && typeof descriptor.value === "function") {
            return nativeRegexTest;
        }
        throw new Error("RegExp.prototype.test is not a function");
    }
    function shouldAbortInlineOrInjectedScript(stackMatch, stackTrace) {
        var INLINE_SCRIPT_STRING = "inlineScript";
        var INJECTED_SCRIPT_STRING = "injectedScript";
        var INJECTED_SCRIPT_MARKER = "<anonymous>";
        var isInlineScript = function isInlineScript(match) {
            return match.includes(INLINE_SCRIPT_STRING);
        };
        var isInjectedScript = function isInjectedScript(match) {
            return match.includes(INJECTED_SCRIPT_STRING);
        };
        if (!(isInlineScript(stackMatch) || isInjectedScript(stackMatch))) {
            return false;
        }
        var documentURL = window.location.href;
        var pos = documentURL.indexOf("#");
        if (pos !== -1) {
            documentURL = documentURL.slice(0, pos);
        }
        var stackSteps = stackTrace.split("\n").slice(2).map((function(line) {
            return line.trim();
        }));
        var stackLines = stackSteps.map((function(line) {
            var stack;
            var getStackTraceValues = /(.*?@)?(\S+)(:\d+)(:\d+)\)?$/.exec(line);
            if (getStackTraceValues) {
                var _stackURL, _stackURL2;
                var stackURL = getStackTraceValues[2];
                var stackLine = getStackTraceValues[3];
                var stackCol = getStackTraceValues[4];
                if ((_stackURL = stackURL) !== null && _stackURL !== void 0 && _stackURL.startsWith("(")) {
                    stackURL = stackURL.slice(1);
                }
                if ((_stackURL2 = stackURL) !== null && _stackURL2 !== void 0 && _stackURL2.startsWith(INJECTED_SCRIPT_MARKER)) {
                    var _stackFunction;
                    stackURL = INJECTED_SCRIPT_STRING;
                    var stackFunction = getStackTraceValues[1] !== undefined ? getStackTraceValues[1].slice(0, -1) : line.slice(0, getStackTraceValues.index).trim();
                    if ((_stackFunction = stackFunction) !== null && _stackFunction !== void 0 && _stackFunction.startsWith("at")) {
                        stackFunction = stackFunction.slice(2).trim();
                    }
                    stack = `${stackFunction} ${stackURL}${stackLine}${stackCol}`.trim();
                } else if (stackURL === documentURL) {
                    stack = `${INLINE_SCRIPT_STRING}${stackLine}${stackCol}`.trim();
                } else {
                    stack = `${stackURL}${stackLine}${stackCol}`.trim();
                }
            } else {
                stack = line;
            }
            return stack;
        }));
        if (stackLines) {
            for (var index = 0; index < stackLines.length; index += 1) {
                if (isInlineScript(stackMatch) && stackLines[index].startsWith(INLINE_SCRIPT_STRING) && stackLines[index].match(toRegExp(stackMatch))) {
                    return true;
                }
                if (isInjectedScript(stackMatch) && stackLines[index].startsWith(INJECTED_SCRIPT_STRING) && stackLines[index].match(toRegExp(stackMatch))) {
                    return true;
                }
            }
        }
        return false;
    }
    function backupRegExpValues() {
        try {
            var arrayOfRegexpValues = [];
            for (var index = 1; index < 10; index += 1) {
                var value = `$${index}`;
                if (!RegExp[value]) {
                    break;
                }
                arrayOfRegexpValues.push(RegExp[value]);
            }
            return arrayOfRegexpValues;
        } catch (error) {
            return [];
        }
    }
    function restoreRegExpValues(array) {
        if (!array.length) {
            return;
        }
        try {
            var stringPattern = "";
            if (array.length === 1) {
                stringPattern = `(${array[0]})`;
            } else {
                stringPattern = array.reduce((function(accumulator, currentValue, currentIndex) {
                    if (currentIndex === 1) {
                        return `(${accumulator}),(${currentValue})`;
                    }
                    return `${accumulator},(${currentValue})`;
                }));
            }
            var regExpGroup = new RegExp(stringPattern);
            array.toString().replace(regExpGroup, "");
        } catch (error) {
            var message = `Failed to restore RegExp values: ${error}`;
            console.log(message);
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        trustedSetConstant.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function trustedSetCookie(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function trustedSetCookie(source, name, value) {
        var offsetExpiresSec = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "";
        var path = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : "/";
        var domain = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : "";
        if (typeof name === "undefined") {
            logMessage(source, "Cookie name should be specified");
            return;
        }
        if (typeof value === "undefined") {
            logMessage(source, "Cookie value should be specified");
            return;
        }
        var parsedValue = parseKeywordValue(value);
        if (!isValidCookiePath(path)) {
            logMessage(source, `Invalid cookie path: '${path}'`);
            return;
        }
        if (!document.location.origin.includes(domain)) {
            logMessage(source, `Cookie domain not matched by origin: '${domain}'`);
            return;
        }
        var cookieToSet = serializeCookie(name, parsedValue, path, domain, false);
        if (!cookieToSet) {
            logMessage(source, "Invalid cookie name or value");
            return;
        }
        if (offsetExpiresSec) {
            var parsedOffsetMs = getTrustedCookieOffsetMs(offsetExpiresSec);
            if (!parsedOffsetMs) {
                logMessage(source, `Invalid offsetExpiresSec value: ${offsetExpiresSec}`);
                return;
            }
            var expires = Date.now() + parsedOffsetMs;
            cookieToSet += `; expires=${new Date(expires).toUTCString()}`;
        }
        document.cookie = cookieToSet;
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function serializeCookie(name, rawValue, rawPath) {
        var domainValue = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "";
        var shouldEncodeValue = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
        var HOST_PREFIX = "__Host-";
        var SECURE_PREFIX = "__Secure-";
        var COOKIE_BREAKER = ";";
        if (!shouldEncodeValue && `${rawValue}`.includes(COOKIE_BREAKER) || name.includes(COOKIE_BREAKER)) {
            return null;
        }
        var value = shouldEncodeValue ? encodeURIComponent(rawValue) : rawValue;
        var resultCookie = `${name}=${value}`;
        if (name.startsWith(HOST_PREFIX)) {
            resultCookie += "; path=/; secure";
            if (domainValue) {
                console.debug(`Domain value: "${domainValue}" has been ignored, because is not allowed for __Host- prefixed cookies`);
            }
            return resultCookie;
        }
        var path = getCookiePath(rawPath);
        if (path) {
            resultCookie += `; ${path}`;
        }
        if (name.startsWith(SECURE_PREFIX)) {
            resultCookie += "; secure";
        }
        if (domainValue) {
            resultCookie += `; domain=${domainValue}`;
        }
        return resultCookie;
    }
    function isValidCookiePath(rawPath) {
        return rawPath === "/" || rawPath === "none";
    }
    function getTrustedCookieOffsetMs(offsetExpiresSec) {
        var ONE_YEAR_EXPIRATION_KEYWORD = "1year";
        var ONE_DAY_EXPIRATION_KEYWORD = "1day";
        var MS_IN_SEC = 1e3;
        var SECONDS_IN_YEAR = 365 * 24 * 60 * 60;
        var SECONDS_IN_DAY = 24 * 60 * 60;
        var parsedSec;
        if (offsetExpiresSec === ONE_YEAR_EXPIRATION_KEYWORD) {
            parsedSec = SECONDS_IN_YEAR;
        } else if (offsetExpiresSec === ONE_DAY_EXPIRATION_KEYWORD) {
            parsedSec = SECONDS_IN_DAY;
        } else {
            parsedSec = Number.parseInt(offsetExpiresSec, 10);
            if (Number.isNaN(parsedSec)) {
                return null;
            }
        }
        return parsedSec * MS_IN_SEC;
    }
    function parseKeywordValue(rawValue) {
        var NOW_VALUE_KEYWORD = "$now$";
        var CURRENT_DATE_KEYWORD = "$currentDate$";
        var CURRENT_ISO_DATE_KEYWORD = "$currentISODate$";
        var parsedValue = rawValue;
        if (rawValue === NOW_VALUE_KEYWORD) {
            parsedValue = Date.now().toString();
        } else if (rawValue === CURRENT_DATE_KEYWORD) {
            parsedValue = Date();
        } else if (rawValue === CURRENT_ISO_DATE_KEYWORD) {
            parsedValue = (new Date).toISOString();
        }
        return parsedValue;
    }
    function getCookiePath(rawPath) {
        if (rawPath === "/") {
            return "path=/";
        }
        return "";
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        trustedSetCookie.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function trustedSetCookieReload(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function trustedSetCookieReload(source, name, value) {
        var offsetExpiresSec = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "";
        var path = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : "/";
        var domain = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : "";
        if (typeof name === "undefined") {
            logMessage(source, "Cookie name should be specified");
            return;
        }
        if (typeof value === "undefined") {
            logMessage(source, "Cookie value should be specified");
            return;
        }
        if (isCookieSetWithValue(document.cookie, name, value)) {
            return;
        }
        var parsedValue = parseKeywordValue(value);
        if (!isValidCookiePath(path)) {
            logMessage(source, `Invalid cookie path: '${path}'`);
            return;
        }
        if (!document.location.origin.includes(domain)) {
            logMessage(source, `Cookie domain not matched by origin: '${domain}'`);
            return;
        }
        var cookieToSet = serializeCookie(name, parsedValue, path, domain, false);
        if (!cookieToSet) {
            logMessage(source, "Invalid cookie name or value");
            return;
        }
        if (offsetExpiresSec) {
            var parsedOffsetMs = getTrustedCookieOffsetMs(offsetExpiresSec);
            if (!parsedOffsetMs) {
                logMessage(source, `Invalid offsetExpiresSec value: ${offsetExpiresSec}`);
                return;
            }
            var expires = Date.now() + parsedOffsetMs;
            cookieToSet += `; expires=${new Date(expires).toUTCString()}`;
        }
        document.cookie = cookieToSet;
        hit(source);
        var cookieValueToCheck = parseCookieString(document.cookie)[name];
        if (isCookieSetWithValue(document.cookie, name, cookieValueToCheck)) {
            window.location.reload();
        }
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function isCookieSetWithValue(cookieString, name, value) {
        return cookieString.split(";").some((function(cookieStr) {
            var pos = cookieStr.indexOf("=");
            if (pos === -1) {
                return false;
            }
            var cookieName = cookieStr.slice(0, pos).trim();
            var cookieValue = cookieStr.slice(pos + 1).trim();
            return name === cookieName && value === cookieValue;
        }));
    }
    function serializeCookie(name, rawValue, rawPath) {
        var domainValue = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "";
        var shouldEncodeValue = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
        var HOST_PREFIX = "__Host-";
        var SECURE_PREFIX = "__Secure-";
        var COOKIE_BREAKER = ";";
        if (!shouldEncodeValue && `${rawValue}`.includes(COOKIE_BREAKER) || name.includes(COOKIE_BREAKER)) {
            return null;
        }
        var value = shouldEncodeValue ? encodeURIComponent(rawValue) : rawValue;
        var resultCookie = `${name}=${value}`;
        if (name.startsWith(HOST_PREFIX)) {
            resultCookie += "; path=/; secure";
            if (domainValue) {
                console.debug(`Domain value: "${domainValue}" has been ignored, because is not allowed for __Host- prefixed cookies`);
            }
            return resultCookie;
        }
        var path = getCookiePath(rawPath);
        if (path) {
            resultCookie += `; ${path}`;
        }
        if (name.startsWith(SECURE_PREFIX)) {
            resultCookie += "; secure";
        }
        if (domainValue) {
            resultCookie += `; domain=${domainValue}`;
        }
        return resultCookie;
    }
    function isValidCookiePath(rawPath) {
        return rawPath === "/" || rawPath === "none";
    }
    function getTrustedCookieOffsetMs(offsetExpiresSec) {
        var ONE_YEAR_EXPIRATION_KEYWORD = "1year";
        var ONE_DAY_EXPIRATION_KEYWORD = "1day";
        var MS_IN_SEC = 1e3;
        var SECONDS_IN_YEAR = 365 * 24 * 60 * 60;
        var SECONDS_IN_DAY = 24 * 60 * 60;
        var parsedSec;
        if (offsetExpiresSec === ONE_YEAR_EXPIRATION_KEYWORD) {
            parsedSec = SECONDS_IN_YEAR;
        } else if (offsetExpiresSec === ONE_DAY_EXPIRATION_KEYWORD) {
            parsedSec = SECONDS_IN_DAY;
        } else {
            parsedSec = Number.parseInt(offsetExpiresSec, 10);
            if (Number.isNaN(parsedSec)) {
                return null;
            }
        }
        return parsedSec * MS_IN_SEC;
    }
    function parseKeywordValue(rawValue) {
        var NOW_VALUE_KEYWORD = "$now$";
        var CURRENT_DATE_KEYWORD = "$currentDate$";
        var CURRENT_ISO_DATE_KEYWORD = "$currentISODate$";
        var parsedValue = rawValue;
        if (rawValue === NOW_VALUE_KEYWORD) {
            parsedValue = Date.now().toString();
        } else if (rawValue === CURRENT_DATE_KEYWORD) {
            parsedValue = Date();
        } else if (rawValue === CURRENT_ISO_DATE_KEYWORD) {
            parsedValue = (new Date).toISOString();
        }
        return parsedValue;
    }
    function parseCookieString(cookieString) {
        var COOKIE_DELIMITER = "=";
        var COOKIE_PAIRS_DELIMITER = ";";
        var cookieChunks = cookieString.split(COOKIE_PAIRS_DELIMITER);
        var cookieData = {};
        cookieChunks.forEach((function(singleCookie) {
            var cookieKey;
            var cookieValue = "";
            var delimiterIndex = singleCookie.indexOf(COOKIE_DELIMITER);
            if (delimiterIndex === -1) {
                cookieKey = singleCookie.trim();
            } else {
                cookieKey = singleCookie.slice(0, delimiterIndex).trim();
                cookieValue = singleCookie.slice(delimiterIndex + 1);
            }
            cookieData[cookieKey] = cookieValue || null;
        }));
        return cookieData;
    }
    function getCookiePath(rawPath) {
        if (rawPath === "/") {
            return "path=/";
        }
        return "";
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        trustedSetCookieReload.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function trustedSetLocalStorageItem(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function trustedSetLocalStorageItem(source, key, value) {
        if (typeof key === "undefined") {
            logMessage(source, "Item key should be specified");
            return;
        }
        if (typeof value === "undefined") {
            logMessage(source, "Item value should be specified");
            return;
        }
        var parsedValue = parseKeywordValue(value);
        var {localStorage: localStorage} = window;
        setStorageItem(source, localStorage, key, parsedValue);
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function setStorageItem(source, storage, key, value) {
        try {
            storage.setItem(key, value);
        } catch (e) {
            var message = `Unable to set storage item due to: ${e.message}`;
            logMessage(source, message);
        }
    }
    function parseKeywordValue(rawValue) {
        var NOW_VALUE_KEYWORD = "$now$";
        var CURRENT_DATE_KEYWORD = "$currentDate$";
        var CURRENT_ISO_DATE_KEYWORD = "$currentISODate$";
        var parsedValue = rawValue;
        if (rawValue === NOW_VALUE_KEYWORD) {
            parsedValue = Date.now().toString();
        } else if (rawValue === CURRENT_DATE_KEYWORD) {
            parsedValue = Date();
        } else if (rawValue === CURRENT_ISO_DATE_KEYWORD) {
            parsedValue = (new Date).toISOString();
        }
        return parsedValue;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        trustedSetLocalStorageItem.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function trustedSetSessionStorageItem(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function trustedSetSessionStorageItem(source, key, value) {
        if (typeof key === "undefined") {
            logMessage(source, "Item key should be specified");
            return;
        }
        if (typeof value === "undefined") {
            logMessage(source, "Item value should be specified");
            return;
        }
        var parsedValue = parseKeywordValue(value);
        var {sessionStorage: sessionStorage} = window;
        setStorageItem(source, sessionStorage, key, parsedValue);
        hit(source);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function setStorageItem(source, storage, key, value) {
        try {
            storage.setItem(key, value);
        } catch (e) {
            var message = `Unable to set storage item due to: ${e.message}`;
            logMessage(source, message);
        }
    }
    function parseKeywordValue(rawValue) {
        var NOW_VALUE_KEYWORD = "$now$";
        var CURRENT_DATE_KEYWORD = "$currentDate$";
        var CURRENT_ISO_DATE_KEYWORD = "$currentISODate$";
        var parsedValue = rawValue;
        if (rawValue === NOW_VALUE_KEYWORD) {
            parsedValue = Date.now().toString();
        } else if (rawValue === CURRENT_DATE_KEYWORD) {
            parsedValue = Date();
        } else if (rawValue === CURRENT_ISO_DATE_KEYWORD) {
            parsedValue = (new Date).toISOString();
        }
        return parsedValue;
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        trustedSetSessionStorageItem.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function trustedSuppressNativeMethod(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function trustedSuppressNativeMethod(source, methodPath, signatureStr) {
        var how = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "abort";
        var stack = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : "";
        if (!methodPath || !signatureStr) {
            return;
        }
        var IGNORE_ARG_SYMBOL = " ";
        var suppress = how === "abort" ? getAbortFunc() : function() {};
        var signatureMatcher;
        try {
            signatureMatcher = signatureStr.split("|").map((function(value) {
                return value === IGNORE_ARG_SYMBOL ? value : inferValue(value);
            }));
        } catch (e) {
            logMessage(source, `Could not parse the signature matcher: ${getErrorMessage(e)}`);
            return;
        }
        var getPathParts = getPropertyInChain;
        var {base: base, chain: chain, prop: prop} = getPathParts(window, methodPath);
        if (typeof chain !== "undefined") {
            logMessage(source, `Could not reach the end of the prop chain: ${methodPath}`);
            return;
        }
        var nativeMethod = base[prop];
        if (!nativeMethod || typeof nativeMethod !== "function") {
            logMessage(source, `Could not retrieve the method: ${methodPath}`);
            return;
        }
        function matchMethodCall(nativeArguments, matchArguments) {
            return matchArguments.every((function(matcher, i) {
                if (matcher === IGNORE_ARG_SYMBOL) {
                    return true;
                }
                var argument = nativeArguments[i];
                return isValueMatched(argument, matcher);
            }));
        }
        var isMatchingSuspended = false;
        function apply(target, thisArg, argumentsList) {
            if (isMatchingSuspended) {
                return Reflect.apply(target, thisArg, argumentsList);
            }
            isMatchingSuspended = true;
            if (stack && !matchStackTrace(stack, (new Error).stack || "")) {
                return Reflect.apply(target, thisArg, argumentsList);
            }
            var isMatching = matchMethodCall(argumentsList, signatureMatcher);
            isMatchingSuspended = false;
            if (isMatching) {
                hit(source);
                return suppress();
            }
            return Reflect.apply(target, thisArg, argumentsList);
        }
        base[prop] = new Proxy(nativeMethod, {
            apply: apply
        });
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function getPropertyInChain(base, chain) {
        var pos = chain.indexOf(".");
        if (pos === -1) {
            return {
                base: base,
                prop: chain
            };
        }
        var prop = chain.slice(0, pos);
        if (base === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        var nextBase = base[prop];
        chain = chain.slice(pos + 1);
        if ((base instanceof Object || typeof base === "object") && isEmptyObject(base)) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase === null) {
            return {
                base: base,
                prop: prop,
                chain: chain
            };
        }
        if (nextBase !== undefined) {
            return getPropertyInChain(nextBase, chain);
        }
        Object.defineProperty(base, prop, {
            configurable: true
        });
        return {
            base: base,
            prop: prop,
            chain: chain
        };
    }
    function inferValue(value) {
        if (value === "undefined") {
            return undefined;
        }
        if (value === "false") {
            return false;
        }
        if (value === "true") {
            return true;
        }
        if (value === "null") {
            return null;
        }
        if (value === "NaN") {
            return NaN;
        }
        if (value.startsWith("/") && value.endsWith("/")) {
            return toRegExp(value);
        }
        var MAX_ALLOWED_NUM = 32767;
        var numVal = Number(value);
        if (!nativeIsNaN(numVal)) {
            if (Math.abs(numVal) > MAX_ALLOWED_NUM) {
                throw new Error("number values bigger than 32767 are not allowed");
            }
            return numVal;
        }
        var errorMessage = `'${value}' value type can't be inferred`;
        try {
            var parsableVal = JSON.parse(value);
            if (parsableVal instanceof Object || typeof parsableVal === "string") {
                return parsableVal;
            }
        } catch (e) {
            errorMessage += `: ${e}`;
        }
        throw new TypeError(errorMessage);
    }
    function isValueMatched(value, matcher) {
        if (typeof value === "function") {
            return false;
        }
        if (nativeIsNaN(value)) {
            return nativeIsNaN(matcher);
        }
        if (value === null || typeof value === "undefined" || typeof value === "number" || typeof value === "boolean") {
            return value === matcher;
        }
        if (typeof value === "string") {
            if (typeof matcher === "string" || matcher instanceof RegExp) {
                return isStringMatched(value, matcher);
            }
            return false;
        }
        if (Array.isArray(value) && Array.isArray(matcher)) {
            return isArrayMatched(value, matcher);
        }
        if (isArbitraryObject(value) && isArbitraryObject(matcher)) {
            return isObjectMatched(value, matcher);
        }
        return false;
    }
    function getAbortFunc() {
        var rid = randomId();
        var isErrorHandlerSet = false;
        return function abort() {
            if (!isErrorHandlerSet) {
                window.onerror = createOnErrorHandler(rid);
                isErrorHandlerSet = true;
            }
            throw new ReferenceError(rid);
        };
    }
    function matchStackTrace(stackMatch, stackTrace) {
        if (!stackMatch || stackMatch === "") {
            return true;
        }
        var regExpValues = backupRegExpValues();
        if (shouldAbortInlineOrInjectedScript(stackMatch, stackTrace)) {
            if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
                restoreRegExpValues(regExpValues);
            }
            return true;
        }
        var stackRegexp = toRegExp(stackMatch);
        var refinedStackTrace = stackTrace.split("\n").slice(2).map((function(line) {
            return line.trim();
        })).join("\n");
        if (regExpValues.length && regExpValues[0] !== RegExp.$1) {
            restoreRegExpValues(regExpValues);
        }
        return getNativeRegexpTest().call(stackRegexp, refinedStackTrace);
    }
    function getErrorMessage(error) {
        var isErrorWithMessage = function isErrorWithMessage(e) {
            return typeof e === "object" && e !== null && "message" in e && typeof e.message === "string";
        };
        if (isErrorWithMessage(error)) {
            return error.message;
        }
        try {
            return new Error(JSON.stringify(error)).message;
        } catch (_unused) {
            return new Error(String(error)).message;
        }
    }
    function shouldAbortInlineOrInjectedScript(stackMatch, stackTrace) {
        var INLINE_SCRIPT_STRING = "inlineScript";
        var INJECTED_SCRIPT_STRING = "injectedScript";
        var INJECTED_SCRIPT_MARKER = "<anonymous>";
        var isInlineScript = function isInlineScript(match) {
            return match.includes(INLINE_SCRIPT_STRING);
        };
        var isInjectedScript = function isInjectedScript(match) {
            return match.includes(INJECTED_SCRIPT_STRING);
        };
        if (!(isInlineScript(stackMatch) || isInjectedScript(stackMatch))) {
            return false;
        }
        var documentURL = window.location.href;
        var pos = documentURL.indexOf("#");
        if (pos !== -1) {
            documentURL = documentURL.slice(0, pos);
        }
        var stackSteps = stackTrace.split("\n").slice(2).map((function(line) {
            return line.trim();
        }));
        var stackLines = stackSteps.map((function(line) {
            var stack;
            var getStackTraceValues = /(.*?@)?(\S+)(:\d+)(:\d+)\)?$/.exec(line);
            if (getStackTraceValues) {
                var _stackURL, _stackURL2;
                var stackURL = getStackTraceValues[2];
                var stackLine = getStackTraceValues[3];
                var stackCol = getStackTraceValues[4];
                if ((_stackURL = stackURL) !== null && _stackURL !== void 0 && _stackURL.startsWith("(")) {
                    stackURL = stackURL.slice(1);
                }
                if ((_stackURL2 = stackURL) !== null && _stackURL2 !== void 0 && _stackURL2.startsWith(INJECTED_SCRIPT_MARKER)) {
                    var _stackFunction;
                    stackURL = INJECTED_SCRIPT_STRING;
                    var stackFunction = getStackTraceValues[1] !== undefined ? getStackTraceValues[1].slice(0, -1) : line.slice(0, getStackTraceValues.index).trim();
                    if ((_stackFunction = stackFunction) !== null && _stackFunction !== void 0 && _stackFunction.startsWith("at")) {
                        stackFunction = stackFunction.slice(2).trim();
                    }
                    stack = `${stackFunction} ${stackURL}${stackLine}${stackCol}`.trim();
                } else if (stackURL === documentURL) {
                    stack = `${INLINE_SCRIPT_STRING}${stackLine}${stackCol}`.trim();
                } else {
                    stack = `${stackURL}${stackLine}${stackCol}`.trim();
                }
            } else {
                stack = line;
            }
            return stack;
        }));
        if (stackLines) {
            for (var index = 0; index < stackLines.length; index += 1) {
                if (isInlineScript(stackMatch) && stackLines[index].startsWith(INLINE_SCRIPT_STRING) && stackLines[index].match(toRegExp(stackMatch))) {
                    return true;
                }
                if (isInjectedScript(stackMatch) && stackLines[index].startsWith(INJECTED_SCRIPT_STRING) && stackLines[index].match(toRegExp(stackMatch))) {
                    return true;
                }
            }
        }
        return false;
    }
    function getNativeRegexpTest() {
        var descriptor = Object.getOwnPropertyDescriptor(RegExp.prototype, "test");
        var nativeRegexTest = descriptor === null || descriptor === void 0 ? void 0 : descriptor.value;
        if (descriptor && typeof descriptor.value === "function") {
            return nativeRegexTest;
        }
        throw new Error("RegExp.prototype.test is not a function");
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function nativeIsNaN(num) {
        var native = Number.isNaN || window.isNaN;
        return native(num);
    }
    function randomId() {
        return Math.random().toString(36).slice(2, 9);
    }
    function createOnErrorHandler(rid) {
        var nativeOnError = window.onerror;
        return function onError(error) {
            if (typeof error === "string" && error.includes(rid)) {
                return true;
            }
            if (nativeOnError instanceof Function) {
                for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                    args[_key - 1] = arguments[_key];
                }
                return nativeOnError.apply(window, [ error, ...args ]);
            }
            return false;
        };
    }
    function isEmptyObject(obj) {
        return Object.keys(obj).length === 0 && !obj.prototype;
    }
    function isArbitraryObject(value) {
        return value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof RegExp);
    }
    function isStringMatched(str, matcher) {
        if (typeof matcher === "string") {
            if (matcher === "") {
                return str === matcher;
            }
            return str.includes(matcher);
        }
        if (matcher instanceof RegExp) {
            return matcher.test(str);
        }
        return false;
    }
    function isArrayMatched(array, matcher) {
        if (array.length === 0) {
            return matcher.length === 0;
        }
        if (matcher.length === 0) {
            return false;
        }
        var _loop = function _loop() {
            var matcherValue = matcher[i];
            var isMatching = array.some((function(arrItem) {
                return isValueMatched(arrItem, matcherValue);
            }));
            if (!isMatching) {
                return {
                    v: false
                };
            }
            return 0;
        }, _ret;
        for (var i = 0; i < matcher.length; i += 1) {
            _ret = _loop();
            if (_ret === 0) continue;
            if (_ret) return _ret.v;
        }
        return true;
    }
    function isObjectMatched(obj, matcher) {
        var matcherKeys = Object.keys(matcher);
        for (var i = 0; i < matcherKeys.length; i += 1) {
            var key = matcherKeys[i];
            var value = obj[key];
            if (!isValueMatched(value, matcher[key])) {
                return false;
            }
            continue;
        }
        return true;
    }
    function backupRegExpValues() {
        try {
            var arrayOfRegexpValues = [];
            for (var index = 1; index < 10; index += 1) {
                var value = `$${index}`;
                if (!RegExp[value]) {
                    break;
                }
                arrayOfRegexpValues.push(RegExp[value]);
            }
            return arrayOfRegexpValues;
        } catch (error) {
            return [];
        }
    }
    function restoreRegExpValues(array) {
        if (!array.length) {
            return;
        }
        try {
            var stringPattern = "";
            if (array.length === 1) {
                stringPattern = `(${array[0]})`;
            } else {
                stringPattern = array.reduce((function(accumulator, currentValue, currentIndex) {
                    if (currentIndex === 1) {
                        return `(${accumulator}),(${currentValue})`;
                    }
                    return `${accumulator},(${currentValue})`;
                }));
            }
            var regExpGroup = new RegExp(stringPattern);
            array.toString().replace(regExpGroup, "");
        } catch (error) {
            var message = `Failed to restore RegExp values: ${error}`;
            console.log(message);
        }
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        trustedSuppressNativeMethod.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

function xmlPrune(source, args) {
    var flag = "done";
    var uniqueIdentifier = source.uniqueId + source.name + "_" + (Array.isArray(args) ? args.join("_") : "");
    if (source.uniqueId) {
        if (Window.prototype.toString[uniqueIdentifier] === flag) {
            return;
        }
    }
    function xmlPrune(source, propsToRemove) {
        var optionalProp = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
        var urlToMatch = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "";
        var verbose = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
        if (typeof Reflect === "undefined" || typeof fetch === "undefined" || typeof Proxy === "undefined" || typeof Response === "undefined") {
            return;
        }
        var shouldPruneResponse = false;
        var shouldLogContent = verbose === "true";
        var urlMatchRegexp = toRegExp(urlToMatch);
        var XPATH_MARKER = "xpath(";
        var isXpath = propsToRemove && propsToRemove.startsWith(XPATH_MARKER);
        var getXPathElements = function getXPathElements(contextNode) {
            var matchedElements = [];
            try {
                var elementsToRemove = propsToRemove.slice(XPATH_MARKER.length, -1);
                var xpathResult = contextNode.evaluate(elementsToRemove, contextNode, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
                for (var i = 0; i < xpathResult.snapshotLength; i += 1) {
                    matchedElements.push(xpathResult.snapshotItem(i));
                }
            } catch (ex) {
                var message = `Invalid XPath parameter: ${propsToRemove}\n${ex}`;
                logMessage(source, message);
            }
            return matchedElements;
        };
        var xPathPruning = function xPathPruning(xPathElements) {
            xPathElements.forEach((function(element) {
                if (element.nodeType === 1) {
                    element.remove();
                } else if (element.nodeType === 2) {
                    element.ownerElement.removeAttribute(element.nodeName);
                }
            }));
        };
        var isXML = function isXML(text) {
            if (typeof text === "string") {
                var trimmedText = text.trim();
                if (trimmedText.startsWith("<") && trimmedText.endsWith(">")) {
                    return true;
                }
            }
            return false;
        };
        var createXMLDocument = function createXMLDocument(text) {
            var xmlParser = new DOMParser;
            var xmlDocument = xmlParser.parseFromString(text, "text/xml");
            return xmlDocument;
        };
        var isPruningNeeded = function isPruningNeeded(response, propsToRemove) {
            if (!isXML(response)) {
                return false;
            }
            var docXML = createXMLDocument(response);
            return isXpath ? getXPathElements(docXML) : !!docXML.querySelector(propsToRemove);
        };
        var pruneXML = function pruneXML(text) {
            if (!isXML(text)) {
                shouldPruneResponse = false;
                return text;
            }
            var xmlDoc = createXMLDocument(text);
            var errorNode = xmlDoc.querySelector("parsererror");
            if (errorNode) {
                return text;
            }
            if (optionalProp !== "" && xmlDoc.querySelector(optionalProp) === null) {
                shouldPruneResponse = false;
                return text;
            }
            var elements = isXpath ? getXPathElements(xmlDoc) : xmlDoc.querySelectorAll(propsToRemove);
            if (!elements.length) {
                shouldPruneResponse = false;
                return text;
            }
            if (shouldLogContent) {
                var cloneXmlDoc = xmlDoc.cloneNode(true);
                logMessage(source, "Original xml:");
                logMessage(source, cloneXmlDoc, true, false);
            }
            if (isXpath) {
                xPathPruning(elements);
            } else {
                elements.forEach((function(elem) {
                    elem.remove();
                }));
            }
            if (shouldLogContent) {
                logMessage(source, "Modified xml:");
                logMessage(source, xmlDoc, true, false);
            }
            var serializer = new XMLSerializer;
            text = serializer.serializeToString(xmlDoc);
            return text;
        };
        var nativeOpen = window.XMLHttpRequest.prototype.open;
        var nativeSend = window.XMLHttpRequest.prototype.send;
        var xhrData;
        var openWrapper = function openWrapper(target, thisArg, args) {
            xhrData = getXhrData.apply(null, args);
            if (matchRequestProps(source, urlToMatch, xhrData)) {
                thisArg.shouldBePruned = true;
            }
            if (thisArg.shouldBePruned) {
                thisArg.collectedHeaders = [];
                var setRequestHeaderWrapper = function setRequestHeaderWrapper(target, thisArg, args) {
                    thisArg.collectedHeaders.push(args);
                    return Reflect.apply(target, thisArg, args);
                };
                var setRequestHeaderHandler = {
                    apply: setRequestHeaderWrapper
                };
                thisArg.setRequestHeader = new Proxy(thisArg.setRequestHeader, setRequestHeaderHandler);
            }
            return Reflect.apply(target, thisArg, args);
        };
        var sendWrapper = function sendWrapper(target, thisArg, args) {
            var allowedResponseTypeValues = [ "", "text" ];
            if (!thisArg.shouldBePruned || !allowedResponseTypeValues.includes(thisArg.responseType)) {
                return Reflect.apply(target, thisArg, args);
            }
            var forgedRequest = new XMLHttpRequest;
            forgedRequest.addEventListener("readystatechange", (function() {
                if (forgedRequest.readyState !== 4) {
                    return;
                }
                var {readyState: readyState, response: response, responseText: responseText, responseURL: responseURL, responseXML: responseXML, status: status, statusText: statusText} = forgedRequest;
                var content = responseText || response;
                if (typeof content !== "string") {
                    return;
                }
                if (!propsToRemove) {
                    if (isXML(response)) {
                        var message = `XMLHttpRequest.open() URL: ${responseURL}\nresponse: ${response}`;
                        logMessage(source, message);
                        logMessage(source, createXMLDocument(response), true, false);
                    }
                } else {
                    shouldPruneResponse = isPruningNeeded(response, propsToRemove);
                }
                var responseContent = shouldPruneResponse ? pruneXML(response) : response;
                Object.defineProperties(thisArg, {
                    readyState: {
                        value: readyState,
                        writable: false
                    },
                    responseURL: {
                        value: responseURL,
                        writable: false
                    },
                    responseXML: {
                        value: responseXML,
                        writable: false
                    },
                    status: {
                        value: status,
                        writable: false
                    },
                    statusText: {
                        value: statusText,
                        writable: false
                    },
                    response: {
                        value: responseContent,
                        writable: false
                    },
                    responseText: {
                        value: responseContent,
                        writable: false
                    }
                });
                setTimeout((function() {
                    var stateEvent = new Event("readystatechange");
                    thisArg.dispatchEvent(stateEvent);
                    var loadEvent = new Event("load");
                    thisArg.dispatchEvent(loadEvent);
                    var loadEndEvent = new Event("loadend");
                    thisArg.dispatchEvent(loadEndEvent);
                }), 1);
                hit(source);
            }));
            nativeOpen.apply(forgedRequest, [ xhrData.method, xhrData.url ]);
            thisArg.collectedHeaders.forEach((function(header) {
                var name = header[0];
                var value = header[1];
                forgedRequest.setRequestHeader(name, value);
            }));
            thisArg.collectedHeaders = [];
            try {
                nativeSend.call(forgedRequest, args);
            } catch (_unused) {
                return Reflect.apply(target, thisArg, args);
            }
            return undefined;
        };
        var openHandler = {
            apply: openWrapper
        };
        var sendHandler = {
            apply: sendWrapper
        };
        XMLHttpRequest.prototype.open = new Proxy(XMLHttpRequest.prototype.open, openHandler);
        XMLHttpRequest.prototype.send = new Proxy(XMLHttpRequest.prototype.send, sendHandler);
        var nativeFetch = window.fetch;
        var fetchWrapper = async function fetchWrapper(target, thisArg, args) {
            var fetchURL = args[0] instanceof Request ? args[0].url : args[0];
            if (typeof fetchURL !== "string" || fetchURL.length === 0) {
                return Reflect.apply(target, thisArg, args);
            }
            if (urlMatchRegexp.test(fetchURL)) {
                var response = await nativeFetch(...args);
                var clonedResponse = response.clone();
                var responseText = await response.text();
                shouldPruneResponse = isPruningNeeded(responseText, propsToRemove);
                if (!shouldPruneResponse) {
                    var message = `fetch URL: ${fetchURL}\nresponse text: ${responseText}`;
                    logMessage(source, message);
                    logMessage(source, createXMLDocument(responseText), true, false);
                    return clonedResponse;
                }
                var prunedText = pruneXML(responseText);
                if (shouldPruneResponse) {
                    hit(source);
                    return new Response(prunedText, {
                        status: response.status,
                        statusText: response.statusText,
                        headers: response.headers
                    });
                }
                return clonedResponse;
            }
            return Reflect.apply(target, thisArg, args);
        };
        var fetchHandler = {
            apply: fetchWrapper
        };
        window.fetch = new Proxy(window.fetch, fetchHandler);
    }
    function hit(source) {
        var ADGUARD_PREFIX = "[AdGuard]";
        if (!source.verbose) {
            return;
        }
        try {
            var trace = console.trace.bind(console);
            var label = `${ADGUARD_PREFIX} `;
            if (source.engine === "corelibs") {
                label += source.ruleText;
            } else {
                if (source.domainName) {
                    label += `${source.domainName}`;
                }
                if (source.args) {
                    label += `#%#//scriptlet('${source.name}', '${source.args.join("', '")}')`;
                } else {
                    label += `#%#//scriptlet('${source.name}')`;
                }
            }
            if (trace) {
                trace(label);
            }
        } catch (e) {}
        if (typeof window.__debug === "function") {
            window.__debug(source);
        }
    }
    function logMessage(source, message) {
        var forced = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var convertMessageToString = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
        var {name: name, verbose: verbose} = source;
        if (!forced && !verbose) {
            return;
        }
        var nativeConsole = console.log;
        if (!convertMessageToString) {
            nativeConsole(`${name}:`, message);
            return;
        }
        nativeConsole(`${name}: ${message}`);
    }
    function toRegExp(rawInput) {
        var input = rawInput || "";
        var DEFAULT_VALUE = ".?";
        var FORWARD_SLASH = "/";
        if (input === "") {
            return new RegExp(DEFAULT_VALUE);
        }
        var delimiterIndex = input.lastIndexOf(FORWARD_SLASH);
        var flagsPart = input.substring(delimiterIndex + 1);
        var regExpPart = input.substring(0, delimiterIndex + 1);
        var isValidRegExpFlag = function isValidRegExpFlag(flag) {
            if (!flag) {
                return false;
            }
            try {
                new RegExp("", flag);
                return true;
            } catch (ex) {
                return false;
            }
        };
        var getRegExpFlags = function getRegExpFlags(regExpStr, flagsStr) {
            if (regExpStr.startsWith(FORWARD_SLASH) && regExpStr.endsWith(FORWARD_SLASH) && !regExpStr.endsWith("\\/") && isValidRegExpFlag(flagsStr)) {
                return flagsStr;
            }
            return "";
        };
        var flags = getRegExpFlags(regExpPart, flagsPart);
        if (input.startsWith(FORWARD_SLASH) && input.endsWith(FORWARD_SLASH) || flags) {
            var regExpInput = flags ? regExpPart : input;
            return new RegExp(regExpInput.slice(1, -1), flags);
        }
        var escaped = input.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        return new RegExp(escaped);
    }
    function getXhrData(method, url, async, user, password) {
        return {
            method: method,
            url: url,
            async: async,
            user: user,
            password: password
        };
    }
    function matchRequestProps(source, propsToMatch, requestData) {
        if (propsToMatch === "" || propsToMatch === "*") {
            return true;
        }
        var isMatched;
        var parsedData = parseMatchProps(propsToMatch);
        if (!isValidParsedData(parsedData)) {
            logMessage(source, `Invalid parameter: ${propsToMatch}`);
            isMatched = false;
        } else {
            var matchData = getMatchPropsData(parsedData);
            var matchKeys = Object.keys(matchData);
            isMatched = matchKeys.every((function(matchKey) {
                var matchValue = matchData[matchKey];
                var dataValue = requestData[matchKey];
                return Object.prototype.hasOwnProperty.call(requestData, matchKey) && typeof dataValue === "string" && (matchValue === null || matchValue === void 0 ? void 0 : matchValue.test(dataValue));
            }));
        }
        return isMatched;
    }
    function getMatchPropsData(data) {
        var matchData = {};
        var dataKeys = Object.keys(data);
        dataKeys.forEach((function(key) {
            matchData[key] = toRegExp(data[key]);
        }));
        return matchData;
    }
    function getRequestProps() {
        return [ "url", "method", "headers", "body", "credentials", "cache", "redirect", "referrer", "referrerPolicy", "integrity", "keepalive", "signal", "mode" ];
    }
    function isValidParsedData(data) {
        return Object.values(data).every((function(value) {
            return isValidStrPattern(value);
        }));
    }
    function parseMatchProps(propsToMatchStr) {
        var PROPS_DIVIDER = " ";
        var PAIRS_MARKER = ":";
        var isRequestProp = function isRequestProp(prop) {
            return getRequestProps().includes(prop);
        };
        var propsObj = {};
        var props = propsToMatchStr.split(PROPS_DIVIDER);
        props.forEach((function(prop) {
            var dividerInd = prop.indexOf(PAIRS_MARKER);
            var key = prop.slice(0, dividerInd);
            if (isRequestProp(key)) {
                var value = prop.slice(dividerInd + 1);
                propsObj[key] = value;
            } else {
                propsObj.url = prop;
            }
        }));
        return propsObj;
    }
    function isValidStrPattern(input) {
        var FORWARD_SLASH = "/";
        var str = escapeRegExp(input);
        if (input[0] === FORWARD_SLASH && input[input.length - 1] === FORWARD_SLASH) {
            str = input.slice(1, -1);
        }
        var isValid;
        try {
            isValid = new RegExp(str);
            isValid = true;
        } catch (e) {
            isValid = false;
        }
        return isValid;
    }
    function escapeRegExp(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    var updatedArgs = args ? [].concat(source).concat(args) : [ source ];
    try {
        xmlPrune.apply(this, updatedArgs);
        if (source.uniqueId) {
            Object.defineProperty(Window.prototype.toString, uniqueIdentifier, {
                value: flag,
                enumerable: false,
                writable: false,
                configurable: false
            });
        }
    } catch (e) {
        console.log(e);
    }
}

var scriptletsMap = {
    "amazon-apstag": AmazonApstag,
    "ubo-amazon_apstag.js": AmazonApstag,
    "amazon_apstag.js": AmazonApstag,
    "didomi-loader": DidomiLoader,
    fingerprintjs2: Fingerprintjs2,
    "ubo-fingerprint2.js": Fingerprintjs2,
    "fingerprint2.js": Fingerprintjs2,
    fingerprintjs3: Fingerprintjs3,
    "ubo-fingerprint3.js": Fingerprintjs3,
    "fingerprint3.js": Fingerprintjs3,
    gemius: Gemius,
    "google-analytics-ga": GoogleAnalyticsGa,
    "ubo-google-analytics_ga.js": GoogleAnalyticsGa,
    "google-analytics_ga.js": GoogleAnalyticsGa,
    "google-analytics": GoogleAnalytics,
    "ubo-google-analytics_analytics.js": GoogleAnalytics,
    "google-analytics_analytics.js": GoogleAnalytics,
    "googletagmanager-gtm": GoogleAnalytics,
    "ubo-googletagmanager_gtm.js": GoogleAnalytics,
    "googletagmanager_gtm.js": GoogleAnalytics,
    "google-ima3": GoogleIma3,
    "ubo-google-ima.js": GoogleIma3,
    "google-ima.js": GoogleIma3,
    "googlesyndication-adsbygoogle": GoogleSyndicationAdsByGoogle,
    "ubo-googlesyndication_adsbygoogle.js": GoogleSyndicationAdsByGoogle,
    "googlesyndication_adsbygoogle.js": GoogleSyndicationAdsByGoogle,
    "googletagservices-gpt": GoogleTagServicesGpt,
    "ubo-googletagservices_gpt.js": GoogleTagServicesGpt,
    "googletagservices_gpt.js": GoogleTagServicesGpt,
    matomo: Matomo,
    "naver-wcslog": NaverWcslog,
    "pardot-1.0": Pardot,
    prebid: Prebid,
    "scorecardresearch-beacon": ScoreCardResearchBeacon,
    "ubo-scorecardresearch_beacon.js": ScoreCardResearchBeacon,
    "scorecardresearch_beacon.js": ScoreCardResearchBeacon,
    "abort-current-inline-script": abortCurrentInlineScript,
    "abort-current-script.js": abortCurrentInlineScript,
    "ubo-abort-current-script.js": abortCurrentInlineScript,
    "acs.js": abortCurrentInlineScript,
    "ubo-acs.js": abortCurrentInlineScript,
    "ubo-abort-current-script": abortCurrentInlineScript,
    "ubo-acs": abortCurrentInlineScript,
    "abort-current-inline-script.js": abortCurrentInlineScript,
    "ubo-abort-current-inline-script.js": abortCurrentInlineScript,
    "acis.js": abortCurrentInlineScript,
    "ubo-acis.js": abortCurrentInlineScript,
    "ubo-abort-current-inline-script": abortCurrentInlineScript,
    "ubo-acis": abortCurrentInlineScript,
    "abp-abort-current-inline-script": abortCurrentInlineScript,
    "abort-on-property-read": abortOnPropertyRead,
    "abort-on-property-read.js": abortOnPropertyRead,
    "ubo-abort-on-property-read.js": abortOnPropertyRead,
    "aopr.js": abortOnPropertyRead,
    "ubo-aopr.js": abortOnPropertyRead,
    "ubo-abort-on-property-read": abortOnPropertyRead,
    "ubo-aopr": abortOnPropertyRead,
    "abp-abort-on-property-read": abortOnPropertyRead,
    "abort-on-property-write": abortOnPropertyWrite,
    "abort-on-property-write.js": abortOnPropertyWrite,
    "ubo-abort-on-property-write.js": abortOnPropertyWrite,
    "aopw.js": abortOnPropertyWrite,
    "ubo-aopw.js": abortOnPropertyWrite,
    "ubo-abort-on-property-write": abortOnPropertyWrite,
    "ubo-aopw": abortOnPropertyWrite,
    "abp-abort-on-property-write": abortOnPropertyWrite,
    "abort-on-stack-trace": abortOnStackTrace,
    "abort-on-stack-trace.js": abortOnStackTrace,
    "ubo-abort-on-stack-trace.js": abortOnStackTrace,
    "aost.js": abortOnStackTrace,
    "ubo-aost.js": abortOnStackTrace,
    "ubo-abort-on-stack-trace": abortOnStackTrace,
    "ubo-aost": abortOnStackTrace,
    "abp-abort-on-stack-trace": abortOnStackTrace,
    "adjust-setInterval": adjustSetInterval,
    "nano-setInterval-booster.js": adjustSetInterval,
    "ubo-nano-setInterval-booster.js": adjustSetInterval,
    "nano-sib.js": adjustSetInterval,
    "ubo-nano-sib.js": adjustSetInterval,
    "adjust-setInterval.js": adjustSetInterval,
    "ubo-adjust-setInterval.js": adjustSetInterval,
    "ubo-nano-setInterval-booster": adjustSetInterval,
    "ubo-nano-sib": adjustSetInterval,
    "ubo-adjust-setInterval": adjustSetInterval,
    "adjust-setTimeout": adjustSetTimeout,
    "adjust-setTimeout.js": adjustSetTimeout,
    "ubo-adjust-setTimeout.js": adjustSetTimeout,
    "nano-setTimeout-booster.js": adjustSetTimeout,
    "ubo-nano-setTimeout-booster.js": adjustSetTimeout,
    "nano-stb.js": adjustSetTimeout,
    "ubo-nano-stb.js": adjustSetTimeout,
    "ubo-adjust-setTimeout": adjustSetTimeout,
    "ubo-nano-setTimeout-booster": adjustSetTimeout,
    "ubo-nano-stb": adjustSetTimeout,
    "call-nothrow": callNoThrow,
    "call-nothrow.js": callNoThrow,
    "ubo-call-nothrow.js": callNoThrow,
    "ubo-call-nothrow": callNoThrow,
    "debug-current-inline-script": debugCurrentInlineScript,
    "debug-on-property-read": debugOnPropertyRead,
    "debug-on-property-write": debugOnPropertyWrite,
    "dir-string": dirString,
    "disable-newtab-links": disableNewtabLinks,
    "disable-newtab-links.js": disableNewtabLinks,
    "ubo-disable-newtab-links.js": disableNewtabLinks,
    "ubo-disable-newtab-links": disableNewtabLinks,
    "evaldata-prune": evalDataPrune,
    "evaldata-prune.js": evalDataPrune,
    "ubo-evaldata-prune.js": evalDataPrune,
    "ubo-evaldata-prune": evalDataPrune,
    "close-window": forceWindowClose,
    "window-close-if.js": forceWindowClose,
    "ubo-window-close-if.js": forceWindowClose,
    "ubo-window-close-if": forceWindowClose,
    "close-window.js": forceWindowClose,
    "ubo-close-window.js": forceWindowClose,
    "ubo-close-window": forceWindowClose,
    "hide-in-shadow-dom": hideInShadowDom,
    "href-sanitizer": hrefSanitizer,
    "href-sanitizer.js": hrefSanitizer,
    "ubo-href-sanitizer.js": hrefSanitizer,
    "ubo-href-sanitizer": hrefSanitizer,
    "inject-css-in-shadow-dom": injectCssInShadowDom,
    "json-prune-fetch-response": jsonPruneFetchResponse,
    "json-prune-fetch-response.js": jsonPruneFetchResponse,
    "ubo-json-prune-fetch-response.js": jsonPruneFetchResponse,
    "ubo-json-prune-fetch-response": jsonPruneFetchResponse,
    "json-prune": jsonPrune,
    "json-prune.js": jsonPrune,
    "ubo-json-prune.js": jsonPrune,
    "ubo-json-prune": jsonPrune,
    "abp-json-prune": jsonPrune,
    "json-prune-xhr-response": jsonPruneXhrResponse,
    "json-prune-xhr-response.js": jsonPruneXhrResponse,
    "ubo-json-prune-xhr-response.js": jsonPruneXhrResponse,
    "ubo-json-prune-xhr-response": jsonPruneXhrResponse,
    "log-addEventListener": logAddEventListener,
    "addEventListener-logger.js": logAddEventListener,
    "ubo-addEventListener-logger.js": logAddEventListener,
    "aell.js": logAddEventListener,
    "ubo-aell.js": logAddEventListener,
    "ubo-addEventListener-logger": logAddEventListener,
    "ubo-aell": logAddEventListener,
    "log-eval": logEval,
    log: log,
    "abp-log": log,
    "log-on-stack-trace": logOnStackTrace,
    "m3u-prune": m3uPrune,
    "m3u-prune.js": m3uPrune,
    "ubo-m3u-prune.js": m3uPrune,
    "ubo-m3u-prune": m3uPrune,
    "metrika-yandex-tag": metrikaYandexTag,
    "metrika-yandex-watch": metrikaYandexWatch,
    "no-protected-audience": noProtectedAudience,
    "no-topics": noTopics,
    noeval: noeval,
    "noeval.js": noeval,
    "silent-noeval.js": noeval,
    "ubo-noeval.js": noeval,
    "ubo-silent-noeval.js": noeval,
    "ubo-noeval": noeval,
    "ubo-silent-noeval": noeval,
    nowebrtc: nowebrtc,
    "nowebrtc.js": nowebrtc,
    "ubo-nowebrtc.js": nowebrtc,
    "ubo-nowebrtc": nowebrtc,
    "prevent-addEventListener": preventAddEventListener,
    "addEventListener-defuser.js": preventAddEventListener,
    "ubo-addEventListener-defuser.js": preventAddEventListener,
    "aeld.js": preventAddEventListener,
    "ubo-aeld.js": preventAddEventListener,
    "ubo-addEventListener-defuser": preventAddEventListener,
    "ubo-aeld": preventAddEventListener,
    "abp-prevent-listener": preventAddEventListener,
    "prevent-adfly": preventAdfly,
    "prevent-bab": preventBab,
    "prevent-canvas": preventCanvas,
    "prevent-canvas.js": preventCanvas,
    "ubo-prevent-canvas.js": preventCanvas,
    "ubo-prevent-canvas": preventCanvas,
    "prevent-element-src-loading": preventElementSrcLoading,
    "prevent-eval-if": preventEvalIf,
    "noeval-if.js": preventEvalIf,
    "ubo-noeval-if.js": preventEvalIf,
    "ubo-noeval-if": preventEvalIf,
    "prevent-fab-3.2.0": preventFab,
    "nofab.js": preventFab,
    "ubo-nofab.js": preventFab,
    "fuckadblock.js-3.2.0": preventFab,
    "ubo-fuckadblock.js-3.2.0": preventFab,
    "ubo-nofab": preventFab,
    "prevent-fetch": preventFetch,
    "prevent-fetch.js": preventFetch,
    "ubo-prevent-fetch.js": preventFetch,
    "ubo-prevent-fetch": preventFetch,
    "no-fetch-if.js": preventFetch,
    "ubo-no-fetch-if.js": preventFetch,
    "ubo-no-fetch-if": preventFetch,
    "prevent-popads-net": preventPopadsNet,
    "popads.net.js": preventPopadsNet,
    "ubo-popads.net.js": preventPopadsNet,
    "ubo-popads.net": preventPopadsNet,
    "prevent-refresh": preventRefresh,
    "prevent-refresh.js": preventRefresh,
    "refresh-defuser.js": preventRefresh,
    "refresh-defuser": preventRefresh,
    "ubo-prevent-refresh.js": preventRefresh,
    "ubo-prevent-refresh": preventRefresh,
    "ubo-refresh-defuser.js": preventRefresh,
    "ubo-refresh-defuser": preventRefresh,
    "prevent-requestAnimationFrame": preventRequestAnimationFrame,
    "no-requestAnimationFrame-if.js": preventRequestAnimationFrame,
    "ubo-no-requestAnimationFrame-if.js": preventRequestAnimationFrame,
    "norafif.js": preventRequestAnimationFrame,
    "ubo-norafif.js": preventRequestAnimationFrame,
    "ubo-no-requestAnimationFrame-if": preventRequestAnimationFrame,
    "ubo-norafif": preventRequestAnimationFrame,
    "prevent-setInterval": preventSetInterval,
    "no-setInterval-if.js": preventSetInterval,
    "ubo-no-setInterval-if.js": preventSetInterval,
    "setInterval-defuser.js": preventSetInterval,
    "ubo-setInterval-defuser.js": preventSetInterval,
    "nosiif.js": preventSetInterval,
    "ubo-nosiif.js": preventSetInterval,
    "sid.js": preventSetInterval,
    "ubo-sid.js": preventSetInterval,
    "ubo-no-setInterval-if": preventSetInterval,
    "ubo-setInterval-defuser": preventSetInterval,
    "ubo-nosiif": preventSetInterval,
    "ubo-sid": preventSetInterval,
    "prevent-setTimeout": preventSetTimeout,
    "no-setTimeout-if.js": preventSetTimeout,
    "ubo-no-setTimeout-if.js": preventSetTimeout,
    "nostif.js": preventSetTimeout,
    "ubo-nostif.js": preventSetTimeout,
    "ubo-no-setTimeout-if": preventSetTimeout,
    "ubo-nostif": preventSetTimeout,
    "setTimeout-defuser.js": preventSetTimeout,
    "ubo-setTimeout-defuser.js": preventSetTimeout,
    "ubo-setTimeout-defuser": preventSetTimeout,
    "std.js": preventSetTimeout,
    "ubo-std.js": preventSetTimeout,
    "ubo-std": preventSetTimeout,
    "prevent-window-open": preventWindowOpen,
    "window.open-defuser.js": preventWindowOpen,
    "ubo-window.open-defuser.js": preventWindowOpen,
    "ubo-window.open-defuser": preventWindowOpen,
    "nowoif.js": preventWindowOpen,
    "ubo-nowoif.js": preventWindowOpen,
    "ubo-nowoif": preventWindowOpen,
    "no-window-open-if.js": preventWindowOpen,
    "ubo-no-window-open-if.js": preventWindowOpen,
    "ubo-no-window-open-if": preventWindowOpen,
    "prevent-xhr": preventXHR,
    "no-xhr-if.js": preventXHR,
    "ubo-no-xhr-if.js": preventXHR,
    "ubo-no-xhr-if": preventXHR,
    "remove-attr": removeAttr,
    "remove-attr.js": removeAttr,
    "ubo-remove-attr.js": removeAttr,
    "ra.js": removeAttr,
    "ubo-ra.js": removeAttr,
    "ubo-remove-attr": removeAttr,
    "ubo-ra": removeAttr,
    "remove-class": removeClass,
    "remove-class.js": removeClass,
    "ubo-remove-class.js": removeClass,
    "rc.js": removeClass,
    "ubo-rc.js": removeClass,
    "ubo-remove-class": removeClass,
    "ubo-rc": removeClass,
    "remove-cookie": removeCookie,
    "cookie-remover.js": removeCookie,
    "ubo-cookie-remover.js": removeCookie,
    "ubo-cookie-remover": removeCookie,
    "remove-cookie.js": removeCookie,
    "ubo-remove-cookie.js": removeCookie,
    "ubo-remove-cookie": removeCookie,
    "abp-cookie-remover": removeCookie,
    "remove-in-shadow-dom": removeInShadowDom,
    "remove-node-text": removeNodeText,
    "remove-node-text.js": removeNodeText,
    "ubo-remove-node-text.js": removeNodeText,
    "rmnt.js": removeNodeText,
    "ubo-rmnt.js": removeNodeText,
    "ubo-remove-node-text": removeNodeText,
    "ubo-rmnt": removeNodeText,
    "set-attr": setAttr,
    "set-attr.js": setAttr,
    "ubo-set-attr.js": setAttr,
    "ubo-set-attr": setAttr,
    "set-constant": setConstant,
    "set-constant.js": setConstant,
    "ubo-set-constant.js": setConstant,
    "set.js": setConstant,
    "ubo-set.js": setConstant,
    "ubo-set-constant": setConstant,
    "ubo-set": setConstant,
    "abp-override-property-read": setConstant,
    "set-cookie": setCookie,
    "set-cookie.js": setCookie,
    "ubo-set-cookie.js": setCookie,
    "ubo-set-cookie": setCookie,
    "set-cookie-reload": setCookieReload,
    "set-cookie-reload.js": setCookieReload,
    "ubo-set-cookie-reload.js": setCookieReload,
    "ubo-set-cookie-reload": setCookieReload,
    "set-local-storage-item": setLocalStorageItem,
    "set-local-storage-item.js": setLocalStorageItem,
    "ubo-set-local-storage-item.js": setLocalStorageItem,
    "ubo-set-local-storage-item": setLocalStorageItem,
    "set-popads-dummy": setPopadsDummy,
    "popads-dummy.js": setPopadsDummy,
    "ubo-popads-dummy.js": setPopadsDummy,
    "ubo-popads-dummy": setPopadsDummy,
    "set-session-storage-item": setSessionStorageItem,
    "set-session-storage-item.js": setSessionStorageItem,
    "ubo-set-session-storage-item.js": setSessionStorageItem,
    "ubo-set-session-storage-item": setSessionStorageItem,
    "spoof-css": spoofCSS,
    "spoof-css.js": spoofCSS,
    "ubo-spoof-css.js": spoofCSS,
    "ubo-spoof-css": spoofCSS,
    "trusted-click-element": trustedClickElement,
    "trusted-create-element": trustedCreateElement,
    "trusted-dispatch-event": trustedDispatchEvent,
    "trusted-prune-inbound-object": trustedPruneInboundObject,
    "trusted-replace-fetch-response": trustedReplaceFetchResponse,
    "trusted-replace-node-text": trustedReplaceNodeText,
    "trusted-replace-outbound-text": trustedReplaceOutboundText,
    "trusted-replace-xhr-response": trustedReplaceXhrResponse,
    "trusted-set-attr": trustedSetAttr,
    "trusted-set-constant": trustedSetConstant,
    "trusted-set-cookie": trustedSetCookie,
    "trusted-set-cookie-reload": trustedSetCookieReload,
    "trusted-set-local-storage-item": trustedSetLocalStorageItem,
    "trusted-set-session-storage-item": trustedSetSessionStorageItem,
    "trusted-suppress-native-method": trustedSuppressNativeMethod,
    "xml-prune": xmlPrune,
    "xml-prune.js": xmlPrune,
    "ubo-xml-prune.js": xmlPrune,
    "ubo-xml-prune": xmlPrune
};

var getScriptletFunction = function getScriptletFunction(name) {
    return scriptletsMap[name];
};

function passSourceAndProps(source, code) {
    var redirect = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
    var sourceString = JSON.stringify(source);
    var argsString = source.args ? `[${source.args.map((function(arg) {
        return JSON.stringify(arg);
    }))}]` : undefined;
    var params = argsString ? `${sourceString}, ${argsString}` : sourceString;
    if (redirect) {
        return `(function(source, args){\n${code}\n})(${params});`;
    }
    return `(${code})(${params});`;
}

function wrapInNonameFunc(code) {
    return `function(source, args){\n${code}\n}`;
}

function getScriptletCode(source) {
    var scriptletFunction = getScriptletFunction(source.name);
    if (typeof scriptletFunction !== "function") {
        throw new Error(`Error: cannot invoke scriptlet with name: '${source.name}'`);
    }
    var scriptletFunctionString = scriptletFunction.toString();
    var result = source.engine === "corelibs" || source.engine === "test" ? wrapInNonameFunc(scriptletFunctionString) : passSourceAndProps(source, scriptletFunctionString);
    return result;
}

var scriptlets = {
    invoke: getScriptletCode,
    getScriptletFunction: getScriptletFunction
};




/***/ }),

/***/ 66448:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  td: () => (/* binding */ isRedirectResourceCompatibleWithAdg),
  GY: () => (/* binding */ isValidScriptletName)
});

// UNUSED EXPORTS: isAbpSnippetRule, isAdgScriptletRule, isUboScriptletRule, isValidAdgRedirectRule, isValidScriptletRule

;// ./node_modules/.pnpm/@adguard+agtree@3.0.1/node_modules/@adguard/agtree/dist/compatibility-tables/platforms.js
/*
 * AGTree v3.0.1 (build date: Fri, 28 Feb 2025 15:31:12 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/* eslint-disable no-bitwise */
/**
 * @file Provides platform enums.
 * The difference between specific and generic platforms is that specific platforms are individual platforms
 * (e.g. AdGuard for Windows, AdGuard for Android, etc.),
 * while generic platforms are groups of specific platforms
 * (e.g. AdGuard for any OS, AdGuard for any Chromium-based extension, etc.).
 */
/**
 * List of specific platforms.
 */
const SpecificPlatform = {
    AdgOsWindows: 1,
    AdgOsMac: 1 << 1,
    AdgOsAndroid: 1 << 2,
    AdgExtChrome: 1 << 3,
    AdgExtOpera: 1 << 4,
    AdgExtEdge: 1 << 5,
    AdgExtFirefox: 1 << 6,
    AdgCbAndroid: 1 << 7,
    AdgCbIos: 1 << 8,
    AdgCbSafari: 1 << 9,
    UboExtChrome: 1 << 10,
    UboExtOpera: 1 << 11,
    UboExtEdge: 1 << 12,
    UboExtFirefox: 1 << 13,
    AbpExtChrome: 1 << 14,
    AbpExtOpera: 1 << 15,
    AbpExtEdge: 1 << 16,
    AbpExtFirefox: 1 << 17,
};
const AdgOsAny = SpecificPlatform.AdgOsWindows
    | SpecificPlatform.AdgOsMac
    | SpecificPlatform.AdgOsAndroid;
const AdgSafariAny = SpecificPlatform.AdgCbSafari | SpecificPlatform.AdgCbIos;
const AdgExtChromium = SpecificPlatform.AdgExtChrome
    | SpecificPlatform.AdgExtOpera
    | SpecificPlatform.AdgExtEdge;
const AdgExtAny = AdgExtChromium | SpecificPlatform.AdgExtFirefox;
const AdgAny = AdgExtAny | AdgOsAny | AdgSafariAny | SpecificPlatform.AdgCbAndroid;
const UboExtChromium = SpecificPlatform.UboExtChrome
    | SpecificPlatform.UboExtOpera
    | SpecificPlatform.UboExtEdge;
const UboExtAny = UboExtChromium | SpecificPlatform.UboExtFirefox;
const UboAny = UboExtAny;
const AbpExtChromium = SpecificPlatform.AbpExtChrome
    | SpecificPlatform.AbpExtOpera
    | SpecificPlatform.AbpExtEdge;
const AbpExtAny = AbpExtChromium | SpecificPlatform.AbpExtFirefox;
const AbpAny = AbpExtAny;
const Any = AdgAny | UboAny | AbpAny;
/**
 * List of generic platforms (combinations of specific platforms).
 */
const platforms_GenericPlatform = {
    AdgOsAny,
    AdgSafariAny,
    AdgExtChromium,
    AdgExtAny,
    AdgAny,
    UboExtChromium,
    UboExtAny,
    UboAny,
    AbpExtChromium,
    AbpExtAny,
    AbpAny,
    Any,
};



;// ./node_modules/.pnpm/@adguard+agtree@3.0.1/node_modules/@adguard/agtree/dist/utils/type-guards.js
/*
 * AGTree v3.0.1 (build date: Fri, 28 Feb 2025 15:31:12 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Checks whether the given value is undefined.
 *
 * @param value Value to check.
 *
 * @returns `true` if the value is 'undefined', `false` otherwise.
 */
const isUndefined = (value) => {
    return typeof value === 'undefined';
};
/**
 * Checks whether the given value is null.
 *
 * @param value Value to check.
 *
 * @returns `true` if the value is 'null', `false` otherwise.
 */
const isNull = (value) => {
    return value === null;
};
/**
 * Checks whether the given value is a string.
 *
 * @param value Value to check.
 * @returns `true` if the value is a string, `false` otherwise.
 */
const isString = (value) => {
    return typeof value === 'string';
};
/**
 * Checks whether the given value is an array of Uint8Arrays.
 *
 * @param value Value to check.
 *
 * @returns True if the value type is an array of Uint8Arrays.
 */
const isArrayOfUint8Arrays = (value) => {
    return Array.isArray(value) && value.every((chunk) => chunk instanceof Uint8Array);
};



;// ./node_modules/.pnpm/@adguard+agtree@3.0.1/node_modules/@adguard/agtree/dist/compatibility-tables/utils/platform-helpers.js
/*
 * AGTree v3.0.1 (build date: Fri, 28 Feb 2025 15:31:12 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/* eslint-disable no-bitwise */
/**
 * @file Provides platform mapping and helper functions.
 */
/**
 * Map of specific platforms string names to their corresponding enum values.
 */
const SPECIFIC_PLATFORM_MAP = new Map([
    ['adg_os_windows', SpecificPlatform.AdgOsWindows],
    ['adg_os_mac', SpecificPlatform.AdgOsMac],
    ['adg_os_android', SpecificPlatform.AdgOsAndroid],
    ['adg_ext_chrome', SpecificPlatform.AdgExtChrome],
    ['adg_ext_opera', SpecificPlatform.AdgExtOpera],
    ['adg_ext_edge', SpecificPlatform.AdgExtEdge],
    ['adg_ext_firefox', SpecificPlatform.AdgExtFirefox],
    ['adg_cb_android', SpecificPlatform.AdgCbAndroid],
    ['adg_cb_ios', SpecificPlatform.AdgCbIos],
    ['adg_cb_safari', SpecificPlatform.AdgCbSafari],
    ['ubo_ext_chrome', SpecificPlatform.UboExtChrome],
    ['ubo_ext_opera', SpecificPlatform.UboExtOpera],
    ['ubo_ext_edge', SpecificPlatform.UboExtEdge],
    ['ubo_ext_firefox', SpecificPlatform.UboExtFirefox],
    ['abp_ext_chrome', SpecificPlatform.AbpExtChrome],
    ['abp_ext_opera', SpecificPlatform.AbpExtOpera],
    ['abp_ext_edge', SpecificPlatform.AbpExtEdge],
    ['abp_ext_firefox', SpecificPlatform.AbpExtFirefox],
]);
/**
 * Map of specific platforms enum values to their corresponding string names.
 *
 * @note Reverse of {@link SPECIFIC_PLATFORM_MAP}.
 */
const SPECIFIC_PLATFORM_MAP_REVERSE = new Map([...SPECIFIC_PLATFORM_MAP].map(([key, value]) => [value, key]));
/**
 * Map of generic platforms string names to their corresponding enum values.
 */
const GENERIC_PLATFORM_MAP = new Map([
    ['adg_os_any', platforms_GenericPlatform.AdgOsAny],
    ['adg_safari_any', platforms_GenericPlatform.AdgSafariAny],
    ['adg_ext_chromium', platforms_GenericPlatform.AdgExtChromium],
    ['adg_ext_any', platforms_GenericPlatform.AdgExtAny],
    ['adg_any', platforms_GenericPlatform.AdgAny],
    ['ubo_ext_chromium', platforms_GenericPlatform.UboExtChromium],
    ['ubo_ext_any', platforms_GenericPlatform.UboExtAny],
    ['ubo_any', platforms_GenericPlatform.UboAny],
    ['abp_ext_chromium', platforms_GenericPlatform.AbpExtChromium],
    ['abp_ext_any', platforms_GenericPlatform.AbpExtAny],
    ['abp_any', platforms_GenericPlatform.AbpAny],
    ['any', platforms_GenericPlatform.Any],
]);
/**
 * Check if the platform is a generic platform.
 *
 * @param platform Platform to check.
 *
 * @returns True if the platform is a generic platform, false otherwise.
 */
const isGenericPlatform = (platform) => {
    // if more than one bit is set, it's a generic platform
    return !!(platform & (platform - 1));
};
/**
 * Returns the platform enum value for the given platform string name.
 *
 * @param platform Platform string name, e.g., 'adg_os_windows'.
 *
 * @returns Specific or generic platform enum value.
 * @throws Error if the platform is unknown.
 */
const getPlatformId = (platform) => {
    const specificPlatform = SPECIFIC_PLATFORM_MAP.get(platform);
    if (specificPlatform) {
        return specificPlatform;
    }
    const genericPlatform = GENERIC_PLATFORM_MAP.get(platform);
    if (genericPlatform) {
        return genericPlatform;
    }
    throw new Error(`Unknown platform: ${platform}`);
};
/**
 * Returns the specific platform string name for the given platform enum value.
 *
 * @param platform Specific platform enum value.
 *
 * @returns Specific platform string name, e.g., 'adg_os_windows'.
 * @throws Error if the platform is unknown.
 */
const getSpecificPlatformName = (platform) => {
    const specificPlatform = SPECIFIC_PLATFORM_MAP_REVERSE.get(platform);
    if (!specificPlatform) {
        throw new Error(`Unknown platform: ${platform}`);
    }
    return specificPlatform;
};



;// ./node_modules/.pnpm/@adguard+agtree@3.0.1/node_modules/@adguard/agtree/dist/utils/adblockers.js
/*
 * AGTree v3.0.1 (build date: Fri, 28 Feb 2025 15:31:12 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * @file Possible adblock syntaxes are listed here.
 */
/**
 * Possible adblock syntaxes (supported by this library)
 */
const adblockers_AdblockSyntax = {
    /**
     * Common syntax, which is supported by more than one adblocker (or by all adblockers).
     *
     * We typically use this syntax when we cannot determine the concrete syntax of the rule,
     * because the syntax is used by more than one adblocker natively.
     *
     * @example
     * - `||example.org^$important` is a common syntax, since it is used by all adblockers natively, and
     * we cannot determine at parsing level whether `important` is a valid option or not, and if it is valid,
     * then which adblocker supports it.
     */
    Common: 'Common',
    /**
     * Adblock Plus syntax.
     *
     * @example
     * - `example.org#$#abort-on-property-read alert` is an Adblock Plus syntax, since it is not used by any other
     * adblockers directly (probably supported by some on-the-fly conversion, but this is not the native syntax).
     * @see {@link https://adblockplus.org/}
     */
    Abp: 'AdblockPlus',
    /**
     * uBlock Origin syntax.
     *
     * @example
     * - `example.com##+js(set, atob, noopFunc)` is an uBlock Origin syntax, since it is not used by any other
     * adblockers directly (probably supported by some on-the-fly conversion, but this is not the native syntax).
     * @see {@link https://github.com/gorhill/uBlock}
     */
    Ubo: 'UblockOrigin',
    /**
     * AdGuard syntax.
     *
     * @example
     * - `example.org#%#//scriptlet("abort-on-property-read", "alert")` is an AdGuard syntax, since it is not used
     * by any other adblockers directly (probably supported by some on-the-fly conversion, but this is not the native
     * syntax).
     * @see {@link https://adguard.com/}
     */
    Adg: 'AdGuard',
};



;// ./node_modules/.pnpm/@adguard+agtree@3.0.1/node_modules/@adguard/agtree/dist/compatibility-tables/base.js
/*
 * AGTree v3.0.1 (build date: Fri, 28 Feb 2025 15:31:12 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */





/* eslint-disable no-bitwise */
/**
 * @file Provides common compatibility table methods.
 */
/**
 * Base compatibility table class which provides common methods to work with compatibility data.
 *
 * @template T Compatibility data schema.
 */
class CompatibilityTableBase {
    /**
     * Compatibility table data.
     */
    data;
    /**
     * Optional name transformer function. If provided,
     * it will be called in all methods before processing compatibility data names.
     */
    nameTransformer;
    /**
     * Creates a new instance of the common compatibility table.
     *
     * @param data Compatibility table data.
     * @param nameTransformer Optional name transformer function.
     */
    constructor(data, nameTransformer = null) {
        this.data = data;
        this.nameTransformer = nameTransformer;
    }
    /**
     * Helper method to get a 'row' from the compatibility table data by name.
     *
     * @param name Compatibility data name.
     * @returns Compatibility table row storage or `null` if not found.
     */
    getRowStorage(name) {
        const idx = this.data.map[name];
        if (isUndefined(idx)) {
            return null;
        }
        return this.data.shared[idx];
    }
    /**
     * Checks whether a compatibility data `name` exists for any platform.
     *
     * @note Technically, do the same as `exists()` method with generic platform _any_
     * but it is faster because it does not apply complex logic.
     *
     * @param name Compatibility data name.
     *
     * @returns True if the compatibility data exists, false otherwise.
     */
    existsAny(name) {
        const normalizedName = this.nameTransformer ? this.nameTransformer(name) : name;
        return !isUndefined(this.data.map[normalizedName]);
    }
    /**
     * Checks whether a compatibility data `name` exists for a specified platform.
     *
     * @param name Compatibility data name.
     * @param platform Specific or generic platform.
     *
     * @returns True if the compatibility data exists, false otherwise.
     */
    exists(name, platform) {
        const normalizedName = this.nameTransformer ? this.nameTransformer(name) : name;
        const data = this.getRowStorage(normalizedName);
        if (!data) {
            return false;
        }
        const isMatch = (idx) => {
            const el = data.shared[idx];
            return !isUndefined(el) && (el.name === normalizedName || !!el.aliases?.includes(normalizedName));
        };
        if (isGenericPlatform(platform)) {
            // Since indexes are specific platforms in the compatibility table data,
            // we can't index them directly if the platform is generic (union of specific platforms).
            // In this case, we need to iterate over the keys and return true on the first match.
            const keys = Object.keys(data.map);
            for (let i = 0; i < keys.length; i += 1) {
                const key = Number(keys[i]);
                if (platform & key) {
                    const idx = data.map[key];
                    if (isMatch(idx)) {
                        return true;
                    }
                }
            }
            return false;
        }
        const idx = data.map[platform];
        return isMatch(idx);
    }
    /**
     * Returns a compatibility data by name and specific platform.
     *
     * @param name The name of the compatibility data.
     * @param platform The specific platform.
     *
     * @returns A single compatibility data or `null` if not found.
     */
    getSingle(name, platform) {
        const normalizedName = this.nameTransformer ? this.nameTransformer(name) : name;
        const data = this.getRowStorage(normalizedName);
        if (!data) {
            return null;
        }
        const idx = data.map[platform];
        return isUndefined(idx) ? null : data.shared[idx];
    }
    /**
     * Returns all compatibility data records for name and specified platform.
     *
     * @param name Compatibility data name.
     * @param platform Specific or generic platform.
     *
     * @returns Multiple records grouped by platforms.
     * Technically, it is an object where keys are platform enums values and values are compatibility data records.
     *
     * @note Platform enum values can be converted to string names using {@link getSpecificPlatformName} on demand.
     */
    getMultiple(name, platform) {
        const normalizedName = this.nameTransformer ? this.nameTransformer(name) : name;
        const data = this.getRowStorage(normalizedName);
        if (!data) {
            return null;
        }
        if (isGenericPlatform(platform)) {
            const result = {};
            const keys = Object.keys(data.map);
            for (let i = 0; i < keys.length; i += 1) {
                const key = Number(keys[i]);
                if (platform & key) {
                    const idx = data.map[key];
                    if (!isUndefined(idx)) {
                        result[key] = data.shared[idx];
                    }
                }
            }
            return result;
        }
        const idx = data.map[platform];
        if (isUndefined(idx)) {
            return null;
        }
        return { key: data.shared[idx] };
    }
    /**
     * Returns all compatibility data records for the specified platform.
     *
     * @param platform Specific or generic platform.
     *
     * @returns Array of multiple records grouped by platforms.
     */
    getAllMultiple(platform) {
        const result = [];
        for (let i = 0; i < this.data.shared.length; i += 1) {
            const data = this.data.shared[i];
            const names = new Set(data.shared.map(({ name }) => name));
            names.forEach((name) => {
                const multipleRecords = this.getMultiple(name, platform);
                if (multipleRecords) {
                    result.push(multipleRecords);
                }
            });
        }
        return result;
    }
    /**
     * Returns the first compatibility data record for name and specified platform.
     *
     * @param name Compatibility data name.
     * @param platform Specific or generic platform.
     *
     * @returns First found compatibility data record or `null` if not found.
     */
    getFirst(name, platform) {
        const normalizedName = this.nameTransformer ? this.nameTransformer(name) : name;
        const data = this.getRowStorage(normalizedName);
        if (!data) {
            return null;
        }
        if (isGenericPlatform(platform)) {
            const keys = Object.keys(data.map);
            for (let i = 0; i < keys.length; i += 1) {
                const key = Number(keys[i]);
                if (platform & key) {
                    const idx = data.map[key];
                    if (!isUndefined(idx)) {
                        // return the first found record
                        return data.shared[idx];
                    }
                }
            }
            return null;
        }
        const idx = data.map[platform];
        if (isUndefined(idx)) {
            return null;
        }
        return data.shared[idx];
    }
    /**
     * Returns all compatibility data records for the specified name.
     *
     * @param name Compatibility data name.
     *
     * @returns Array of multiple records grouped by platforms.
     */
    getRow(name) {
        const normalizedName = this.nameTransformer ? this.nameTransformer(name) : name;
        const data = this.getRowStorage(normalizedName);
        if (!data) {
            return [];
        }
        return data.shared;
    }
    /**
     * Returns all compatibility data grouped by products.
     *
     * @returns Array of multiple records grouped by products.
     */
    getRowsByProduct() {
        const result = [];
        for (let i = 0; i < this.data.shared.length; i += 1) {
            const data = this.data.shared[i];
            const keys = Object.keys(data.map);
            const row = {
                [adblockers_AdblockSyntax.Adg]: {},
                [adblockers_AdblockSyntax.Ubo]: {},
                [adblockers_AdblockSyntax.Abp]: {},
            };
            for (let j = 0; j < keys.length; j += 1) {
                const key = Number(keys[j]);
                if (key & platforms_GenericPlatform.AdgAny) {
                    row[adblockers_AdblockSyntax.Adg][key] = data.shared[data.map[key]];
                }
                else if (key & platforms_GenericPlatform.UboAny) {
                    row[adblockers_AdblockSyntax.Ubo][key] = data.shared[data.map[key]];
                }
                else if (key & platforms_GenericPlatform.AbpAny) {
                    row[adblockers_AdblockSyntax.Abp][key] = data.shared[data.map[key]];
                }
            }
            result.push(row);
        }
        return result;
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.0.1/node_modules/@adguard/agtree/dist/compatibility-tables/compatibility-table-data.js
/*
 * AGTree v3.0.1 (build date: Fri, 28 Feb 2025 15:31:12 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
const modifiersCompatibilityTableData = {shared:[{shared:[{name:'all',aliases:null,description:'$all modifier is made of $document, $popup, and all content-type modifiers combined.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#all-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:true,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'all',aliases:null,description:'The `all` option is equivalent to specifying all network-based types\n+ `popup`, `document`, `inline-font` and `inline-script`.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#all',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'app',aliases:null,description:'The `$app` modifier lets you narrow the rule coverage down to a specific application or a list of applications.\nThe modifier\'s behavior and syntax perfectly match the corresponding basic rules `$app` modifier.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#app-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_apps',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0}},{shared:[{name:'badfilter',aliases:null,description:'The rules with the `$badfilter` modifier disable other basic rules to which they refer. It means that\nthe text of the disabled rule should match the text of the `$badfilter` rule (without the `$badfilter` modifier).',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#badfilter-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'badfilter',aliases:null,description:'The rules with the `$badfilter` modifier disable other basic rules to which they refer. It means that\nthe text of the disabled rule should match the text of the `$badfilter` rule (without the `$badfilter` modifier).',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#badfilter',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'cname',aliases:null,description:'When used in an exception filter,\nit will bypass blocking CNAME uncloaked requests for the current (specified) document.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#cname',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'content',aliases:null,description:'Disables HTML filtering and `$replace` rules on the pages that match the rule.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#content-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0}},{shared:[{name:'cookie',aliases:null,description:'The `$cookie` modifier completely changes rule behavior.\nInstead of blocking a request, this modifier makes us suppress or modify the Cookie and Set-Cookie headers.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#cookie-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'^([^;=\\s]*?)((?:;(maxAge=\\d+;?)?|(sameSite=(lax|none|strict);?)?){1,3})(?<!;)$',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'csp',aliases:null,description:'This modifier completely changes the rule behavior.\nIf it is applied to a rule, it will not block the matching request.\nThe response headers are going to be modified instead.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#csp-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','important','subdocument','badfilter'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'csp_value',valueFormatFlags:null},{name:'csp',aliases:null,description:'This modifier completely changes the rule behavior.\nIf it is applied to a rule, it will not block the matching request.\nThe response headers are going to be modified instead.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#csp',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['1p','3p','domain','badfilter'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'csp_value',valueFormatFlags:null},{name:'csp',aliases:null,description:'This modifier completely changes the rule behavior.\nIf it is applied to a rule, it will not block the matching request.\nThe response headers are going to be modified instead.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#content-security-policies',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','subdocument'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'csp_value',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'denyallow',aliases:null,description:'The `$denyallow` modifier allows to avoid creating additional rules\nwhen it is needed to disable a certain rule for specific domains.\n`$denyallow` matches only target domains and not referrer domains.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#denyallow-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['to'],inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_denyallow_domains',valueFormatFlags:null},{name:'denyallow',aliases:null,description:'The `$denyallow` modifier allows to avoid creating additional rules\nwhen it is needed to disable a certain rule for specific domains.\n`$denyallow` matches only target domains and not referrer domains.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#denyallow',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['to'],inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_denyallow_domains',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'document',aliases:null,description:'The rule corresponds to the main frame document requests,\ni.e. HTML documents that are loaded in the browser tab.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#document-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'document',aliases:null,description:'The rule corresponds to the main frame document requests,\ni.e. HTML documents that are loaded in the browser tab.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#document-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'document',aliases:null,description:'The rule corresponds to the main frame document requests,\ni.e. HTML documents that are loaded in the browser tab.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#document-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'document',aliases:null,description:'The rule corresponds to the main frame document requests,\ni.e. HTML documents that are loaded in the browser tab.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#document-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'document',aliases:['doc'],description:'The rule corresponds to the main frame document requests,\ni.e. HTML documents that are loaded in the browser tab.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#document',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'document',aliases:null,description:'The rule corresponds to the main frame document requests,\ni.e. HTML documents that are loaded in the browser tab.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#allowlist',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'256':2,'512':3,'1024':4,'2048':4,'4096':4,'8192':4,'16384':5,'32768':5,'65536':5,'131072':5}},{shared:[{name:'domain',aliases:['from'],description:'The `$domain` modifier limits the rule application area to a list of domains and their subdomains.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#domain-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_domains',valueFormatFlags:null},{name:'domain',aliases:['from'],description:'The `$domain` modifier limits the rule application area to a list of domains and their subdomains.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#from',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_domains',valueFormatFlags:null},{name:'domain',aliases:null,description:'The `$domain` modifier limits the rule application area to a list of domains and their subdomains.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#domain-restrictions',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_domains',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'elemhide',aliases:['ehide'],description:'Disables any cosmetic rules on the pages matching the rule.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#elemhide-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'elemhide',aliases:['ehide'],description:'Disables any cosmetic rules on the pages matching the rule.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#elemhide-1',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'elemhide',aliases:['ehide'],description:'Disables any cosmetic rules on the pages matching the rule.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'empty',aliases:null,description:'This modifier is deprecated in favor of the $redirect modifier.\nRules with `$empty` are still supported and being converted into `$redirect=nooptext` now\nbut the support shall be removed in the future.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#empty-modifier',versionAdded:null,versionRemoved:null,deprecated:true,deprecationMessage:'Rules with `$empty` are still supported and being converted into `$redirect=nooptext` now\nbut the support shall be removed in the future.',removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'empty',aliases:null,description:'This modifier is deprecated in favor of the $redirect modifier.\nRules with `$empty` are still supported and being converted into `$redirect=nooptext` now\nbut the support shall be removed in the future.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#empty-modifier',versionAdded:null,versionRemoved:null,deprecated:true,deprecationMessage:'Rules with `$empty` are still supported and being converted into `$redirect=nooptext` now\nbut the support shall be removed in the future.',removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'empty',aliases:null,description:'This modifier is deprecated in favor of the $redirect modifier.\nRules with `$empty` are supported and being converted into `$redirect=nooptext`.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#empty',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'1024':2,'2048':2,'4096':2,'8192':2}},{shared:[{name:'extension',aliases:null,description:'Disables all userscripts on the pages matching this rule.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#extension-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','specifichide','generichide','elemhide','genericblock','urlblock','jsinject','content','xmlhttprequest','badfilter'],inverseConflicts:true,assignable:false,negatable:true,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0}},{shared:[{name:'first-party',aliases:['1p','~third-party'],description:'A restriction of first-party requests. Equal to `~third-party`.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#third-party-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'first-party',aliases:['1p','~third-party'],description:'A restriction of first-party requests. Equal to `~third-party`.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#1p',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'font',aliases:null,description:'The rule corresponds to requests for fonts, e.g. `.woff` filename extension.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#font-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'font',aliases:null,description:'The rule corresponds to requests for fonts, e.g. `.woff` filename extension.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'font',aliases:null,description:'The rule corresponds to requests for fonts, e.g. `.woff` filename extension.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'genericblock',aliases:null,description:'Disables generic basic rules on pages that correspond to exception rule.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#genericblock-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','specifichide','generichide','elemhide','extension','jsinject','content','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'genericblock',aliases:null,description:'Disables generic basic rules on pages that correspond to exception rule.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#genericblock-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','specifichide','generichide','elemhide','jsinject','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'genericblock',aliases:null,description:'Disables generic basic rules on pages that correspond to exception rule.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#genericblock-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','specifichide','generichide','elemhide','jsinject','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'genericblock',aliases:null,description:'Disables generic basic rules on pages that correspond to exception rule.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#genericblock-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','specifichide','generichide','elemhide','jsinject','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'genericblock',aliases:null,description:'Disables generic basic rules on pages that correspond to exception rule.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'256':2,'512':3,'16384':4,'32768':4,'65536':4,'131072':4}},{shared:[{name:'generichide',aliases:['ghide'],description:'Disables all generic cosmetic rules.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#generichide-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','genericblock','urlblock','extension','jsinject','content','xmlhttprequest','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'generichide',aliases:['ghide'],description:'Disables all generic cosmetic rules.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#generichide',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'generichide',aliases:null,description:'Disables all generic cosmetic rules.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'header',aliases:null,description:'The `$header` modifier allows matching the HTTP response\nhaving a specific header with (optionally) a specific value.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#header-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'^(?:)[\\w-]+(:(?:)(\\w+|\\/.+\\/))?',valueFormatFlags:'i'},{name:'header',aliases:null,description:'The `$header` modifier allows matching the HTTP response\nhaving a specific header with (optionally) a specific value.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#header-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'^(?:)[\\w-]+(:(?:)(\\w+|\\/.+\\/))?',valueFormatFlags:'i'},{name:'header',aliases:null,description:'The `$header` modifier allows matching the HTTP response\nhaving a specific header with (optionally) a specific value.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#header',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'^(?:)[\\w-]+(:(?:)(\\w+|\\/.+\\/))?',valueFormatFlags:'i'}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'1024':2,'2048':2,'4096':2,'8192':2}},{shared:[{name:'hls',aliases:null,description:'The `$hls` rules modify the response of a matching request.\nThey are intended as a convenient way to remove segments from HLS playlists (RFC 8216).',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#hls-modifier',versionAdded:'CoreLibs 1.10',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','third-party','app','important','match-case','xmlhttprequest'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'((?:)\\w+(?:)|(?:)\\/.+\\/(?:)([ti]*)?)',valueFormatFlags:'i'}],map:{'1':0,'2':0,'4':0}},{shared:[{name:'image',aliases:null,description:'The rule corresponds to images requests.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#image-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'image',aliases:null,description:'The rule corresponds to images requests.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'image',aliases:null,description:'The rule corresponds to images requests.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'important',aliases:null,description:'The `$important` modifier applied to a rule increases its priority\nover any other rule without `$important` modifier. Even over basic exception rules.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#important-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'important',aliases:null,description:'The `$important` modifier applied to a rule increases its priority\nover any other rule without `$important` modifier. Even over basic exception rules.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#important',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'inline-font',aliases:null,description:'The `$inline-font` modifier is a sort of a shortcut for $csp modifier with specific value.\nE.g. `||example.org^$inline-font` is converting into:\n```adblock\n||example.org^$csp=font-src \'self\' \'unsafe-eval\' http: https: data: blob: mediastream: filesystem:\n```',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#inline-font-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'inline-font',aliases:null,description:'The `$inline-font` modifier is a sort of a shortcut for $csp modifier with specific value.\nE.g. `||example.org^$inline-font` is converting into:\n```adblock\n||example.org^$csp=font-src \'self\' \'unsafe-eval\' http: https: data: blob: mediastream: filesystem:\n```',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#inline-font-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'inline-font',aliases:null,description:'The `$inline-font` modifier is a sort of a shortcut for $csp modifier with specific value.\nE.g. `||example.org^$inline-font` is converting into:\n```adblock\n||example.org^$csp=font-src \'self\' \'unsafe-eval\' http: https: data: blob: mediastream: filesystem:\n```',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#inline-font',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'1024':2,'2048':2,'4096':2,'8192':2}},{shared:[{name:'inline-script',aliases:null,description:'The `$inline-script` modifier is a sort of a shortcut for $csp modifier with specific value.\nE.g. `||example.org^$inline-script` is converting into:\n```adblock\n||example.org^$csp=script-src \'self\' \'unsafe-eval\' http: https: data: blob: mediastream: filesystem:\n```',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#inline-script-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'inline-script',aliases:null,description:'The `$inline-script` modifier is a sort of a shortcut for $csp modifier with specific value.\nE.g. `||example.org^$inline-script` is converting into:\n```adblock\n||example.org^$csp=script-src \'self\' \'unsafe-eval\' http: https: data: blob: mediastream: filesystem:\n```',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#inline-script-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'inline-script',aliases:null,description:'The `$inline-script` modifier is a sort of a shortcut for $csp modifier with specific value.\nE.g. `||example.org^$inline-script` is converting into:\n```adblock\n||example.org^$csp=script-src \'self\' \'unsafe-eval\' http: https: data: blob: mediastream: filesystem:\n```',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#inline-script',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'1024':2,'2048':2,'4096':2,'8192':2}},{shared:[{name:'jsinject',aliases:null,description:'Forbids adding of javascript code to the page.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#jsinject-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','specifichide','generichide','elemhide','genericblock','urlblock','extension','content','xmlhttprequest','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'jsinject',aliases:null,description:'Forbids adding of javascript code to the page.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#jsinject-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','specifichide','generichide','elemhide','genericblock','urlblock','xmlhttprequest','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'jsinject',aliases:null,description:'Forbids adding of javascript code to the page.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#jsinject-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','specifichide','generichide','elemhide','genericblock','urlblock','xmlhttprequest','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'jsinject',aliases:null,description:'Forbids adding of javascript code to the page.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#jsinject-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','specifichide','generichide','elemhide','genericblock','urlblock','xmlhttprequest','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'256':2,'512':3}},{shared:[{name:'jsonprune',aliases:null,description:'The `$jsonprune` rules modify the response to a matching request\nby removing JSON items that match a modified JSONPath expression.\nThey do not modify responses which are not valid JSON documents.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#jsonprune-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'^(?:)\\\\(?:)\\$(?:)\\.?(?:).+(?:)$',valueFormatFlags:'i'}],map:{'1':0,'2':0,'4':0}},{shared:[{name:'match-case',aliases:null,description:'This modifier defines a rule which applies only to addresses that match the case.\nDefault rules are case-insensitive.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#match-case-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'match-case',aliases:null,description:'This modifier defines a rule which applies only to addresses that match the case.\nDefault rules are case-insensitive.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#match-case',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'match-case',aliases:null,description:'This modifier defines a rule which applies only to addresses that match the case.\nDefault rules are case-insensitive.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'media',aliases:null,description:'A restriction of third-party and own requests.\nA third-party request is a request from a different domain.\nFor example, a request to `example.org` from `domain.com` is a third-party request.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#media-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'media',aliases:null,description:'A restriction of third-party and own requests.\nA third-party request is a request from a different domain.\nFor example, a request to `example.org` from `domain.com` is a third-party request.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'media',aliases:null,description:'A restriction of third-party and own requests.\nA third-party request is a request from a different domain.\nFor example, a request to `example.org` from `domain.com` is a third-party request.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'method',aliases:null,description:'This modifier limits the rule scope to requests that use the specified set of HTTP methods.\nNegated methods are allowed.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#method-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_methods',valueFormatFlags:null},{name:'method',aliases:null,description:'This modifier limits the rule scope to requests that use the specified set of HTTP methods.\nNegated methods are allowed.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#method-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_methods',valueFormatFlags:null},{name:'method',aliases:null,description:'This modifier limits the rule scope to requests that use the specified set of HTTP methods.\nNegated methods are allowed.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#method',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_methods',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'1024':2,'2048':2,'4096':2,'8192':2}},{shared:[{name:'mp4',aliases:null,description:'As a response to blocked request AdGuard returns a short video placeholder.\nRules with `$mp4` are still supported and being converted into `$redirect=noopmp4-1s` now\nbut the support shall be removed in the future.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#mp4-modifier',versionAdded:null,versionRemoved:null,deprecated:true,deprecationMessage:'Rules with `$mp4` are still supported and being converted into `$redirect=noopmp4-1s` now\nbut the support shall be removed in the future.',removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'mp4',aliases:null,description:'As a response to blocked request AdGuard returns a short video placeholder.\nRules with `$mp4` are still supported and being converted into `$redirect=noopmp4-1s` now\nbut the support shall be removed in the future.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#mp4-modifier',versionAdded:null,versionRemoved:null,deprecated:true,deprecationMessage:'Rules with `$mp4` are still supported and being converted into `$redirect=noopmp4-1s` now\nbut the support shall be removed in the future.',removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'mp4',aliases:null,description:'As a response to blocked request a short video placeholder is returned.\nRules with `$mp4` are supported and being converted into `$redirect=noopmp4-1s`.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#mp4',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'1024':2,'2048':2,'4096':2,'8192':2}},{shared:[{name:'network',aliases:null,description:'This is basically a Firewall-kind of rules allowing to fully block\nor unblock access to a specified remote address.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#network-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['app','important'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0}},{shared:[{name:'_',aliases:null,description:'The noop modifier does nothing and can be used solely to increase rules\' readability.\nIt consists of a sequence of underscore characters (_) of any length\nand can appear in a rule as many times as needed.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#noop-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'_',aliases:null,description:'The noop modifier does nothing and can be used solely to increase rules\' readability.\nIt consists of a sequence of underscore characters (_) of any length\nand can appear in a rule as many times as needed.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#noop-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'_',aliases:null,description:'The noop modifier does nothing and can be used solely to increase rules\' readability.\nIt consists of a sequence of underscore characters (_) of any length\nand can appear in a rule as many times as needed.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#noop-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'_',aliases:null,description:'The noop modifier does nothing and can be used solely to increase rules\' readability.\nIt consists of a sequence of underscore characters (_) of any length\nand can appear in a rule as many times as needed.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#noop-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'_',aliases:null,description:'The noop modifier does nothing and can be used solely to increase rules\' readability.\nIt consists of a sequence of underscore characters (_) of any length\nand can appear in a rule as many times as needed.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#_-aka-noop',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'256':2,'512':3,'1024':4,'2048':4,'4096':4,'8192':4}},{shared:[{name:'object-subrequest',aliases:null,description:'The `$object-subrequest` modifier is removed and is no longer supported.\nRules with it are considered as invalid.\nThe rule corresponds to requests by browser plugins (it is usually Flash).',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#object-subrequest-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:true,removalMessage:'The `$object-subrequest` modifier is removed and is no longer supported.\nRules with it are considered as invalid.',conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0}},{shared:[{name:'object',aliases:null,description:'The rule corresponds to browser plugins resources, e.g. Java or Flash',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#object-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'object',aliases:null,description:'The rule corresponds to browser plugins resources, e.g. Java or Flash.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'object',aliases:null,description:'The rule corresponds to browser plugins resources, e.g. Java or Flash.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'other',aliases:null,description:'The rule applies to requests for which the type has not been determined\nor does not match the types listed above.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#other-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'other',aliases:null,description:'The rule applies to requests for which the type has not been determined\nor does not match the types listed above.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'other',aliases:null,description:'The rule applies to requests for which the type has not been determined\nor does not match the types listed above.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'permissions',aliases:null,description:'For the requests matching a `$permissions` rule, ad blocker strengthens response\'s feature policy\nby adding additional feature policy equal to the `$permissions` modifier contents.\n`$permissions` rules are applied independently from any other rule type.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#permissions-modifier',versionAdded:'CoreLibs 1.11',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','important','subdocument'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'permissions_value',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0}},{shared:[{name:'ping',aliases:null,description:'The rule corresponds to requests caused by either navigator.sendBeacon() or the ping attribute on links.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#ping-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'ping',aliases:null,description:'The rule corresponds to requests caused by either navigator.sendBeacon() or the ping attribute on links.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'ping',aliases:null,description:'The rule corresponds to requests caused by either navigator.sendBeacon() or the ping attribute on links.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'popunder',aliases:null,description:'To block "popunders" windows/tabs where the original page redirects to an advertisement\nand the desired content loads in the newly created one.\nTo be used in the same manner as the popup filter option, except that it will block popunders.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#popunder',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:true,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'popup',aliases:null,description:'Pages opened in a new tab or window.\nNote: Filters will not block pop-ups by default, only if the `$popup`  type option is specified.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#popup-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'popup',aliases:null,description:'Pages opened in a new tab or window.\nNote: Filters will not block pop-ups by default, only if the `$popup`  type option is specified.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'popup',aliases:null,description:'Pages opened in a new tab or window.\nNote: Filters will not block pop-ups by default, only if the `$popup`  type option is specified.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'redirect-rule',aliases:null,description:'This is basically an alias to `$redirect`\nsince it has the same "redirection" values and the logic is almost similar.\nThe difference is that `$redirect-rule` is applied only in the case\nwhen the target request is blocked by a different basic rule.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#redirect-rule-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','to','third-party','popup','match-case','header','first-party','document','image','stylesheet','script','object','font','media','subdocument','ping','xmlhttprequest','websocket','other','webrtc','important','badfilter','app'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'^(1x1-transparent\\.gif|2x2-transparent\\.png|3x2-transparent\\.png|32x32-transparent\\.png|noopframe|noopcss|noopjs|noopjson|nooptext|empty|noopvmap-1\\.0|noopvast-2\\.0|noopvast-3\\.0|noopvast-4\\.0|noopmp3-0\\.1s|noopmp4-1s|amazon-apstag|ati-smarttag|didomi-loader|fingerprintjs2|fingerprintjs3|gemius|google-analytics-ga|google-analytics|google-ima3|googlesyndication-adsbygoogle|googletagservices-gpt|matomo|metrika-yandex-tag|metrika-yandex-watch|naver-wcslog|noeval|pardot-1\\.0|prebid-ads|prebid|prevent-bab|prevent-bab2|prevent-fab-3\\.2\\.0|prevent-popads-net|scorecardresearch-beacon|set-popads-dummy|click2load\\.html|)?$',valueFormatFlags:null},{name:'redirect-rule',aliases:null,description:'This is basically an alias to `$redirect`\nsince it has the same "redirection" values and the logic is almost similar.\nThe difference is that `$redirect-rule` is applied only in the case\nwhen the target request is blocked by a different basic rule.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#redirect-rule-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','to','third-party','popup','match-case','header','first-party','document','image','stylesheet','script','object','font','media','subdocument','ping','xmlhttprequest','websocket','other','webrtc','important','badfilter'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'^(1x1-transparent\\.gif|2x2-transparent\\.png|3x2-transparent\\.png|32x32-transparent\\.png|noopframe|noopcss|noopjs|noopjson|nooptext|empty|noopvmap-1\\.0|noopvast-2\\.0|noopvast-3\\.0|noopvast-4\\.0|noopmp3-0\\.1s|noopmp4-1s|amazon-apstag|ati-smarttag|didomi-loader|fingerprintjs2|fingerprintjs3|gemius|google-analytics-ga|google-analytics|google-ima3|googlesyndication-adsbygoogle|googletagservices-gpt|matomo|metrika-yandex-tag|metrika-yandex-watch|naver-wcslog|noeval|pardot-1\\.0|prebid-ads|prebid|prevent-bab|prevent-bab2|prevent-fab-3\\.2\\.0|prevent-popads-net|scorecardresearch-beacon|set-popads-dummy|click2load\\.html|)?$',valueFormatFlags:null},{name:'redirect-rule',aliases:null,description:'This is basically an alias to `$redirect`\nsince it has the same "redirection" values and the logic is almost similar.\nThe difference is that `$redirect-rule` is applied only in the case\nwhen the target request is blocked by a different basic rule.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#redirect-rule',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','to','third-party','popup','match-case','header','first-party','document','image','stylesheet','script','object','font','media','subdocument','ping','xmlhttprequest','websocket','other','webrtc','important','badfilter'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'^(1x1\\.gif|2x2\\.png|3x2\\.png|32x32\\.png|noop\\.css|noop\\.html|noopframe|noop\\.js|noop\\.txt|noop-0\\.1s\\.mp3|noop-0\\.5s\\.mp3|noop-1s\\.mp4|none|click2load\\.html|addthis_widget\\.js|amazon_ads\\.js|amazon_apstag\\.js|monkeybroker\\.js|doubleclick_instream_ad_status|google-analytics_ga\\.js|google-analytics_analytics\\.js|google-analytics_inpage_linkid\\.js|google-analytics_cx_api\\.js|google-ima\\.js|googletagservices_gpt\\.js|googletagmanager_gtm\\.js|googlesyndication_adsbygoogle\\.js|scorecardresearch_beacon\\.js|outbrain-widget\\.js|hd-main\\.js)(:[0-9]+)?$',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'1024':2,'2048':2,'4096':2,'8192':2}},{shared:[{name:'redirect',aliases:null,description:'Used to redirect web requests to a local "resource".',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#redirect-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'^(1x1-transparent\\.gif|2x2-transparent\\.png|3x2-transparent\\.png|32x32-transparent\\.png|noopframe|noopcss|noopjs|noopjson|nooptext|empty|noopvmap-1\\.0|noopvast-2\\.0|noopvast-3\\.0|noopvast-4\\.0|noopmp3-0\\.1s|noopmp4-1s|amazon-apstag|ati-smarttag|didomi-loader|fingerprintjs2|fingerprintjs3|gemius|google-analytics-ga|google-analytics|googletagmanager-gtm|google-ima3|googlesyndication-adsbygoogle|googletagservices-gpt|matomo|metrika-yandex-tag|metrika-yandex-watch|naver-wcslog|noeval|pardot-1\\.0|prebid-ads|prebid|prevent-bab|prevent-bab2|prevent-fab-3\\.2\\.0|prevent-popads-net|scorecardresearch-beacon|set-popads-dummy|click2load\\.html)?$',valueFormatFlags:null},{name:'redirect',aliases:null,description:'Used to redirect web requests to a local "resource".',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#redirect-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'^(1x1-transparent\\.gif|2x2-transparent\\.png|3x2-transparent\\.png|32x32-transparent\\.png|noopframe|noopcss|noopjs|noopjson|nooptext|empty|noopvmap-1\\.0|noopvast-2\\.0|noopvast-3\\.0|noopvast-4\\.0|noopmp3-0\\.1s|noopmp4-1s|amazon-apstag|ati-smarttag|didomi-loader|fingerprintjs2|fingerprintjs3|gemius|google-analytics-ga|google-analytics|googletagmanager-gtm|google-ima3|googlesyndication-adsbygoogle|googletagservices-gpt|matomo|metrika-yandex-tag|metrika-yandex-watch|naver-wcslog|noeval|pardot-1\\.0|prebid-ads|prebid|prevent-bab|prevent-bab2|prevent-fab-3\\.2\\.0|prevent-popads-net|scorecardresearch-beacon|set-popads-dummy|click2load\\.html)?$',valueFormatFlags:null},{name:'redirect',aliases:null,description:'Used to redirect web requests to a local "resource".',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#redirect',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'^(1x1\\.gif|2x2\\.png|3x2\\.png|32x32\\.png|noop\\.css|noop\\.html|noopframe|noop\\.js|noop\\.txt|noop-0\\.1s\\.mp3|noop-0\\.5s\\.mp3|noop-1s\\.mp4|none|click2load\\.html|addthis_widget\\.js|amazon_ads\\.js|amazon_apstag\\.js|monkeybroker\\.js|doubleclick_instream_ad_status|google-analytics_ga\\.js|google-analytics_analytics\\.js|google-analytics_inpage_linkid\\.js|google-analytics_cx_api\\.js|google-ima\\.js|googletagservices_gpt\\.js|googletagmanager_gtm\\.js|googlesyndication_adsbygoogle\\.js|scorecardresearch_beacon\\.js|outbrain-widget\\.js|hd-main\\.js)(:[0-9]+)?$',valueFormatFlags:null},{name:'rewrite',aliases:null,description:'The `rewrite=` option allows the rewriting of URLs (or redirecting requests) to an internal\nresource in order to deactivate it without causing an error. Indicate the internal resource\nby name and prefix `abp-resource:` in order to be recognized. For example\n`$rewrite=abp-resource:blank-js` sends an empty JavaScript.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#rewrite',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'(?:)^abp-resource:(?:)(blank-text|blank-css|blank-js|blank-html|blank-mp3|1x1-transparent-gif|2x2-transparent-png|3x2-transparent-png|32x32-transparent-png)$',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'1024':2,'2048':2,'4096':2,'8192':2,'16384':3,'32768':3,'65536':3,'131072':3}},{shared:[{name:'referrerpolicy',aliases:null,description:'This modifier allows overriding of a page\'s referrer policy.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#referrerpolicy-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['document','subdocument'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'referrerpolicy_value',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0}},{shared:[{name:'removeheader',aliases:null,description:'Rules with the `$removeheader` modifier are intended to remove headers from HTTP requests and responses.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#removeheader-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','third-party','first-party','app','important','match-case','document','image','stylesheet','script','object','font','media','subdocument','ping','xmlhttpreqeust','websocket','other','webrtc'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'^(?:)(request:)?(?:)(?!(access-control-allow-origin|access-control-allow-credentials|access-control-allow-headers|access-control-allow-methods|access-control-expose-headers|access-control-max-age|access-control-request-headers|access-control-request-method|origin|timing-allow-origin|allow|cross-origin-embedder-policy|cross-origin-opener-policy|cross-origin-resource-policy|content-security-policy|content-security-policy-report-only|expect-ct|feature-policy|origin-isolation|strict-transport-security|upgrade-insecure-requests|x-content-type-options|x-download-options|x-frame-options|x-permitted-cross-domain-policies|x-powered-by|x-xss-protection|public-key-pins|public-key-pins-report-only|sec-websocket-key|sec-websocket-extensions|sec-websocket-accept|sec-websocket-protocol|sec-websocket-version|p3p|sec-fetch-mode|sec-fetch-dest|sec-fetch-site|sec-fetch-user|referrer-policy|content-type|content-length|accept|accept-encoding|host|connection|transfer-encoding|upgrade)$)(?:)[A-z0-9-]+(?:)$',valueFormatFlags:'i'},{name:'removeheader',aliases:null,description:'Rules with the `$removeheader` modifier are intended to remove headers from HTTP requests and responses.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#removeheader-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','third-party','first-party','app','important','match-case','document','image','stylesheet','script','object','font','media','subdocument','ping','xmlhttpreqeust','websocket','other','webrtc'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'^(?:)(request:)?(?:)(?!(access-control-allow-origin|access-control-allow-credentials|access-control-allow-headers|access-control-allow-methods|access-control-expose-headers|access-control-max-age|access-control-request-headers|access-control-request-method|origin|timing-allow-origin|allow|cross-origin-embedder-policy|cross-origin-opener-policy|cross-origin-resource-policy|content-security-policy|content-security-policy-report-only|expect-ct|feature-policy|origin-isolation|strict-transport-security|upgrade-insecure-requests|x-content-type-options|x-download-options|x-frame-options|x-permitted-cross-domain-policies|x-powered-by|x-xss-protection|public-key-pins|public-key-pins-report-only|sec-websocket-key|sec-websocket-extensions|sec-websocket-accept|sec-websocket-protocol|sec-websocket-version|p3p|sec-fetch-mode|sec-fetch-dest|sec-fetch-site|sec-fetch-user|referrer-policy|content-type|content-length|accept|accept-encoding|host|connection|transfer-encoding|upgrade)$)(?:)[A-z0-9-]+(?:)$',valueFormatFlags:'i'}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1}},{shared:[{name:'removeparam',aliases:null,description:'Rules with the `$removeparam` modifier are intended to strip query parameters from requests\' URLs.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#removeparam-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'((?:)\\w+(?:)|\\/.+\\/(?:)([gimuy]+)?)',valueFormatFlags:'i'},{name:'removeparam',aliases:null,description:'Rules with the `$removeparam` modifier are intended to strip query parameters from requests\' URLs.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#removeparam-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:true,valueFormat:'((?:)\\w+(?:)|\\/.+\\/(?:)([gimuy]+)?)',valueFormatFlags:'i'},{name:'removeparam',aliases:null,description:'Rules with the `$removeparam` modifier are intended to strip query parameters from requests\' URLs.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#removeparam',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'((?:)\\w+(?:)|\\/.+\\/(?:)([gimuy]+)?)',valueFormatFlags:'i'}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'1024':2,'2048':2,'4096':2,'8192':2}},{shared:[{name:'replace',aliases:null,description:'This modifier completely changes the rule behavior.\nIf it is applied, the rule will not block the request. The response is going to be modified instead.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#replace-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['app','domain','document','subdocument','script','stylesheet','other','xmlhttprequest','first-party','third-party','important','badfilter'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'^(?:)\\/(?:)(.+)(?:)\\/(?:)(.+)?(?:)\\/(?:)([gimuy]*)?(?:)$',valueFormatFlags:'i'},{name:'replace',aliases:null,description:'This modifier completely changes the rule behavior.\nIf it is applied, the rule will not block the request. The response is going to be modified instead.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#replace-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['app','domain','document','subdocument','script','stylesheet','other','xmlhttprequest','first-party','third-party','important','badfilter'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'^(?:)\\/(?:)(.+)(?:)\\/(?:)(.+)?(?:)\\/(?:)([gimuy]*)?(?:)$',valueFormatFlags:'i'},{name:'replace',aliases:null,description:'This modifier completely changes the rule behavior.\nIf it is applied, the rule will not block the request. The response is going to be modified instead.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#replace',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['app','domain','document','subdocument','script','stylesheet','other','xmlhttprequest','first-party','third-party','important','badfilter'],inverseConflicts:true,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'^(?:)\\/(?:)(.+)(?:)\\/(?:)(.+)?(?:)\\/(?:)([gimuy]*)?(?:)$',valueFormatFlags:'i'}],map:{'1':0,'2':0,'4':0,'64':1,'8192':2}},{shared:[{name:'script',aliases:null,description:'The rule corresponds to script requests, e.g. javascript, vbscript.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#script-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'script',aliases:null,description:'The rule corresponds to script requests, e.g. javascript, vbscript.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'script',aliases:null,description:'The rule corresponds to script requests, e.g. javascript, vbscript.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'specifichide',aliases:['shide'],description:'Disables all specific element hiding and CSS rules, but not general ones.\nHas an opposite effect to `$generichide`.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#specifichide-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','genericblock','urlblock','extension','jsinject','content','xmlhttprequest','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'specifichide',aliases:['shide'],description:'Disables all specific element hiding and CSS rules, but not general ones.\nHas an opposite effect to `$generichide`.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#specifichide',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'stealth',aliases:null,description:'Disables the Stealth Mode module for all corresponding pages and requests.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#stealth-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:true,valueFormat:'pipe_separated_stealth_options',valueFormatFlags:null},{name:'stealth',aliases:null,description:'Disables the Stealth Mode module for all corresponding pages and requests.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#stealth-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:true,valueFormat:'pipe_separated_stealth_options',valueFormatFlags:null},{name:'stealth',aliases:null,description:'Disables the Stealth Mode module for all corresponding pages and requests.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#stealth-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:true,valueFormat:'pipe_separated_stealth_options',valueFormatFlags:null},{name:'stealth',aliases:null,description:'Disables the Stealth Mode module for all corresponding pages and requests.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#stealth-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:true,valueFormat:'pipe_separated_stealth_options',valueFormatFlags:null},{name:'stealth',aliases:null,description:'Disables the Stealth Mode module for all corresponding pages and requests.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#stealth-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:true,valueFormat:'pipe_separated_stealth_options',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':2,'32':3,'64':4}},{shared:[{name:'strict1p',aliases:null,description:'This new `strict1p` option can check for strict partyness.\nFor example, a network request qualifies as 1st-party if both the context and the request share the same hostname.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#strict1p',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'strict3p',aliases:null,description:'This new `strict3p` option can check for strict partyness.\nFor example, a network request qualifies as 3rd-party if the context and the request hostnames are different.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#strict3p',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'stylesheet',aliases:null,description:'The rule corresponds to CSS files requests.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#stylesheet-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'stylesheet',aliases:['css'],description:'The rule corresponds to CSS files requests.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#css',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'stylesheet',aliases:null,description:'The rule corresponds to CSS files requests.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'subdocument',aliases:null,description:'The rule corresponds to requests for built-in pages — HTML tags frame and iframe.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#subdocument-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'subdocument',aliases:['frame'],description:'The rule corresponds to requests for built-in pages — HTML tags frame and iframe.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#frame',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'subdocument',aliases:null,description:'The rule corresponds to requests for built-in pages — HTML tags frame and iframe.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'third-party',aliases:['3p'],description:'A restriction of third-party and own requests.\nA third-party request is a request from a different domain.\nFor example, a request to `example.org` from `domain.com` is a third-party request.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#third-party-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'3p',aliases:['third-party'],description:'A restriction of third-party and own requests.\nA third-party request is a request from a different domain.\nFor example, a request to `example.org` from `domain.com` is a third-party request.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#3p',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'third-party',aliases:null,description:'A restriction of third-party and own requests.\nA third-party request is a request from a different domain.\nFor example, a request to `example.org` from `domain.com` is a third-party request.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#party-requests',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'to',aliases:null,description:'`$to` limits the rule scope to requests made to the specified domains and their subdomains.\nTo add multiple domains to one rule, use the `|` character as a separator.',docs:'https://adguard.com/kb/general/ad-filtering/create-own-filters/#to-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['denyallow'],inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_domains',valueFormatFlags:null},{name:'to',aliases:null,description:'`$to` limits the rule scope to requests made to the specified domains and their subdomains.\nTo add multiple domains to one rule, use the `|` character as a separator.',docs:'https://adguard.com/kb/general/ad-filtering/create-own-filters/#to-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['denyallow'],inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_domains',valueFormatFlags:null},{name:'to',aliases:null,description:'The main motivation of this option is\nto give static network filtering engine an equivalent of DNR\'s `requestDomains` and `excludedRequestDomains`.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#to',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['denyallow'],inverseConflicts:false,assignable:true,negatable:false,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:'pipe_separated_domains',valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'1024':2,'2048':2,'4096':2,'8192':2}},{shared:[{name:'urlblock',aliases:null,description:'Disables blocking of all requests sent from the pages matching the rule.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#urlblock-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:['domain','specifichide','generichide','elemhide','extension','jsinject','content','badfilter'],inverseConflicts:true,assignable:false,negatable:false,blockOnly:false,exceptionOnly:true,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0}},{shared:[{name:'webrtc',aliases:null,description:'The rule applies only to WebRTC connections.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#webrtc-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:true,removalMessage:'This modifier is removed and is no longer supported.\nRules with it are considered as invalid. If you need to suppress WebRTC, consider using\nthe [nowebrtc scriptlet](https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#nowebrtc).',conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'webrtc',aliases:null,description:'The rule applies only to WebRTC connections.',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:true,removalMessage:'This modifier is removed and is no longer supported.\nIf you need to suppress WebRTC, consider using\nthe [nowebrtc scriptlet](https://github.com/gorhill/uBlock/wiki/Resources-Library#nowebrtcjs-).',conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'webrtc',aliases:null,description:'The rule applies only to WebRTC connections.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:'1.13.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'websocket',aliases:null,description:'The rule applies only to WebSocket connections.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#websocket-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'websocket',aliases:null,description:'The rule applies only to WebSocket connections.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#websocket-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'websocket',aliases:null,description:'The rule applies only to WebSocket connections.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#websocket-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'websocket',aliases:null,description:'The rule applies only to WebSocket connections.',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#websocket-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'websocket',aliases:null,description:'The rule applies only to WebSocket connections.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'websocket',aliases:null,description:'The rule applies only to WebSocket connections.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':1,'16':1,'32':1,'64':1,'256':2,'512':3,'1024':4,'2048':4,'4096':4,'8192':4,'16384':5,'32768':5,'65536':5,'131072':5}},{shared:[{name:'xmlhttprequest',aliases:['xhr'],description:'The rule applies only to ajax requests (requests sent via javascript object XMLHttpRequest).',docs:'https://adguard.app/kb/general/ad-filtering/create-own-filters/#xmlhttprequest-modifier',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'xhr',aliases:['xmlhttprequest'],description:'The rule applies only to ajax requests (requests sent via javascript object XMLHttpRequest).',docs:'https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#xhr',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null},{name:'xmlhttprequest',aliases:null,description:'The rule applies only to ajax requests (requests sent via javascript object XMLHttpRequest).',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters#type-options',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,conflicts:null,inverseConflicts:false,assignable:false,negatable:true,blockOnly:false,exceptionOnly:false,valueOptional:false,valueFormat:null,valueFormatFlags:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'128':0,'256':0,'512':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}}],map:{all:0,app:1,badfilter:2,cname:3,content:4,cookie:5,csp:6,denyallow:7,document:8,doc:8,domain:9,from:9,elemhide:10,ehide:10,empty:11,extension:12,'first-party':13,'1p':13,'~third-party':13,font:14,genericblock:15,generichide:16,ghide:16,header:17,hls:18,image:19,important:20,'inline-font':21,'inline-script':22,jsinject:23,jsonprune:24,'match-case':25,media:26,method:27,mp4:28,network:29,_:30,'object-subrequest':31,object:32,other:33,permissions:34,ping:35,popunder:36,popup:37,'redirect-rule':38,redirect:39,rewrite:39,referrerpolicy:40,removeheader:41,removeparam:42,replace:43,script:44,specifichide:45,shide:45,stealth:46,strict1p:47,strict3p:48,stylesheet:49,css:49,subdocument:50,frame:50,'third-party':51,'3p':51,to:52,urlblock:53,webrtc:54,websocket:55,xmlhttprequest:56,xhr:56}};
const redirectsCompatibilityTableData = {shared:[{shared:[{name:'1x1-transparent.gif',aliases:['1x1.gif','1x1-transparent-gif'],description:'Redirects to a 1x1 transparent GIF.',docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-redirects.md#1x1-transparent.gif',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'1x1.gif',aliases:null,description:'Redirects to a 1x1 transparent GIF.',docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#available-empty-redirect-resources',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['image']},{name:'1x1-transparent-gif',aliases:null,description:'Redirects to a 1x1 transparent GIF.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#rewrite',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'2x2-transparent.png',aliases:['2x2.png','2x2-transparent-png'],description:'Redirects to a 2x2 transparent PNG.',docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-redirects.md#2x2-transparent.png',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'2x2.png',aliases:null,description:'Redirects to a 2x2 transparent PNG.',docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#available-empty-redirect-resources',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['image']},{name:'2x2-transparent-png',aliases:null,description:'Redirects to a 2x2 transparent PNG.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#rewrite',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'32x32-transparent.png',aliases:['32x32.png','32x32-transparent-png'],description:'Redirects to a 32x32 transparent PNG.',docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-redirects.md#32x32-transparent.png',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'32x32.png',aliases:null,description:'Redirects to a 32x32 transparent PNG.',docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#available-empty-redirect-resources',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['image']},{name:'32x32-transparent-png',aliases:null,description:'Redirects to a 32x32 transparent PNG.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#rewrite',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'3x2-transparent.png',aliases:['3x2.png','3x2-transparent-png'],description:'Redirects to a 3x2 transparent PNG.',docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-redirects.md#3x2-transparent.png',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'3x2.png',aliases:null,description:'Redirects to a 3x2 transparent PNG.',docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#available-empty-redirect-resources',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['image']},{name:'3x2-transparent-png',aliases:null,description:'Redirects to a 3x2 transparent PNG.',docs:'https://help.adblockplus.org/hc/en-us/articles/360062733293#rewrite',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'amazon-apstag',aliases:['ubo-amazon_apstag.js','amazon_apstag.js'],description:'Mocks Amazon\'s apstag.js',docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-redirects.md#amazon-apstag',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'amazon_apstag.js',aliases:null,description:'Mocks Amazon\'s apstag.js',docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#amazon_apstagjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'amazon_ads.js',aliases:null,description:null,docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'ampproject_v0.js',aliases:null,description:null,docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'ati-smarttag',aliases:null,description:null,docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'chartbeat.js',aliases:null,description:null,docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'click2load.html',aliases:['click2load.html','ubo-click2load.html'],description:'Redirects resource and replaces supposed content by decoy frame with button for original content recovering.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:true,resourceTypes:[]},{name:'click2load.html',aliases:null,description:'Redirects resource and replaces supposed content by decoy frame with button for original content recovering.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:true,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'didomi-loader',aliases:null,description:'Mocks Didomi\'s CMP loader script.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'empty',aliases:null,description:'Redirects to an empty file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'empty',aliases:null,description:'Redirects to an empty file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'fingerprintjs2',aliases:['fingerprint2.js'],description:'Mocks FingerprintJS2 script.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'fingerprint2.js',aliases:null,description:'Mocks FingerprintJS2 script.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'fingerprintjs3',aliases:['fingerprint3.js'],description:'Mocks FingerprintJS v3.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'fingerprint3.js',aliases:null,description:'Mocks FingerprintJS v3.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'gemius',aliases:null,description:'Mocks Gemius Analytics.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'google-analytics-ga',aliases:['ubo-google-analytics_ga.js','google-analytics_ga.js'],description:'Mocks old Google Analytics API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'google-analytics_ga.js',aliases:null,description:'Mocks old Google Analytics API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'google-analytics',aliases:['ubo-google-analytics_analytics.js','google-analytics_analytics.js','googletagmanager-gtm','ubo-googletagmanager_gtm.js','googletagmanager_gtm.js'],description:'Mocks Google\'s Analytics and Tag Manager APIs.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'google-analytics_analytics.js',aliases:null,description:'Mocks Google\'s Analytics and Tag Manager APIs.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'google-analytics_cx_api.js',aliases:null,description:null,docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'google-analytics_inpage_linkid.js',aliases:null,description:null,docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'google-ima3',aliases:['ubo-google-ima.js','google-ima.js'],description:'Mocks the IMA SDK of Google.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'google-ima.js',aliases:null,description:'Mocks the IMA SDK of Google.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'googlesyndication-adsbygoogle',aliases:['ubo-googlesyndication_adsbygoogle.js','ubo-googlesyndication.com/adsbygoogle.js','googlesyndication_adsbygoogle.js'],description:'Mocks Google AdSense API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'googlesyndication_adsbygoogle.js',aliases:['googlesyndication.com/adsbygoogle.js'],description:'Mocks Google AdSense API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'googletagservices-gpt',aliases:['ubo-googletagservices_gpt.js','googletagservices_gpt.js'],description:'Mocks Google Publisher Tag API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'googletagservices_gpt.js',aliases:null,description:'Mocks Google Publisher Tag API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'hd-main.js',aliases:null,description:null,docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'matomo',aliases:null,description:'Mocks the piwik.js file of Matomo (formerly Piwik).',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'metrika-yandex-tag',aliases:null,description:'Mocks Yandex Metrika API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'metrika-yandex-watch',aliases:null,description:'Mocks the old Yandex Metrika API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'naver-wcslog',aliases:null,description:'Mocks wcslog.js of Naver Analytics.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'no-protected-audience',aliases:null,description:'Prevents using the Protected Audience API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'no-topics',aliases:null,description:'Prevents using the Topics API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'noeval',aliases:['noeval.js','silent-noeval.js','ubo-noeval.js','ubo-silent-noeval.js','ubo-noeval','ubo-silent-noeval'],description:'Prevents page to use eval.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'noeval.js',aliases:null,description:'Prevents page to use eval.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'noop-0.5s.mp3',aliases:null,description:'Redirects to an empty MP3 file with a duration of 0.5 seconds.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['media']}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'noopcss',aliases:['noop.css','blank-css'],description:'Redirects to an empty CSS file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'noop.css',aliases:null,description:'Redirects to an empty CSS file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['stylesheet']},{name:'blank-css',aliases:null,description:'Redirects to an empty CSS file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'noopframe',aliases:['noop.html','blank-html'],description:'Redirects to an empty HTML file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'noop.html',aliases:null,description:'Redirects to an empty HTML file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['sub_frame']},{name:'blank-html',aliases:null,description:'Redirects to an empty HTML file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'noopjs',aliases:['noop.js','blank-js'],description:'Redirects to an empty JavaScript file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'noop.js',aliases:null,description:'Redirects to an empty JavaScript file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']},{name:'blank-js',aliases:null,description:'Redirects to an empty JavaScript file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'noopjson',aliases:['noop.json'],description:'Redirects to an empty JSON file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'noop.json',aliases:null,description:'Redirects to an empty JSON file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'noopmp3-0.1s',aliases:['noop-0.1s.mp3','blank-mp3'],description:'Redirects to an empty MP3 file with a duration of 0.1 seconds.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'noop-0.1s.mp3',aliases:null,description:'Redirects to an empty MP3 file with a duration of 0.1 seconds.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['media']},{name:'blank-mp3',aliases:null,description:'Redirects to an empty MP3 file with a duration of 0.1 seconds.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'noopmp4-1s',aliases:['noop-1s.mp4','blank-mp4'],description:'Redirects to an empty MP4 file with a duration of 1 second.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'noop-1s.mp4',aliases:null,description:'Redirects to an empty MP4 file with a duration of 1 second.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['media']},{name:'blank-mp4',aliases:null,description:'Redirects to an empty MP4 file with a duration of 1 second.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'nooptext',aliases:['noop.txt','blank-text'],description:'Redirects to an empty text file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'noop.txt',aliases:null,description:'Redirects to an empty text file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['image','media','sub_frame','stylesheet','script','xmlhttprequest','other']},{name:'blank-text',aliases:null,description:'Redirects to an empty text file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'noopvast-2.0',aliases:null,description:'Redirects to an empty VAST 2.0 XML file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'noopvast-3.0',aliases:null,description:'Redirects to an empty VAST 3.0 XML file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'noopvast-4.0',aliases:null,description:'Redirects to an empty VAST 4.0 XML file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'noopvmap-1.0',aliases:['noop-vmap1.0.xml'],description:'Redirects to an empty VMAP 1.0 XML file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'noop-vmap1.0.xml',aliases:null,description:'Redirects to an empty VMAP 1.0 XML file.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['media']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'nowebrtc',aliases:['nowebrtc.js','ubo-nowebrtc.js','ubo-nowebrtc'],description:'Disables WebRTC by overriding `RTCPeerConnection`.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'nowebrtc.js',aliases:null,description:'Disables WebRTC by overriding `RTCPeerConnection`.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['other']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'outbrain-widget.js',aliases:null,description:null,docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1024':0,'2048':0,'4096':0,'8192':0}},{shared:[{name:'pardot-1.0',aliases:null,description:'Mocks the pd.js file of Salesforce.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'prebid-ads',aliases:['prebid-ads.js'],description:'Mocks prebid-ads.js script.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'prebid-ads.js',aliases:null,description:'Mocks prebid-ads.js script.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prebid',aliases:null,description:'Mocks the prebid.js header bidding suit.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'prevent-bab',aliases:['nobab.js'],description:'Prevents BlockAdblock script from detecting an ad blocker.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'nobab.js',aliases:null,description:'Prevents BlockAdblock script from detecting an ad blocker.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-bab2',aliases:['nobab2.js'],description:'Prevents BlockAdblock script from detecting an ad blocker.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'nobab2.js',aliases:null,description:'Prevents BlockAdblock script from detecting an ad blocker.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-fab-3.2.0',aliases:['nofab.js'],description:'Mocks FAB script v3.2.0.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'nofab.js',aliases:['fuckadblock.js-3.2.0','fuckadblock.js-3.2.0.js'],description:'Mocks FAB script v3.2.0.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-popads-net',aliases:['popads.js'],description:'Aborts on property write (PopAds, popns), throws reference error with random id.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'popads.js',aliases:null,description:'Aborts on property write (PopAds, popns), throws reference error with random id.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'scorecardresearch-beacon',aliases:['scorecardresearch_beacon.js'],description:'Mocks Scorecard Research API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'scorecardresearch_beacon.js',aliases:null,description:'Mocks Scorecard Research API.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'set-popads-dummy',aliases:['popads-dummy.js'],description:'Sets static properties PopAds and popns.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:[]},{name:'popads-dummy.js',aliases:null,description:'Sets static properties PopAds and popns.',docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,isBlocking:false,resourceTypes:['script']}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}}],map:{'1x1-transparent.gif':0,'1x1.gif':0,'1x1-transparent-gif':0,'2x2-transparent.png':1,'2x2.png':1,'2x2-transparent-png':1,'32x32-transparent.png':2,'32x32.png':2,'32x32-transparent-png':2,'3x2-transparent.png':3,'3x2.png':3,'3x2-transparent-png':3,'amazon-apstag':4,'ubo-amazon_apstag.js':4,'amazon_apstag.js':4,'amazon_ads.js':5,'ampproject_v0.js':6,'ati-smarttag':7,'chartbeat.js':8,'click2load.html':9,'ubo-click2load.html':9,'didomi-loader':10,empty:11,fingerprintjs2:12,'fingerprint2.js':12,fingerprintjs3:13,'fingerprint3.js':13,gemius:14,'google-analytics-ga':15,'ubo-google-analytics_ga.js':15,'google-analytics_ga.js':15,'google-analytics':16,'ubo-google-analytics_analytics.js':16,'google-analytics_analytics.js':16,'googletagmanager-gtm':16,'ubo-googletagmanager_gtm.js':16,'googletagmanager_gtm.js':16,'google-analytics_cx_api.js':17,'google-analytics_inpage_linkid.js':18,'google-ima3':19,'ubo-google-ima.js':19,'google-ima.js':19,'googlesyndication-adsbygoogle':20,'ubo-googlesyndication_adsbygoogle.js':20,'ubo-googlesyndication.com/adsbygoogle.js':20,'googlesyndication_adsbygoogle.js':20,'googlesyndication.com/adsbygoogle.js':20,'googletagservices-gpt':21,'ubo-googletagservices_gpt.js':21,'googletagservices_gpt.js':21,'hd-main.js':22,matomo:23,'metrika-yandex-tag':24,'metrika-yandex-watch':25,'naver-wcslog':26,'no-protected-audience':27,'no-topics':28,noeval:29,'noeval.js':29,'silent-noeval.js':29,'ubo-noeval.js':29,'ubo-silent-noeval.js':29,'ubo-noeval':29,'ubo-silent-noeval':29,'noop-0.5s.mp3':30,noopcss:31,'noop.css':31,'blank-css':31,noopframe:32,'noop.html':32,'blank-html':32,noopjs:33,'noop.js':33,'blank-js':33,noopjson:34,'noop.json':34,'noopmp3-0.1s':35,'noop-0.1s.mp3':35,'blank-mp3':35,'noopmp4-1s':36,'noop-1s.mp4':36,'blank-mp4':36,nooptext:37,'noop.txt':37,'blank-text':37,'noopvast-2.0':38,'noopvast-3.0':39,'noopvast-4.0':40,'noopvmap-1.0':41,'noop-vmap1.0.xml':41,nowebrtc:42,'nowebrtc.js':42,'ubo-nowebrtc.js':42,'ubo-nowebrtc':42,'outbrain-widget.js':43,'pardot-1.0':44,'prebid-ads':45,'prebid-ads.js':45,prebid:46,'prevent-bab':47,'nobab.js':47,'prevent-bab2':48,'nobab2.js':48,'prevent-fab-3.2.0':49,'nofab.js':49,'fuckadblock.js-3.2.0':49,'fuckadblock.js-3.2.0.js':49,'prevent-popads-net':50,'popads.js':50,'scorecardresearch-beacon':51,'scorecardresearch_beacon.js':51,'set-popads-dummy':52,'popads-dummy.js':52}};
const scriptletsCompatibilityTableData = {shared:[{shared:[{name:'abort-current-inline-script',aliases:['abort-current-script.js','ubo-abort-current-script.js','acs.js','ubo-acs.js','ubo-abort-current-script','ubo-acs','abort-current-inline-script.js','ubo-abort-current-inline-script.js','acis.js','ubo-acis.js','ubo-abort-current-inline-script','ubo-acis','abp-abort-current-inline-script'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#abort-current-inline-script',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false},{name:'search',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'abort-current-script.js',aliases:['acs.js','abort-current-inline-script.js','acis.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#abort-current-scriptjs-',versionAdded:'1.37.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false},{name:'search',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'abort-current-inline-script',aliases:null,description:null,docs:'https://help.adblockplus.org/hc/en-us/articles/1500002338501-Snippet-filters-tutorial#snippets-ref',versionAdded:'3.4.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'api',required:true,description:null,pattern:null,'default':null,debug:false},{name:'search',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'abort-on-property-read',aliases:['abort-on-property-read.js','ubo-abort-on-property-read.js','aopr.js','ubo-aopr.js','ubo-abort-on-property-read','ubo-aopr','abp-abort-on-property-read'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#abort-on-property-read',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false}]},{name:'abort-on-property-read.js',aliases:['aopr.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#abort-on-property-readjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false}]},{name:'abort-on-property-read',aliases:null,description:null,docs:'https://help.adblockplus.org/hc/en-us/articles/1500002338501-Snippet-filters-tutorial#snippets-ref',versionAdded:'3.4.1',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false},{name:'setConfigurable',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'abort-on-property-write',aliases:['abort-on-property-write.js','ubo-abort-on-property-write.js','aopw.js','ubo-aopw.js','ubo-abort-on-property-write','ubo-aopw','abp-abort-on-property-write'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#abort-on-property-write',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false}]},{name:'abort-on-property-write.js',aliases:['aopw.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#abort-on-property-writejs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false}]},{name:'abort-on-property-write',aliases:null,description:null,docs:'https://help.adblockplus.org/hc/en-us/articles/1500002338501-Snippet-filters-tutorial#snippets-ref',versionAdded:'3.4.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false},{name:'setConfigurable',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'abort-on-stack-trace',aliases:['abort-on-stack-trace.js','ubo-abort-on-stack-trace.js','aost.js','ubo-aost.js','ubo-abort-on-stack-trace','ubo-aost','abp-abort-on-stack-trace'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#abort-on-stack-trace',versionAdded:'1.5.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:true,description:null,pattern:null,'default':null,debug:false}]},{name:'abort-on-stack-trace.js',aliases:['aost.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#abort-on-stack-tracejs-',versionAdded:'1.29.3rc9',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'adjust-setInterval',aliases:['nano-setInterval-booster.js','ubo-nano-setInterval-booster.js','nano-sib.js','ubo-nano-sib.js','adjust-setInterval.js','ubo-adjust-setInterval.js','ubo-nano-setInterval-booster','ubo-nano-sib','ubo-adjust-setInterval'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#adjust-setInterval',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'matchCallback',required:false,description:null,pattern:null,'default':null,debug:false},{name:'matchDelay',required:false,description:null,pattern:null,'default':null,debug:false},{name:'boost',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'adjust-setInterval.js',aliases:['nano-setInterval-booster.js','nano-sib.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#adjust-setIntervaljs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'matchCallback',required:false,description:null,pattern:null,'default':null,debug:false},{name:'matchDelay',required:false,description:null,pattern:null,'default':null,debug:false},{name:'boost',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'adjust-setTimeout',aliases:['adjust-setTimeout.js','ubo-adjust-setTimeout.js','nano-setTimeout-booster.js','ubo-nano-setTimeout-booster.js','nano-stb.js','ubo-nano-stb.js','ubo-adjust-setTimeout','ubo-nano-setTimeout-booster','ubo-nano-stb'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#adjust-setTimeout',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'matchCallback',required:false,description:null,pattern:null,'default':null,debug:false},{name:'matchDelay',required:false,description:null,pattern:null,'default':null,debug:false},{name:'boost',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'adjust-setTimeout.js',aliases:['nano-setTimeout-booster.js','nano-stb.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#adjust-setTimeoutjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'matchCallback',required:false,description:null,pattern:null,'default':null,debug:false},{name:'matchDelay',required:false,description:null,pattern:null,'default':null,debug:false},{name:'boost',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'amazon-apstag',aliases:['ubo-amazon_apstag.js','amazon_apstag.js'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#amazon-apstag',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'call-nothrow',aliases:['call-nothrow.js','ubo-call-nothrow.js','ubo-call-nothrow'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#call-nothrow',versionAdded:'1.10.1',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'functionName',required:true,description:null,pattern:null,'default':null,debug:false}]},{name:'call-nothrow.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#call-nothrowjs-',versionAdded:'1.48.1b0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'functionName',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'close-window',aliases:['window-close-if.js','ubo-window-close-if.js','ubo-window-close-if','close-window.js','ubo-close-window.js','ubo-close-window'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#close-window',versionAdded:'1.5.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'path',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'close-window.js',aliases:['window-close-if.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#close-windowjs-',versionAdded:'1.39.3b10',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'path',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'debug-current-inline-script',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#debug-current-inline-script',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false},{name:'search',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'debug-on-property-read',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#debug-on-property-read',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'debug-on-property-write',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#debug-on-property-write',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'didomi-loader',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#didomi-loader',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'dir-string',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#dir-string',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'times',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'disable-newtab-links',aliases:['disable-newtab-links.js','ubo-disable-newtab-links.js','ubo-disable-newtab-links'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#disable-newtab-links',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null},{name:'disable-newtab-links.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#disable-newtab-linksjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'evaldata-prune',aliases:['evaldata-prune.js','ubo-evaldata-prune.js','ubo-evaldata-prune'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#evaldata-prune',versionAdded:'1.9.37',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'obligatoryProps',required:false,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'evaldata-prune.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#evaldata-prunejs-',versionAdded:'1.49.3rc15',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'obligatoryProps',required:false,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'fingerprintjs2',aliases:['ubo-fingerprint2.js','fingerprint2.js'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#fingerprintjs2',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'fingerprintjs3',aliases:['ubo-fingerprint3.js','fingerprint3.js'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#fingerprintjs3',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'gemius',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#gemius',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'google-analytics-ga',aliases:['ubo-google-analytics_ga.js','google-analytics_ga.js'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#google-analytics-ga',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'google-analytics',aliases:['ubo-google-analytics_analytics.js','google-analytics_analytics.js','googletagmanager-gtm','ubo-googletagmanager_gtm.js','googletagmanager_gtm.js'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#google-analytics',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'google-ima3',aliases:['ubo-google-ima.js','google-ima.js'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#google-ima3',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'googlesyndication-adsbygoogle',aliases:['ubo-googlesyndication_adsbygoogle.js','googlesyndication_adsbygoogle.js'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#googlesyndication-adsbygoogle',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'googletagservices-gpt',aliases:['ubo-googletagservices_gpt.js','googletagservices_gpt.js'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#googletagservices-gpt',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'hide-in-shadow-dom',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#hide-in-shadow-dom',versionAdded:'1.3.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'selector',required:true,description:null,pattern:null,'default':null,debug:false},{name:'baseSelector',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'href-sanitizer',aliases:['href-sanitizer.js','ubo-href-sanitizer.js','ubo-href-sanitizer'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#href-sanitizer',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'selector',required:true,description:null,pattern:null,'default':null,debug:false},{name:'attribute',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'href-sanitizer.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#href-sanitizerjs-',versionAdded:'1.47.5b4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'selector',required:true,description:null,pattern:null,'default':null,debug:false},{name:'attribute',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'inject-css-in-shadow-dom',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#inject-css-in-shadow-dom',versionAdded:'1.8.2',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'cssRule',required:true,description:null,pattern:null,'default':null,debug:false},{name:'hostSelector',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'json-prune-fetch-response',aliases:['json-prune-fetch-response.js','ubo-json-prune-fetch-response.js','ubo-json-prune-fetch-response'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#json-prune-fetch-response',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'obligatoryProps',required:false,description:null,pattern:null,'default':null,debug:false},{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'json-prune-fetch-response.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#json-prune-fetch-responsejs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'obligatoryProps',required:false,description:null,pattern:null,'default':null,debug:false},{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'json-prune-xhr-response',aliases:['json-prune-xhr-response.js','ubo-json-prune-xhr-response.js','ubo-json-prune-xhr-response'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#json-prune-xhr-response',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'obligatoryProps',required:false,description:null,pattern:null,'default':null,debug:false},{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'json-prune-xhr-response.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#json-prune-xhr-responsejs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'obligatoryProps',required:false,description:null,pattern:null,'default':null,debug:false},{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'json-prune',aliases:['json-prune.js','ubo-json-prune.js','ubo-json-prune','abp-json-prune'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#json-prune',versionAdded:'1.1.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'obligatoryProps',required:false,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'json-prune.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#json-prunejs-',versionAdded:'1.23.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'obligatoryProps',required:false,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'json-prune',aliases:null,description:null,docs:'https://help.adblockplus.org/hc/en-us/articles/1500002338501-Snippet-filters-tutorial#snippets-ref',versionAdded:'3.9.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'rawPrunePaths',required:true,description:null,pattern:null,'default':null,debug:false},{name:'rawNeedlePaths',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'log-addEventListener',aliases:['addEventListener-logger.js','ubo-addEventListener-logger.js','aell.js','ubo-aell.js','ubo-addEventListener-logger','ubo-aell'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#log-addEventListener',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'log-eval',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#log-eval',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'log-on-stack-trace',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#log-on-stack-trace',versionAdded:'1.5.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'log',aliases:['abp-log'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#log',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'arguments',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'m3u-prune',aliases:['m3u-prune.js','ubo-m3u-prune.js','ubo-m3u-prune'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#m3u-prune',versionAdded:'1.9.1',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'urlToMatch',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'m3u-prune.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#m3u-prunejs-',versionAdded:'1.44.5b6',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'urlToMatch',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'matomo',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#matomo',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'metrika-yandex-tag',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#metrika-yandex-tag',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'metrika-yandex-watch',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#metrika-yandex-watch',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'naver-wcslog',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#naver-wcslog',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'no-protected-audience',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#no-protected-audience',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'no-topics',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#no-topics',versionAdded:'1.6.18',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'noeval',aliases:['noeval.js','silent-noeval.js','ubo-noeval.js','ubo-silent-noeval.js','ubo-noeval','ubo-silent-noeval'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#noeval',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'nowebrtc',aliases:['nowebrtc.js','ubo-nowebrtc.js','ubo-nowebrtc'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#nowebrtc',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null},{name:'nowebrtc.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#nowebrtcjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'pardot-1.0',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#pardot-1.0',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'prebid',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prebid',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'prevent-addEventListener',aliases:['addEventListener-defuser.js','ubo-addEventListener-defuser.js','aeld.js','ubo-aeld.js','ubo-addEventListener-defuser','ubo-aeld','abp-prevent-listener'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-addEventListener',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'typeSearch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'listenerSearch',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'addEventListener-defuser.js',aliases:['aeld.js','prevent-addEventListener.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#addEventListener-defuserjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'typeSearch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'listenerSearch',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'prevent-listener',aliases:null,description:null,docs:'https://help.adblockplus.org/hc/en-us/articles/1500002338501-Snippet-filters-tutorial#snippets-ref',versionAdded:'3.11.2',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'type',required:true,description:null,pattern:null,'default':null,debug:false},{name:'handler',required:false,description:null,pattern:null,'default':null,debug:false},{name:'selector',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'prevent-adfly',aliases:['adfly-defuser.js','ubo-adfly-defuser.js','ubo-adfly-defuser'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-adfly',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'prevent-bab',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-bab',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'prevent-element-src-loading',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-element-src-loading',versionAdded:'1.6.2',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'tagName',required:true,description:null,pattern:null,'default':null,debug:false},{name:'match',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'prevent-eval-if',aliases:['noeval-if.js','ubo-noeval-if.js','ubo-noeval-if'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-eval-if',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'search',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'noeval-if.js',aliases:['prevent-eval-if.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#noeval-ifjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'search',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-fab-3.2.0',aliases:['nofab.js','ubo-nofab.js','fuckadblock.js-3.2.0','ubo-fuckadblock.js-3.2.0','ubo-nofab'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-fab-3.2.0',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'prevent-fetch',aliases:['prevent-fetch.js','no-fetch-if.js','ubo-no-fetch-if.js','ubo-no-fetch-if'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-fetch',versionAdded:'1.3.18',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'responseBody',required:false,description:null,pattern:null,'default':null,debug:false},{name:'responseType',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'prevent-fetch.js',aliases:['no-fetch-if.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#prevent-fetchjs-',versionAdded:'1.31.3b9',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'responseBody',required:false,description:null,pattern:null,'default':null,debug:false},{name:'responseType',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-popads-net',aliases:['popads.net.js','ubo-popads.net.js','ubo-popads.net'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-popads-net',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'prevent-refresh',aliases:['prevent-refresh.js','refresh-defuser.js','refresh-defuser','ubo-prevent-refresh.js','ubo-prevent-refresh','ubo-refresh-defuser.js','ubo-refresh-defuser'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-refresh',versionAdded:'1.6.2',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'delay',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'prevent-refresh.js',aliases:['refresh-defuser.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#prevent-refreshjs-',versionAdded:'1.38.7b3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'delay',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-requestAnimationFrame',aliases:['no-requestAnimationFrame-if.js','ubo-no-requestAnimationFrame-if.js','norafif.js','ubo-norafif.js','ubo-no-requestAnimationFrame-if','ubo-norafif'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-requestAnimationFrame',versionAdded:'1.1.15',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'search',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'no-requestAnimationFrame-if.js',aliases:['norafif.js','prevent-requestAnimationFrame.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#no-requestAnimationFrame-ifjs-',versionAdded:'1.27.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'search',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-setInterval',aliases:['no-setInterval-if.js','ubo-no-setInterval-if.js','setInterval-defuser.js','ubo-setInterval-defuser.js','nosiif.js','ubo-nosiif.js','sid.js','ubo-sid.js','ubo-no-setInterval-if','ubo-setInterval-defuser','ubo-nosiif','ubo-sid'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-setInterval',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'matchCallback',required:false,description:null,pattern:null,'default':null,debug:false},{name:'matchDelay',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'no-setInterval-if.js',aliases:['nosiif.js','prevent-setInterval.js','setInterval-defuser.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#no-setInterval-ifjs-',versionAdded:'1.23.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'matchCallback',required:false,description:null,pattern:null,'default':null,debug:false},{name:'matchDelay',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-setTimeout',aliases:['no-setTimeout-if.js','ubo-no-setTimeout-if.js','nostif.js','ubo-nostif.js','ubo-no-setTimeout-if','ubo-nostif','setTimeout-defuser.js','ubo-setTimeout-defuser.js','ubo-setTimeout-defuser','std.js','ubo-std.js','ubo-std'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-setTimeout',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'matchCallback',required:false,description:null,pattern:null,'default':null,debug:false},{name:'matchDelay',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'no-setTimeout-if.js',aliases:['nostif.js','prevent-setTimeout.js','setTimeout-defuser.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#no-setTimeout-ifjs-',versionAdded:'1.23.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'matchCallback',required:false,description:null,pattern:null,'default':null,debug:false},{name:'matchDelay',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-window-open',aliases:['window.open-defuser.js','ubo-window.open-defuser.js','ubo-window.open-defuser','nowoif.js','ubo-nowoif.js','ubo-nowoif','no-window-open-if.js','ubo-no-window-open-if.js','ubo-no-window-open-if'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-window-open',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'match',required:false,description:null,pattern:null,'default':null,debug:false},{name:'delay',required:false,description:null,pattern:null,'default':null,debug:false},{name:'replacement',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'no-window-open-if.js',aliases:['nowoif.js','prevent-window-open.js','window.open-defuser.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#no-window-open-ifjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'match',required:false,description:null,pattern:null,'default':null,debug:false},{name:'delay',required:false,description:null,pattern:null,'default':null,debug:false},{name:'replacement',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'prevent-xhr',aliases:['no-xhr-if.js','ubo-no-xhr-if.js','ubo-no-xhr-if'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#prevent-xhr',versionAdded:'1.5.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'randomize',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'no-xhr-if.js',aliases:['prevent-xhr.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#no-xhr-ifjs-',versionAdded:'1.38.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'randomize',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'remove-attr',aliases:['remove-attr.js','ubo-remove-attr.js','ra.js','ubo-ra.js','ubo-remove-attr','ubo-ra'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#remove-attr',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'attrs',required:true,description:null,pattern:null,'default':null,debug:false},{name:'selector',required:false,description:null,pattern:null,'default':null,debug:false},{name:'applying',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'remove-attr.js',aliases:['ra.js','ra','remove-attr'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#remove-attrjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'attrs',required:true,description:null,pattern:null,'default':null,debug:false},{name:'selector',required:false,description:null,pattern:null,'default':null,debug:false},{name:'applying',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'remove-class',aliases:['remove-class.js','ubo-remove-class.js','rc.js','ubo-rc.js','ubo-remove-class','ubo-rc'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#remove-class',versionAdded:'1.1.1',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'classes',required:true,description:null,pattern:null,'default':null,debug:false},{name:'selector',required:false,description:null,pattern:null,'default':null,debug:false},{name:'applying',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'remove-class.js',aliases:['rc.js','rc','remove-class'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#remove-classjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'classes',required:true,description:null,pattern:null,'default':null,debug:false},{name:'selector',required:false,description:null,pattern:null,'default':null,debug:false},{name:'applying',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'remove-cookie',aliases:['cookie-remover.js','ubo-cookie-remover.js','ubo-cookie-remover','remove-cookie.js','ubo-remove-cookie.js','ubo-remove-cookie','abp-cookie-remover'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#remove-cookie',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'match',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'remove-cookie.js',aliases:['cookie-remover.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#remove-cookiejs-',versionAdded:'1.28.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'match',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'cookie-remover',aliases:null,description:null,docs:'https://help.adblockplus.org/hc/en-us/articles/1500002338501-Snippet-filters-tutorial#snippets-ref',versionAdded:'3.11.2',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'cookie',required:true,description:null,pattern:null,'default':null,debug:false},{name:'autoRemoveCookie',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'remove-in-shadow-dom',aliases:null,description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#remove-in-shadow-dom',versionAdded:'1.3.14',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'selector',required:true,description:null,pattern:null,'default':null,debug:false},{name:'baseSelector',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'remove-node-text',aliases:['remove-node-text.js','ubo-remove-node-text.js','rmnt.js','ubo-rmnt.js','ubo-remove-node-text','ubo-rmnt'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#remove-node-text',versionAdded:'1.9.37',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'nodeName',required:true,description:null,pattern:null,'default':null,debug:false},{name:'textMatch',required:true,description:null,pattern:null,'default':null,debug:false}]},{name:'remove-node-text.js',aliases:['rmnt.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#remove-node-textjs-',versionAdded:'1.49.3rc15',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'nodeName',required:true,description:null,pattern:null,'default':null,debug:false},{name:'textMatch',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'scorecardresearch-beacon',aliases:['ubo-scorecardresearch_beacon.js','scorecardresearch_beacon.js'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#scorecardresearch-beacon',versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'set-attr',aliases:['set-attr.js','ubo-set-attr.js','ubo-set-attr'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#set-attr',versionAdded:'1.5.0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'selector',required:true,description:null,pattern:null,'default':null,debug:false},{name:'attr',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'set-attr.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#set-attrjs-',versionAdded:'1.50.1b16',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'selector',required:true,description:null,pattern:null,'default':null,debug:false},{name:'attr',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'set-constant',aliases:['set-constant.js','ubo-set-constant.js','set.js','ubo-set.js','ubo-set-constant','ubo-set'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#set-constant',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false},{name:'valueWrapper',required:false,description:null,pattern:null,'default':null,debug:false},{name:'setProxyTrap',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'set-constant.js',aliases:['set.js'],description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#set-constantjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'chain',required:true,description:null,pattern:null,'default':null,debug:false},{name:'rawValue',required:true,description:null,pattern:null,'default':null,debug:false},{name:'runAt',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'override-property-read',aliases:null,description:null,docs:'https://help.adblockplus.org/hc/en-us/articles/1500002338501-Snippet-filters-tutorial#snippets-ref',versionAdded:'3.9.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false},{name:'setConfigurable',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1,'16384':2,'32768':2,'65536':2,'131072':2}},{shared:[{name:'set-cookie-reload',aliases:['set-cookie-reload.js','ubo-set-cookie-reload.js','ubo-set-cookie-reload'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#set-cookie-reload',versionAdded:'1.3.14',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'name',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false},{name:'path',required:false,description:null,pattern:null,'default':null,debug:false},{name:'domain',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'set-cookie-reload.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#set-cookie-reloadjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'name',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false},{name:'path',required:false,description:null,pattern:null,'default':null,debug:false},{name:'domain',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'set-cookie',aliases:['set-cookie.js','ubo-set-cookie.js','ubo-set-cookie'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#set-cookie',versionAdded:'1.2.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'name',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false},{name:'path',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'set-cookie.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#set-cookiejs-',versionAdded:'1.50.1b0',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'name',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false},{name:'path',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'set-local-storage-item',aliases:['set-local-storage-item.js','ubo-set-local-storage-item.js','ubo-set-local-storage-item'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#set-local-storage-item',versionAdded:'1.4.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'key',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false}]},{name:'set-local-storage-item.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#set-local-storage-itemjs-',versionAdded:'1.50.1b4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'key',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'set-popads-dummy',aliases:['popads-dummy.js','ubo-popads-dummy.js','ubo-popads-dummy'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#set-popads-dummy',versionAdded:'1.0.4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'set-session-storage-item',aliases:['set-session-storage-item.js','ubo-set-session-storage-item.js','ubo-set-session-storage-item'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#set-session-storage-item',versionAdded:'1.4.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'key',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false}]},{name:'set-session-storage-item.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#set-session-storage-itemjs-',versionAdded:'1.50.1b4',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'key',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'spoof-css',aliases:['spoof-css.js','ubo-spoof-css.js','ubo-spoof-css'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#spoof-css',versionAdded:'1.10.1',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'selectors',required:true,description:null,pattern:null,'default':null,debug:false},{name:'cssPropertyName',required:true,description:null,pattern:null,'default':null,debug:false},{name:'cssPropertyValue',required:true,description:null,pattern:null,'default':null,debug:false}]},{name:'spoof-css.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#spoof-cssjs-',versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'selectors',required:true,description:null,pattern:null,'default':null,debug:false},{name:'cssPropertyName',required:true,description:null,pattern:null,'default':null,debug:false},{name:'cssPropertyValue',required:true,description:null,pattern:null,'default':null,debug:false},{name:'arguments',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}},{shared:[{name:'trusted-click-element',aliases:null,description:null,docs:null,versionAdded:'1.7.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'selectors',required:true,description:null,pattern:null,'default':null,debug:false},{name:'extraMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'delay',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-create-element',aliases:null,description:null,docs:null,versionAdded:'1.10.1',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'parentSelector',required:true,description:null,pattern:null,'default':null,debug:false},{name:'tagName',required:true,description:null,pattern:null,'default':null,debug:false},{name:'attributePairs',required:false,description:null,pattern:null,'default':null,debug:false},{name:'textContent',required:false,description:null,pattern:null,'default':null,debug:false},{name:'cleanupDelayMs',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-dispatch-event',aliases:null,description:null,docs:null,versionAdded:null,versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'event',required:true,description:null,pattern:null,'default':null,debug:false},{name:'target',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-prune-inbound-object',aliases:null,description:null,docs:null,versionAdded:'1.9.91',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'functionName',required:true,description:null,pattern:null,'default':null,debug:false},{name:'propsToRemove',required:false,description:null,pattern:null,'default':null,debug:false},{name:'obligatoryProps',required:false,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-replace-fetch-response',aliases:null,description:null,docs:null,versionAdded:'1.7.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'pattern',required:false,description:null,pattern:null,'default':null,debug:false},{name:'replacement',required:false,description:null,pattern:null,'default':null,debug:false},{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-replace-node-text',aliases:null,description:null,docs:null,versionAdded:'1.9.37',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'nodeName',required:true,description:null,pattern:null,'default':null,debug:false},{name:'textMatch',required:true,description:null,pattern:null,'default':null,debug:false},{name:'pattern',required:true,description:null,pattern:null,'default':null,debug:false},{name:'replacement',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-replace-xhr-response',aliases:null,description:null,docs:null,versionAdded:'1.7.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'pattern',required:false,description:null,pattern:null,'default':null,debug:false},{name:'replacement',required:false,description:null,pattern:null,'default':null,debug:false},{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-set-attr',aliases:null,description:null,docs:null,versionAdded:'1.10.1',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'selector',required:true,description:null,pattern:null,'default':null,debug:false},{name:'attr',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-set-constant',aliases:null,description:null,docs:null,versionAdded:'1.8.2',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'property',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-set-cookie-reload',aliases:null,description:null,docs:null,versionAdded:'1.7.10',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'name',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false},{name:'offsetExpiresSec',required:false,description:null,pattern:null,'default':null,debug:false},{name:'path',required:false,description:null,pattern:null,'default':null,debug:false},{name:'domain',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-set-cookie',aliases:null,description:null,docs:null,versionAdded:'1.7.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'name',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false},{name:'offsetExpiresSec',required:false,description:null,pattern:null,'default':null,debug:false},{name:'path',required:false,description:null,pattern:null,'default':null,debug:false},{name:'domain',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-set-local-storage-item',aliases:null,description:null,docs:null,versionAdded:'1.7.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'key',required:true,description:null,pattern:null,'default':null,debug:false},{name:'value',required:true,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'trusted-suppress-native-method',aliases:null,description:null,docs:null,versionAdded:'1.10.25',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'methodPath',required:true,description:null,pattern:null,'default':null,debug:false},{name:'signatureStr',required:true,description:null,pattern:null,'default':null,debug:false},{name:'how',required:false,description:null,pattern:null,'default':null,debug:false},{name:'stack',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0}},{shared:[{name:'xml-prune',aliases:['xml-prune.js','ubo-xml-prune.js','ubo-xml-prune'],description:null,docs:'https://github.com/AdguardTeam/Scriptlets/blob/master/wiki/about-scriptlets.md#xml-prune',versionAdded:'1.7.3',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'optionalProp',required:false,description:null,pattern:null,'default':null,debug:false},{name:'urlToMatch',required:false,description:null,pattern:null,'default':null,debug:false}]},{name:'xml-prune.js',aliases:null,description:null,docs:'https://github.com/gorhill/uBlock/wiki/Resources-Library#xml-prunejs-',versionAdded:'1.49.3rc6',versionRemoved:null,deprecated:false,deprecationMessage:null,removed:false,removalMessage:null,parameters:[{name:'propsToMatch',required:false,description:null,pattern:null,'default':null,debug:false},{name:'optionalProp',required:false,description:null,pattern:null,'default':null,debug:false},{name:'urlToMatch',required:false,description:null,pattern:null,'default':null,debug:false}]}],map:{'1':0,'2':0,'4':0,'8':0,'16':0,'32':0,'64':0,'1024':1,'2048':1,'4096':1,'8192':1}}],map:{'abort-current-inline-script':0,'abort-current-script.js':0,'ubo-abort-current-script.js':0,'acs.js':0,'ubo-acs.js':0,'ubo-abort-current-script':0,'ubo-acs':0,'abort-current-inline-script.js':0,'ubo-abort-current-inline-script.js':0,'acis.js':0,'ubo-acis.js':0,'ubo-abort-current-inline-script':0,'ubo-acis':0,'abp-abort-current-inline-script':0,'abort-on-property-read':1,'abort-on-property-read.js':1,'ubo-abort-on-property-read.js':1,'aopr.js':1,'ubo-aopr.js':1,'ubo-abort-on-property-read':1,'ubo-aopr':1,'abp-abort-on-property-read':1,'abort-on-property-write':2,'abort-on-property-write.js':2,'ubo-abort-on-property-write.js':2,'aopw.js':2,'ubo-aopw.js':2,'ubo-abort-on-property-write':2,'ubo-aopw':2,'abp-abort-on-property-write':2,'abort-on-stack-trace':3,'abort-on-stack-trace.js':3,'ubo-abort-on-stack-trace.js':3,'aost.js':3,'ubo-aost.js':3,'ubo-abort-on-stack-trace':3,'ubo-aost':3,'abp-abort-on-stack-trace':3,'adjust-setInterval':4,'nano-setInterval-booster.js':4,'ubo-nano-setInterval-booster.js':4,'nano-sib.js':4,'ubo-nano-sib.js':4,'adjust-setInterval.js':4,'ubo-adjust-setInterval.js':4,'ubo-nano-setInterval-booster':4,'ubo-nano-sib':4,'ubo-adjust-setInterval':4,'adjust-setTimeout':5,'adjust-setTimeout.js':5,'ubo-adjust-setTimeout.js':5,'nano-setTimeout-booster.js':5,'ubo-nano-setTimeout-booster.js':5,'nano-stb.js':5,'ubo-nano-stb.js':5,'ubo-adjust-setTimeout':5,'ubo-nano-setTimeout-booster':5,'ubo-nano-stb':5,'amazon-apstag':6,'ubo-amazon_apstag.js':6,'amazon_apstag.js':6,'call-nothrow':7,'call-nothrow.js':7,'ubo-call-nothrow.js':7,'ubo-call-nothrow':7,'close-window':8,'window-close-if.js':8,'ubo-window-close-if.js':8,'ubo-window-close-if':8,'close-window.js':8,'ubo-close-window.js':8,'ubo-close-window':8,'debug-current-inline-script':9,'debug-on-property-read':10,'debug-on-property-write':11,'didomi-loader':12,'dir-string':13,'disable-newtab-links':14,'disable-newtab-links.js':14,'ubo-disable-newtab-links.js':14,'ubo-disable-newtab-links':14,'evaldata-prune':15,'evaldata-prune.js':15,'ubo-evaldata-prune.js':15,'ubo-evaldata-prune':15,fingerprintjs2:16,'ubo-fingerprint2.js':16,'fingerprint2.js':16,fingerprintjs3:17,'ubo-fingerprint3.js':17,'fingerprint3.js':17,gemius:18,'google-analytics-ga':19,'ubo-google-analytics_ga.js':19,'google-analytics_ga.js':19,'google-analytics':20,'ubo-google-analytics_analytics.js':20,'google-analytics_analytics.js':20,'googletagmanager-gtm':20,'ubo-googletagmanager_gtm.js':20,'googletagmanager_gtm.js':20,'google-ima3':21,'ubo-google-ima.js':21,'google-ima.js':21,'googlesyndication-adsbygoogle':22,'ubo-googlesyndication_adsbygoogle.js':22,'googlesyndication_adsbygoogle.js':22,'googletagservices-gpt':23,'ubo-googletagservices_gpt.js':23,'googletagservices_gpt.js':23,'hide-in-shadow-dom':24,'href-sanitizer':25,'href-sanitizer.js':25,'ubo-href-sanitizer.js':25,'ubo-href-sanitizer':25,'inject-css-in-shadow-dom':26,'json-prune-fetch-response':27,'json-prune-fetch-response.js':27,'ubo-json-prune-fetch-response.js':27,'ubo-json-prune-fetch-response':27,'json-prune-xhr-response':28,'json-prune-xhr-response.js':28,'ubo-json-prune-xhr-response.js':28,'ubo-json-prune-xhr-response':28,'json-prune':29,'json-prune.js':29,'ubo-json-prune.js':29,'ubo-json-prune':29,'abp-json-prune':29,'log-addEventListener':30,'addEventListener-logger.js':30,'ubo-addEventListener-logger.js':30,'aell.js':30,'ubo-aell.js':30,'ubo-addEventListener-logger':30,'ubo-aell':30,'log-eval':31,'log-on-stack-trace':32,log:33,'abp-log':33,'m3u-prune':34,'m3u-prune.js':34,'ubo-m3u-prune.js':34,'ubo-m3u-prune':34,matomo:35,'metrika-yandex-tag':36,'metrika-yandex-watch':37,'naver-wcslog':38,'no-protected-audience':39,'no-topics':40,noeval:41,'noeval.js':41,'silent-noeval.js':41,'ubo-noeval.js':41,'ubo-silent-noeval.js':41,'ubo-noeval':41,'ubo-silent-noeval':41,nowebrtc:42,'nowebrtc.js':42,'ubo-nowebrtc.js':42,'ubo-nowebrtc':42,'pardot-1.0':43,prebid:44,'prevent-addEventListener':45,'addEventListener-defuser.js':45,'ubo-addEventListener-defuser.js':45,'aeld.js':45,'ubo-aeld.js':45,'ubo-addEventListener-defuser':45,'ubo-aeld':45,'abp-prevent-listener':45,'prevent-addEventListener.js':45,'prevent-listener':45,'prevent-adfly':46,'adfly-defuser.js':46,'ubo-adfly-defuser.js':46,'ubo-adfly-defuser':46,'prevent-bab':47,'prevent-element-src-loading':48,'prevent-eval-if':49,'noeval-if.js':49,'ubo-noeval-if.js':49,'ubo-noeval-if':49,'prevent-eval-if.js':49,'prevent-fab-3.2.0':50,'nofab.js':50,'ubo-nofab.js':50,'fuckadblock.js-3.2.0':50,'ubo-fuckadblock.js-3.2.0':50,'ubo-nofab':50,'prevent-fetch':51,'prevent-fetch.js':51,'no-fetch-if.js':51,'ubo-no-fetch-if.js':51,'ubo-no-fetch-if':51,'prevent-popads-net':52,'popads.net.js':52,'ubo-popads.net.js':52,'ubo-popads.net':52,'prevent-refresh':53,'prevent-refresh.js':53,'refresh-defuser.js':53,'refresh-defuser':53,'ubo-prevent-refresh.js':53,'ubo-prevent-refresh':53,'ubo-refresh-defuser.js':53,'ubo-refresh-defuser':53,'prevent-requestAnimationFrame':54,'no-requestAnimationFrame-if.js':54,'ubo-no-requestAnimationFrame-if.js':54,'norafif.js':54,'ubo-norafif.js':54,'ubo-no-requestAnimationFrame-if':54,'ubo-norafif':54,'prevent-requestAnimationFrame.js':54,'prevent-setInterval':55,'no-setInterval-if.js':55,'ubo-no-setInterval-if.js':55,'setInterval-defuser.js':55,'ubo-setInterval-defuser.js':55,'nosiif.js':55,'ubo-nosiif.js':55,'sid.js':55,'ubo-sid.js':55,'ubo-no-setInterval-if':55,'ubo-setInterval-defuser':55,'ubo-nosiif':55,'ubo-sid':55,'prevent-setInterval.js':55,'prevent-setTimeout':56,'no-setTimeout-if.js':56,'ubo-no-setTimeout-if.js':56,'nostif.js':56,'ubo-nostif.js':56,'ubo-no-setTimeout-if':56,'ubo-nostif':56,'setTimeout-defuser.js':56,'ubo-setTimeout-defuser.js':56,'ubo-setTimeout-defuser':56,'std.js':56,'ubo-std.js':56,'ubo-std':56,'prevent-setTimeout.js':56,'prevent-window-open':57,'window.open-defuser.js':57,'ubo-window.open-defuser.js':57,'ubo-window.open-defuser':57,'nowoif.js':57,'ubo-nowoif.js':57,'ubo-nowoif':57,'no-window-open-if.js':57,'ubo-no-window-open-if.js':57,'ubo-no-window-open-if':57,'prevent-window-open.js':57,'prevent-xhr':58,'no-xhr-if.js':58,'ubo-no-xhr-if.js':58,'ubo-no-xhr-if':58,'prevent-xhr.js':58,'remove-attr':59,'remove-attr.js':59,'ubo-remove-attr.js':59,'ra.js':59,'ubo-ra.js':59,'ubo-remove-attr':59,'ubo-ra':59,ra:59,'remove-class':60,'remove-class.js':60,'ubo-remove-class.js':60,'rc.js':60,'ubo-rc.js':60,'ubo-remove-class':60,'ubo-rc':60,rc:60,'remove-cookie':61,'cookie-remover.js':61,'ubo-cookie-remover.js':61,'ubo-cookie-remover':61,'remove-cookie.js':61,'ubo-remove-cookie.js':61,'ubo-remove-cookie':61,'abp-cookie-remover':61,'cookie-remover':61,'remove-in-shadow-dom':62,'remove-node-text':63,'remove-node-text.js':63,'ubo-remove-node-text.js':63,'rmnt.js':63,'ubo-rmnt.js':63,'ubo-remove-node-text':63,'ubo-rmnt':63,'scorecardresearch-beacon':64,'ubo-scorecardresearch_beacon.js':64,'scorecardresearch_beacon.js':64,'set-attr':65,'set-attr.js':65,'ubo-set-attr.js':65,'ubo-set-attr':65,'set-constant':66,'set-constant.js':66,'ubo-set-constant.js':66,'set.js':66,'ubo-set.js':66,'ubo-set-constant':66,'ubo-set':66,'override-property-read':66,'set-cookie-reload':67,'set-cookie-reload.js':67,'ubo-set-cookie-reload.js':67,'ubo-set-cookie-reload':67,'set-cookie':68,'set-cookie.js':68,'ubo-set-cookie.js':68,'ubo-set-cookie':68,'set-local-storage-item':69,'set-local-storage-item.js':69,'ubo-set-local-storage-item.js':69,'ubo-set-local-storage-item':69,'set-popads-dummy':70,'popads-dummy.js':70,'ubo-popads-dummy.js':70,'ubo-popads-dummy':70,'set-session-storage-item':71,'set-session-storage-item.js':71,'ubo-set-session-storage-item.js':71,'ubo-set-session-storage-item':71,'spoof-css':72,'spoof-css.js':72,'ubo-spoof-css.js':72,'ubo-spoof-css':72,'trusted-click-element':73,'trusted-create-element':74,'trusted-dispatch-event':75,'trusted-prune-inbound-object':76,'trusted-replace-fetch-response':77,'trusted-replace-node-text':78,'trusted-replace-xhr-response':79,'trusted-set-attr':80,'trusted-set-constant':81,'trusted-set-cookie-reload':82,'trusted-set-cookie':83,'trusted-set-local-storage-item':84,'trusted-suppress-native-method':85,'xml-prune':86,'xml-prune.js':86,'ubo-xml-prune.js':86,'ubo-xml-prune':86}};



;// ./node_modules/.pnpm/@adguard+agtree@3.0.1/node_modules/@adguard/agtree/dist/utils/deep-freeze.js
/*
 * AGTree v3.0.1 (build date: Fri, 28 Feb 2025 15:31:12 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * Simple deep freeze implementation.
 * It freezes the object and all its properties recursively.
 *
 * @param object Object to freeze.
 *
 * @returns Frozen object.
 *
 * @template T Type of the object to freeze.
 *
 * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze#deep_freezing}
 */
const deepFreeze = (object) => {
    // Retrieve the property names defined on object
    const propNames = Reflect.ownKeys(object);
    // Freeze properties before freezing self
    for (const name of propNames) {
        const value = object[name];
        if ((value && typeof value === 'object') || typeof value === 'function') {
            deepFreeze(value);
        }
    }
    return Object.freeze(object);
};



;// ./node_modules/.pnpm/@adguard+agtree@3.0.1/node_modules/@adguard/agtree/dist/utils/constants.js
/*
 * AGTree v3.0.1 (build date: Fri, 28 Feb 2025 15:31:12 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/**
 * @file Constant values used by all parts of the library
 */
// TODO: remove unused constants
// General
/**
 * Empty string.
 */
const EMPTY = '';
const SPACE = ' ';
const TAB = '\t';
const COLON = ':';
const COMMA = ',';
const DOT = '.';
const SEMICOLON = ';';
const AMPERSAND = '&';
const ASTERISK = '*';
const AT_SIGN = '@';
const CARET = '^';
const DOLLAR_SIGN = '$';
const EQUALS = '=';
const EXCLAMATION_MARK = '!';
const HASHMARK = '#';
const PIPE = '|';
const PLUS = '+';
const QUESTION_MARK = '?';
const SLASH = '/';
const UNDERSCORE = '_';
// Escape characters
const BACKSLASH = '\\';
const ESCAPE_CHARACTER = (/* unused pure expression or super */ null && (BACKSLASH));
// Newlines
const CR = '\r';
const FF = '\f';
const LF = '\n';
const CRLF = CR + LF;
const NEWLINE = (/* unused pure expression or super */ null && (LF));
// Quotes
const BACKTICK_QUOTE = '`';
const DOUBLE_QUOTE = '"';
const SINGLE_QUOTE = '\'';
// Brackets
const OPEN_PARENTHESIS = '(';
const CLOSE_PARENTHESIS = ')';
const OPEN_SQUARE_BRACKET = '[';
const CLOSE_SQUARE_BRACKET = ']';
const OPEN_CURLY_BRACKET = '{';
const CLOSE_CURLY_BRACKET = '}';
// Letters
const SMALL_LETTER_A = 'a';
const SMALL_LETTER_B = 'b';
const SMALL_LETTER_C = 'c';
const SMALL_LETTER_D = 'd';
const SMALL_LETTER_E = 'e';
const SMALL_LETTER_F = 'f';
const SMALL_LETTER_G = 'g';
const SMALL_LETTER_H = 'h';
const SMALL_LETTER_I = 'i';
const SMALL_LETTER_J = 'j';
const SMALL_LETTER_K = 'k';
const SMALL_LETTER_L = 'l';
const SMALL_LETTER_M = 'm';
const SMALL_LETTER_N = 'n';
const SMALL_LETTER_O = 'o';
const SMALL_LETTER_P = 'p';
const SMALL_LETTER_Q = 'q';
const SMALL_LETTER_R = 'r';
const SMALL_LETTER_S = 's';
const SMALL_LETTER_T = 't';
const SMALL_LETTER_U = 'u';
const SMALL_LETTER_V = 'v';
const SMALL_LETTER_W = 'w';
const SMALL_LETTER_X = 'x';
const SMALL_LETTER_Y = 'y';
const SMALL_LETTER_Z = 'z';
/**
 * Set of all small letters.
 */
const SMALL_LETTERS = new Set([
    SMALL_LETTER_A,
    SMALL_LETTER_B,
    SMALL_LETTER_C,
    SMALL_LETTER_D,
    SMALL_LETTER_E,
    SMALL_LETTER_F,
    SMALL_LETTER_G,
    SMALL_LETTER_H,
    SMALL_LETTER_I,
    SMALL_LETTER_J,
    SMALL_LETTER_K,
    SMALL_LETTER_L,
    SMALL_LETTER_M,
    SMALL_LETTER_N,
    SMALL_LETTER_O,
    SMALL_LETTER_P,
    SMALL_LETTER_Q,
    SMALL_LETTER_R,
    SMALL_LETTER_S,
    SMALL_LETTER_T,
    SMALL_LETTER_U,
    SMALL_LETTER_V,
    SMALL_LETTER_W,
    SMALL_LETTER_X,
    SMALL_LETTER_Y,
    SMALL_LETTER_Z,
]);
// Capital letters
const CAPITAL_LETTER_A = 'A';
const CAPITAL_LETTER_B = 'B';
const CAPITAL_LETTER_C = 'C';
const CAPITAL_LETTER_D = 'D';
const CAPITAL_LETTER_E = 'E';
const CAPITAL_LETTER_F = 'F';
const CAPITAL_LETTER_G = 'G';
const CAPITAL_LETTER_H = 'H';
const CAPITAL_LETTER_I = 'I';
const CAPITAL_LETTER_J = 'J';
const CAPITAL_LETTER_K = 'K';
const CAPITAL_LETTER_L = 'L';
const CAPITAL_LETTER_M = 'M';
const CAPITAL_LETTER_N = 'N';
const CAPITAL_LETTER_O = 'O';
const CAPITAL_LETTER_P = 'P';
const CAPITAL_LETTER_Q = 'Q';
const CAPITAL_LETTER_R = 'R';
const CAPITAL_LETTER_S = 'S';
const CAPITAL_LETTER_T = 'T';
const CAPITAL_LETTER_U = 'U';
const CAPITAL_LETTER_V = 'V';
const CAPITAL_LETTER_W = 'W';
const CAPITAL_LETTER_X = 'X';
const CAPITAL_LETTER_Y = 'Y';
const CAPITAL_LETTER_Z = 'Z';
/**
 * Set of all capital letters.
 */
const CAPITAL_LETTERS = new Set([
    CAPITAL_LETTER_A,
    CAPITAL_LETTER_B,
    CAPITAL_LETTER_C,
    CAPITAL_LETTER_D,
    CAPITAL_LETTER_E,
    CAPITAL_LETTER_F,
    CAPITAL_LETTER_G,
    CAPITAL_LETTER_H,
    CAPITAL_LETTER_I,
    CAPITAL_LETTER_J,
    CAPITAL_LETTER_K,
    CAPITAL_LETTER_L,
    CAPITAL_LETTER_M,
    CAPITAL_LETTER_N,
    CAPITAL_LETTER_O,
    CAPITAL_LETTER_P,
    CAPITAL_LETTER_Q,
    CAPITAL_LETTER_R,
    CAPITAL_LETTER_S,
    CAPITAL_LETTER_T,
    CAPITAL_LETTER_U,
    CAPITAL_LETTER_V,
    CAPITAL_LETTER_W,
    CAPITAL_LETTER_X,
    CAPITAL_LETTER_Y,
    CAPITAL_LETTER_Z,
]);
// Numbers as strings
const NUMBER_0 = '0';
const NUMBER_1 = '1';
const NUMBER_2 = '2';
const NUMBER_3 = '3';
const NUMBER_4 = '4';
const NUMBER_5 = '5';
const NUMBER_6 = '6';
const NUMBER_7 = '7';
const NUMBER_8 = '8';
const NUMBER_9 = '9';
/**
 * Set of all numbers as strings.
 */
const NUMBERS = new Set([
    NUMBER_0,
    NUMBER_1,
    NUMBER_2,
    NUMBER_3,
    NUMBER_4,
    NUMBER_5,
    NUMBER_6,
    NUMBER_7,
    NUMBER_8,
    NUMBER_9,
]);
const REGEX_MARKER = '/';
const ADG_SCRIPTLET_MASK = '//scriptlet';
const UBO_SCRIPTLET_MASK = '+js';
const UBO_SCRIPTLET_MASK_LEGACY = 'script:inject';
const UBO_HTML_MASK = '^';
// Modifiers are separated by ",". For example: "script,domain=example.com"
const MODIFIERS_SEPARATOR = ',';
const MODIFIER_ASSIGN_OPERATOR = '=';
const NEGATION_MARKER = '~';
/**
 * The wildcard symbol — `*`.
 */
const WILDCARD = (/* unused pure expression or super */ null && (ASTERISK));
/**
 * Classic domain separator.
 *
 * @example
 * ```adblock
 * ! Domains are separated by ",":
 * example.com,~example.org##.ads
 * ```
 */
const COMMA_DOMAIN_LIST_SEPARATOR = ',';
/**
 * Modifier separator for $app, $denyallow, $domain, $method.
 *
 * @example
 * ```adblock
 * ! Domains are separated by "|":
 * ads.js^$script,domains=example.com|~example.org
 * ```
 */
const PIPE_MODIFIER_SEPARATOR = '|';
const CSS_MEDIA_MARKER = '@media';
const CSS_NOT_PSEUDO = 'not';
const CSS_BLOCK_OPEN = '{';
const CSS_BLOCK_CLOSE = '}';
const HINT_MARKER = '!+';
const HINT_MARKER_LEN = HINT_MARKER.length;
const NETWORK_RULE_EXCEPTION_MARKER = '@@';
const NETWORK_RULE_EXCEPTION_MARKER_LEN = NETWORK_RULE_EXCEPTION_MARKER.length;
const NETWORK_RULE_SEPARATOR = '$';
const AGLINT_COMMAND_PREFIX = 'aglint';
const AGLINT_CONFIG_COMMENT_MARKER = '--';
const PREPROCESSOR_MARKER = '!#';
const PREPROCESSOR_MARKER_LEN = PREPROCESSOR_MARKER.length;
const PREPROCESSOR_SEPARATOR = ' ';
const SAFARI_CB_AFFINITY = 'safari_cb_affinity';
const IF = 'if';
const INCLUDE = 'include';
const NULL = 0;
const UINT8_MAX = 255;
const UINT16_MAX = 65535;



;// ./node_modules/.pnpm/@adguard+agtree@3.0.1/node_modules/@adguard/agtree/dist/compatibility-tables/modifiers.js
/*
 * AGTree v3.0.1 (build date: Fri, 28 Feb 2025 15:31:12 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */





/**
 * @file Compatibility tables for modifiers.
 */
/**
 * Transforms the name of the modifier to a normalized form.
 * This is a special case: the noop modifier normally '_', but it can consist of any number of characters,
 * e.g. '____' is also valid. In this case, we need to normalize the name to '_'.
 *
 * @param name Modifier name to normalize.
 * @returns Normalized modifier name.
 */
const noopModifierNameNormalizer = (name) => {
    if (name.startsWith(UNDERSCORE)) {
        if (name.split(EMPTY).every((char) => char === UNDERSCORE)) {
            // in compatibility tables, we just store '_', so we need to reduce the number of underscores to 1
            // before checking the existence of the noop modifier
            return UNDERSCORE;
        }
    }
    return name;
};
/**
 * Compatibility table for modifiers.
 */
class ModifiersCompatibilityTable extends CompatibilityTableBase {
    /**
     * Creates a new instance of the compatibility table for modifiers.
     *
     * @param data Compatibility table data.
     */
    constructor(data) {
        super(data, noopModifierNameNormalizer);
    }
}
/**
 * Deep freeze the compatibility table data to avoid accidental modifications.
 */
deepFreeze(modifiersCompatibilityTableData);
/**
 * Compatibility table instance for modifiers.
 */
const modifiers_modifiersCompatibilityTable = new ModifiersCompatibilityTable(modifiersCompatibilityTableData);



// EXTERNAL MODULE: ./node_modules/.pnpm/zod@3.21.4/node_modules/zod/lib/index.mjs
var lib = __webpack_require__(69509);
;// ./node_modules/.pnpm/@adguard+agtree@3.0.1/node_modules/@adguard/agtree/dist/compatibility-tables/schemas/resource-type.js
/*
 * AGTree v3.0.1 (build date: Fri, 28 Feb 2025 15:31:12 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * @file Resource type schema.
 */
/**
 * Resource type.
 *
 * @see {@link https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#type-ResourceType}
 */
const resource_type_ResourceType = {
    MainFrame: 'main_frame',
    SubFrame: 'sub_frame',
    Stylesheet: 'stylesheet',
    Script: 'script',
    Image: 'image',
    Font: 'font',
    Object: 'object',
    XmlHttpRequest: 'xmlhttprequest',
    Ping: 'ping',
    Media: 'media',
    WebSocket: 'websocket',
    Other: 'other',
};
/**
 * Resource type schema.
 */
const resourceTypeSchema = lib/* default.nativeEnum */.Ay.nativeEnum(resource_type_ResourceType);



;// ./node_modules/.pnpm/@adguard+agtree@3.0.1/node_modules/@adguard/agtree/dist/compatibility-tables/utils/resource-type-helpers.js
/*
 * AGTree v3.0.1 (build date: Fri, 28 Feb 2025 15:31:12 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * Map of resource types to their corresponding adblock modifier names.
 *
 * @note Record type is used to ensure that all resource types are present in the map.
 */
const RESOURCE_TYPE_MODIFIER_MAP = Object.freeze({
    [resource_type_ResourceType.MainFrame]: 'document',
    [resource_type_ResourceType.SubFrame]: 'subdocument',
    [resource_type_ResourceType.Stylesheet]: 'stylesheet',
    [resource_type_ResourceType.Script]: 'script',
    [resource_type_ResourceType.Image]: 'image',
    [resource_type_ResourceType.Font]: 'font',
    [resource_type_ResourceType.Object]: 'object',
    [resource_type_ResourceType.XmlHttpRequest]: 'xmlhttprequest',
    [resource_type_ResourceType.Ping]: 'ping',
    [resource_type_ResourceType.Media]: 'media',
    [resource_type_ResourceType.WebSocket]: 'websocket',
    [resource_type_ResourceType.Other]: 'other',
});
/**
 * Gets the adblock modifier name for the given resource type.
 *
 * @param resourceType Resource type to get the modifier name for.
 * @param platform Platform to get the modifier for.
 *
 * @returns A string containing the adblock modifier name for the given resource type
 * or `null` if the modifier could not be found.
 */
const getResourceTypeModifier = (resourceType, platform) => {
    const modifierName = RESOURCE_TYPE_MODIFIER_MAP[resourceType];
    if (!modifierName) {
        return null;
    }
    const modifierData = modifiers_modifiersCompatibilityTable.getFirst(modifierName, platform);
    if (isNull(modifierData)) {
        return null;
    }
    return modifierData.name;
};
/**
 * Checks if the given resource type is valid.
 *
 * @param resourceType Resource type to check.
 *
 * @returns `true` if the resource type is valid, `false` otherwise.
 */
const isValidResourceType = (resourceType) => {
    return Object.values(ResourceType).includes(resourceType);
};



;// ./node_modules/.pnpm/@adguard+agtree@3.0.1/node_modules/@adguard/agtree/dist/compatibility-tables/redirects.js
/*
 * AGTree v3.0.1 (build date: Fri, 28 Feb 2025 15:31:12 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/**
 * @file Compatibility tables for redirects.
 */
/**
 * Prefix for resource redirection names.
 */
const ABP_RESOURCE_PREFIX = 'abp-resource:';
const ABP_RESOURCE_PREFIX_LENGTH = ABP_RESOURCE_PREFIX.length;
/**
 * Normalizes the redirect name.
 *
 * @param name Redirect name to normalize.
 *
 * @returns Normalized redirect name.
 *
 * @example
 * redirectNameNormalizer('abp-resource:my-resource') // => 'my-resource'
 * redirectNameNormalizer('noop.js:99') // => 'noop.js'
 */
const redirectNameNormalizer = (name) => {
    // Remove ABP resource prefix, if present
    if (name.startsWith(ABP_RESOURCE_PREFIX)) {
        return name.slice(ABP_RESOURCE_PREFIX_LENGTH);
    }
    // Remove :[integer] priority suffix from the name, if present
    // See:
    // - https://github.com/AdguardTeam/tsurlfilter/issues/59
    // - https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#redirect
    const colonIndex = name.lastIndexOf(COLON);
    if (colonIndex !== -1 && /^\d+$/.test(name.slice(colonIndex + 1))) {
        return name.slice(0, colonIndex);
    }
    return name;
};
/**
 * Compatibility table for redirects.
 */
class RedirectsCompatibilityTable extends CompatibilityTableBase {
    /**
     * Creates a new instance of the compatibility table for redirects.
     *
     * @param data Compatibility table data.
     */
    constructor(data) {
        super(data, redirectNameNormalizer);
    }
    /**
     * Gets the resource type adblock modifiers for the redirect for the given platform
     * based on the `resourceTypes` field.
     *
     * @param redirect Redirect name or redirect data.
     * @param platform Platform to get the modifiers for.
     *
     * @returns Set of resource type modifiers or an empty set if the redirect is not found or has no resource types.
     */
    getResourceTypeModifiers(redirect, platform) {
        let redirectData = null;
        if (isString(redirect)) {
            redirectData = this.getFirst(redirect, platform);
        }
        else {
            redirectData = redirect;
        }
        const modifierNames = new Set();
        if (isNull(redirectData) || isUndefined(redirectData.resourceTypes)) {
            return modifierNames;
        }
        for (const resourceType of redirectData.resourceTypes) {
            const modifierName = getResourceTypeModifier(resourceType, platform);
            if (isNull(modifierName)) {
                continue;
            }
            modifierNames.add(modifierName);
        }
        return modifierNames;
    }
}
/**
 * Deep freeze the compatibility table data to avoid accidental modifications.
 */
deepFreeze(redirectsCompatibilityTableData);
/**
 * Compatibility table instance for redirects.
 */
const redirectsCompatibilityTable = new RedirectsCompatibilityTable(redirectsCompatibilityTableData);



;// ./node_modules/.pnpm/@adguard+scriptlets@2.1.6/node_modules/@adguard/scriptlets/dist/validators/index.js












var trustedClickElementNames = [ "trusted-click-element" ];

var abortOnPropertyReadNames = [ "abort-on-property-read", "abort-on-property-read.js", "ubo-abort-on-property-read.js", "aopr.js", "ubo-aopr.js", "ubo-abort-on-property-read", "ubo-aopr", "abp-abort-on-property-read" ];

var abortOnPropertyWriteNames = [ "abort-on-property-write", "abort-on-property-write.js", "ubo-abort-on-property-write.js", "aopw.js", "ubo-aopw.js", "ubo-abort-on-property-write", "ubo-aopw", "abp-abort-on-property-write" ];

var preventSetTimeoutNames = [ "prevent-setTimeout", "no-setTimeout-if.js", "ubo-no-setTimeout-if.js", "nostif.js", "ubo-nostif.js", "ubo-no-setTimeout-if", "ubo-nostif", "setTimeout-defuser.js", "ubo-setTimeout-defuser.js", "ubo-setTimeout-defuser", "std.js", "ubo-std.js", "ubo-std" ];

var preventSetIntervalNames = [ "prevent-setInterval", "no-setInterval-if.js", "ubo-no-setInterval-if.js", "setInterval-defuser.js", "ubo-setInterval-defuser.js", "nosiif.js", "ubo-nosiif.js", "sid.js", "ubo-sid.js", "ubo-no-setInterval-if", "ubo-setInterval-defuser", "ubo-nosiif", "ubo-sid" ];

var preventWindowOpenNames = [ "prevent-window-open", "window.open-defuser.js", "ubo-window.open-defuser.js", "ubo-window.open-defuser", "nowoif.js", "ubo-nowoif.js", "ubo-nowoif", "no-window-open-if.js", "ubo-no-window-open-if.js", "ubo-no-window-open-if" ];

var abortCurrentInlineScriptNames = [ "abort-current-inline-script", "abort-current-script.js", "ubo-abort-current-script.js", "acs.js", "ubo-acs.js", "ubo-abort-current-script", "ubo-acs", "abort-current-inline-script.js", "ubo-abort-current-inline-script.js", "acis.js", "ubo-acis.js", "ubo-abort-current-inline-script", "ubo-acis", "abp-abort-current-inline-script" ];

var setConstantNames = [ "set-constant", "set-constant.js", "ubo-set-constant.js", "set.js", "ubo-set.js", "ubo-set-constant", "ubo-set", "abp-override-property-read" ];

var removeCookieNames = [ "remove-cookie", "cookie-remover.js", "ubo-cookie-remover.js", "ubo-cookie-remover", "remove-cookie.js", "ubo-remove-cookie.js", "ubo-remove-cookie", "abp-cookie-remover" ];

var preventAddEventListenerNames = [ "prevent-addEventListener", "addEventListener-defuser.js", "ubo-addEventListener-defuser.js", "aeld.js", "ubo-aeld.js", "ubo-addEventListener-defuser", "ubo-aeld", "abp-prevent-listener" ];

var preventBabNames = [ "prevent-bab" ];

var nowebrtcNames = [ "nowebrtc", "nowebrtc.js", "ubo-nowebrtc.js", "ubo-nowebrtc" ];

var logAddEventListenerNames = [ "log-addEventListener", "addEventListener-logger.js", "ubo-addEventListener-logger.js", "aell.js", "ubo-aell.js", "ubo-addEventListener-logger", "ubo-aell" ];

var logEvalNames = [ "log-eval" ];

var logNames = [ "log", "abp-log" ];

var noevalNames = [ "noeval", "noeval.js", "silent-noeval.js", "ubo-noeval.js", "ubo-silent-noeval.js", "ubo-noeval", "ubo-silent-noeval" ];

var preventEvalIfNames = [ "prevent-eval-if", "noeval-if.js", "ubo-noeval-if.js", "ubo-noeval-if" ];

var preventFabNames = [ "prevent-fab-3.2.0", "nofab.js", "ubo-nofab.js", "fuckadblock.js-3.2.0", "ubo-fuckadblock.js-3.2.0", "ubo-nofab" ];

var setPopadsDummyNames = [ "set-popads-dummy", "popads-dummy.js", "ubo-popads-dummy.js", "ubo-popads-dummy" ];

var preventPopadsNetNames = [ "prevent-popads-net", "popads.net.js", "ubo-popads.net.js", "ubo-popads.net" ];

var preventAdflyNames = [ "prevent-adfly" ];

var debugOnPropertyReadNames = [ "debug-on-property-read" ];

var debugOnPropertyWriteNames = [ "debug-on-property-write" ];

var debugCurrentInlineScriptNames = [ "debug-current-inline-script" ];

var removeAttrNames = [ "remove-attr", "remove-attr.js", "ubo-remove-attr.js", "ra.js", "ubo-ra.js", "ubo-remove-attr", "ubo-ra" ];

var setAttrNames = [ "set-attr", "set-attr.js", "ubo-set-attr.js", "ubo-set-attr" ];

var removeClassNames = [ "remove-class", "remove-class.js", "ubo-remove-class.js", "rc.js", "ubo-rc.js", "ubo-remove-class", "ubo-rc" ];

var disableNewtabLinksNames = [ "disable-newtab-links", "disable-newtab-links.js", "ubo-disable-newtab-links.js", "ubo-disable-newtab-links" ];

var adjustSetIntervalNames = [ "adjust-setInterval", "nano-setInterval-booster.js", "ubo-nano-setInterval-booster.js", "nano-sib.js", "ubo-nano-sib.js", "adjust-setInterval.js", "ubo-adjust-setInterval.js", "ubo-nano-setInterval-booster", "ubo-nano-sib", "ubo-adjust-setInterval" ];

var adjustSetTimeoutNames = [ "adjust-setTimeout", "adjust-setTimeout.js", "ubo-adjust-setTimeout.js", "nano-setTimeout-booster.js", "ubo-nano-setTimeout-booster.js", "nano-stb.js", "ubo-nano-stb.js", "ubo-adjust-setTimeout", "ubo-nano-setTimeout-booster", "ubo-nano-stb" ];

var dirStringNames = [ "dir-string" ];

var jsonPruneNames = [ "json-prune", "json-prune.js", "ubo-json-prune.js", "ubo-json-prune", "abp-json-prune" ];

var preventRequestAnimationFrameNames = [ "prevent-requestAnimationFrame", "no-requestAnimationFrame-if.js", "ubo-no-requestAnimationFrame-if.js", "norafif.js", "ubo-norafif.js", "ubo-no-requestAnimationFrame-if", "ubo-norafif" ];

var setCookieNames = [ "set-cookie", "set-cookie.js", "ubo-set-cookie.js", "ubo-set-cookie" ];

var setCookieReloadNames = [ "set-cookie-reload", "set-cookie-reload.js", "ubo-set-cookie-reload.js", "ubo-set-cookie-reload" ];

var hideInShadowDomNames = [ "hide-in-shadow-dom" ];

var removeInShadowDomNames = [ "remove-in-shadow-dom" ];

var preventFetchNames = [ "prevent-fetch", "prevent-fetch.js", "ubo-prevent-fetch.js", "ubo-prevent-fetch", "no-fetch-if.js", "ubo-no-fetch-if.js", "ubo-no-fetch-if" ];

var setLocalStorageItemNames = [ "set-local-storage-item", "set-local-storage-item.js", "ubo-set-local-storage-item.js", "ubo-set-local-storage-item" ];

var setSessionStorageItemNames = [ "set-session-storage-item", "set-session-storage-item.js", "ubo-set-session-storage-item.js", "ubo-set-session-storage-item" ];

var abortOnStackTraceNames = [ "abort-on-stack-trace", "abort-on-stack-trace.js", "ubo-abort-on-stack-trace.js", "aost.js", "ubo-aost.js", "ubo-abort-on-stack-trace", "ubo-aost", "abp-abort-on-stack-trace" ];

var logOnStackTraceNames = [ "log-on-stack-trace" ];

var preventXHRNames = [ "prevent-xhr", "no-xhr-if.js", "ubo-no-xhr-if.js", "ubo-no-xhr-if" ];

var forceWindowCloseNames = [ "close-window", "window-close-if.js", "ubo-window-close-if.js", "ubo-window-close-if", "close-window.js", "ubo-close-window.js", "ubo-close-window" ];

var preventRefreshNames = [ "prevent-refresh", "prevent-refresh.js", "refresh-defuser.js", "refresh-defuser", "ubo-prevent-refresh.js", "ubo-prevent-refresh", "ubo-refresh-defuser.js", "ubo-refresh-defuser" ];

var preventElementSrcLoadingNames = [ "prevent-element-src-loading" ];

var noTopicsNames = [ "no-topics" ];

var trustedReplaceXhrResponseNames = [ "trusted-replace-xhr-response" ];

var xmlPruneNames = [ "xml-prune", "xml-prune.js", "ubo-xml-prune.js", "ubo-xml-prune" ];

var m3uPruneNames = [ "m3u-prune", "m3u-prune.js", "ubo-m3u-prune.js", "ubo-m3u-prune" ];

var trustedSetCookieNames = [ "trusted-set-cookie" ];

var trustedSetCookieReloadNames = [ "trusted-set-cookie-reload" ];

var trustedReplaceFetchResponseNames = [ "trusted-replace-fetch-response" ];

var trustedSetLocalStorageItemNames = [ "trusted-set-local-storage-item" ];

var trustedSetSessionStorageItemNames = [ "trusted-set-session-storage-item" ];

var trustedSetConstantNames = [ "trusted-set-constant" ];

var injectCssInShadowDomNames = [ "inject-css-in-shadow-dom" ];

var removeNodeTextNames = [ "remove-node-text", "remove-node-text.js", "ubo-remove-node-text.js", "rmnt.js", "ubo-rmnt.js", "ubo-remove-node-text", "ubo-rmnt" ];

var trustedReplaceNodeTextNames = [ "trusted-replace-node-text" ];

var evalDataPruneNames = [ "evaldata-prune", "evaldata-prune.js", "ubo-evaldata-prune.js", "ubo-evaldata-prune" ];

var trustedPruneInboundObjectNames = [ "trusted-prune-inbound-object" ];

var trustedSetAttrNames = [ "trusted-set-attr" ];

var spoofCSSNames = [ "spoof-css", "spoof-css.js", "ubo-spoof-css.js", "ubo-spoof-css" ];

var callNoThrowNames = [ "call-nothrow", "call-nothrow.js", "ubo-call-nothrow.js", "ubo-call-nothrow" ];

var trustedCreateElementNames = [ "trusted-create-element" ];

var hrefSanitizerNames = [ "href-sanitizer", "href-sanitizer.js", "ubo-href-sanitizer.js", "ubo-href-sanitizer" ];

var jsonPruneFetchResponseNames = [ "json-prune-fetch-response", "json-prune-fetch-response.js", "ubo-json-prune-fetch-response.js", "ubo-json-prune-fetch-response" ];

var noProtectedAudienceNames = [ "no-protected-audience" ];

var trustedSuppressNativeMethodNames = [ "trusted-suppress-native-method" ];

var jsonPruneXhrResponseNames = [ "json-prune-xhr-response", "json-prune-xhr-response.js", "ubo-json-prune-xhr-response.js", "ubo-json-prune-xhr-response" ];

var trustedDispatchEventNames = [ "trusted-dispatch-event" ];

var trustedReplaceOutboundTextNames = [ "trusted-replace-outbound-text" ];

var preventCanvasNames = [ "prevent-canvas", "prevent-canvas.js", "ubo-prevent-canvas.js", "ubo-prevent-canvas" ];

var AmazonApstagNames = [ "amazon-apstag", "ubo-amazon_apstag.js", "amazon_apstag.js" ];

var DidomiLoaderNames = [ "didomi-loader" ];

var Fingerprintjs2Names = [ "fingerprintjs2", "ubo-fingerprint2.js", "fingerprint2.js" ];

var Fingerprintjs3Names = [ "fingerprintjs3", "ubo-fingerprint3.js", "fingerprint3.js" ];

var GemiusNames = [ "gemius" ];

var GoogleAnalyticsNames = [ "google-analytics", "ubo-google-analytics_analytics.js", "google-analytics_analytics.js", "googletagmanager-gtm", "ubo-googletagmanager_gtm.js", "googletagmanager_gtm.js" ];

var GoogleAnalyticsGaNames = [ "google-analytics-ga", "ubo-google-analytics_ga.js", "google-analytics_ga.js" ];

var GoogleIma3Names = [ "google-ima3", "ubo-google-ima.js", "google-ima.js" ];

var GoogleSyndicationAdsByGoogleNames = [ "googlesyndication-adsbygoogle", "ubo-googlesyndication_adsbygoogle.js", "googlesyndication_adsbygoogle.js" ];

var GoogleTagServicesGptNames = [ "googletagservices-gpt", "ubo-googletagservices_gpt.js", "googletagservices_gpt.js" ];

var MatomoNames = [ "matomo" ];

var metrikaYandexTagNames = [ "metrika-yandex-tag" ];

var metrikaYandexWatchNames = [ "metrika-yandex-watch" ];

var NaverWcslogNames = [ "naver-wcslog" ];

var PardotNames = [ "pardot-1.0" ];

var PrebidNames = [ "prebid" ];

var ScoreCardResearchBeaconNames = [ "scorecardresearch-beacon", "ubo-scorecardresearch_beacon.js", "scorecardresearch_beacon.js" ];

var scriptletsNamesList = Object.freeze({
    __proto__: null,
    AmazonApstagNames: AmazonApstagNames,
    DidomiLoaderNames: DidomiLoaderNames,
    Fingerprintjs2Names: Fingerprintjs2Names,
    Fingerprintjs3Names: Fingerprintjs3Names,
    GemiusNames: GemiusNames,
    GoogleAnalyticsGaNames: GoogleAnalyticsGaNames,
    GoogleAnalyticsNames: GoogleAnalyticsNames,
    GoogleIma3Names: GoogleIma3Names,
    GoogleSyndicationAdsByGoogleNames: GoogleSyndicationAdsByGoogleNames,
    GoogleTagServicesGptNames: GoogleTagServicesGptNames,
    MatomoNames: MatomoNames,
    NaverWcslogNames: NaverWcslogNames,
    PardotNames: PardotNames,
    PrebidNames: PrebidNames,
    ScoreCardResearchBeaconNames: ScoreCardResearchBeaconNames,
    abortCurrentInlineScriptNames: abortCurrentInlineScriptNames,
    abortOnPropertyReadNames: abortOnPropertyReadNames,
    abortOnPropertyWriteNames: abortOnPropertyWriteNames,
    abortOnStackTraceNames: abortOnStackTraceNames,
    adjustSetIntervalNames: adjustSetIntervalNames,
    adjustSetTimeoutNames: adjustSetTimeoutNames,
    callNoThrowNames: callNoThrowNames,
    debugCurrentInlineScriptNames: debugCurrentInlineScriptNames,
    debugOnPropertyReadNames: debugOnPropertyReadNames,
    debugOnPropertyWriteNames: debugOnPropertyWriteNames,
    dirStringNames: dirStringNames,
    disableNewtabLinksNames: disableNewtabLinksNames,
    evalDataPruneNames: evalDataPruneNames,
    forceWindowCloseNames: forceWindowCloseNames,
    hideInShadowDomNames: hideInShadowDomNames,
    hrefSanitizerNames: hrefSanitizerNames,
    injectCssInShadowDomNames: injectCssInShadowDomNames,
    jsonPruneFetchResponseNames: jsonPruneFetchResponseNames,
    jsonPruneNames: jsonPruneNames,
    jsonPruneXhrResponseNames: jsonPruneXhrResponseNames,
    logAddEventListenerNames: logAddEventListenerNames,
    logEvalNames: logEvalNames,
    logNames: logNames,
    logOnStackTraceNames: logOnStackTraceNames,
    m3uPruneNames: m3uPruneNames,
    metrikaYandexTagNames: metrikaYandexTagNames,
    metrikaYandexWatchNames: metrikaYandexWatchNames,
    noProtectedAudienceNames: noProtectedAudienceNames,
    noTopicsNames: noTopicsNames,
    noevalNames: noevalNames,
    nowebrtcNames: nowebrtcNames,
    preventAddEventListenerNames: preventAddEventListenerNames,
    preventAdflyNames: preventAdflyNames,
    preventBabNames: preventBabNames,
    preventCanvasNames: preventCanvasNames,
    preventElementSrcLoadingNames: preventElementSrcLoadingNames,
    preventEvalIfNames: preventEvalIfNames,
    preventFabNames: preventFabNames,
    preventFetchNames: preventFetchNames,
    preventPopadsNetNames: preventPopadsNetNames,
    preventRefreshNames: preventRefreshNames,
    preventRequestAnimationFrameNames: preventRequestAnimationFrameNames,
    preventSetIntervalNames: preventSetIntervalNames,
    preventSetTimeoutNames: preventSetTimeoutNames,
    preventWindowOpenNames: preventWindowOpenNames,
    preventXHRNames: preventXHRNames,
    removeAttrNames: removeAttrNames,
    removeClassNames: removeClassNames,
    removeCookieNames: removeCookieNames,
    removeInShadowDomNames: removeInShadowDomNames,
    removeNodeTextNames: removeNodeTextNames,
    setAttrNames: setAttrNames,
    setConstantNames: setConstantNames,
    setCookieNames: setCookieNames,
    setCookieReloadNames: setCookieReloadNames,
    setLocalStorageItemNames: setLocalStorageItemNames,
    setPopadsDummyNames: setPopadsDummyNames,
    setSessionStorageItemNames: setSessionStorageItemNames,
    spoofCSSNames: spoofCSSNames,
    trustedClickElementNames: trustedClickElementNames,
    trustedCreateElementNames: trustedCreateElementNames,
    trustedDispatchEventNames: trustedDispatchEventNames,
    trustedPruneInboundObjectNames: trustedPruneInboundObjectNames,
    trustedReplaceFetchResponseNames: trustedReplaceFetchResponseNames,
    trustedReplaceNodeTextNames: trustedReplaceNodeTextNames,
    trustedReplaceOutboundTextNames: trustedReplaceOutboundTextNames,
    trustedReplaceXhrResponseNames: trustedReplaceXhrResponseNames,
    trustedSetAttrNames: trustedSetAttrNames,
    trustedSetConstantNames: trustedSetConstantNames,
    trustedSetCookieNames: trustedSetCookieNames,
    trustedSetCookieReloadNames: trustedSetCookieReloadNames,
    trustedSetLocalStorageItemNames: trustedSetLocalStorageItemNames,
    trustedSetSessionStorageItemNames: trustedSetSessionStorageItemNames,
    trustedSuppressNativeMethodNames: trustedSuppressNativeMethodNames,
    xmlPruneNames: xmlPruneNames
});

function _createForOfIteratorHelper(r, e) {
    var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
    if (!t) {
        if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {
            t && (r = t);
            var _n = 0, F = function F() {};
            return {
                s: F,
                n: function n() {
                    return _n >= r.length ? {
                        done: !0
                    } : {
                        done: !1,
                        value: r[_n++]
                    };
                },
                e: function e(r) {
                    throw r;
                },
                f: F
            };
        }
        throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
    }
    var o, a = !0, u = !1;
    return {
        s: function s() {
            t = t.call(r);
        },
        n: function n() {
            var r = t.next();
            return a = r.done, r;
        },
        e: function e(r) {
            u = !0, o = r;
        },
        f: function f() {
            try {
                a || null == t.return || t.return();
            } finally {
                if (u) throw o;
            }
        }
    };
}

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;
    }
}

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;
}

var UBO_JS_SUFFIX = ".js";

var isScriptletRuleForSyntax = function isScriptletRuleForSyntax(rule, syntax) {
    try {
        var ruleNode = getRuleNode(rule);
        return ruleNode.category === RuleCategory.Cosmetic && ruleNode.type === CosmeticRuleType.ScriptletInjectionRule && ruleNode.syntax === syntax;
    } catch (e) {
        return false;
    }
};

var isAdgScriptletRule = function isAdgScriptletRule(rule) {
    return isScriptletRuleForSyntax(rule, AdblockSyntax.Adg);
};

var isUboScriptletRule = function isUboScriptletRule(rule) {
    return isScriptletRuleForSyntax(rule, AdblockSyntax.Ubo);
};

var isAbpSnippetRule = function isAbpSnippetRule(rule) {
    return isScriptletRuleForSyntax(rule, AdblockSyntax.Abp);
};

var scriptletsNamesContainer;

var getScriptletsNames = function getScriptletsNames() {
    if (scriptletsNamesContainer) {
        return scriptletsNamesContainer;
    }
    scriptletsNamesContainer = new Set;
    var names = Object.values(scriptletsNamesList).flat();
    scriptletsNamesContainer = new Set(names);
    return scriptletsNamesContainer;
};

var hasScriptlet = function hasScriptlet(name) {
    var scriptletsNames = getScriptletsNames();
    return scriptletsNames.has(name) || !name.endsWith(UBO_JS_SUFFIX) && scriptletsNames.has(`${name}${UBO_JS_SUFFIX}`);
};

var isValidScriptletNameNotCached = function isValidScriptletNameNotCached(name) {
    if (!name) {
        return false;
    }
    return hasScriptlet(name);
};

var scriptletNameValidationCache = new Map;

var isValidScriptletName = function isValidScriptletName(name) {
    if (name === "") {
        return true;
    }
    if (!name) {
        return false;
    }
    if (!scriptletNameValidationCache.has(name)) {
        var isValid = isValidScriptletNameNotCached(name);
        scriptletNameValidationCache.set(name, isValid);
        return isValid;
    }
    return scriptletNameValidationCache.get(name);
};

var isArrayOfScriptletRules = function isArrayOfScriptletRules(rules) {
    return rules.every((function(rule) {
        return rule.category === RuleCategory.Cosmetic && rule.type === CosmeticRuleType.ScriptletInjectionRule;
    }));
};

var isValidScriptletRule = function isValidScriptletRule(rule) {
    var ruleNodes;
    try {
        ruleNodes = RuleConverter.convertToAdg(getRuleNode(rule)).result;
    } catch (e) {
        return false;
    }
    if (!isArrayOfScriptletRules(ruleNodes)) {
        return false;
    }
    var isValid = ruleNodes.every((function(ruleNode) {
        var _ruleNode$body$childr;
        var name = (_ruleNode$body$childr = ruleNode.body.children[0]) === null || _ruleNode$body$childr === void 0 || (_ruleNode$body$childr = _ruleNode$body$childr.children[0]) === null || _ruleNode$body$childr === void 0 ? void 0 : _ruleNode$body$childr.value;
        if (!name) {
            return ruleNode.exception;
        }
        var unquotedName = QuoteUtils.removeQuotes(name);
        if (!unquotedName) {
            return false;
        }
        return isValidScriptletName(unquotedName);
    }));
    return isValid;
};

var POSSIBLE_REDIRECT_MODIFIERS = new Set([ "redirect", "redirect-rule", "rewrite" ]);

var getRedirectResourcesFromRule = function getRedirectResourcesFromRule(rule) {
    var result = [];
    try {
        var ruleNode = getRuleNode(rule);
        if (ruleNode.category !== RuleCategory.Network) {
            return result;
        }
        if (ruleNode.type !== NetworkRuleType.NetworkRule) {
            return result;
        }
        var ruleModifiers = ruleNode.modifiers;
        if (!ruleModifiers) {
            return result;
        }
        var _iterator = _createForOfIteratorHelper(ruleModifiers.children), _step;
        try {
            for (_iterator.s(); !(_step = _iterator.n()).done; ) {
                var el = _step.value;
                if (el.exception) {
                    continue;
                }
                if (POSSIBLE_REDIRECT_MODIFIERS.has(el.name.value)) {
                    var _el$value;
                    result.push({
                        modifier: el.name.value,
                        resource: (_el$value = el.value) === null || _el$value === void 0 ? void 0 : _el$value.value,
                        exceptionRule: ruleNode.exception
                    });
                }
            }
        } catch (err) {
            _iterator.e(err);
        } finally {
            _iterator.f();
        }
        return result;
    } catch (e) {
        return result;
    }
};

var isRedirectResourceCompatibleWithAdg = function isRedirectResourceCompatibleWithAdg(redirectName) {
    return redirectsCompatibilityTable.exists(redirectName, platforms_GenericPlatform.AdgAny);
};

var isValidAdgRedirectRule = function isValidAdgRedirectRule(rule) {
    var resources = getRedirectResourcesFromRule(rule);
    if (!resources.length || resources.length > 1) {
        return false;
    }
    var resource = resources[0];
    if (!resource.resource) {
        return resource.exceptionRule;
    }
    return modifiersCompatibilityTable.exists(resource.modifier, GenericPlatform.AdgAny) && isRedirectResourceCompatibleWithAdg(resource.resource);
};




/***/ }),

/***/ 84333:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  zV: () => (/* binding */ BufferRuleList),
  B$: () => (/* binding */ CSP_HEADER_NAME),
  YD: () => (/* binding */ CompatibilityTypes),
  jw: () => (/* binding */ CosmeticResult),
  N$: () => (/* binding */ Engine),
  aQ: () => (/* binding */ FilterListPreprocessor),
  iR: () => (/* binding */ NetworkRuleOption),
  iw: () => (/* binding */ PERMISSIONS_POLICY_HEADER_NAME),
  JX: () => (/* binding */ RULE_INDEX_NONE),
  Kd: () => (/* binding */ Request),
  Vf: () => (/* binding */ RuleFactory),
  _6: () => (/* binding */ RuleStorage),
  Tl: () => (/* binding */ RuleSyntaxUtils),
  _L: () => (/* binding */ StealthOptionName),
  e_: () => (/* binding */ TSURLFILTER_VERSION),
  kn: () => (/* binding */ createAllowlistRuleList),
  tF: () => (/* binding */ fetchExtensionResourceText),
  B8: () => (/* binding */ filterListChunksValidator),
  kA: () => (/* binding */ filterListSourceMapValidator),
  gx: () => (/* binding */ getRuleSourceIndex),
  Bv: () => (/* binding */ getRuleSourceText),
  gC: () => (/* binding */ preprocessedFilterListValidator),
  xN: () => (/* binding */ setConfiguration)
});

// UNUSED EXPORTS: CookieModifier, CosmeticEngine, CosmeticOption, CosmeticRule, DnsEngine, DnsResult, HTTPMethod, HostRule, IndexedRule, IndexedStorageRule, LIST_ID_MAX_VALUE, MatchingResult, NETWORK_RULE_OPTIONS, NetworkEngine, NetworkRule, NetworkRuleGroupOptions, OPTIONS_DELIMITER, PREPROCESSOR_AGTREE_OPTIONS, RemoveHeaderModifier, RemoveParamModifier, ReplaceModifier, RequestType, STEALTH_MODE_FILTER_ID, SimpleRegex, cleanUrlParamByRegExp, config, countEnabledBits, fastHash, fastHash31, filterListConversionMapValidator, findNextLineBreakIndex, findNextUnescapedIndex, getBitCount, getIdFromFilterName, getRelativeUrl, hasSpaces, hasUnquotedSubstring, indexOfAny, isAlpha, isAlphaNumeric, isCompatibleWith, isHttpOrWsRequest, isNumber, isString, logger, replaceAll, setLogger, splitByDelimiterWithEscapeCharacter, startsAtIndexWith, stringArraysEquals, stringArraysHaveIntersection, unescapeChar

// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/constants.js
var constants = __webpack_require__(65523);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/quotes.js
var quotes = __webpack_require__(8725);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/domain.js
var utils_domain = __webpack_require__(35508);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/nodes/index.js
var nodes = __webpack_require__(64638);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/cosmetic-rule-separator.js
var cosmetic_rule_separator = __webpack_require__(90692);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/binary-schema-version.js
var binary_schema_version = __webpack_require__(63396);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/byte-buffer.js
var byte_buffer = __webpack_require__(96489);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/is-chromium.js
var is_chromium = __webpack_require__(13753);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/text-encoder-polyfill.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */
/* eslint-disable no-param-reassign */
/* eslint-disable no-bitwise */
/**
 * @file Utility for encoding strings to byte sequences.
 */
/**
 * Checks if the given code point is an ASCII code point.
 *
 * @param codePoint Code point to check.
 * @returns `true` if the given code point is an ASCII code point, `false` otherwise.
 * @see {@link https://infra.spec.whatwg.org/#ascii-code-point}
 */
const isAsciiCodePoint = (codePoint) => {
    return codePoint >= 0x0000 && codePoint <= 0x007F;
};
const OFFSETS = [0xC0, 0xE0, 0xF0];
/**
 * Encodes an UTF-8 string into a byte sequence according to the WHATWG spec.
 *
 * @param str String to encode.
 * @param buffer Buffer to write the encoded bytes to.
 * @returns Number of bytes written to the buffer.
 * @see {@link https://encoding.spec.whatwg.org/#utf-8-encoder}
 * @note Bytes written maybe larger than the string length, but never smaller.
 * For example, the string '你好' has a length of 2, but its byte representation has a length of 6.
 */
const encodeIntoPolyfill = (str, buffer) => {
    const { length } = buffer;
    let read = 0;
    let written = 0;
    for (let i = 0; i < str.length;) {
        const codePoint = str.codePointAt(i) || 0;
        let bytesNeeded = 1;
        if (isAsciiCodePoint(codePoint)) {
            if (written >= length)
                break; // Stop if no space in buffer
            buffer[written] = codePoint;
            written += 1;
            read += 1; // Increment read for ASCII
            i += 1;
        }
        else {
            if (codePoint >= 0x0080 && codePoint <= 0x07FF) {
                bytesNeeded = 2;
            }
            else if (codePoint >= 0x0800 && codePoint <= 0xFFFF) {
                bytesNeeded = 3;
            }
            else if (codePoint >= 0x10000 && codePoint <= 0x10FFFF) {
                bytesNeeded = 4;
            }
            if (written + bytesNeeded - 1 >= length) {
                // Stop if no space for the whole encoding
                break;
            }
            let count = bytesNeeded - 1;
            const offset = OFFSETS[bytesNeeded - 2];
            buffer[written] = (codePoint >> (6 * count)) + offset;
            written += 1;
            while (count > 0) {
                buffer[written] = 0x80 | ((codePoint >> (6 * (count - 1))) & 0x3F);
                written += 1;
                count -= 1;
            }
            read += codePoint >= 0x10000 ? 2 : 1; // Increment read by 1 or 2 depending on code point
            i += codePoint >= 0x10000 ? 2 : 1; // Move i by 1 or 2
        }
    }
    return { read, written };
};



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/output-byte-buffer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */





/* eslint-disable no-plusplus */
/* eslint-disable no-bitwise */
/**
 * @file Output byte buffer for writing binary data.
 */
/**
 * Output byte buffer for writing binary data.
 *
 * @note Internally, this class uses a {@link ByteBuffer} instance, just providing a convenient API for reading data.
 */
class OutputByteBuffer extends byte_buffer/* ByteBuffer */.$ {
    /**
     * Current offset in the buffer for writing.
     */
    offset;
    /**
     * Size of the shared buffer for encoding strings in bytes.
     * This is a divisor of ByteBuffer.CHUNK_SIZE and experience shows that this value works optimally.
     * This is sufficient for most strings that occur in filter lists (we checked average string length in popular
     * filter lists).
     */
    static ENCODER_BUFFER_SIZE = 8192;
    /**
     * Length threshold for using a shared buffer for encoding strings.
     * This temp buffer is needed because we write the short strings in it
     * (so there is no need to constantly allocate a new buffer).
     * The reason for dividing ENCODER_BUFFER_SIZE by 4 is to ensure that the encoded string fits in the buffer,
     * if we also take into account the worst possible case (each character is encoded with 4 bytes).
     */
    static SHORT_STRING_THRESHOLD = 2048; // 8192 / 4
    /**
     * Represents the maximum value that can be written as a 'storage optimized' unsigned integer.
     * 0x1FFFFFFF means 29 bits — 32 bits minus 3 bits — because the last bit in each byte is a flag indicating
     * if there are more bytes (except for the last byte).
     */
    static MAX_OPTIMIZED_UINT = 0x1FFFFFFF;
    /**
     * Shared buffer for encoding strings.
     */
    sharedBuffer;
    /**
     * Shared native encoder for encoding strings.
     */
    sharedNativeEncoder;
    /**
     * Flag indicating if the current environment is Chromium.
     * This is used for performance optimizations, because Chromium's TextEncoder/TextDecoder has a relatively
     * large marshalling overhead for small strings.
     */
    isChromium;
    /**
     * Constructs a new OutputByteBuffer instance.
     */
    // TODO: add chunks as a parameter, if ever needed
    constructor() {
        super();
        this.sharedBuffer = new Uint8Array(OutputByteBuffer.ENCODER_BUFFER_SIZE);
        this.sharedNativeEncoder = new TextEncoder();
        this.isChromium = (0,is_chromium/* isChromium */.F)();
        // write the schema version at the beginning of the buffer
        this.writeUint32ToIndex(binary_schema_version/* BINARY_SCHEMA_VERSION */.T, 0);
        this.offset = 4; // schema version is already written
    }
    /**
     * Writes a 8-bit unsigned integer to the buffer.
     *
     * @param value Value to write.
     * @returns Number of bytes written to the buffer.
     */
    writeUint8(value) {
        this.writeByte(this.offset++, value);
        return 1;
    }
    /**
     * Writes a 16-bit unsigned integer to the buffer.
     *
     * @param value Value to write.
     * @returns Number of bytes written to the buffer.
     */
    writeUint16(value) {
        this.writeByte(this.offset++, value >> 8);
        this.writeByte(this.offset++, value);
        return 2;
    }
    /**
     * Writes a 32-bit unsigned integer to the buffer at a specific index.
     *
     * @param value Value to write.
     * @param index Index to write the value to.
     * @returns Number of bytes written to the buffer.
     */
    writeUint32ToIndex(value, index) {
        this.writeByte(index, value >> 24);
        this.writeByte(index + 1, value >> 16);
        this.writeByte(index + 2, value >> 8);
        this.writeByte(index + 3, value);
        return 4;
    }
    /**
     * Writes a 32-bit unsigned integer to the buffer.
     *
     * @param value Value to write.
     * @returns Number of bytes written to the buffer.
     */
    writeUint32(value) {
        this.writeUint32ToIndex(value, this.offset);
        this.offset += 4;
        return 4;
    }
    /**
     * Writes a 32-bit signed integer to the buffer.
     *
     * @param value Value to write.
     * @returns Number of bytes written to the buffer.
     */
    writeInt32(value) {
        return this.writeUint32(value ? value >>> 0 : 0);
    }
    /**
     * Writes a Uint8Array to the byte buffer.
     *
     * @param buffer Buffer to write.
     */
    writeBuffer(buffer) {
        const { length } = buffer;
        this.ensureCapacity(this.offset + length);
        let chunkIndex = this.offset >>> 0x000F;
        let chunkOffset = this.offset & 0x7FFF;
        let remainingBytes = length;
        while (remainingBytes) {
            const leftInChunk = byte_buffer/* ByteBuffer */.$.CHUNK_SIZE - chunkOffset;
            const bytesToWrite = Math.min(remainingBytes, leftInChunk);
            this.chunks[chunkIndex].set(buffer.subarray(length - remainingBytes, length - remainingBytes + bytesToWrite), chunkOffset);
            remainingBytes -= bytesToWrite;
            chunkIndex += 1;
            chunkOffset = 0;
        }
    }
    /**
     * Writes a string to the buffer.
     *
     * @param value Value to write.
     * @returns Number of bytes written to the buffer.
     */
    writeString(value) {
        const start = this.offset;
        if (value.length <= OutputByteBuffer.SHORT_STRING_THRESHOLD) {
            let bytesWritten;
            if (this.isChromium) {
                bytesWritten = encodeIntoPolyfill(value, this.sharedBuffer).written ?? 0;
            }
            else {
                bytesWritten = this.sharedNativeEncoder.encodeInto(value, this.sharedBuffer).written ?? 0;
            }
            this.writeOptimizedUint(bytesWritten);
            this.writeBuffer(this.sharedBuffer.subarray(0, bytesWritten));
            this.offset += bytesWritten;
            return this.offset - start;
        }
        // TODO: Optimize for long strings, if needed. Not a common case for our use case
        const buffer = this.sharedNativeEncoder.encode(value);
        const bytesWritten = buffer.length;
        this.writeOptimizedUint(bytesWritten);
        this.writeBuffer(buffer);
        this.offset += bytesWritten;
        return this.offset - start;
    }
    /**
     * Writes chunks to the storage.
     *
     * @param storage Storage to write the chunks to.
     * @param key Key to write the chunks to.
     * @note For performance reasons, chunks are passed by reference and not copied.
     * @throws If the storage write operation throws.
     */
    async writeChunksToStorage(storage, key) {
        await storage.set(key, this.chunks);
    }
    /**
     * Writes an 'optimized' unsigned integer to the buffer.
     * 'Optimized' means smaller storage usage for smaller numbers.
     * Except for the last byte, each byte's most significant bit is a flag indicating if there are more bytes.
     *
     * @param value Value to write.
     * @returns Number of bytes written to the buffer.
     * @throws If the value exceeds the 29-bit limit.
     */
    writeOptimizedUint(value) {
        if (value < 0 || value > OutputByteBuffer.MAX_OPTIMIZED_UINT) {
            throw new Error('Value exceeds 29-bit limit');
        }
        let remainingValue = value;
        const startOffset = this.offset;
        while (remainingValue >= 0x80) {
            const byteValue = remainingValue & 0x7F;
            remainingValue >>>= 7;
            this.writeByte(this.offset++, byteValue | 0x80);
        }
        this.writeByte(this.offset++, remainingValue);
        return this.offset - startOffset;
    }
    /**
     * Gets the current offset in the buffer for writing.
     *
     * @returns Current offset in the buffer for writing.
     */
    get currentOffset() {
        return this.offset;
    }
    /**
     * Gets the chunks of the buffer.
     *
     * @returns Chunks of the buffer.
     */
    getChunks() {
        return this.chunks;
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/tldts@5.7.112/node_modules/tldts/dist/es6/index.js + 12 modules
var es6 = __webpack_require__(13548);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/misc/domain-list-parser.js + 1 modules
var domain_list_parser = __webpack_require__(26571);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/options.js
var options = __webpack_require__(56928);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/rule-parser.js + 21 modules
var rule_parser = __webpack_require__(58660);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+tsurlfilter@3.3.3_@adguard+re2-wasm@1.2.0/node_modules/@adguard/tsurlfilter/dist/es/simple-regex-Dw3J24Ss.js
var simple_regex_Dw3J24Ss = __webpack_require__(12389);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+scriptlets@2.1.6/node_modules/@adguard/scriptlets/dist/scriptlets/index.js
var scriptlets = __webpack_require__(3030);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+scriptlets@2.1.6/node_modules/@adguard/scriptlets/dist/validators/index.js + 12 modules
var validators = __webpack_require__(66448);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/cosmetic/cosmetic-rule-body-generator.js + 4 modules
var cosmetic_rule_body_generator = __webpack_require__(98442);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/rule-generator.js + 18 modules
var rule_generator = __webpack_require__(48094);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+css-tokenizer@1.2.0/node_modules/@adguard/css-tokenizer/dist/csstokenizer.mjs
var csstokenizer = __webpack_require__(25651);
// EXTERNAL MODULE: ./node_modules/.pnpm/zod@3.24.4/node_modules/zod/lib/index.mjs
var lib = __webpack_require__(3290);
// EXTERNAL MODULE: ./node_modules/.pnpm/zod-validation-error@3.4.0_zod@3.24.4/node_modules/zod-validation-error/dist/index.mjs
var dist = __webpack_require__(93300);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+tsurlfilter@3.3.3_@adguard+re2-wasm@1.2.0/node_modules/@adguard/tsurlfilter/dist/es/network-rule-options.js
var network_rule_options = __webpack_require__(95892);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+tsurlfilter@3.3.3_@adguard+re2-wasm@1.2.0/node_modules/@adguard/tsurlfilter/dist/es/request-type.js
var request_type = __webpack_require__(55712);
// EXTERNAL MODULE: ./node_modules/.pnpm/is-cidr@4.0.2/node_modules/is-cidr/index.js
var is_cidr = __webpack_require__(32537);
// EXTERNAL MODULE: ./node_modules/.pnpm/is-ip@3.1.0/node_modules/is-ip/index.js
var is_ip = __webpack_require__(85183);
// EXTERNAL MODULE: ./node_modules/.pnpm/cidr-tools@6.4.2/node_modules/cidr-tools/index.js + 3 modules
var cidr_tools = __webpack_require__(47562);
// EXTERNAL MODULE: ./node_modules/.pnpm/lru-cache@11.0.2/node_modules/lru-cache/dist/esm/index.js
var esm = __webpack_require__(38037);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/adblockers.js
var adblockers = __webpack_require__(88226);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/input-byte-buffer.js + 2 modules
var input_byte_buffer = __webpack_require__(35629);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/rule-deserializer.js + 32 modules
var rule_deserializer = __webpack_require__(97907);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/converter/rule.js + 33 modules
var rule = __webpack_require__(87363);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/base-serializer.js
var base_serializer = __webpack_require__(54349);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/type-guards.js
var type_guards = __webpack_require__(30239);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/misc/value-common.js
var value_common = __webpack_require__(34097);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/misc/binary-type-common.js
var binary_type_common = __webpack_require__(16318);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/misc/value-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */






/**
 * Value serializer.
 */
class ValueSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a value node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     * @param frequentValuesMap Optional map of frequent values.
     * @param toLower Whether to lowercase the value before the frequent value match (defaults to `false`).
     */
    static serialize(node, buffer, frequentValuesMap, toLower = false) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ValueNode);
        const frequentValue = frequentValuesMap?.get(toLower ? node.value.toLowerCase() : node.value);
        // note: do not use just `if (frequentValue)` because it can be 0
        if (!(0,type_guards/* isUndefined */.b0)(frequentValue)) {
            buffer.writeUint8(value_common/* ValueNodeMarshallingMap */.e.FrequentValue);
            buffer.writeUint8(frequentValue);
        }
        else {
            buffer.writeUint8(value_common/* ValueNodeMarshallingMap */.e.Value);
            buffer.writeString(node.value);
        }
        // note: do not use just `if (node.start)` because it can be 0
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(value_common/* ValueNodeMarshallingMap */.e.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(value_common/* ValueNodeMarshallingMap */.e.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/comment/agent-common.js
var agent_common = __webpack_require__(86186);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/comment/agent-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/**
 * Value map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
let frequentAgentsSerializationMap;
const getFrequentAgentsSerializationMap = () => {
    if (!frequentAgentsSerializationMap) {
        frequentAgentsSerializationMap = new Map(Array.from(agent_common/* FREQUENT_AGENTS_DESERIALIZATION_MAP */.h).map(([key, value]) => [value.toLowerCase(), key]));
    }
    return frequentAgentsSerializationMap;
};
/**
 * `AgentSerializer` is responsible for serializing single adblock agent elements into a binary format.
 */
class AgentSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes an agent node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    static serialize(node, buffer) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.AgentNode);
        buffer.writeUint8(agent_common/* AgentNodeMarshallingMap */.o.Adblock);
        ValueSerializer.serialize(node.adblock, buffer, getFrequentAgentsSerializationMap(), true);
        if (!(0,type_guards/* isUndefined */.b0)(node.version)) {
            buffer.writeUint8(agent_common/* AgentNodeMarshallingMap */.o.Version);
            ValueSerializer.serialize(node.version, buffer);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(agent_common/* AgentNodeMarshallingMap */.o.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(agent_common/* AgentNodeMarshallingMap */.o.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/comment/agent-comment-common.js
var agent_comment_common = __webpack_require__(72778);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/comment/agent-comment-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/**
 * `AgentCommentSerializer` is responsible for serializing an Adblock agent comments.
 * Adblock agent comment marks that the filter list is supposed to
 * be used by the specified ad blockers.
 *
 * @example
 *  - ```adblock
 *    [AdGuard]
 *    ```
 *  - ```adblock
 *    [Adblock Plus 2.0]
 *    ```
 *  - ```adblock
 *    [uBlock Origin]
 *    ```
 *  - ```adblock
 *    [uBlock Origin 1.45.3]
 *    ```
 *  - ```adblock
 *    [Adblock Plus 2.0; AdGuard]
 *    ```
 */
class AgentCommentSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes an adblock agent list node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    // TODO: add support for raws, if ever needed
    static serialize(node, buffer) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.AgentRuleNode);
        const count = node.children.length;
        // If there are no children, we do not write any data related to them, to avoid using unnecessary storage,
        // but children is a required field, so during deserialization we should initialize it as an empty array,
        // if there are no children in the binary data.
        if (count) {
            buffer.writeUint8(agent_comment_common/* AgentCommentMarshallingMap */.j.Children);
            // note: we store the count, because re-construction of the array is faster if we know the length
            // 8 bits is more than enough here
            if (count > constants/* UINT8_MAX */.II) {
                throw new Error(`Too many children: ${count}, the limit is ${constants/* UINT8_MAX */.II}`);
            }
            buffer.writeUint8(count);
            for (let i = 0; i < count; i += 1) {
                AgentSerializer.serialize(node.children[i], buffer);
            }
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(agent_comment_common/* AgentCommentMarshallingMap */.j.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(agent_comment_common/* AgentCommentMarshallingMap */.j.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/misc/parameter-list-common.js
var parameter_list_common = __webpack_require__(12974);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/misc/parameter-list-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/**
 * Serializer for parameter list nodes.
 */
class ParameterListSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a parameter list node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     * @param frequentValuesMap Optional map of frequent values.
     * @param toLower Whether to lowercase the value before the frequent value match (defaults to `false`).
     */
    static serialize(node, buffer, frequentValuesMap, toLower = false) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ParameterListNode);
        const count = node.children.length;
        buffer.writeUint8(parameter_list_common/* ParameterListNodeMarshallingMap */._.Children);
        // note: we store the count, because re-construction of the array is faster if we know the length
        buffer.writeUint32(count);
        for (let i = 0; i < count; i += 1) {
            const child = node.children[i];
            if ((0,type_guards/* isNull */.kZ)(child)) {
                buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.Null);
                continue;
            }
            ValueSerializer.serialize(child, buffer, frequentValuesMap, toLower);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(parameter_list_common/* ParameterListNodeMarshallingMap */._.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(parameter_list_common/* ParameterListNodeMarshallingMap */._.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/comment/config-comment-common.js
var config_comment_common = __webpack_require__(92687);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/comment/config-comment-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */








/**
 * `ConfigCommentSerializer` is responsible for serializing inline AGLint configuration rules into a binary format.
 * Generally, the idea is inspired by ESLint inline configuration comments.
 *
 * @see {@link https://eslint.org/docs/latest/user-guide/configuring/rules#using-configuration-comments}
 */
class ConfigCommentSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a config node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    static serializeConfigNode(node, buffer) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ConfigNode);
        buffer.writeUint8(config_comment_common/* ConfigNodeMarshallingMap */.H4.Value);
        // note: we don't support serializing generic objects, only AGTree nodes
        // this is a very special case, so we just stringify the configuration object
        buffer.writeString(JSON.stringify(node.value));
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(config_comment_common/* ConfigNodeMarshallingMap */.H4.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(config_comment_common/* ConfigNodeMarshallingMap */.H4.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
    /**
     * Serializes a metadata comment node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    // TODO: add support for raws, if ever needed
    static serialize(node, buffer) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ConfigCommentRuleNode);
        buffer.writeUint8(config_comment_common/* ConfigCommentRuleMarshallingMap */.E0.Marker);
        ValueSerializer.serialize(node.marker, buffer);
        buffer.writeUint8(config_comment_common/* ConfigCommentRuleMarshallingMap */.E0.Command);
        ValueSerializer.serialize(node.command, buffer, config_comment_common/* FREQUENT_COMMANDS_SERIALIZATION_MAP */.O6, true);
        if (!(0,type_guards/* isUndefined */.b0)(node.params)) {
            buffer.writeUint8(config_comment_common/* ConfigCommentRuleMarshallingMap */.E0.Params);
            if (node.params.type === 'ParameterList') {
                ParameterListSerializer.serialize(node.params, buffer);
            }
            else {
                ConfigCommentSerializer.serializeConfigNode(node.params, buffer);
            }
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.comment)) {
            buffer.writeUint8(config_comment_common/* ConfigCommentRuleMarshallingMap */.E0.Comment);
            ValueSerializer.serialize(node.comment, buffer);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(config_comment_common/* ConfigCommentRuleMarshallingMap */.E0.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(config_comment_common/* ConfigCommentRuleMarshallingMap */.E0.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/comment/hint-common.js
var hint_common = __webpack_require__(99490);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/comment/hint-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */








/**
 * `HintSerializer` is responsible for serializing AdGuard hints.
 *
 * @example
 * If the hint rule is
 * ```adblock
 * !+ NOT_OPTIMIZED PLATFORM(windows)
 * ```
 * then the hints are `NOT_OPTIMIZED` and `PLATFORM(windows)`, and this
 * class is responsible for parsing them. The rule itself is parsed by
 * the `HintRuleParser`, which uses this class to parse single hints.
 */
class HintSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a hint node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    static serialize(node, buffer) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.HintNode);
        buffer.writeUint8(hint_common/* HintNodeMarshallingMap */.ae.Name);
        ValueSerializer.serialize(node.name, buffer, hint_common/* FREQUENT_HINTS_SERIALIZATION_MAP */.EX);
        if (!(0,type_guards/* isUndefined */.b0)(node.params)) {
            buffer.writeUint8(hint_common/* HintNodeMarshallingMap */.ae.Params);
            ParameterListSerializer.serialize(node.params, buffer, hint_common/* FREQUENT_PLATFORMS_SERIALIZATION_MAP */.QE);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(hint_common/* HintNodeMarshallingMap */.ae.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(hint_common/* HintNodeMarshallingMap */.ae.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/comment/hint-comment-common.js
var hint_comment_common = __webpack_require__(55762);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/syntax-serialization-map.js
var syntax_serialization_map = __webpack_require__(74252);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/comment/hint-comment-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */









/**
 * `HintCommentSerializer` is responsible for serializing AdGuard hint rules.
 *
 * @example
 * The following hint rule
 * ```adblock
 * !+ NOT_OPTIMIZED PLATFORM(windows)
 * ```
 * contains two hints: `NOT_OPTIMIZED` and `PLATFORM`.
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#hints}
 */
class HintCommentSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a hint rule node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    // TODO: add support for raws, if ever needed
    static serialize(node, buffer) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.HintRuleNode);
        if (node.syntax === adblockers/* AdblockSyntax */.Y.Adg) {
            buffer.writeUint8(hint_comment_common/* HintCommentMarshallingMap */.r.Syntax);
            buffer.writeUint8((0,syntax_serialization_map/* getSyntaxSerializationMap */.M)().get(adblockers/* AdblockSyntax */.Y.Adg) ?? 0);
        }
        const count = node.children.length;
        // If there are no children, we do not write any data related to them, to avoid using unnecessary storage,
        // but children is a required field, so during deserialization we should initialize it as an empty array,
        // if there are no children in the binary data.
        if (count) {
            buffer.writeUint8(hint_comment_common/* HintCommentMarshallingMap */.r.Children);
            // note: we store the count, because re-construction of the array is faster if we know the length
            buffer.writeUint8(count);
            for (let i = 0; i < count; i += 1) {
                HintSerializer.serialize(node.children[i], buffer);
            }
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(hint_comment_common/* HintCommentMarshallingMap */.r.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(hint_comment_common/* HintCommentMarshallingMap */.r.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/comment/metadata-comment-common.js
var metadata_comment_common = __webpack_require__(89990);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/comment/metadata-comment-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/**
 * Value map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 * @note This map is generated from `FREQUENT_HEADERS_DESERIALIZATION_MAP` to keep uppercase characters
 * while deserializing.
 */
let frequentHeadersSerializationMap;
const getFrequentHeadersSerializationMap = () => {
    if (!frequentHeadersSerializationMap) {
        frequentHeadersSerializationMap = new Map(Array.from(metadata_comment_common/* FREQUENT_HEADERS_DESERIALIZATION_MAP */.l.entries())
            .map(([key, value]) => [value.toLowerCase(), key]));
    }
    return frequentHeadersSerializationMap;
};
/**
 * `MetadataCommentSerializer` is responsible for serializing metadata comments.
 * Metadata comments are special comments that specify some properties of the list.
 *
 * @example
 * For example, in the case of
 * ```adblock
 * ! Title: My List
 * ```
 * the name of the header is `Title`, and the value is `My List`, which means that
 * the list title is `My List`, and it can be used in the adblocker UI.
 * @see {@link https://help.eyeo.com/adblockplus/how-to-write-filters#special-comments}
 */
class MetadataCommentSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a metadata comment node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    // TODO: add support for raws, if ever needed
    static serialize(node, buffer) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.MetadataCommentRuleNode);
        buffer.writeUint8(metadata_comment_common/* MetadataCommentMarshallingMap */.Z.Marker);
        ValueSerializer.serialize(node.marker, buffer);
        buffer.writeUint8(metadata_comment_common/* MetadataCommentMarshallingMap */.Z.Header);
        ValueSerializer.serialize(node.header, buffer, getFrequentHeadersSerializationMap(), true);
        buffer.writeUint8(metadata_comment_common/* MetadataCommentMarshallingMap */.Z.Value);
        ValueSerializer.serialize(node.value, buffer);
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(metadata_comment_common/* MetadataCommentMarshallingMap */.Z.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(metadata_comment_common/* MetadataCommentMarshallingMap */.Z.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/misc/logical-expression-serializer.js
var logical_expression_serializer = __webpack_require__(58421);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/comment/pre-processor-comment-common.js
var pre_processor_comment_common = __webpack_require__(20805);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/comment/pre-processor-comment-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */










/**
 * `PreProcessorSerializer` is responsible for serializing preprocessor rules.
 * Pre-processor comments are special comments that are used to control the behavior of the filter list processor.
 * Please note that this parser only handles general syntax for now, and does not validate the parameters at
 * the parsing stage.
 *
 * @example
 * If your rule is
 * ```adblock
 * !#if (adguard)
 * ```
 * then the directive's name is `if` and its value is `(adguard)`, but the parameter list
 * is not parsed / validated further.
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#pre-processor-directives}
 * @see {@link https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#pre-parsing-directives}
 */
class PreProcessorCommentSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a pre-processor comment node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    // TODO: add support for raws, if ever needed
    static serialize(node, buffer) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.PreProcessorCommentRuleNode);
        buffer.writeUint8(pre_processor_comment_common/* PreProcessorRuleMarshallingMap */.Qz.Name);
        ValueSerializer.serialize(node.name, buffer, pre_processor_comment_common/* FREQUENT_DIRECTIVES_SERIALIZATION_MAP */.u_);
        buffer.writeUint8(pre_processor_comment_common/* PreProcessorRuleMarshallingMap */.Qz.Syntax);
        buffer.writeUint8((0,syntax_serialization_map/* getSyntaxSerializationMap */.M)().get(node.syntax) ?? 0);
        if (!(0,type_guards/* isUndefined */.b0)(node.params)) {
            buffer.writeUint8(pre_processor_comment_common/* PreProcessorRuleMarshallingMap */.Qz.Params);
            if (node.params.type === 'Value') {
                ValueSerializer.serialize(node.params, buffer);
            }
            else if (node.params.type === 'ParameterList') {
                ParameterListSerializer.serialize(node.params, buffer, pre_processor_comment_common/* FREQUENT_PARAMS_SERIALIZATION_MAP */.k7, true);
            }
            else {
                logical_expression_serializer/* LogicalExpressionSerializer */.y.serialize(node.params, buffer);
            }
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(pre_processor_comment_common/* PreProcessorRuleMarshallingMap */.Qz.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(pre_processor_comment_common/* PreProcessorRuleMarshallingMap */.Qz.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/comment/simple-comment-common.js
var simple_comment_common = __webpack_require__(25331);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/comment/simple-comment-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/**
 * `SimpleCommentSerializer` is responsible for serializing simple comments.
 * Some comments have a special meaning in adblock syntax, like agent comments or hints,
 * but this serializer is only responsible for serializing regular comments,
 * whose only purpose is to provide some human-readable information.
 *
 * @example
 * ```adblock
 * ! This is a simple comment
 * # This is a simple comment, but in host-like syntax
 * ```
 */
class SimpleCommentSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a simple comment rule node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    // TODO: add support for raws, if ever needed
    static serialize(node, buffer) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.CommentRuleNode);
        buffer.writeUint8(simple_comment_common/* SimpleCommentMarshallingMap */.i.Marker);
        ValueSerializer.serialize(node.marker, buffer);
        buffer.writeUint8(simple_comment_common/* SimpleCommentMarshallingMap */.i.Text);
        ValueSerializer.serialize(node.text, buffer);
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(simple_comment_common/* SimpleCommentMarshallingMap */.i.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(simple_comment_common/* SimpleCommentMarshallingMap */.i.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/comment/comment-rule-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */









/**
 * `CommentRuleSerializer` is responsible for serializing any comment-like adblock rules.
 *
 * @example
 * Example rules:
 *  - Adblock agent rules:
 *      - ```adblock
 *        [AdGuard]
 *        ```
 *      - ```adblock
 *        [Adblock Plus 2.0]
 *        ```
 *      - etc.
 *  - AdGuard hint rules:
 *      - ```adblock
 *        !+ NOT_OPTIMIZED
 *        ```
 *      - ```adblock
 *        !+ NOT_OPTIMIZED PLATFORM(windows)
 *        ```
 *      - etc.
 *  - Pre-processor rules:
 *      - ```adblock
 *        !#if (adguard)
 *        ```
 *      - ```adblock
 *        !#endif
 *        ```
 *      - etc.
 *  - Metadata rules:
 *      - ```adblock
 *        ! Title: My List
 *        ```
 *      - ```adblock
 *        ! Version: 2.0.150
 *        ```
 *      - etc.
 *  - AGLint inline config rules:
 *      - ```adblock
 *        ! aglint-enable some-rule
 *        ```
 *      - ```adblock
 *        ! aglint-disable some-rule
 *        ```
 *      - etc.
 *  - Simple comments:
 *      - Regular version:
 *        ```adblock
 *        ! This is just a comment
 *        ```
 *      - uBlock Origin / "hostlist" version:
 *        ```adblock
 *        # This is just a comment
 *        ```
 *      - etc.
 */
class CommentRuleSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a comment rule node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    static serialize(node, buffer) {
        switch (node.type) {
            case nodes/* CommentRuleType */.gV.AgentCommentRule:
                AgentCommentSerializer.serialize(node, buffer);
                return;
            case nodes/* CommentRuleType */.gV.HintCommentRule:
                HintCommentSerializer.serialize(node, buffer);
                return;
            case nodes/* CommentRuleType */.gV.PreProcessorCommentRule:
                PreProcessorCommentSerializer.serialize(node, buffer);
                return;
            case nodes/* CommentRuleType */.gV.MetadataCommentRule:
                MetadataCommentSerializer.serialize(node, buffer);
                return;
            case nodes/* CommentRuleType */.gV.ConfigCommentRule:
                ConfigCommentSerializer.serialize(node, buffer);
                return;
            case nodes/* CommentRuleType */.gV.CommentRule:
                SimpleCommentSerializer.serialize(node, buffer);
                break;
            default:
                throw new Error('Unknown comment rule type');
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/misc/list-item-common.js
var list_item_common = __webpack_require__(80486);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/misc/list-item-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/**
 * Serializer for list item nodes.
 */
class ListItemSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a list item to binary format.
     *
     * @param item List item to serialize.
     * @param buffer Output byte buffer.
     * @template T Type of the list item.
     */
    static serialize(item, buffer) {
        switch (item.type) {
            case nodes/* ListItemNodeType */.WR.App:
                buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.AppNode);
                break;
            case nodes/* ListItemNodeType */.WR.Domain:
                buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.DomainNode);
                break;
            case nodes/* ListItemNodeType */.WR.Method:
                buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.MethodNode);
                break;
            case nodes/* ListItemNodeType */.WR.StealthOption:
                buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.StealthOptionNode);
                break;
            default:
                throw new Error(`Invalid list item type: ${item.type}`);
        }
        buffer.writeUint8(list_item_common/* ListItemMarshallingMap */.i.Exception);
        buffer.writeUint8(item.exception ? 1 : 0);
        buffer.writeUint8(list_item_common/* ListItemMarshallingMap */.i.Value);
        buffer.writeString(item.value);
        if (!(0,type_guards/* isUndefined */.b0)(item.start)) {
            buffer.writeUint8(list_item_common/* ListItemMarshallingMap */.i.Start);
            buffer.writeUint32(item.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(item.end)) {
            buffer.writeUint8(list_item_common/* ListItemMarshallingMap */.i.End);
            buffer.writeUint32(item.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/misc/list-items-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */


/**
 * Serializer for list items.
 */
class ListItemsSerializer {
    /**
     * Serializes a list of items to binary format.
     *
     * @param items List of items to serialize.
     * @param buffer Output byte buffer.
     * @template T Type of the list items.
     */
    static serialize(items, buffer) {
        const { length } = items;
        buffer.writeUint16(length);
        for (let i = 0; i < length; i += 1) {
            ListItemSerializer.serialize(items[i], buffer);
        }
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/misc/domain-list-common.js
var domain_list_common = __webpack_require__(44859);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/misc/domain-list-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/**
 * Value map for binary serialization. This helps to reduce the size of the serialized data,
 * as it allows us to use a single byte to represent frequently used values.
 *
 * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}!
 *
 * @note Only 256 values can be represented this way.
 */
const SEPARATOR_SERIALIZATION_MAP = new Map([
    [constants/* COMMA */.KE, 0],
    [constants/* PIPE */.L5, 1],
]);
/**
 * `DomainListSerializer` is responsible for serializing a domain list.
 *
 * @example
 * - If the rule is `example.com,~example.net##.ads`, the domain list is `example.com,~example.net`.
 * - If the rule is `ads.js^$script,domains=example.com|~example.org`, the domain list is `example.com|~example.org`.
 * This serializer is responsible for serializing these domain lists.
 * @see {@link https://help.eyeo.com/adblockplus/how-to-write-filters#elemhide_domains}
 */
class DomainListSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a domain list node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    static serialize(node, buffer) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.DomainListNode);
        const separator = SEPARATOR_SERIALIZATION_MAP.get(node.separator);
        if ((0,type_guards/* isUndefined */.b0)(separator)) {
            throw new Error(`Invalid separator: ${node.separator}`);
        }
        buffer.writeUint8(domain_list_common/* DomainListMarshallingMap */.T.Separator);
        buffer.writeUint8(separator);
        buffer.writeUint8(domain_list_common/* DomainListMarshallingMap */.T.Children);
        ListItemsSerializer.serialize(node.children, buffer);
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(domain_list_common/* DomainListMarshallingMap */.T.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(domain_list_common/* DomainListMarshallingMap */.T.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/cosmetic/body/abp-snippet-injection-body-common.js
var abp_snippet_injection_body_common = __webpack_require__(66604);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/cosmetic/body/scriptlet-body-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/**
 * Serializer for scriptlet injection rule body nodes.
 */
class ScriptletBodySerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a scriptlet injection rule body node into a compact binary format.
     *
     * @param node The ScriptletInjectionRuleBody node to serialize.
     * @param buffer The OutputByteBuffer used for writing the binary data.
     * @param frequentScriptletArgs An optional map of frequently used scriptlet names and their arguments,
     * along with their corresponding serialization index.
     */
    static serialize = (node, buffer, frequentScriptletArgs) => {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ScriptletInjectionRuleBodyNode);
        const { length } = node.children;
        buffer.writeUint8(abp_snippet_injection_body_common/* AbpSnippetBodyMarshallingMap */.f.Children);
        // note: we store the count, because re-construction of the array is faster if we know the length
        if (length > constants/* UINT8_MAX */.II) {
            throw new Error(`Too many scriptlet children: ${length}, the limit is ${constants/* UINT8_MAX */.II}`);
        }
        buffer.writeUint8(length);
        for (let i = 0; i < length; i += 1) {
            ParameterListSerializer.serialize(node.children[i], buffer, frequentScriptletArgs);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(abp_snippet_injection_body_common/* AbpSnippetBodyMarshallingMap */.f.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(abp_snippet_injection_body_common/* AbpSnippetBodyMarshallingMap */.f.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    };
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/cosmetic/body/abp-snippet-injection-body-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * `AbpSnippetInjectionBodySerializer` is responsible for serializing the body of an Adblock Plus-style snippet rule.
 *
 * Please note that the serializer will serialize any scriptlet rule if it is syntactically correct.
 * For example, it will serialize this:
 * ```adblock
 * example.com#$#snippet0 arg0
 * ```
 *
 * but it doesn't check if the scriptlet `snippet0` is actually supported by any adblocker.
 *
 * @see {@link https://help.eyeo.com/adblockplus/snippet-filters-tutorial}
 */
class AbpSnippetInjectionBodySerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a scriptlet call body node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    static serialize(node, buffer) {
        ScriptletBodySerializer.serialize(node, buffer, abp_snippet_injection_body_common/* FREQUENT_ABP_SNIPPET_ARGS_SERIALIZATION_MAP */.T);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/cosmetic/body/ubo-scriptlet-injection-body-common.js
var ubo_scriptlet_injection_body_common = __webpack_require__(62224);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/cosmetic/body/ubo-scriptlet-injection-body-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * `UboScriptletInjectionBodySerializer` is responsible for serializing the body of a uBlock-style scriptlet rule.
 *
 * Please note that the parser will parse any scriptlet rule if it is syntactically correct.
 * For example, it will parse this:
 * ```adblock
 * example.com##+js(scriptlet0, arg0)
 * ```
 *
 * but it didn't check if the scriptlet `scriptlet0` actually supported by any adblocker.
 *
 * @see {@link https://github.com/gorhill/uBlock/wiki/Static-filter-syntax#scriptlet-injection}
 */
class UboScriptletInjectionBodySerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a scriptlet call body node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    static serialize(node, buffer) {
        ScriptletBodySerializer.serialize(node, buffer, ubo_scriptlet_injection_body_common/* FREQUENT_UBO_SCRIPTLET_ARGS_SERIALIZATION_MAP */.Z);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/cosmetic/body/adg-scriptlet-injection-body-common.js
var adg_scriptlet_injection_body_common = __webpack_require__(56874);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/cosmetic/body/adg-scriptlet-injection-body-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */




/**
 * `AdgScriptletInjectionBodySerializer` is responsible for serializing the body of an AdGuard-style scriptlet rule.
 *
 * Please note that the serializer will serialize any scriptlet rule if it is syntactically correct.
 * For example, it will serialize this:
 * ```adblock
 * example.com#%#//scriptlet('scriptlet0', 'arg0')
 * ```
 *
 * but it doesn't check if the scriptlet `scriptlet0` is actually supported by any adblocker.
 *
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#scriptlets}
 */
class AdgScriptletInjectionBodySerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a scriptlet call body node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    static serialize(node, buffer) {
        ScriptletBodySerializer.serialize(node, buffer, adg_scriptlet_injection_body_common/* FREQUENT_ADG_SCRIPTLET_ARGS_SERIALIZATION_MAP */.T);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/cosmetic/body/element-hiding-body-common.js
var element_hiding_body_common = __webpack_require__(69803);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/cosmetic/element-hiding-body-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/**
 * Serializer for element hiding rule body nodes.
 */
class ElementHidingBodySerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes an element hiding rule body node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    static serialize(node, buffer) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ElementHidingRuleBody);
        buffer.writeUint8(element_hiding_body_common/* ElementHidingRuleMarshallingMap */.G.SelectorList);
        ValueSerializer.serialize(node.selectorList, buffer);
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(element_hiding_body_common/* ElementHidingRuleMarshallingMap */.G.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(element_hiding_body_common/* ElementHidingRuleMarshallingMap */.G.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/cosmetic/body/css-injection-body-common.js
var css_injection_body_common = __webpack_require__(52002);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/cosmetic/css-injection-body-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/**
 * Serializer for CSS injection rule body nodes.
 */
class CssInjectionBodySerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a CSS injection rule body node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    static serialize(node, buffer) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.CssInjectionRuleBody);
        if (node.mediaQueryList) {
            buffer.writeUint8(css_injection_body_common/* CssInjectionRuleMarshallingMap */.V.MediaQueryList);
            ValueSerializer.serialize(node.mediaQueryList, buffer);
        }
        buffer.writeUint8(css_injection_body_common/* CssInjectionRuleMarshallingMap */.V.SelectorList);
        ValueSerializer.serialize(node.selectorList, buffer);
        if (node.declarationList) {
            buffer.writeUint8(css_injection_body_common/* CssInjectionRuleMarshallingMap */.V.DeclarationList);
            ValueSerializer.serialize(node.declarationList, buffer);
        }
        if (node.remove) {
            buffer.writeUint8(css_injection_body_common/* CssInjectionRuleMarshallingMap */.V.Remove);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(css_injection_body_common/* CssInjectionRuleMarshallingMap */.V.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(css_injection_body_common/* CssInjectionRuleMarshallingMap */.V.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/misc/modifier-common.js
var modifier_common = __webpack_require__(14299);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/misc/modifier-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/**
 * `ModifierSerializer` is responsible for serializing modifiers.
 *
 * @example
 * `match-case`, `~third-party`, `domain=example.com|~example.org`
 */
class ModifierSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a modifier node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    static serialize(node, buffer) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ModifierNode);
        buffer.writeUint8(modifier_common/* ModifierNodeMarshallingMap */.sD.Name);
        ValueSerializer.serialize(node.name, buffer, modifier_common/* FREQUENT_MODIFIERS_SERIALIZATION_MAP */.uu);
        if (!(0,type_guards/* isUndefined */.b0)(node.value)) {
            buffer.writeUint8(modifier_common/* ModifierNodeMarshallingMap */.sD.Value);
            ValueSerializer.serialize(node.value, buffer, modifier_common/* FREQUENT_REDIRECT_MODIFIERS_SERIALIZATION_MAP */.vG.get(node.name.value));
        }
        buffer.writeUint8(modifier_common/* ModifierNodeMarshallingMap */.sD.Exception);
        buffer.writeUint8(node.exception ? 1 : 0);
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(modifier_common/* ModifierNodeMarshallingMap */.sD.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(modifier_common/* ModifierNodeMarshallingMap */.sD.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/misc/modifier-list-common.js
var modifier_list_common = __webpack_require__(92006);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/misc/modifier-list-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/**
 * `ModifierListSerializer` is responsible for serializing modifier lists. Please note that the name is not
 * uniform, "modifiers" are also known as "options".
 *
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#basic-rules-modifiers}
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#non-basic-rules-modifiers}
 * @see {@link https://help.eyeo.com/adblockplus/how-to-write-filters#options}
 */
class ModifierListSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a modifier list node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    static serialize(node, buffer) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ModifierListNode);
        const count = node.children.length;
        // If there are no children, we do not write any data related to them, to avoid using unnecessary storage,
        // but children is a required field, so during deserialization we should initialize it as an empty array,
        // if there are no children in the binary data.
        if (count) {
            buffer.writeUint8(modifier_list_common/* ModifierListNodeMarshallingMap */.I.Children);
            // note: we store the count, because re-construction of the array is faster if we know the length
            if (count > constants/* UINT16_MAX */.zg) {
                throw new Error(`Too many modifiers: ${count}, the limit is ${constants/* UINT16_MAX */.zg}`);
            }
            buffer.writeUint16(count);
            for (let i = 0; i < count; i += 1) {
                ModifierSerializer.serialize(node.children[i], buffer);
            }
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(modifier_list_common/* ModifierListNodeMarshallingMap */.I.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(modifier_list_common/* ModifierListNodeMarshallingMap */.I.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/cosmetic/cosmetic-rule-common.js
var cosmetic_rule_common = __webpack_require__(42983);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/cosmetic/cosmetic-rule-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */

















/**
 * `CosmeticRuleSerializer` is responsible for serializing cosmetic rules into a binary format.
 *
 * This class takes a cosmetic rule Abstract Syntax Tree (AST) and converts it into a compact binary representation.
 * It handles the serialization of different types of cosmetic rules, including element hiding, CSS injection,
 * JavaScript injection, HTML filtering, and scriptlet injection rules.
 */
class CosmeticRuleSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a cosmetic rule node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    // TODO: add support for raws, if ever needed
    static serialize(node, buffer) {
        // specific properties
        switch (node.type) {
            case nodes/* CosmeticRuleType */.k9.ElementHidingRule:
                // rule type
                buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ElementHidingRule);
                // syntax
                buffer.writeUint8((0,syntax_serialization_map/* getSyntaxSerializationMap */.M)().get(node.syntax) ?? 0);
                // rule body
                ElementHidingBodySerializer.serialize(node.body, buffer);
                break;
            case nodes/* CosmeticRuleType */.k9.CssInjectionRule:
                // rule type
                buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.CssInjectionRule);
                // syntax
                buffer.writeUint8((0,syntax_serialization_map/* getSyntaxSerializationMap */.M)().get(node.syntax) ?? 0);
                // rule body
                CssInjectionBodySerializer.serialize(node.body, buffer);
                break;
            case nodes/* CosmeticRuleType */.k9.JsInjectionRule:
                // rule type
                buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.JsInjectionRule);
                // syntax
                buffer.writeUint8((0,syntax_serialization_map/* getSyntaxSerializationMap */.M)().get(node.syntax) ?? 0);
                // rule body
                ValueSerializer.serialize(node.body, buffer);
                break;
            case nodes/* CosmeticRuleType */.k9.HtmlFilteringRule:
                // rule type
                buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.HtmlFilteringRule);
                // syntax
                buffer.writeUint8((0,syntax_serialization_map/* getSyntaxSerializationMap */.M)().get(node.syntax) ?? 0);
                // rule body
                ValueSerializer.serialize(node.body, buffer);
                break;
            case nodes/* CosmeticRuleType */.k9.ScriptletInjectionRule:
                // rule type
                buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.ScriptletInjectionRule);
                // syntax
                buffer.writeUint8((0,syntax_serialization_map/* getSyntaxSerializationMap */.M)().get(node.syntax) ?? 0);
                // rule body
                switch (node.syntax) {
                    case adblockers/* AdblockSyntax */.Y.Adg:
                        AdgScriptletInjectionBodySerializer.serialize(node.body, buffer);
                        break;
                    case adblockers/* AdblockSyntax */.Y.Abp:
                        AbpSnippetInjectionBodySerializer.serialize(node.body, buffer);
                        break;
                    case adblockers/* AdblockSyntax */.Y.Ubo:
                        UboScriptletInjectionBodySerializer.serialize(node.body, buffer);
                        break;
                    default:
                        throw new Error('Scriptlet rule should have an explicit syntax');
                }
                break;
            default:
                throw new Error('Unknown cosmetic rule type');
        }
        // common properties
        buffer.writeUint8(cosmetic_rule_common/* CosmeticRuleMarshallingMap */.U.Exception);
        buffer.writeUint8(node.exception ? 1 : 0);
        buffer.writeUint8(cosmetic_rule_common/* CosmeticRuleMarshallingMap */.U.Separator);
        ValueSerializer.serialize(node.separator, buffer, cosmetic_rule_common/* COSMETIC_RULE_SEPARATOR_SERIALIZATION_MAP */.h);
        if (node.modifiers) {
            buffer.writeUint8(cosmetic_rule_common/* CosmeticRuleMarshallingMap */.U.Modifiers);
            ModifierListSerializer.serialize(node.modifiers, buffer);
        }
        buffer.writeUint8(cosmetic_rule_common/* CosmeticRuleMarshallingMap */.U.Domains);
        DomainListSerializer.serialize(node.domains, buffer);
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(cosmetic_rule_common/* CosmeticRuleMarshallingMap */.U.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(cosmetic_rule_common/* CosmeticRuleMarshallingMap */.U.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/misc/hostname-list-common.js
var hostname_list_common = __webpack_require__(89410);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/network/hostname-list-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/**
 * Serializer for hostname list nodes.
 */
class HostnameListSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a hostname list node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    static serialize(node, buffer) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.HostnameListNode);
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(hostname_list_common/* HostnameListNodeMarshallingMap */.W.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(hostname_list_common/* HostnameListNodeMarshallingMap */.W.End);
            buffer.writeUint32(node.end);
        }
        const count = node.children.length;
        // If there are no children, we do not write any data related to them, to avoid using unnecessary storage,
        // but children is a required field, so during deserialization we should initialize it as an empty array,
        // if there are no children in the binary data.
        if (count) {
            // note: we store the count, because re-construction of the array is faster if we know the length
            if (count > constants/* UINT16_MAX */.zg) {
                throw new Error(`Too many children: ${count}, the limit is ${constants/* UINT16_MAX */.zg}`);
            }
            buffer.writeUint8(hostname_list_common/* HostnameListNodeMarshallingMap */.W.Children);
            buffer.writeUint16(count);
            for (let i = 0; i < count; i += 1) {
                ValueSerializer.serialize(node.children[i], buffer);
            }
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/misc/host-rule-common.js
var host_rule_common = __webpack_require__(41351);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/network/host-rule-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */









/**
 * `HostRuleSerializer` is responsible for serializing hosts-like rules.
 *
 * HostRule is a structure for simple host-level rules (i.e. /etc/hosts syntax).
 * It also supports "just domain" syntax. In this case, the IP will be set to 0.0.0.0.
 *
 * Rules syntax looks like this:
 * ```text
 * IP_address canonical_hostname [aliases...]
 * ```
 *
 * @example
 * `192.168.1.13 bar.mydomain.org bar` -- ipv4
 * `ff02::1 ip6-allnodes` -- ipv6
 * `::1 localhost ip6-localhost ip6-loopback` -- ipv6 aliases
 * `example.org` -- "just domain" syntax
 * @see {@link http://man7.org/linux/man-pages/man5/hosts.5.html}
 */
class HostRuleSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a host rule node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    // TODO: add support for raws, if ever needed
    static serialize(node, buffer) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.HostRuleNode);
        buffer.writeUint8(host_rule_common/* HostRuleMarshallingMap */.J.Syntax);
        buffer.writeUint8((0,syntax_serialization_map/* getSyntaxSerializationMap */.M)().get(node.syntax) ?? 0);
        if (node.ip) {
            buffer.writeUint8(host_rule_common/* HostRuleMarshallingMap */.J.Ip);
            ValueSerializer.serialize(node.ip, buffer);
        }
        if (node.hostnames) {
            buffer.writeUint8(host_rule_common/* HostRuleMarshallingMap */.J.HostnameList);
            HostnameListSerializer.serialize(node.hostnames, buffer);
        }
        if (node.comment) {
            buffer.writeUint8(host_rule_common/* HostRuleMarshallingMap */.J.Comment);
            ValueSerializer.serialize(node.comment, buffer);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(host_rule_common/* HostRuleMarshallingMap */.J.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(host_rule_common/* HostRuleMarshallingMap */.J.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/network/network-rule-common.js
var network_rule_common = __webpack_require__(49459);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/network/network-rule-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */









/**
 * `NetworkRuleSerializer` is responsible for serializing network rules.
 *
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#basic-rules}
 * @see {@link https://help.eyeo.com/adblockplus/how-to-write-filters#basic}
 */
class NetworkRuleSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a network rule node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    // TODO: add support for raws, if ever needed
    static serialize(node, buffer) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.NetworkRuleNode);
        buffer.writeUint8(network_rule_common/* NetworkRuleMarshallingMap */.v.Syntax);
        buffer.writeUint8((0,syntax_serialization_map/* getSyntaxSerializationMap */.M)().get(node.syntax) ?? 0);
        buffer.writeUint8(network_rule_common/* NetworkRuleMarshallingMap */.v.Exception);
        buffer.writeUint8(node.exception ? 1 : 0);
        buffer.writeUint8(network_rule_common/* NetworkRuleMarshallingMap */.v.Pattern);
        ValueSerializer.serialize(node.pattern, buffer);
        if (!(0,type_guards/* isUndefined */.b0)(node.modifiers)) {
            buffer.writeUint8(network_rule_common/* NetworkRuleMarshallingMap */.v.ModifierList);
            ModifierListSerializer.serialize(node.modifiers, buffer);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(network_rule_common/* NetworkRuleMarshallingMap */.v.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(network_rule_common/* NetworkRuleMarshallingMap */.v.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/empty-rule-common.js
var empty_rule_common = __webpack_require__(27813);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/empty-rule-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */






/**
 * Serializer for empty rule nodes.
 */
class EmptyRuleSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes an empty rule node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    static serialize(node, buffer) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.EmptyRule);
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(empty_rule_common/* EmptyRuleMarshallingMap */.K.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(empty_rule_common/* EmptyRuleMarshallingMap */.K.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/invalid-rule-error-node-common.js
var invalid_rule_error_node_common = __webpack_require__(6229);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/invalid-rule-error-node-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */






/**
 * Serializer for invalid rule error nodes.
 */
class InvalidRuleErrorNodeSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes an invalid rule error node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    static serialize(node, buffer) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.InvalidRuleErrorNode);
        buffer.writeUint8(invalid_rule_error_node_common/* InvalidRuleErrorNodeMarshallingMap */.K.Name);
        buffer.writeString(node.name);
        buffer.writeUint8(invalid_rule_error_node_common/* InvalidRuleErrorNodeMarshallingMap */.K.Message);
        buffer.writeString(node.message);
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(invalid_rule_error_node_common/* InvalidRuleErrorNodeMarshallingMap */.K.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(invalid_rule_error_node_common/* InvalidRuleErrorNodeMarshallingMap */.K.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/marshalling-utils/invalid-rule-common.js
var invalid_rule_common = __webpack_require__(51175);
;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/invalid-rule-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */







/**
 * Serializer for invalid rule nodes.
 */
class InvalidRuleSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes an invalid rule node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    static serialize(node, buffer) {
        buffer.writeUint8(binary_type_common/* BinaryTypeMarshallingMap */.u.InvalidRule);
        buffer.writeUint8(invalid_rule_common/* InvalidRuleMarshallingMap */.W.Error);
        InvalidRuleErrorNodeSerializer.serialize(node.error, buffer);
        if (!(0,type_guards/* isUndefined */.b0)(node.start)) {
            buffer.writeUint8(invalid_rule_common/* InvalidRuleMarshallingMap */.W.Start);
            buffer.writeUint32(node.start);
        }
        if (!(0,type_guards/* isUndefined */.b0)(node.end)) {
            buffer.writeUint8(invalid_rule_common/* InvalidRuleMarshallingMap */.W.End);
            buffer.writeUint32(node.end);
        }
        buffer.writeUint8(constants/* NULL */.Cq);
    }
}



;// ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/serializer/rule-serializer.js
/*
 * AGTree v3.2.0 (build date: Thu, 22 May 2025 15:50:51 GMT)
 * (c) 2025 Adguard Software Ltd.
 * Released under the MIT license
 * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
 */









/**
 * `RuleSerializer` is responsible for serializing the rules.
 *
 * It automatically determines the category and syntax of the rule, so you can pass any kind of rule to it.
 */
class RuleSerializer extends base_serializer/* BaseSerializer */.S {
    /**
     * Serializes a rule node to binary format.
     *
     * @param node Node to serialize.
     * @param buffer ByteBuffer for writing binary data.
     */
    // TODO: add support for raws, if ever needed
    static serialize(node, buffer) {
        switch (node.category) {
            case nodes/* RuleCategory */.$O.Comment:
                CommentRuleSerializer.serialize(node, buffer);
                break;
            case nodes/* RuleCategory */.$O.Cosmetic:
                CosmeticRuleSerializer.serialize(node, buffer);
                break;
            case nodes/* RuleCategory */.$O.Network:
                switch (node.type) {
                    case nodes/* NetworkRuleType */.vY.HostRule:
                        HostRuleSerializer.serialize(node, buffer);
                        break;
                    case nodes/* NetworkRuleType */.vY.NetworkRule:
                        NetworkRuleSerializer.serialize(node, buffer);
                        break;
                    default:
                        throw new Error('Unknown network rule type');
                }
                break;
            case nodes/* RuleCategory */.$O.Empty:
                EmptyRuleSerializer.serialize(node, buffer);
                break;
            case nodes/* RuleCategory */.$O.Invalid:
                InvalidRuleSerializer.serialize(node, buffer);
                break;
            default:
                throw new Error('Unknown rule category');
        }
    }
}



;// ./node_modules/.pnpm/@adguard+tsurlfilter@3.3.3_@adguard+re2-wasm@1.2.0/node_modules/@adguard/tsurlfilter/dist/es/index.js























var version = "3.3.3";

const TSURLFILTER_VERSION = version;
/**
 * Compatibility types are used to configure engine for better support of different libraries
 * For example:
 *  extension doesn't support $app modifier. So if we set in configuration CompatibilityTypes.Extension,
 *  engine would ignore rules with $app modifier.
 */
var CompatibilityTypes;
(function (CompatibilityTypes) {
    CompatibilityTypes[CompatibilityTypes["Extension"] = 1] = "Extension";
    CompatibilityTypes[CompatibilityTypes["CoreLibs"] = 2] = "CoreLibs";
    CompatibilityTypes[CompatibilityTypes["Dns"] = 4] = "Dns";
})(CompatibilityTypes || (CompatibilityTypes = {}));
/**
 * Application configuration class.
 */
class Configuration {
    defaultConfig = {
        engine: null,
        version: null,
        verbose: false,
        compatibility: null,
    };
    /**
     * {'extension'|'corelibs'} engine application type.
     */
    engine = null;
    /**
     * {string} version.
     */
    version = null;
    /**
     * {boolean} verbose flag.
     */
    verbose = false;
    /**
     * Compatibility flag.
     */
    compatibility = CompatibilityTypes.Extension;
    constructor(inputConfig) {
        const config = { ...this.defaultConfig, ...inputConfig };
        this.engine = config.engine;
        this.version = config.version;
        this.verbose = config.verbose;
        this.compatibility = config.compatibility;
    }
}
// eslint-disable-next-line import/no-mutable-exports
let config = new Configuration();
/**
 * Checks config is compatible with input level.
 *
 * @param compatibilityLevel Compatibility level to check against.
 *
 * @returns True if compatible, otherwise false.
 */
function isCompatibleWith(compatibilityLevel) {
    if (config.compatibility === null) {
        return false;
    }
    return (config.compatibility & compatibilityLevel) === compatibilityLevel;
}
const setConfiguration = (outerConfig) => {
    config = new Configuration(outerConfig);
};

/**
 * Export logger implementation.
 */
let logger = console;
/**
 * Set logger implementation.
 *
 * @param loggerImpl The logger implementation to set.
 */
function setLogger(loggerImpl) {
    logger = loggerImpl;
}

/**
 * Pipe separator.
 */
const PIPE_SEPARATOR$1 = '|';
/**
 * This is a helper class that is used specifically to work
 * with domains restrictions.
 *
 * There are two options how you can add a domain restriction:
 * - `$domain` modifier;
 * - domains list for the cosmetic rules.
 *
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#domain-modifier}
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#cosmetic-rules}
 *
 * The only difference between them is that in one case we use `|` as a separator,
 * and in the other case - `,`.
 *
 * @example
 * `||example.org^$domain=example.com|~sub.example.com` -- network rule
 * `example.com,~sub.example.com##banner` -- cosmetic rule
 */
class DomainModifier {
    /**
     * List of permitted domains or null.
     */
    permittedDomains;
    /**
     * List of restricted domains or null.
     */
    restrictedDomains;
    /**
     * Processes domain list node, which means extracting permitted and restricted
     * domains from it.
     *
     * @param domainListNode Domain list node to process.
     *
     * @returns Processed domain list (permitted and restricted domains) ({@link ProcessedDomainList}).
     */
    static processDomainList(domainListNode) {
        const result = {
            permittedDomains: [],
            restrictedDomains: [],
        };
        const { children: domains } = domainListNode;
        for (const { exception, value: domain } of domains) {
            const domainLowerCased = domain.toLowerCase();
            if (!simple_regex_Dw3J24Ss.S.isRegexPattern(domain) && domain.includes(simple_regex_Dw3J24Ss.W) && !domain.endsWith(simple_regex_Dw3J24Ss.W)) {
                throw new SyntaxError(`Wildcards are only supported for top-level domains: "${domain}"`);
            }
            if (exception) {
                result.restrictedDomains.push(domainLowerCased);
            }
            else {
                result.permittedDomains.push(domainLowerCased);
            }
        }
        return result;
    }
    /**
     * Parses the `domains` string and initializes the object.
     *
     * @param domains Domain list string or AGTree DomainList node.
     * @param separator Separator — `,` or `|`.
     *
     * @throws An error if the domains string is empty or invalid.
     */
    constructor(domains, separator) {
        let processed;
        if ((0,simple_regex_Dw3J24Ss.i)(domains)) {
            const node = domain_list_parser/* DomainListParser */.y.parse(domains.trim(), { ...options/* defaultParserOptions */.n, isLocIncluded: false }, 0, separator);
            if (node.children.length === 0) {
                throw new SyntaxError('At least one domain must be specified');
            }
            processed = DomainModifier.processDomainList(node);
        }
        else {
            // domain list node stores the separator
            if (separator !== domains.separator) {
                throw new SyntaxError('Separator mismatch');
            }
            processed = DomainModifier.processDomainList(domains);
        }
        // Unescape separator character in domains
        processed.permittedDomains = processed.permittedDomains.map((domain) => (0,simple_regex_Dw3J24Ss.u)(domain, separator));
        processed.restrictedDomains = processed.restrictedDomains.map((domain) => (0,simple_regex_Dw3J24Ss.u)(domain, separator));
        this.restrictedDomains = processed.restrictedDomains.length > 0 ? processed.restrictedDomains : null;
        this.permittedDomains = processed.permittedDomains.length > 0 ? processed.permittedDomains : null;
    }
    /**
     * Checks if the filtering rule is allowed on this domain.
     *
     * @param domain Domain to check.
     *
     * @returns True if the filtering rule is allowed on this domain.
     */
    matchDomain(domain) {
        if (this.hasRestrictedDomains()) {
            if (DomainModifier.isDomainOrSubdomainOfAny(domain, this.restrictedDomains)) {
                // Domain or host is restricted
                // i.e. $domain=~example.org
                return false;
            }
        }
        if (this.hasPermittedDomains()) {
            if (!DomainModifier.isDomainOrSubdomainOfAny(domain, this.permittedDomains)) {
                // Domain is not among permitted
                // i.e. $domain=example.org and we're checking example.com
                return false;
            }
        }
        return true;
    }
    /**
     * Checks if rule has permitted domains.
     *
     * @returns True if the rule has permitted domains.
     */
    hasPermittedDomains() {
        return !!this.permittedDomains && this.permittedDomains.length > 0;
    }
    /**
     * Checks if rule has restricted domains.
     *
     * @returns True if the rule has restricted domains.
     */
    hasRestrictedDomains() {
        return !!this.restrictedDomains && this.restrictedDomains.length > 0;
    }
    /**
     * Gets list of permitted domains.
     *
     * @returns List of permitted domains or null if none.
     */
    getPermittedDomains() {
        return this.permittedDomains;
    }
    /**
     * Gets list of restricted domains.
     *
     * @returns List of restricted domains or null if none.
     */
    getRestrictedDomains() {
        return this.restrictedDomains;
    }
    /**
     * Checks if `domain` is the same or a subdomain
     * of any of `domains`.
     *
     * @param domain Domain to check.
     * @param domains Domains list to check against.
     *
     * @returns True if `domain` is the same or a subdomain of any of `domains`.
     */
    static isDomainOrSubdomainOfAny(domain, domains) {
        for (let i = 0; i < domains.length; i += 1) {
            const d = domains[i];
            if (DomainModifier.isWildcardDomain(d)) {
                if (DomainModifier.matchAsWildcard(d, domain)) {
                    return true;
                }
            }
            if (domain === d || (domain.endsWith(d) && domain.endsWith(`.${d}`))) {
                return true;
            }
            if (simple_regex_Dw3J24Ss.S.isRegexPattern(d)) {
                try {
                    /**
                     * Regular expressions are cached internally by the browser
                     * (for instance, they're stored in the CompilationCache in V8/Chromium),
                     * so calling the constructor here should not be a problem.
                     *
                     * TODO: use SimpleRegex.patternFromString(d) after it is refactored to not add 'g' flag.
                     */
                    const domainPattern = new RegExp(d.slice(1, -1));
                    if (domainPattern.test(domain)) {
                        return true;
                    }
                }
                catch {
                    logger.error(`Invalid regular expression as domain pattern: "${d}"`);
                }
                continue;
            }
        }
        return false;
    }
    /**
     * Checks if domain ends with wildcard.
     *
     * @param domain Domain string to check.
     *
     * @returns True if domain ends with wildcard.
     */
    static isWildcardDomain(domain) {
        return domain.endsWith('.*');
    }
    /**
     * Checks if domain string does not ends with wildcard and is not regex pattern.
     *
     * @param domain Domain string to check.
     *
     * @returns True if given domain is a wildcard or regexp pattern.
     */
    static isWildcardOrRegexDomain(domain) {
        return DomainModifier.isWildcardDomain(domain) || simple_regex_Dw3J24Ss.S.isRegexPattern(domain);
    }
    /**
     * Checks if wildcard matches domain.
     *
     * @param wildcard The wildcard pattern to match against the domain.
     * @param domainNameToCheck The domain name to check against the wildcard pattern.
     *
     * @returns True if wildcard matches domain.
     */
    static matchAsWildcard(wildcard, domainNameToCheck) {
        const wildcardedDomainToCheck = DomainModifier.genTldWildcard(domainNameToCheck);
        if (wildcardedDomainToCheck) {
            return wildcardedDomainToCheck === wildcard
                || (wildcardedDomainToCheck.endsWith(wildcard) && wildcardedDomainToCheck.endsWith(`.${wildcard}`));
        }
        return false;
    }
    /**
     * Generates from domain tld wildcard.
     *
     * @param domainName The domain name to generate the TLD wildcard for.
     *
     * @returns String is empty if tld for provided domain name doesn't exists.
     *
     * @example
     * `google.com` -> `google.*`
     * `youtube.co.uk` -> `youtube.*`
     */
    static genTldWildcard(domainName) {
        // To match eTld like "com.ru" we use allowPrivateDomains wildcard
        // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2650
        const tld = (0,es6/* getPublicSuffix */.pj)(domainName, { allowPrivateDomains: true });
        if (tld) {
            // lastIndexOf() is needed not to match the domain, e.g. 'www.chrono24.ch'.
            // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2312.
            return `${domainName.slice(0, domainName.lastIndexOf(`.${tld}`))}.*`;
        }
        return '';
    }
}

/**
 * @typedef {import('./cosmetic-engine').CosmeticEngine} CosmeticEngine
 */
/**
 * CosmeticLookupTable lets quickly lookup cosmetic rules for the specified hostname.
 * It is primarily used by the {@link CosmeticEngine}.
 */
class CosmeticLookupTable {
    /**
     * Map with rules indices grouped by the permitted domains names.
     */
    byHostname;
    /**
     * List of domain-specific rules that are not organized into any index structure.
     * These rules are sequentially scanned one by one.
     */
    seqScanRules;
    /**
     * Collection of generic rules.
     * Generic means that the rule is not limited to particular websites and works (almost) everywhere.
     */
    genericRules;
    /**
     * Map with allowlist rules indices. Key is the rule content.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#element-hiding-rules-exceptions}
     */
    allowlist;
    /**
     * Storage for the filtering rules.
     */
    ruleStorage;
    /**
     * Creates a new instance.
     *
     * @param storage Rules storage. We store "rule indexes" in the lookup table which
     * can be used to retrieve the full rules from the storage.
     */
    constructor(storage) {
        this.byHostname = new Map();
        this.seqScanRules = [];
        this.genericRules = [];
        this.allowlist = new Map();
        this.ruleStorage = storage;
    }
    /**
     * Adds rule to the allowlist map.
     *
     * @param key Can be used any string, but here we use ruleContent, scriptlet content, or scriptlet name.
     * @param storageIdx Index of the rule.
     */
    addAllowlistRule(key, storageIdx) {
        const existingRules = this.allowlist.get(key);
        if (!existingRules) {
            this.allowlist.set(key, [storageIdx]);
            return;
        }
        existingRules.push(storageIdx);
    }
    /**
     * Adds rule to the appropriate collection.
     *
     * @param rule Rule to add.
     * @param storageIdx Index of the rule in the storage.
     */
    addRule(rule, storageIdx) {
        if (rule.isAllowlist()) {
            if (rule.isScriptlet) {
                // Store scriptlet rules by name to enable the possibility of allowlisting them.
                // See https://github.com/AdguardTeam/Scriptlets/issues/377 for more details.
                if (rule.scriptletParams.name !== undefined
                    && rule.scriptletParams.args.length === 0) {
                    this.addAllowlistRule(rule.scriptletParams.name, storageIdx);
                }
                // Use normalized scriptlet content for better matching.
                // For example, //scriptlet('log', 'arg') can be matched by //scriptlet("log", "arg").
                this.addAllowlistRule(rule.scriptletParams.toString(), storageIdx);
            }
            else {
                // Store all other rules by their content.
                this.addAllowlistRule(rule.getContent(), storageIdx);
            }
            return;
        }
        if (rule.isGeneric()) {
            this.genericRules.push(rule);
            return;
        }
        const permittedDomains = rule.getPermittedDomains();
        if (permittedDomains) {
            if (permittedDomains.some(DomainModifier.isWildcardOrRegexDomain)) {
                this.seqScanRules.push(rule);
                return;
            }
            for (const domain of permittedDomains) {
                const tldResult = (0,es6/* parse */.qg)(domain);
                // tldResult.domain equals to eTLD domain,
                // e.g. sub.example.uk.org would result in example.uk.org
                const parsedDomain = tldResult.domain || domain;
                const key = (0,simple_regex_Dw3J24Ss.f)(parsedDomain);
                const rules = this.byHostname.get(key) || [];
                rules.push(storageIdx);
                this.byHostname.set(key, rules);
            }
        }
    }
    /**
     * Finds rules by hostname.
     *
     * @param request Request to check.
     *
     * @returns Array of matching cosmetic rules.
     */
    findByHostname(request) {
        const result = [];
        const { subdomains } = request;
        // Iterate over all sub-domains
        for (let i = 0; i < subdomains.length; i += 1) {
            const subdomain = subdomains[i];
            let rulesIndexes = this.byHostname.get((0,simple_regex_Dw3J24Ss.f)(subdomain));
            if (rulesIndexes) {
                // Filtering out duplicates
                rulesIndexes = rulesIndexes.filter((v, index) => rulesIndexes.indexOf(v) === index);
                for (let j = 0; j < rulesIndexes.length; j += 1) {
                    const rule = this.ruleStorage.retrieveRule(rulesIndexes[j]);
                    if (rule && !rule.isAllowlist() && rule.match(request)) {
                        result.push(rule);
                    }
                }
            }
        }
        result.push(...this.seqScanRules.filter((r) => !r.isAllowlist() && r.match(request)));
        return result;
    }
    /**
     * Checks if a scriptlet is allowlisted for a request. It looks up the scriptlet
     * by content in the allowlist map and evaluates two conditions:
     * 1. If there's a generic allowlist rule applicable to all sites.
     * 2. If there's a specific allowlist rule that matches the request.
     *
     * @param content Content of the scriptlet. Empty string '' searches for scriptlets allowlisted globally.
     * @param request Request details to match against allowlist rules.
     *
     * @returns True if allowlisted by a matching rule or a generic rule. False otherwise.
     */
    isScriptletAllowlisted = (content, request) => {
        // check for rules with that content
        const allowlistScriptletRulesIndexes = this.allowlist.get(content);
        if (allowlistScriptletRulesIndexes) {
            const rules = allowlistScriptletRulesIndexes
                .map((i) => {
                return this.ruleStorage.retrieveRule(i);
            })
                .filter((r) => r);
            // here we check if there is at least one generic allowlist rule
            const hasAllowlistGenericScriptlet = rules.some((r) => {
                return r.isGeneric();
            });
            if (hasAllowlistGenericScriptlet) {
                return true;
            }
            // here we check if there is at least one allowlist rule that matches the request
            const hasRuleMatchingRequest = rules.some((r) => r.match(request));
            if (hasRuleMatchingRequest) {
                return true;
            }
        }
        return false;
    };
    /**
     * Checks if the rule is disabled on the specified hostname.
     *
     * @param request Request to check.
     * @param rule Rule to check.
     *
     * @returns True if the rule is disabled on the specified hostname.
     */
    isAllowlisted(request, rule) {
        if (rule.isScriptlet) {
            // Empty string '' is a special case for scriptlet when the allowlist scriptlet has no name
            // e.g. #@%#//scriptlet(); example.org#@%#//scriptlet();
            const EMPTY_SCRIPTLET_NAME = '';
            if (this.isScriptletAllowlisted(EMPTY_SCRIPTLET_NAME, request)) {
                return true;
            }
            // If scriptlet allowlisted by name
            // e.g. #@%#//scriptlet('set-cookie'); example.org#@%#//scriptlet('set-cookie');
            if (rule.scriptletParams.name !== undefined
                && this.isScriptletAllowlisted(rule.scriptletParams.name, request)) {
                return true;
            }
            // If scriptlet allowlisted with args, using normalized scriptlet content for better matching
            // on different quote types (see https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2947)
            // e.g. #@%#//scriptlet("set-cookie", "arg1"); example.org#@%#//scriptlet('set-cookie', 'arg1');
            if (rule.scriptletParams.name !== undefined
                && rule.scriptletParams.args.length > 0
                && this.isScriptletAllowlisted(rule.scriptletParams.toString(), request)) {
                return true;
            }
        }
        const rulesIndexes = this.allowlist.get(rule.getContent());
        if (!rulesIndexes) {
            return false;
        }
        for (let j = 0; j < rulesIndexes.length; j += 1) {
            const r = this.ruleStorage.retrieveRule(rulesIndexes[j]);
            if (r && r.match(request)) {
                return true;
            }
        }
        return false;
    }
}

/* eslint-disable max-classes-per-file */
/**
 * Default rule index for source mapping.
 *
 * It is -1, similar to `Array.indexOf()` return value when element is not found.
 */
const RULE_INDEX_NONE = -1;
/**
 * Rule with index.
 */
// TODO: Consider remove this because rule already has an index field
class IndexedRule {
    /**
     * Rule.
     */
    rule;
    /**
     * Index.
     */
    index;
    /**
     * Constructor.
     *
     * @param rule Rule.
     * @param index Index of the rule.
     */
    constructor(rule, index) {
        this.rule = rule;
        this.index = index;
    }
}
/**
 * Rule with storage index.
 */
class IndexedStorageRule {
    /**
     * Rule.
     */
    rule;
    /**
     * Index.
     */
    index;
    /**
     * Constructor.
     *
     * @param rule Rule.
     * @param index Index of the rule.
     */
    constructor(rule, index) {
        this.rule = rule;
        this.index = index;
    }
}

/**
 * Splits url into parts.
 *
 * @param url The URL to be checked.
 *
 * @returns An object containing the path, query, and hash of the URL.
 */
function splitUrl(url) {
    let strippedUrl = url;
    let hash = '';
    const hashIndex = url.indexOf('#');
    if (hashIndex >= 0) {
        hash = url.slice(hashIndex);
        strippedUrl = url.slice(0, hashIndex);
    }
    let query = '';
    const queryIndex = url.indexOf('?');
    if (queryIndex >= 0) {
        query = strippedUrl.slice(queryIndex + 1);
        strippedUrl = strippedUrl.slice(0, queryIndex);
    }
    return {
        path: strippedUrl,
        query,
        hash,
    };
}
/**
 * Normalizes url query parameters.
 *
 * @param query The query string to be normalized.
 *
 * @returns The normalized query string.
 */
function normalizeQuery(query) {
    // Cleanup empty params (p0=0&=2&=3)
    let result = query
        .split('&')
        .filter((x) => x && !x.startsWith('='))
        .join('&');
    // If we've collapsed the URL to the point where there's an '&' against the '?'
    // then we need to get rid of that.
    while (result.charAt(0) === '&') {
        result = result.slice(1);
    }
    return result;
}
/**
 * Removes query params from url by regexp.
 *
 * @param url The URL from which query parameters will be removed.
 * @param regExp The regular expression to match query parameters.
 * @param invert Remove every parameter in url except the ones matched regexp.
 *
 * @returns The URL with the specified query parameters removed.
 */
function cleanUrlParamByRegExp(url, regExp, invert = false) {
    const searchIndex = url.indexOf('?');
    // If no params, nothing to modify
    if (searchIndex === -1) {
        return url;
    }
    const split = splitUrl(url);
    /**
     * We are checking both regular param and decoded param, in case if regexp
     * contains decoded params and url contains encoded params.
     *
     * @see {@link https://github.com/AdguardTeam/AdguardBrowserExtension/issues/3015}
     */
    let modifiedQuery;
    if (invert) {
        modifiedQuery = split.query
            .split('&')
            .filter((x) => x && (x.match(regExp) || decodeURIComponent(x).match(regExp)))
            .join('&');
    }
    else {
        modifiedQuery = split.query
            .split('&')
            .filter((x) => {
            const test = x.includes('=') ? x : `${x}=`;
            return !test.match(regExp) && !decodeURIComponent(test).match(regExp);
        })
            .join('&');
    }
    // Do not normalize if regexp is not applied
    if (modifiedQuery === split.query) {
        return url;
    }
    modifiedQuery = normalizeQuery(modifiedQuery);
    let result = split.path;
    if (modifiedQuery) {
        result += `?${modifiedQuery}`;
    }
    return result + split.hash;
}
/**
 * Extract relative part from hierarchical structured URL.
 *
 * @param url The URL from which the relative part will be extracted.
 *
 * @returns The relative part of the URL or null if not found.
 */
const getRelativeUrl = (url) => {
    const i = url.indexOf('/', url.indexOf('://') + 3);
    return i !== -1 ? url.slice(i) : null;
};
/**
 * Checks if url is http or websocket.
 *
 * @param url Request url.
 *
 * @returns True if url starts with http{s?} or ws.
 */
function isHttpOrWsRequest(url) {
    return !!url && (url.startsWith('http') || url.startsWith('ws'));
}

/**
 * Rule pattern class.
 *
 * This class parses rule pattern text to simple fields.
 */
class Pattern {
    /**
     * Original pattern text.
     */
    pattern;
    /**
     * Shortcut string.
     */
    shortcut;
    /**
     * If this pattern already prepared indicator.
     */
    prepared;
    /**
     * Parsed hostname.
     */
    hostname;
    /**
     * Parsed regular expression.
     */
    regex;
    /**
     * Invalid regex flag.
     */
    regexInvalid;
    /**
     * Domain specific pattern flag.
     */
    patternDomainSpecific;
    /**
     * If true, pattern and shortcut are the same.
     * In this case, we don't actually need to use `matchPattern`
     * if shortcut was already matched.
     */
    patternShortcut;
    /**
     * If pattern is match-case regex.
     */
    matchcase;
    /**
     * Constructor.
     *
     * @param pattern Pattern.
     * @param matchcase Flag for case-sensitive matching, default is false.
     */
    constructor(pattern, matchcase = false) {
        this.pattern = pattern;
        this.shortcut = simple_regex_Dw3J24Ss.S.extractShortcut(this.pattern);
        this.matchcase = matchcase;
    }
    /**
     * Checks if this rule pattern matches the specified request.
     *
     * @param request Request to check.
     * @param shortcutMatched If true, it means that the request already matches
     * this pattern's shortcut and we don't need to match it again.
     *
     * @returns True if pattern matches.
     */
    matchPattern(request, shortcutMatched) {
        this.prepare();
        if (this.patternShortcut) {
            return shortcutMatched || this.matchShortcut(request.urlLowercase);
        }
        if (this.hostname) {
            // If we have a `||example.org^` rule, it's easier to match
            // against the request's hostname only without matching
            // a regular expression.
            return request.hostname === this.hostname
                || ( // First light check without new string memory allocation
                request.hostname.endsWith(this.hostname)
                    // Strict check
                    && request.hostname.endsWith(`.${this.hostname}`));
        }
        // If the regular expression is invalid, just return false right away.
        if (this.regexInvalid || !this.regex) {
            return false;
        }
        // This is needed for DNS filtering only, not used in browser blocking.
        if (this.shouldMatchHostname(request)) {
            return this.regex.test(request.hostname);
        }
        return this.regex.test(request.url);
    }
    /**
     * Checks if this rule pattern matches the specified relative path string.
     * This method is used in cosmetic rules to implement the $path modifier matching logic.
     *
     * @param path Path to check.
     *
     * @returns True if pattern matches.
     */
    matchPathPattern(path) {
        this.prepare();
        if (this.hostname) {
            return false;
        }
        const pathIsEmptyString = this.pattern === '';
        // No-value $path should match root URL
        if (pathIsEmptyString && path === '/') {
            return true;
        }
        if (!pathIsEmptyString && this.patternShortcut) {
            return this.matchShortcut(path);
        }
        // If the regular expression is invalid, just return false right away.
        if (this.regexInvalid || !this.regex) {
            return false;
        }
        return this.regex.test(path);
    }
    /**
     * Simply checks if shortcut is a substring of the URL.
     *
     * @param str Shortcut to check.
     *
     * @returns True if the shortcut is a substring of the URL.
     */
    matchShortcut(str) {
        return str.indexOf(this.shortcut) >= 0;
    }
    /**
     * Prepares this pattern.
     */
    prepare() {
        if (this.prepared) {
            return;
        }
        this.prepared = true;
        // If shortcut and pattern are the same, we don't need to actually compile
        // a regex and can simply use matchShortcut instead,
        // except for the $match-case modifier
        if (this.pattern === this.shortcut && !this.matchcase) {
            this.patternShortcut = true;
            return;
        }
        // Rules like `/example/*` are rather often in the real-life filters,
        // we might want to process them.
        if (this.pattern.startsWith(this.shortcut)
            && this.pattern.length === this.shortcut.length + 1
            && this.pattern.endsWith('*')) {
            this.patternShortcut = true;
            return;
        }
        if (this.pattern.startsWith(simple_regex_Dw3J24Ss.S.MASK_START_URL)
            && this.pattern.endsWith(simple_regex_Dw3J24Ss.S.MASK_SEPARATOR)
            && this.pattern.indexOf('*') < 0
            && this.pattern.indexOf('/') < 0) {
            this.hostname = this.pattern.slice(2, this.pattern.length - 1);
            return;
        }
        this.compileRegex();
    }
    /**
     * Compiles this pattern regex.
     */
    compileRegex() {
        const regexText = simple_regex_Dw3J24Ss.S.patternToRegexp(this.pattern);
        try {
            let flags = 'i';
            if (this.matchcase) {
                flags = '';
            }
            this.regex = new RegExp(regexText, flags);
        }
        catch (e) {
            this.regexInvalid = true;
        }
    }
    /**
     * Checks if we should match hostnames and not the URL
     * this is important for the cases when we use urlfilter for DNS-level blocking
     * Note, that even though we may work on a DNS-level, we should still sometimes match full URL instead.
     *
     * @param request Request to check.
     *
     * @returns True if the hostname should be matched.
     */
    shouldMatchHostname(request) {
        if (!request.isHostnameRequest) {
            return false;
        }
        return !this.isPatternDomainSpecific();
    }
    /**
     * In case pattern starts with the following it targets some specific domain.
     *
     * @returns True if the pattern targets a specific domain.
     */
    isPatternDomainSpecific() {
        if (this.patternDomainSpecific === undefined) {
            this.patternDomainSpecific = this.pattern.startsWith(simple_regex_Dw3J24Ss.S.MASK_START_URL)
                || this.pattern.startsWith('http://')
                || this.pattern.startsWith('https:/')
                || this.pattern.startsWith('://');
        }
        return this.patternDomainSpecific;
    }
}

/**
 * @file Known CSS / Extended CSS elements.
 */
/**
 * Supported Extended CSS pseudo-classes.
 *
 * These pseudo-classes are not supported by browsers natively, so we need Extended CSS library to support them.
 *
 * Please keep this list sorted alphabetically.
 */
const SUPPORTED_EXT_CSS_PSEUDO_CLASSES = new Set([
    /**
     * Pseudo-classes :is(), and :not() may use native implementation.
     *
     * @see {@link https://github.com/AdguardTeam/ExtendedCss#extended-css-is}
     * @see {@link https://github.com/AdguardTeam/ExtendedCss#extended-css-not}
     */
    /**
     * :has() should also be conditionally considered as extended and should not be in this list,
     * for details check: https://github.com/AdguardTeam/ExtendedCss#extended-css-has,
     * but there is a bug with content blocker in safari:
     * for details check: https://bugs.webkit.org/show_bug.cgi?id=248868.
     *
     * TODO: remove 'has' later.
     */
    '-abp-contains', // alias for 'contains'
    '-abp-has', // alias for 'has'
    'contains',
    'has', // some browsers support 'has' natively
    'has-text', // alias for 'contains'
    'if',
    'if-not',
    'matches-attr',
    'matches-css',
    'matches-css-after', // deprecated, replaced by 'matches-css'
    'matches-css-before', // deprecated, replaced by 'matches-css'
    'matches-property',
    'nth-ancestor',
    'remove',
    'upward',
    'xpath',
]);
/**
 * Supported native CSS pseudo-classes.
 *
 * These pseudo-classes are supported by browsers natively, so we don't need Extended CSS library to support them.
 *
 * The problem with pseudo-classes is that any unknown pseudo-class makes browser ignore the whole CSS rule,
 * which contains a lot more selectors. So, if CSS selector contains a pseudo-class, we should try to validate it.
 * One more problem with pseudo-classes is that they are actively used in uBlock, hence it may mess AG styles.
 *
 * Please keep this list sorted alphabetically.
 */
const SUPPORTED_CSS_PSEUDO_CLASSES = new Set([
    'active', // https://developer.mozilla.org/en-US/docs/Web/CSS/:active
    'checked', // https://developer.mozilla.org/en-US/docs/Web/CSS/:checked
    'disabled', // https://developer.mozilla.org/en-US/docs/Web/CSS/:disabled
    'empty', // https://developer.mozilla.org/en-US/docs/Web/CSS/:empty
    'enabled', // https://developer.mozilla.org/en-US/docs/Web/CSS/:enabled
    'first-child', // https://developer.mozilla.org/en-US/docs/Web/CSS/:first-child
    'first-of-type', // https://developer.mozilla.org/en-US/docs/Web/CSS/:first-of-type
    'focus', // https://developer.mozilla.org/en-US/docs/Web/CSS/:focus
    'has', // https://developer.mozilla.org/en-US/docs/Web/CSS/:has
    'hover', // https://developer.mozilla.org/en-US/docs/Web/CSS/:hover
    'in-range', // https://developer.mozilla.org/en-US/docs/Web/CSS/:in-range
    'invalid', // https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid
    'is', // https://developer.mozilla.org/en-US/docs/Web/CSS/:is
    'lang', // https://developer.mozilla.org/en-US/docs/Web/CSS/:lang
    'last-child', // https://developer.mozilla.org/en-US/docs/Web/CSS/:last-child
    'last-of-type', // https://developer.mozilla.org/en-US/docs/Web/CSS/:last-of-type
    'link', // https://developer.mozilla.org/en-US/docs/Web/CSS/:link
    'not', // https://developer.mozilla.org/en-US/docs/Web/CSS/:not
    'nth-child', // https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child
    'nth-last-child', // https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child
    'nth-last-of-type', // https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-of-type
    'nth-of-type', // https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-of-type
    'only-child', // https://developer.mozilla.org/en-US/docs/Web/CSS/:only-child
    'only-of-type', // https://developer.mozilla.org/en-US/docs/Web/CSS/:only-of-type
    'optional', // https://developer.mozilla.org/en-US/docs/Web/CSS/:optional
    'out-of-range', // https://developer.mozilla.org/en-US/docs/Web/CSS/:out-of-range
    'read-only', // https://developer.mozilla.org/en-US/docs/Web/CSS/:read-only
    'read-write', // https://developer.mozilla.org/en-US/docs/Web/CSS/:read-write
    'required', // https://developer.mozilla.org/en-US/docs/Web/CSS/:required
    'root', // https://developer.mozilla.org/en-US/docs/Web/CSS/:root
    'target', // https://developer.mozilla.org/en-US/docs/Web/CSS/:target
    'valid', // https://developer.mozilla.org/en-US/docs/Web/CSS/:valid
    'visited', // https://developer.mozilla.org/en-US/docs/Web/CSS/:visited
    'where', // https://developer.mozilla.org/en-US/docs/Web/CSS/:where
]);
/**
 * Every Extended CSS pseudo-class should start with this prefix.
 *
 * @see {@link https://github.com/AdguardTeam/ExtendedCss#-backward-compatible-syntax}
 */
const EXT_CSS_ATTRIBUTE_SELECTOR_PREFIX = '-ext-';
/**
 * Supported legacy Extended CSS attribute selectors.
 *
 * Attribute selector way is deprecated and will be removed completely in the future,
 * we replaced it with Extended CSS pseudo-classes. For example, instead of
 * `[-ext-has="a[href]"]` you should use `:has(a[href])`.
 *
 * Please keep this list sorted alphabetically.
 */
const SUPPORTED_EXT_CSS_ATTRIBUTE_SELECTORS = new Set([
    `${EXT_CSS_ATTRIBUTE_SELECTOR_PREFIX}has`,
    `${EXT_CSS_ATTRIBUTE_SELECTOR_PREFIX}contains`,
    `${EXT_CSS_ATTRIBUTE_SELECTOR_PREFIX}has-text`,
    `${EXT_CSS_ATTRIBUTE_SELECTOR_PREFIX}matches-css`,
    `${EXT_CSS_ATTRIBUTE_SELECTOR_PREFIX}matches-css-before`,
    `${EXT_CSS_ATTRIBUTE_SELECTOR_PREFIX}matches-css-after`,
]);
/**
 * Known CSS functions that aren't allowed in CSS injection rules, because they
 * able to load external resources. Please, keep this list sorted.
 */
const FORBIDDEN_CSS_FUNCTIONS = new Set([
    // https://developer.mozilla.org/en-US/docs/Web/CSS/cross-fade
    '-webkit-cross-fade',
    'cross-fade',
    // https://developer.mozilla.org/en-US/docs/Web/CSS/image
    'image',
    // https://developer.mozilla.org/en-US/docs/Web/CSS/image-set
    '-webkit-image-set',
    'image-set',
    // https://developer.mozilla.org/en-US/docs/Web/CSS/url
    'url',
]);

/**
 * Checks if error has message.
 *
 * @param error Error object.
 *
 * @returns If param is error.
 */
function isErrorWithMessage(error) {
    return (typeof error === 'object'
        && error !== null
        && 'message' in error
        && typeof error.message === 'string');
}
/**
 * Converts error to the error with message.
 *
 * @param maybeError Possible error.
 *
 * @returns Error with message.
 */
function toErrorWithMessage(maybeError) {
    if (isErrorWithMessage(maybeError)) {
        return maybeError;
    }
    try {
        return new Error(JSON.stringify(maybeError));
    }
    catch {
        // fallback in case there's an error stringifying the maybeError
        // like with circular references for example.
        return new Error(String(maybeError));
    }
}
/**
 * Converts error object to error with message. This method might be helpful to handle thrown errors.
 *
 * @param error Error object.
 *
 * @returns Message of the error.
 */
function getErrorMessage(error) {
    // Special case: pretty print Zod errors
    if (error instanceof lib/* ZodError */.G) {
        return (0,dist/* fromZodError */.yu)(error).toString();
    }
    return toErrorWithMessage(error).message;
}

/**
 * @file Selector list validator.
 */
/**
 * Does a basic validation of a selector list.
 * Checks for unsupported pseudo-classes and attribute selectors,
 * and determines if the selector is an Extended CSS selector.
 *
 * @param selectorList Selector list to validate.
 *
 * @returns Validation result, see {@link CssValidationResult}.
 *
 * @note This is a basic validation for the most necessary things, it does not guarantee that the CSS is completely
 * valid.
 */
const validateSelectorList = (selectorList) => {
    const result = {
        isValid: true,
        isExtendedCss: false,
    };
    try {
        let prevIsDoubleColon = false;
        let prevToken;
        let prevNonWhitespaceToken;
        (0,csstokenizer/* tokenizeExtended */.jz)(selectorList, (token, start, end) => {
            if ((token === csstokenizer/* TokenType */.ks.Function || token === csstokenizer/* TokenType */.ks.Ident)
                && prevToken === csstokenizer/* TokenType */.ks.Colon
                && !prevIsDoubleColon) {
                // whitespace is NOT allowed between the ':' and the pseudo-class name, like ': active('
                const name = selectorList.slice(start, 
                // function tokens look like 'func(', so we need to remove the last character
                token === csstokenizer/* TokenType */.ks.Function ? end - 1 : end);
                // function name may contain escaped characters, like '\75' instead of 'u', so we need to decode it
                const decodedName = (0,csstokenizer/* decodeIdent */.f0)(name);
                if (SUPPORTED_EXT_CSS_PSEUDO_CLASSES.has(decodedName)) {
                    result.isExtendedCss = true;
                }
                else if (!SUPPORTED_CSS_PSEUDO_CLASSES.has(decodedName)) {
                    throw new Error(`Unsupported pseudo-class: ':${decodedName}'`);
                }
            }
            else if (token === csstokenizer/* TokenType */.ks.Ident && prevNonWhitespaceToken === csstokenizer/* TokenType */.ks.OpenSquareBracket) {
                // whitespace is allowed between the '[' and the attribute name, like '[ attr]'
                const attributeName = selectorList.slice(start, end);
                if (attributeName.startsWith(EXT_CSS_ATTRIBUTE_SELECTOR_PREFIX)) {
                    result.isExtendedCss = true;
                    if (!SUPPORTED_EXT_CSS_ATTRIBUTE_SELECTORS.has(attributeName)) {
                        throw new Error(`Unsupported Extended CSS attribute selector: '${attributeName}'`);
                    }
                }
            }
            else if (token === csstokenizer/* TokenType */.ks.OpenCurlyBracket || token === csstokenizer/* TokenType */.ks.CloseCurlyBracket) {
                throw new Error('Curly brackets are not allowed in selector lists');
            }
            else if (token === csstokenizer/* TokenType */.ks.Comment) {
                throw new Error('Comments are not allowed in selector lists');
            }
            // memorize tokens, we need them later
            if (token === csstokenizer/* TokenType */.ks.Colon) {
                prevIsDoubleColon = prevToken === csstokenizer/* TokenType */.ks.Colon;
            }
            prevToken = token;
            if (token !== csstokenizer/* TokenType */.ks.Whitespace) {
                prevNonWhitespaceToken = token;
            }
        });
    }
    catch (error) {
        result.isValid = false;
        result.errorMessage = getErrorMessage(error);
    }
    return result;
};

/**
 * @file Declaration list validator.
 */
const REMOVE_PROPERTY = 'remove';
const REMOVE_LENGTH = REMOVE_PROPERTY.length;
/**
 * Check if function name is forbidden. If so, throws an error.
 *
 * @param functionName Function name to check.
 *
 * @throws Error if function name is forbidden.
 */
const checkFunctionName = (functionName) => {
    // function name may contain escaped characters, like '\75' instead of 'u', so we need to decode it
    const decodedFunctionName = (0,csstokenizer/* decodeIdent */.f0)(functionName);
    if (FORBIDDEN_CSS_FUNCTIONS.has(decodedFunctionName)) {
        throw new Error(`Using '${decodedFunctionName}()' is not allowed`);
    }
};
/**
 * Does a basic validation of a declaration list.
 * Checks for unsafe resource loading and determines if the declaration list is an Extended CSS declaration list.
 *
 * @param declarationList Declaration list to validate.
 *
 * @returns Validation result, see {@link CssValidationResult}.
 *
 * @note This is a basic validation for the most necessary things, it does not guarantee that the CSS is completely
 * valid.
 */
const validateDeclarationList = (declarationList) => {
    const result = {
        isValid: true,
        isExtendedCss: false,
    };
    try {
        (0,csstokenizer/* tokenizeExtended */.jz)(declarationList, (token, start, end) => {
            switch (token) {
                // Special case: according to CSS specs, sometimes url() is handled as a separate token type
                case csstokenizer/* TokenType */.ks.Url:
                case csstokenizer/* TokenType */.ks.BadUrl:
                    throw new Error("Using 'url()' is not allowed");
                case csstokenizer/* TokenType */.ks.Function:
                    // we need -1 to exclude closing bracket, because function tokens look like 'func('
                    checkFunctionName(declarationList.slice(start, end - 1));
                    break;
                case csstokenizer/* TokenType */.ks.Ident:
                    // do a fast check before getting the substring
                    if (end - start === REMOVE_LENGTH) {
                        // TODO: Improve this check, and check the whole `remove: true` sequence.
                        // Please note that the `remove : true` case also valid.
                        if ((0,csstokenizer/* decodeIdent */.f0)(declarationList.slice(start, end)) === REMOVE_PROPERTY) {
                            result.isExtendedCss = true;
                        }
                    }
                    break;
                case csstokenizer/* TokenType */.ks.Comment:
                    throw new Error('Comments are not allowed in declaration lists');
                default:
                    break;
            }
        });
    }
    catch (error) {
        result.isValid = false;
        result.errorMessage = getErrorMessage(error);
    }
    return result;
};

/* eslint-disable max-classes-per-file */
class ScriptletParams {
    props = null;
    constructor(name, args) {
        if (typeof name !== 'undefined') {
            this.props = {
                name,
                args: args || [],
            };
        }
    }
    get name() {
        return this.props?.name;
    }
    get args() {
        return this.props?.args ?? [];
    }
    toString() {
        const result = [];
        result.push(constants/* ADG_SCRIPTLET_MASK */.x$);
        result.push('(');
        if (this.name) {
            result.push(quotes/* QuoteUtils */.Qj.setStringQuoteType(this.name, quotes/* QuoteType */.XA.Single));
        }
        if (this.args.length) {
            result.push(', ');
            result.push(this.args.map((arg) => quotes/* QuoteUtils */.Qj.setStringQuoteType(arg, quotes/* QuoteType */.XA.Single)).join(', '));
        }
        result.push(')');
        return result.join(simple_regex_Dw3J24Ss.E);
    }
}
/**
 * @typedef {import('./cosmetic-result').CosmeticResult} CosmeticResult
 */
/**
 * Implements a basic cosmetic rule.
 *
 * Cosmetic rules syntax are almost similar and looks like this.
 * ```
 * rule = [domains] "marker" content
 * domains = [domain0, domain1[, ...[, domainN]]]
 * ```
 *
 * The rule type is defined by the `type` property, you can find the list of them
 * in the {@link CosmeticRuleType} enumeration.
 *
 * What matters, though, is what's in the `content` part of it.
 *
 * @example
 * `example.org##.banner` -- element hiding rule
 * `example.org#$#.banner { display: block; }` -- CSS rule
 * `example.org#%#window.x=1;` -- JS rule
 * `example.org#%#//scriptlet('scriptlet-name')` -- Scriptlet rule
 * `example.org$$div[id="test"]` -- HTML filtering rule
 */
class CosmeticRule {
    ruleIndex;
    filterListId;
    content;
    type;
    allowlist = false;
    extendedCss = false;
    /**
     * $domain modifier pattern. It is only set if $domain modifier is specified for this rule.
     */
    domainModifier = null;
    /**
     * $path modifier pattern. It is only set if $path modifier is specified for this rule.
     */
    pathModifier;
    /**
     * $url modifier pattern. It is only set if $url modifier is specified for this rule,
     * but $path and $domain modifiers are not.
     *
     * TODO: add this to test cases.
     */
    urlModifier;
    /**
     * Js script to execute.
     */
    script = undefined;
    /**
     * Object with script code ready to execute and debug, domain values.
     *
     * @private
     */
    scriptData = null;
    /**
     * Object with scriptlet function and params.
     *
     * @private
     */
    scriptletData = null;
    /**
     * Scriptlet parameters.
     */
    scriptletParams;
    /**
     * If the rule contains scriptlet content.
     */
    isScriptlet = false;
    getIndex() {
        return this.ruleIndex;
    }
    getFilterListId() {
        return this.filterListId;
    }
    /**
     * Returns the rule content.
     *
     * @returns The content of the rule.
     */
    getContent() {
        return this.content;
    }
    /**
     * Cosmetic rule type (always present).
     *
     * @returns The type of the cosmetic rule.
     */
    getType() {
        return this.type;
    }
    /**
     * Allowlist means that this rule is meant to disable other rules,
     * i.e. an exception rule.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#elemhide-exceptions}
     *
     * @returns True if the rule is an allowlist rule, false otherwise.
     */
    isAllowlist() {
        return this.allowlist;
    }
    /**
     * Returns script ready to execute or null
     * Rebuilds scriptlet script if debug or domain params change.
     *
     * @param options Script options.
     *
     * @returns Script code or null.
     */
    getScript(options = {}) {
        const { debug = false, frameUrl } = options;
        const { scriptData } = this;
        if (scriptData && !this.isScriptlet) {
            return scriptData.code;
        }
        if (scriptData && scriptData.debug === debug) {
            if (frameUrl) {
                if (frameUrl === scriptData.frameUrl) {
                    return scriptData.code;
                }
            }
            else {
                return scriptData.code;
            }
        }
        this.initScript(options);
        return this.scriptData?.code ?? null;
    }
    /**
     * Gets list of permitted domains.
     *
     * @returns List of permitted domains or null if no domain modifier is set.
     */
    getPermittedDomains() {
        if (this.domainModifier) {
            return this.domainModifier.getPermittedDomains();
        }
        return null;
    }
    /**
     * Gets list of restricted domains.
     *
     * @returns List of restricted domains or null if no domain modifier is set.
     */
    getRestrictedDomains() {
        if (this.domainModifier) {
            return this.domainModifier.getRestrictedDomains();
        }
        return null;
    }
    /**
     * Returns true if the rule is considered "generic"
     * "generic" means that the rule is not restricted to a limited set of domains
     * Please note that it might be forbidden on some domains, though.
     *
     * @returns True if the rule is generic, false otherwise.
     */
    isGeneric() {
        return !this.domainModifier?.hasPermittedDomains();
    }
    /**
     * Checks if the rule is ExtendedCss.
     *
     * @returns True if the rule is ExtendedCss, false otherwise.
     */
    isExtendedCss() {
        return this.extendedCss;
    }
    /**
     * Processes cosmetic rule modifiers, e.g. `$path`.
     *
     * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#modifiers-for-non-basic-type-of-rules}
     *
     * @param ruleNode Cosmetic rule node to process.
     *
     * @returns Processed modifiers ({@link ProcessedModifiers}) or `null` if there are no modifiers.
     */
    static processModifiers(ruleNode) {
        // Do nothing if there are no modifiers in the rule node
        if (!ruleNode.modifiers) {
            return null;
        }
        const result = {};
        // We don't allow duplicate modifiers, so we collect them in a set
        const usedModifiers = new Set();
        // Destructure the modifiers array just for convenience
        const { children: modifierNodes } = ruleNode.modifiers;
        // AGTree parser tolerates this case: [$]example.com##.foo
        // However, we should throw an error here if the modifier list is empty
        // (if the modifier list isn't specified at all, then ruleNode.modifiers
        // will be undefined, so we won't get here)
        if (modifierNodes.length < 1) {
            throw new SyntaxError('Modifiers list cannot be be empty');
        }
        for (const modifierNode of modifierNodes) {
            const modifierName = modifierNode.name.value;
            // Check if the modifier is already used
            if (usedModifiers.has(modifierName)) {
                throw new Error(`Duplicated modifier: '${modifierName}'`);
            }
            // Mark the modifier as used by adding it to the set
            usedModifiers.add(modifierName);
            const modifierValue = modifierNode.value?.value || simple_regex_Dw3J24Ss.E;
            // Every modifier should have a value at the moment, so for simplicity we throw an error here if the
            // modifier value is not present.
            // TODO: Improve this when we decide to add modifiers without values
            if (modifierValue.length < 1 && modifierName !== "path" /* CosmeticRuleModifier.Path */) {
                throw new SyntaxError(`'$${modifierName}' modifier should have a value`);
            }
            // Process the modifier based on its name
            switch (modifierName) {
                case "domain" /* CosmeticRuleModifier.Domain */:
                    if (ruleNode.domains.children.length > 0) {
                        throw new SyntaxError(`'$${modifierName}' modifier is not allowed in a domain-specific rule`);
                    }
                    result.domainModifier = new DomainModifier(modifierValue, constants/* PIPE_MODIFIER_SEPARATOR */.fW);
                    break;
                case "path" /* CosmeticRuleModifier.Path */:
                    result.pathModifier = new Pattern(simple_regex_Dw3J24Ss.S.isRegexPattern(modifierValue)
                        // eslint-disable-next-line max-len
                        ? simple_regex_Dw3J24Ss.S.unescapeRegexSpecials(modifierValue, simple_regex_Dw3J24Ss.S.reModifierPatternEscapedSpecialCharacters)
                        : modifierValue);
                    break;
                case "url" /* CosmeticRuleModifier.Url */:
                    if (ruleNode.domains.children.length > 0) {
                        throw new SyntaxError(`'$${modifierName}' modifier is not allowed in a domain-specific rule`);
                    }
                    result.urlModifier = new Pattern(simple_regex_Dw3J24Ss.S.isRegexPattern(modifierValue)
                        // eslint-disable-next-line max-len
                        ? simple_regex_Dw3J24Ss.S.unescapeRegexSpecials(modifierValue, simple_regex_Dw3J24Ss.S.reModifierPatternEscapedSpecialCharacters)
                        : modifierValue);
                    break;
                // Don't allow unknown modifiers
                default:
                    throw new SyntaxError(`'$${modifierName}' modifier is not supported`);
            }
        }
        // $url modifier can't be used with other modifiers
        // TODO: Extend / change this check if we decide to add more such modifiers
        if (result.urlModifier && usedModifiers.size > 1) {
            throw new SyntaxError(`'$${"url" /* CosmeticRuleModifier.Url */}' modifier cannot be used with other modifiers`);
        }
        return result;
    }
    /**
     * Validates cosmetic rule node.
     *
     * @param ruleNode Cosmetic rule node to validate.
     *
     * @returns Validation result {@link ValidationResult}.
     */
    static validate(ruleNode) {
        const result = {
            isValid: true,
            isExtendedCss: false,
        };
        let scriptletName;
        let selectorListValidationResult;
        const { type: ruleType } = ruleNode;
        try {
            // Common validation: every cosmetic rule has a domain list
            if (ruleNode.domains?.children.length) {
                // Iterate over the domain list and check every domain
                for (const { value: domain } of ruleNode.domains.children) {
                    if (!utils_domain/* DomainUtils */.Aw.isValidDomainOrHostname(domain)) {
                        throw new Error(`'${domain}' is not a valid domain name`);
                    }
                }
            }
            // Type-specific validation
            switch (ruleType) {
                case nodes/* CosmeticRuleType */.k9.ElementHidingRule:
                    selectorListValidationResult = validateSelectorList(ruleNode.body.selectorList.value);
                    if (!selectorListValidationResult.isValid) {
                        throw new Error(selectorListValidationResult.errorMessage);
                    }
                    // Detect ExtendedCss and unsupported pseudo-classes
                    result.isExtendedCss = selectorListValidationResult.isExtendedCss;
                    break;
                case nodes/* CosmeticRuleType */.k9.CssInjectionRule:
                    selectorListValidationResult = validateSelectorList(ruleNode.body.selectorList.value);
                    if (!selectorListValidationResult.isValid) {
                        throw new Error(selectorListValidationResult.errorMessage);
                    }
                    // Detect ExtendedCss and unsupported pseudo-classes
                    result.isExtendedCss = selectorListValidationResult.isExtendedCss;
                    // AGTree won't allow the following rule:
                    // `#$#selector { remove: true; padding: 0; }`
                    // because it mixes removal and non-removal declarations.
                    if (ruleNode.body.declarationList) {
                        // eslint-disable-next-line max-len
                        const declarationListValidationResult = validateDeclarationList(ruleNode.body.declarationList.value);
                        if (!declarationListValidationResult.isValid) {
                            throw new Error(declarationListValidationResult.errorMessage);
                        }
                        // If the selector list is not ExtendedCss, then we should set this flag based on the
                        // declaration list validation result
                        if (!result.isExtendedCss) {
                            result.isExtendedCss = declarationListValidationResult.isExtendedCss;
                        }
                    }
                    break;
                case nodes/* CosmeticRuleType */.k9.ScriptletInjectionRule:
                    // Scriptlet name is the first child of the parameter list
                    // eslint-disable-next-line max-len
                    scriptletName = quotes/* QuoteUtils */.Qj.removeQuotes(ruleNode.body.children[0]?.children[0]?.value ?? simple_regex_Dw3J24Ss.E);
                    // Special case: scriptlet name is empty, e.g. '#%#//scriptlet()'
                    if (scriptletName.length === 0) {
                        break;
                    }
                    // Check if the scriptlet name is valid
                    if (!(0,validators/* isValidScriptletName */.GY)(scriptletName)) {
                        throw new Error(`'${scriptletName}' is not a known scriptlet name`);
                    }
                    break;
                case nodes/* CosmeticRuleType */.k9.HtmlFilteringRule:
                    // TODO: Validate HTML filtering rules
                    break;
                case nodes/* CosmeticRuleType */.k9.JsInjectionRule:
                    // TODO: Validate JS injection rules
                    break;
                default:
                    break;
            }
        }
        catch (error) {
            result.isValid = false;
            result.errorMessage = getErrorMessage(error);
        }
        return result;
    }
    /**
     * Checks if the domain list contains any domains, but returns `false` if only
     * the wildcard domain is specified.
     *
     * @param domainListNode Domain list node to check.
     *
     * @returns `true` if the domain list contains any domains, `false` otherwise.
     */
    static isAnyDomainSpecified(domainListNode) {
        if (domainListNode.children.length > 0) {
            // Skip wildcard domain list (*)
            return !(domainListNode.children.length === 1 && domainListNode.children[0].value === simple_regex_Dw3J24Ss.W);
        }
        return false;
    }
    /**
     * Creates an instance of the {@link CosmeticRule}.
     * It parses the rule and extracts the permitted/restricted domains,
     * and also the cosmetic rule's content.
     *
     * Depending on the rule type, the content might be transformed in
     * one of the helper classes, or kept as string when it's appropriate.
     *
     * @param node AST node of the cosmetic rule.
     * @param filterListId ID of the filter list this rule belongs to.
     * @param ruleIndex Line start index in the source filter list; it will be used to find the original rule text
     * in the filtering log when a rule is applied. Default value is {@link RULE_INDEX_NONE} which means that
     * the rule does not have source index.
     *
     * @throws Error if it fails to parse the rule.
     */
    constructor(node, filterListId, ruleIndex = RULE_INDEX_NONE) {
        this.ruleIndex = ruleIndex;
        this.filterListId = filterListId;
        this.allowlist = cosmetic_rule_separator/* CosmeticRuleSeparatorUtils */.m.isException(node.separator.value);
        this.type = node.type;
        this.isScriptlet = node.type === nodes/* CosmeticRuleType */.k9.ScriptletInjectionRule;
        this.content = cosmetic_rule_body_generator/* CosmeticRuleBodyGenerator */.H.generate(node);
        // Store the scriptlet parameters. They will be used later, when we initialize the scriptlet,
        // but at this point we need to store them in order to avoid double parsing
        if (node.type === nodes/* CosmeticRuleType */.k9.ScriptletInjectionRule) {
            // Transform complex node into a simple array of strings
            const params = node.body.children[0]?.children.map((param) => (param === null ? simple_regex_Dw3J24Ss.E : quotes/* QuoteUtils */.Qj.removeQuotesAndUnescape(param.value))) ?? [];
            this.scriptletParams = new ScriptletParams(params[0] ?? '', params.slice(1));
        }
        else {
            this.scriptletParams = new ScriptletParams();
        }
        const validationResult = CosmeticRule.validate(node);
        // We should throw an error if the validation failed for any reason
        if (!validationResult.isValid) {
            throw new SyntaxError(validationResult.errorMessage);
        }
        // Check if the rule is ExtendedCss
        const isExtendedCssSeparator = cosmetic_rule_separator/* CosmeticRuleSeparatorUtils */.m.isExtendedCssMarker(node.separator.value);
        this.extendedCss = isExtendedCssSeparator || validationResult.isExtendedCss;
        // Process cosmetic rule modifiers
        const processedModifiers = CosmeticRule.processModifiers(node);
        if (processedModifiers) {
            if (processedModifiers.domainModifier) {
                this.domainModifier = processedModifiers.domainModifier;
            }
            if (processedModifiers.pathModifier) {
                this.pathModifier = processedModifiers.pathModifier;
            }
            if (processedModifiers.urlModifier) {
                this.urlModifier = processedModifiers.urlModifier;
            }
        }
        // Process domain list, if at least one domain is specified
        const { domains: domainListNode } = node;
        if (CosmeticRule.isAnyDomainSpecified(domainListNode)) {
            this.domainModifier = new DomainModifier(domainListNode, constants/* COMMA_DOMAIN_LIST_SEPARATOR */.oo);
        }
    }
    /**
     * Match returns true if this rule can be used on the specified request.
     *
     * @param request Request to check.
     *
     * @returns True if the rule matches the request, false otherwise.
     */
    match(request) {
        if (!this.domainModifier
            && !this.pathModifier
            && !this.urlModifier) {
            return true;
        }
        if (this.urlModifier) {
            return this.urlModifier.matchPattern(request, false);
        }
        if (this.domainModifier) {
            if (!this.domainModifier.matchDomain(request.hostname)) {
                return false;
            }
        }
        if (this.pathModifier) {
            const path = getRelativeUrl(request.urlLowercase);
            if (path) {
                return this.pathModifier.matchPathPattern(path);
            }
            return false;
        }
        return true;
    }
    /**
     * Returns the scriptlet's data consisting of the scriptlet function and its arguments.
     * This method is supposed to be used in the manifest V3 extension.
     *
     * @returns The scriptlet data or null if not available.
     */
    getScriptletData() {
        if (this.scriptletData) {
            return this.scriptletData;
        }
        this.initScript();
        return this.scriptletData;
    }
    /**
     * Updates this.scriptData and this.scriptletData when it is necessary in a lazy way.
     *
     * @param options Initialization options for the script.
     */
    initScript(options = {}) {
        const { debug = false, frameUrl } = options;
        const ruleContent = this.getContent();
        if (!this.isScriptlet) {
            this.scriptData = {
                code: ruleContent,
            };
            return;
        }
        // A scriptlet without a name can only be an allowlist scriptlet
        // https://github.com/AdguardTeam/Scriptlets/issues/377
        // or it is considered invalid if the scriptlet was invalid.
        // This does not require finding scriptData and scriptletData.
        if (!this.scriptletParams?.name) {
            return;
        }
        const params = {
            args: this.scriptletParams.args,
            engine: config.engine || simple_regex_Dw3J24Ss.E,
            name: this.scriptletParams.name,
            verbose: debug,
            domainName: frameUrl,
            version: config.version || simple_regex_Dw3J24Ss.E,
        };
        this.scriptData = {
            code: scriptlets/* scriptlets */.e.invoke(params) ?? null,
            debug,
            frameUrl,
        };
        this.scriptletData = {
            func: scriptlets/* scriptlets */.e.getScriptletFunction(params.name),
            params,
        };
    }
}

/**
 * @typedef {import('./cosmetic-result').CosmeticResult} CosmeticResult
 */
/**
 * This class stores found cosmetic css rules content in the appropriate collections
 * It is primarily used by the {@link CosmeticResult}.
 */
class CosmeticStylesResult {
    /**
     * Collection of generic rules.
     */
    generic;
    /**
     * Collection of specific rules.
     */
    specific;
    /**
     * Collection of generic ext-css rules.
     */
    genericExtCss;
    /**
     * Collection of specific ext-css rules.
     */
    specificExtCss;
    /**
     * Constructor.
     */
    constructor() {
        this.generic = [];
        this.specific = [];
        this.genericExtCss = [];
        this.specificExtCss = [];
    }
    /**
     * Appends rule to the appropriate collection.
     *
     * @param rule Cosmetic rule.
     */
    append(rule) {
        if (rule.isGeneric()) {
            if (rule.isExtendedCss()) {
                this.genericExtCss.push(rule);
            }
            else {
                this.generic.push(rule);
            }
        }
        else if (rule.isExtendedCss()) {
            this.specificExtCss.push(rule);
        }
        else {
            this.specific.push(rule);
        }
    }
}

/**
 * @typedef {import('./cosmetic-result').CosmeticResult} CosmeticResult
 */
/**
 * This class stores found script rules content in the appropriate collections
 * It is primarily used by the {@link CosmeticResult}.
 */
class CosmeticScriptsResult {
    /**
     * Collection of generic (domain insensitive) rules.
     */
    generic;
    /**
     * Collection of domain specific rules.
     */
    specific;
    /**
     * Constructor.
     */
    constructor() {
        this.generic = [];
        this.specific = [];
    }
    /**
     * Appends rule to appropriate collection.
     *
     * @param rule Cosmetic rule.
     */
    append(rule) {
        if (rule.isGeneric()) {
            this.generic.push(rule);
        }
        else {
            this.specific.push(rule);
        }
    }
    /**
     * Returns collected cosmetic rules — both generic and specific.
     *
     * @returns Array of collected cosmetic rules.
     */
    getRules() {
        return [...this.generic, ...this.specific];
    }
}

/**
 * @typedef {import('./cosmetic-result').CosmeticResult} CosmeticResult
 */
/**
 * This class stores found cosmetic html rules content in the appropriate collections
 * It is primarily used by the {@link CosmeticResult}.
 */
class CosmeticHtmlResult {
    /**
     * Collection of generic rules.
     */
    generic;
    /**
     * Collection of specific rules.
     */
    specific;
    /**
     * Constructor.
     */
    constructor() {
        this.generic = [];
        this.specific = [];
    }
    /**
     * Appends rule to the appropriate collection.
     *
     * @param rule Rule to process.
     */
    append(rule) {
        if (rule.isGeneric()) {
            this.generic.push(rule);
        }
        else {
            this.specific.push(rule);
        }
    }
    /**
     * Returns collected cosmetic **HTML** rules — both generic and specific.
     *
     * @returns Array of collected rules.
     */
    getRules() {
        return [...this.generic, ...this.specific];
    }
}

/**
 * @typedef {import('./cosmetic-engine').CosmeticEngine} CosmeticEngine
 */
/**
 * Cosmetic result is the representation of rules
 * It is primarily used by the {@link CosmeticEngine}.
 */
class CosmeticResult {
    /**
     * Storage of element hiding rules.
     */
    elementHiding;
    /**
     * Storage of CSS rules.
     */
    CSS;
    /**
     * Storage of JS rules.
     */
    JS;
    /**
     * Storage of Html filtering rules.
     */
    Html;
    /**
     * Constructor.
     */
    constructor() {
        this.elementHiding = new CosmeticStylesResult();
        this.CSS = new CosmeticStylesResult();
        this.JS = new CosmeticScriptsResult();
        this.Html = new CosmeticHtmlResult();
    }
    /**
     * Script rules.
     *
     * @returns Array of cosmetic **JavaScript** rules.
     */
    getScriptRules() {
        return this.JS.getRules();
    }
}

/**
 * CosmeticOption is the enumeration of various content script options.
 * Depending on the set of enabled flags the content script will contain different set of settings.
 */
var CosmeticOption;
(function (CosmeticOption) {
    /**
     * If generic elemhide and CSS rules are enabled.
     * Could be disabled by a $generichide rule and $elemhide rule.
     */
    CosmeticOption[CosmeticOption["CosmeticOptionGenericCSS"] = 2] = "CosmeticOptionGenericCSS";
    /**
     * If specific elemhide and CSS rules are enabled.
     * Could be disabled by a $specifichide rule and $elemhide rule.
     */
    CosmeticOption[CosmeticOption["CosmeticOptionSpecificCSS"] = 4] = "CosmeticOptionSpecificCSS";
    /**
     * If JS rules and scriptlets are enabled.
     * Could be disabled by a $jsinject rule.
     */
    CosmeticOption[CosmeticOption["CosmeticOptionJS"] = 8] = "CosmeticOptionJS";
    /**
     * If HTML filtering rules are enabled.
     * Could be disabled by a $content rule.
     */
    CosmeticOption[CosmeticOption["CosmeticOptionHtml"] = 16] = "CosmeticOptionHtml";
    /**
     * TODO: Add support for these flags.
     *
     * They are useful when content script is injected into an iframe.
     * In this case we can check what flags were applied to the top-level frame.
     */
    CosmeticOption[CosmeticOption["CosmeticOptionSourceGenericCSS"] = 32] = "CosmeticOptionSourceGenericCSS";
    CosmeticOption[CosmeticOption["CosmeticOptionSourceCSS"] = 64] = "CosmeticOptionSourceCSS";
    CosmeticOption[CosmeticOption["CosmeticOptionSourceJS"] = 128] = "CosmeticOptionSourceJS";
    /**
     * Everything is enabled.
     */
    CosmeticOption[CosmeticOption["CosmeticOptionAll"] = 30] = "CosmeticOptionAll";
    /**
     * Everything is disabled.
     */
    CosmeticOption[CosmeticOption["CosmeticOptionNone"] = 0] = "CosmeticOptionNone";
})(CosmeticOption || (CosmeticOption = {}));

/**
 * Scanner types enum.
 */
var ScannerType;
(function (ScannerType) {
    /**
     * Scanning for network rules.
     */
    ScannerType[ScannerType["NetworkRules"] = 0] = "NetworkRules";
    /**
     * Scanning for cosmetic rules.
     */
    ScannerType[ScannerType["CosmeticRules"] = 2] = "CosmeticRules";
    /**
     * Scanning for host rules.
     */
    ScannerType[ScannerType["HostRules"] = 4] = "HostRules";
    /**
     * All types of rules.
     */
    ScannerType[ScannerType["All"] = 6] = "All";
})(ScannerType || (ScannerType = {}));

/**
 * @typedef {import('../engine').Engine} Engine
 */
/**
 * CosmeticEngine combines all the cosmetic rules and allows to quickly
 * find all rules matching this or that hostname
 * It is primarily used by the {@link Engine}.
 */
class CosmeticEngine {
    /**
     * Rules storage.
     */
    ruleStorage;
    /**
     * Count of rules added to the engine.
     */
    rulesCount;
    /**
     * Lookup table for elemhide rules.
     */
    elementHidingLookupTable;
    /**
     * Lookup table for css rules.
     */
    cssLookupTable;
    /**
     * Lookup table for js and scriptlets rules.
     */
    jsLookupTable;
    /**
     * Lookup table for html filtering rules.
     */
    htmlLookupTable;
    /**
     * Builds instance of cosmetic engine.
     *
     * @param ruleStorage Rule storage.
     * @param skipStorageScan Create an instance without storage scanning.
     */
    constructor(ruleStorage, skipStorageScan = false) {
        this.ruleStorage = ruleStorage;
        this.rulesCount = 0;
        this.elementHidingLookupTable = new CosmeticLookupTable(ruleStorage);
        this.cssLookupTable = new CosmeticLookupTable(ruleStorage);
        this.jsLookupTable = new CosmeticLookupTable(ruleStorage);
        this.htmlLookupTable = new CosmeticLookupTable(ruleStorage);
        if (skipStorageScan) {
            return;
        }
        const scanner = this.ruleStorage.createRuleStorageScanner(ScannerType.CosmeticRules);
        while (scanner.scan()) {
            const indexedRule = scanner.getRule();
            if (indexedRule
                && indexedRule.rule instanceof CosmeticRule) {
                this.addRule(indexedRule.rule, indexedRule.index);
            }
        }
    }
    /**
     * Adds rules into appropriate tables.
     *
     * @param rule Rule to add.
     * @param storageIdx Index of the rule in the storage.
     */
    addRule(rule, storageIdx) {
        switch (rule.getType()) {
            case nodes/* CosmeticRuleType */.k9.ElementHidingRule: {
                this.elementHidingLookupTable.addRule(rule, storageIdx);
                break;
            }
            case nodes/* CosmeticRuleType */.k9.CssInjectionRule: {
                this.cssLookupTable.addRule(rule, storageIdx);
                break;
            }
            case nodes/* CosmeticRuleType */.k9.ScriptletInjectionRule: {
                this.jsLookupTable.addRule(rule, storageIdx);
                break;
            }
            case nodes/* CosmeticRuleType */.k9.JsInjectionRule: {
                this.jsLookupTable.addRule(rule, storageIdx);
                break;
            }
            case nodes/* CosmeticRuleType */.k9.HtmlFilteringRule: {
                this.htmlLookupTable.addRule(rule, storageIdx);
                break;
            }
        }
        this.rulesCount += 1;
    }
    /**
     * Checks if bitwise mask matches option.
     *
     * @param option Option to match.
     * @param targetOption Target option.
     *
     * @returns True if option matches targetOption.
     */
    static matchOption(option, targetOption) {
        return (option & targetOption) === targetOption;
    }
    /**
     * Prepares cosmetic result by request.
     *
     * @param request Request to match.
     * @param option Mask of enabled cosmetic types.
     *
     * @returns CosmeticResult.
     */
    match(request, option) {
        const includeGeneric = CosmeticEngine.matchOption(option, CosmeticOption.CosmeticOptionGenericCSS);
        const includeSpecific = CosmeticEngine.matchOption(option, CosmeticOption.CosmeticOptionSpecificCSS);
        const includeJs = CosmeticEngine.matchOption(option, CosmeticOption.CosmeticOptionJS);
        const includeHtml = CosmeticEngine.matchOption(option, CosmeticOption.CosmeticOptionHtml);
        const cosmeticResult = new CosmeticResult();
        if (includeGeneric) {
            CosmeticEngine.appendGenericRules(cosmeticResult.elementHiding, this.elementHidingLookupTable, request);
            CosmeticEngine.appendGenericRules(cosmeticResult.CSS, this.cssLookupTable, request);
        }
        if (includeSpecific) {
            CosmeticEngine.appendSpecificRules(cosmeticResult.elementHiding, this.elementHidingLookupTable, request);
            CosmeticEngine.appendSpecificRules(cosmeticResult.CSS, this.cssLookupTable, request);
        }
        if (includeJs) {
            CosmeticEngine.appendGenericRules(cosmeticResult.JS, this.jsLookupTable, request);
            CosmeticEngine.appendSpecificRules(cosmeticResult.JS, this.jsLookupTable, request);
        }
        if (includeHtml) {
            if (includeGeneric) {
                CosmeticEngine.appendGenericRules(cosmeticResult.Html, this.htmlLookupTable, request);
            }
            CosmeticEngine.appendSpecificRules(cosmeticResult.Html, this.htmlLookupTable, request);
        }
        return cosmeticResult;
    }
    /**
     * Selects generic rules and appends rules content to cosmetic result.
     *
     * @param cosmeticResult Cosmetic result.
     * @param lookupTable Lookup table.
     * @param request Request.
     */
    static appendGenericRules(cosmeticResult, lookupTable, request) {
        for (const genericRule of lookupTable.genericRules) {
            if (!lookupTable.isAllowlisted(request, genericRule)
                && genericRule.match(request)) {
                cosmeticResult.append(genericRule, request);
            }
        }
    }
    /**
     * Selects specific rules and appends rules content to cosmetic result.
     *
     * @param cosmeticResult Cosmetic result.
     * @param lookupTable Lookup table.
     * @param request Request.
     */
    static appendSpecificRules(cosmeticResult, lookupTable, request) {
        const hostnameRules = lookupTable.findByHostname(request);
        if (hostnameRules.length > 0) {
            for (const rule of hostnameRules) {
                if (!lookupTable.isAllowlisted(request, rule)) {
                    cosmeticResult.append(rule, request);
                }
            }
        }
    }
}

/**
 * Replace modifier class.
 */
class ReplaceModifier {
    /**
     * Replace option value.
     */
    replaceOption;
    /**
     * Replace option apply function.
     */
    replaceApply;
    /**
     * Constructor.
     *
     * @param value Replace modifier value.
     */
    constructor(value) {
        const parsed = ReplaceModifier.parseReplaceOption(value);
        this.replaceOption = parsed.optionText;
        this.replaceApply = parsed.apply;
    }
    /**
     * Parses replace option.
     *
     * @param option Replace option.
     *
     * @returns Parsed replace option.
     */
    static parseReplaceOption(option) {
        if (!option) {
            return {
                apply: (x) => x,
                optionText: '',
            };
        }
        const parts = (0,simple_regex_Dw3J24Ss.s)(option, '/', '\\', true);
        let modifiers = (parts[2] || '');
        if (modifiers.indexOf('g') < 0) {
            modifiers += 'g';
        }
        const pattern = new RegExp(parts[0], modifiers);
        // unescape replacement alias
        let replacement = parts[1].replace(/\\\$/g, '$');
        replacement = simple_regex_Dw3J24Ss.S.unescapeSpecials(replacement);
        const apply = (input) => input.replace(pattern, replacement);
        return {
            apply,
            optionText: option,
        };
    }
    /**
     * Replace content.
     *
     * @returns The replace option value.
     */
    getValue() {
        return this.replaceOption;
    }
    /**
     * Replace apply function.
     *
     * @returns The function to apply the replacement.
     */
    getApplyFunc() {
        return this.replaceApply;
    }
}

const CSP_HEADER_NAME = 'Content-Security-Policy';
/**
 * Csp modifier class.
 */
class CspModifier {
    /**
     * Csp directive.
     *
     * @returns The CSP directive.
     */
    cspDirective;
    /**
     * Is allowlist rule.
     */
    isAllowlist;
    /**
     * Constructor.
     *
     * @param value Value of the modifier.
     * @param isAllowlist Whether the rule is an allowlist rule or not.
     */
    constructor(value, isAllowlist) {
        this.cspDirective = value;
        this.isAllowlist = isAllowlist;
        this.validateCspDirective();
    }
    /**
     * Csp directive.
     *
     * @returns The CSP directive.
     */
    getValue() {
        return this.cspDirective;
    }
    /**
     * Validates CSP rule.
     */
    validateCspDirective() {
        /**
         * CSP directive may be empty in case of allowlist rule,
         * it means to disable all $csp rules matching the allowlist rule.
         *
         * @see {@link https://github.com/AdguardTeam/AdguardBrowserExtension/issues/685}
         */
        if (!this.isAllowlist && !this.cspDirective) {
            throw new Error('Invalid $CSP rule: CSP directive must not be empty');
        }
        if (this.cspDirective) {
            /**
             * Forbids report-to and report-uri directives.
             *
             * @see {@link https://github.com/AdguardTeam/AdguardBrowserExtension/issues/685#issue-228287090}
             */
            const cspDirective = this.cspDirective.toLowerCase();
            if (cspDirective.indexOf('report-') >= 0) {
                throw new Error(`Forbidden CSP directive: ${cspDirective}`);
            }
        }
    }
}

/**
 * Cookie modifier class.
 *
 * Learn more about it here:
 * https://github.com/AdguardTeam/AdguardBrowserExtension/issues/961.
 */
class CookieModifier {
    /**
     * Cookie `maxAge` name.
     */
    static MAX_AGE = 'maxAge';
    /**
     * Cookie `sameSite` name.
     */
    static SAME_SITE = 'sameSite';
    /**
     * Option value.
     */
    optionValue;
    /**
     * Regexp value.
     */
    regex;
    /**
     * Cookie name.
     */
    cookieName;
    /**
     * Cookie `sameSite` value.
     */
    sameSite;
    /**
     * Cookie `maxAge` value.
     */
    maxAge;
    /**
     * Constructor.
     *
     * @param value Value of the modifier.
     */
    constructor(value) {
        // Save the source text of the option modifier
        this.optionValue = value || '';
        this.regex = null;
        this.cookieName = null;
        this.sameSite = null;
        this.maxAge = null;
        // Parse cookie name/regex
        const parts = this.optionValue.split(/;/);
        if (parts.length < 1) {
            throw new Error(`Cannot parse ${this.optionValue}`);
        }
        const cookieName = parts[0];
        if (cookieName.startsWith('/') && cookieName.endsWith('/')) {
            const pattern = cookieName.substring(1, cookieName.length - 1);
            // Save regex to be used further for matching cookies
            this.regex = new RegExp(pattern);
        }
        else {
            // Match by cookie name
            this.cookieName = cookieName;
        }
        // Parse other cookie options
        if (parts.length > 1) {
            for (let i = 1; i < parts.length; i += 1) {
                const nameValue = parts[i].split('=');
                const optionName = nameValue[0];
                const optionValue = nameValue[1];
                if (optionName === CookieModifier.MAX_AGE) {
                    this.maxAge = parseInt(optionValue, 10);
                }
                else if (optionName === CookieModifier.SAME_SITE) {
                    this.sameSite = optionValue;
                }
                else {
                    throw new Error(`Unknown $cookie option: ${optionName}`);
                }
            }
        }
    }
    /**
     * Gets modifier value.
     *
     * @returns Modifier value.
     */
    getValue() {
        return this.optionValue;
    }
    /**
     * First cookie name.
     *
     * @returns The first cookie name.
     */
    getCookieName() {
        return this.cookieName;
    }
    /**
     * Max age cookie value.
     *
     * @returns The max age cookie value.
     */
    getMaxAge() {
        return this.maxAge;
    }
    /**
     * Same site cookie value.
     *
     * @returns The same site cookie value.
     */
    getSameSite() {
        return this.sameSite;
    }
    /**
     * Checks if cookie with the specified name matches this option.
     *
     * @param name Cookie name.
     *
     * @returns True if matches, false otherwise.
     */
    matches(name) {
        if (!name) {
            return false;
        }
        if (this.regex) {
            return this.regex.test(name);
        }
        if (this.cookieName) {
            return this.cookieName === name;
        }
        // Empty regex and cookieName means that we must match all cookies
        return true;
    }
    /**
     * Checks if cookie rule has an empty $cookie option.
     *
     * @returns True if $cookie option is empty.
     */
    isEmpty() {
        return !this.regex && !this.cookieName;
    }
    /**
     * Checks if the given modifier is an instance of CookieModifier.
     *
     * @param m The modifier to check.
     *
     * @returns True if the modifier is an instance of CookieModifier, false otherwise.
     */
    static isCookieModifier = (m) => {
        return m instanceof CookieModifier;
    };
}

/**
 * Array of all stealth options available, even those which are not supported by browser extension.
 */
var UniversalStealthOption;
(function (UniversalStealthOption) {
    UniversalStealthOption["HideSearchQueries"] = "searchqueries";
    UniversalStealthOption["DoNotTrack"] = "donottrack";
    UniversalStealthOption["ThirdPartyCookies"] = "3p-cookie";
    UniversalStealthOption["FirstPartyCookies"] = "1p-cookie";
    UniversalStealthOption["ThirdPartyCache"] = "3p-cache";
    UniversalStealthOption["ThirdPartyAuth"] = "3p-auth";
    UniversalStealthOption["WebRTC"] = "webrtc";
    UniversalStealthOption["Push"] = "push";
    UniversalStealthOption["Location"] = "location";
    UniversalStealthOption["Flash"] = "flash";
    UniversalStealthOption["Java"] = "java";
    UniversalStealthOption["HideReferrer"] = "referrer";
    UniversalStealthOption["UserAgent"] = "useragent";
    UniversalStealthOption["IP"] = "ip";
    UniversalStealthOption["XClientData"] = "xclientdata";
    UniversalStealthOption["DPI"] = "dpi";
})(UniversalStealthOption || (UniversalStealthOption = {}));
/**
 * List of stealth options, supported by browser extension, which can be disabled by $stealth modifier.
 *
 * Following stealth options are initialized on the engine start
 * and can't be disabled via $stealth modifier:
 * - `Block trackers` and `Remove tracking parameters`, as they are applied by a specific
 *   rule lists, initialized on app start;
 * - `Disabling WebRTC`, as it is not being applied on per-request basis.
 */
var StealthOptionName;
(function (StealthOptionName) {
    StealthOptionName["HideSearchQueries"] = "searchqueries";
    StealthOptionName["DoNotTrack"] = "donottrack";
    StealthOptionName["HideReferrer"] = "referrer";
    StealthOptionName["XClientData"] = "xclientdata";
    StealthOptionName["FirstPartyCookies"] = "1p-cookie";
    StealthOptionName["ThirdPartyCookies"] = "3p-cookie";
})(StealthOptionName || (StealthOptionName = {}));
const StealthModifierOptions = new Set(Object.values(StealthOptionName));
const UniversalStealthOptions = new Set(Object.values(UniversalStealthOption));
const StealthOption = {
    NotSet: 0,
    [StealthOptionName.HideSearchQueries]: 1,
    [StealthOptionName.DoNotTrack]: 1 << 1,
    [StealthOptionName.HideReferrer]: 1 << 2,
    [StealthOptionName.XClientData]: 1 << 3,
    [StealthOptionName.FirstPartyCookies]: 1 << 4,
    [StealthOptionName.ThirdPartyCookies]: 1 << 5,
};
/**
 * Id to create stealth mode rule lists with,
 * e.g cookie rules for `Self-destructing third-party/first-party cookies` options.
 * It is also used to identify such rules when disabling on per-rule basis.
 */
const STEALTH_MODE_FILTER_ID = -1;
/**
 * Stealth modifier class.
 * Rules with $stealth modifier will disable specified stealth options for matched requests.
 *
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#stealth-modifier}
 */
class StealthModifier {
    PIPE_SEPARATOR = '|';
    options = StealthOption.NotSet;
    /**
     * Parses the options string and creates a new stealth modifier instance.
     *
     * @param optionsStr Options string.
     *
     * @throws SyntaxError on inverted stealth options, which are not supported.
     */
    constructor(optionsStr) {
        if (optionsStr.trim().length === 0) {
            return;
        }
        // This prevents parsing invalid syntax as rule without supported options
        if (optionsStr.includes(',')) {
            throw new SyntaxError(`Invalid separator of stealth options used: "${optionsStr}"`);
        }
        const tokens = optionsStr.split(this.PIPE_SEPARATOR);
        for (let i = 0; i < tokens.length; i += 1) {
            const optionName = tokens[i].trim();
            if (optionName === '') {
                continue;
            }
            if (optionName.startsWith('~')) {
                throw new SyntaxError(`Inverted $stealth modifier values are not allowed: "${optionsStr}"`);
            }
            if (!StealthModifier.isValidStealthOption(optionName)) {
                throw new SyntaxError(`Invalid $stealth option in modifier value: "${optionsStr}"`);
            }
            // Skip options which are not supported by browser extension
            if (!StealthModifier.isSupportedStealthOption(optionName)) {
                continue;
            }
            const option = StealthOption[optionName];
            if (this.options & option) {
                logger.debug(`Duplicate $stealth modifier value "${optionName}" in "${optionsStr}"`);
            }
            this.options |= option;
        }
        if (this.options === StealthOption.NotSet) {
            // eslint-disable-next-line max-len
            const msg = `$stealth modifier does not contain any options supported by browser extension: "${optionsStr}"`;
            logger.debug(msg);
        }
    }
    /**
     * Checks if the given string is a valid $stealth option, supported by browser extension.
     *
     * @param option Option name.
     *
     * @returns True if the given string is a valid $stealth option.
     */
    static isSupportedStealthOption = (option) => StealthModifierOptions.has(option);
    /**
     * Checks if the given string is a valid $stealth option.
     *
     * @param option Option name.
     *
     * @returns True if the given string is a valid $stealth option.
     */
    static isValidStealthOption = (option) => UniversalStealthOptions.has(option);
    /**
     * Checks if this stealth modifier has values.
     *
     * @returns True if this stealth modifier has at least one value.
     */
    hasValues() {
        return this.options !== StealthOption.NotSet;
    }
    /**
     * Checks if this stealth modifier is disabling the given stealth option.
     *
     * @param optionName Stealth option name.
     *
     * @returns True if this stealth modifier is disabling the given stealth option.
     */
    hasStealthOption(optionName) {
        const option = StealthOption[optionName];
        return !!(option && this.options & option);
    }
}

/**
 * Redirect modifier class.
 */
class RedirectModifier {
    /**
     * Redirect title.
     */
    redirectTitle;
    /**
     * Is redirecting only blocked requests
     * See $redirect-rule options.
     */
    isRedirectingOnlyBlocked = false;
    /**
     * Constructor.
     *
     * @param value Redirect modifier value.
     * @param isAllowlist Is allowlist rule.
     * @param isRedirectingOnlyBlocked Is redirect-rule modifier.
     */
    constructor(value, isAllowlist, isRedirectingOnlyBlocked = false) {
        RedirectModifier.validate(value, isAllowlist);
        this.redirectTitle = value;
        this.isRedirectingOnlyBlocked = isRedirectingOnlyBlocked;
    }
    /**
     * Redirect title.
     *
     * @returns The redirect title.
     */
    getValue() {
        return this.redirectTitle;
    }
    /**
     * Validates redirect rule.
     *
     * @param redirectTitle The title of the redirect.
     * @param isAllowlist Indicates if the rule is an allowlist rule.
     */
    static validate(redirectTitle, isAllowlist) {
        if (isAllowlist && !redirectTitle) {
            return;
        }
        if (!redirectTitle) {
            throw new SyntaxError('Invalid $redirect rule, redirect value must not be empty');
        }
        if (!(0,validators/* isRedirectResourceCompatibleWithAdg */.td)(redirectTitle)) {
            throw new SyntaxError('$redirect modifier is invalid');
        }
    }
}

/**
 * Query parameters filtering modifier class.
 * Works with `$removeparam` modifier.
 */
class RemoveParamModifier {
    /**
     * Value of the modifier.
     */
    value;
    /**
     * Is modifier valid for MV3 or not.
     *
     * @returns True if the modifier is valid for MV3, false otherwise.
     */
    mv3Valid = true;
    /**
     * RegExp to apply.
     */
    valueRegExp;
    /**
     * Constructor.
     *
     * @param value The value used to initialize the modifier.
     */
    constructor(value) {
        this.value = value;
        let rawValue = value;
        // TODO: Seems like negation not using in valueRegExp
        if (value.startsWith('~')) {
            rawValue = value.substring(1);
            this.mv3Valid = false;
        }
        if (rawValue.startsWith('/')) {
            this.valueRegExp = simple_regex_Dw3J24Ss.S.patternFromString(rawValue);
            this.mv3Valid = false;
        }
        else {
            if (rawValue.includes('|')) {
                throw new Error('Unsupported option in $removeparam: multiple values are not allowed');
            }
            // no need to match "&" in the beginning, because we are splitting by "&"
            // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/3076
            this.valueRegExp = new RegExp(`^${simple_regex_Dw3J24Ss.S.escapeRegexSpecials(rawValue)}=[^&#]*$`, 'g');
        }
    }
    /**
     * Modifier value.
     *
     * @returns The value of the modifier.
     */
    getValue() {
        return this.value;
    }
    /**
     * Is modifier valid for MV3 or not.
     *
     * @returns True if the modifier is valid for MV3, false otherwise.
     */
    getMV3Validity() {
        return this.mv3Valid;
    }
    /**
     * Checks if the given modifier is an instance of RemoveParamModifier.
     *
     * @param m The modifier to check.
     *
     * @returns True if the modifier is an instance of RemoveParamModifier, false otherwise.
     */
    static isRemoveParamModifier = (m) => {
        return m instanceof RemoveParamModifier;
    };
    /**
     * Removes query parameters from url.
     *
     * @param url The URL from which query parameters should be removed.
     *
     * @returns The URL with the query parameters removed.
     */
    removeParameters(url) {
        const sepIndex = url.indexOf('?');
        if (sepIndex < 0) {
            return url;
        }
        if (!this.value) {
            return url.substring(0, sepIndex);
        }
        if (sepIndex === url.length - 1) {
            return url;
        }
        if (this.value.startsWith('~')) {
            return cleanUrlParamByRegExp(url, this.valueRegExp, true);
        }
        return cleanUrlParamByRegExp(url, this.valueRegExp);
    }
}

/**
 * Headers filtering modifier class.
 * Rules with $removeheader modifier are intended to remove headers from HTTP requests and responses.
 */
class RemoveHeaderModifier {
    /**
     * List of forbidden headers.
     */
    static FORBIDDEN_HEADERS = [
        'access-control-allow-origin',
        'access-control-allow-credentials',
        'access-control-allow-headers',
        'access-control-allow-methods',
        'access-control-expose-headers',
        'access-control-max-age',
        'access-control-request-headers',
        'access-control-request-method',
        'origin',
        'timing-allow-origin',
        'allow',
        'cross-origin-embedder-policy',
        'cross-origin-opener-policy',
        'cross-origin-resource-policy',
        'content-security-policy',
        'content-security-policy-report-only',
        'expect-ct',
        'feature-policy',
        'origin-isolation',
        'strict-transport-security',
        'upgrade-insecure-requests',
        'x-content-type-options',
        'x-download-options',
        'x-frame-options',
        'x-permitted-cross-domain-policies',
        'x-powered-by',
        'x-xss-protection',
        'public-key-pins',
        'public-key-pins-report-only',
        'sec-websocket-key',
        'sec-websocket-extensions',
        'sec-websocket-accept',
        'sec-websocket-protocol',
        'sec-websocket-version',
        'p3p',
        'sec-fetch-mode',
        'sec-fetch-dest',
        'sec-fetch-site',
        'sec-fetch-user',
        'referrer-policy',
        'content-type',
        'content-length',
        'accept',
        'accept-encoding',
        'host',
        'connection',
        'transfer-encoding',
        'upgrade',
    ];
    /**
     * Request prefix.
     */
    static REQUEST_PREFIX = 'request:';
    /**
     * Prefixed headers are applied to request headers.
     */
    isRequestModifier;
    /**
     * Effective header name to be removed.
     */
    applicableHeaderName;
    /**
     * Value.
     */
    value;
    /**
     * Is rule valid or not.
     */
    valid;
    /**
     * Constructor.
     *
     * @param value Value of the modifier.
     * @param isAllowlist Whether the rule is an allowlist rule or not.
     */
    constructor(value, isAllowlist) {
        this.value = value.toLowerCase();
        if (!isAllowlist && !this.value) {
            throw new SyntaxError('Invalid $removeheader rule, removeheader value must not be empty');
        }
        this.isRequestModifier = this.value.startsWith(RemoveHeaderModifier.REQUEST_PREFIX);
        const headerName = this.isRequestModifier
            ? this.value.substring(RemoveHeaderModifier.REQUEST_PREFIX.length)
            : this.value;
        // Values with ":" are not supported in MV3 declarative rules, e.g. "$removeheader=dnt:1"
        this.valid = RemoveHeaderModifier.isAllowedHeader(headerName) && !headerName.includes(':');
        this.applicableHeaderName = this.valid ? headerName : null;
    }
    /**
     * Modifier value.
     *
     * @returns The value of the modifier.
     */
    getValue() {
        return this.value;
    }
    /**
     * Modifier validity.
     *
     * @returns True if the rule is valid, false otherwise.
     */
    get isValid() {
        return this.valid;
    }
    /**
     * Checks if the given modifier is an instance of RemoveHeaderModifier.
     *
     * @param m The modifier to check.
     *
     * @returns True if the modifier is an instance of RemoveHeaderModifier, false otherwise.
     */
    static isRemoveHeaderModifier = (m) => {
        return m instanceof RemoveHeaderModifier;
    };
    /**
     * Returns effective header name to be removed.
     *
     * @param isRequestHeaders Flag to determine that the header is a *request* header,
     * otherwise *response* header.
     *
     * @returns The applicable header name if valid, otherwise null.
     */
    getApplicableHeaderName(isRequestHeaders) {
        if (!this.applicableHeaderName) {
            return null;
        }
        if (isRequestHeaders !== this.isRequestModifier) {
            return null;
        }
        return this.applicableHeaderName;
    }
    /**
     * Some headers are forbidden to remove.
     *
     * @param headerName Header name to check.
     *
     * @returns True if the header is allowed to be removed, false otherwise.
     */
    static isAllowedHeader(headerName) {
        return !this.FORBIDDEN_HEADERS.includes(headerName);
    }
}

/**
 * This is a helper class that is used specifically to work with app restrictions.
 *
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#app}
 *
 * @example
 * ```adblock
 * ||baddomain.com^$app=org.example.app
 * ||baddomain.com^$app=org.example.app1|org.example.app2
 * ```
 */
class AppModifier {
    /**
     * List of permitted apps or null.
     */
    permittedApps;
    /**
     * List of restricted apps or null.
     */
    restrictedApps;
    /**
     * Parses the `apps` string.
     *
     * @param apps Apps string.
     *
     * @throws An error if the app string is empty or invalid.
     */
    constructor(apps) {
        if (!apps) {
            throw new SyntaxError('$app modifier cannot be empty');
        }
        const permittedApps = [];
        const restrictedApps = [];
        const parts = apps.split(simple_regex_Dw3J24Ss.a);
        for (let i = 0; i < parts.length; i += 1) {
            let app = parts[i];
            let restricted = false;
            if (app.startsWith('~')) {
                restricted = true;
                app = app.substring(1).trim();
            }
            if (app === '') {
                throw new SyntaxError(`Empty app specified in "${apps}"`);
            }
            if (restricted) {
                restrictedApps.push(app);
            }
            else {
                permittedApps.push(app);
            }
        }
        this.restrictedApps = restrictedApps.length > 0 ? restrictedApps : null;
        this.permittedApps = permittedApps.length > 0 ? permittedApps : null;
    }
}

var HTTPMethod;
(function (HTTPMethod) {
    HTTPMethod["GET"] = "GET";
    HTTPMethod["POST"] = "POST";
    HTTPMethod["PUT"] = "PUT";
    HTTPMethod["DELETE"] = "DELETE";
    HTTPMethod["PATCH"] = "PATCH";
    HTTPMethod["HEAD"] = "HEAD";
    HTTPMethod["OPTIONS"] = "OPTIONS";
    HTTPMethod["CONNECT"] = "CONNECT";
    HTTPMethod["TRACE"] = "TRACE";
})(HTTPMethod || (HTTPMethod = {}));
/**
 * Method modifier class.
 * Rules with $method modifier will be applied only to requests with specified methods.
 *
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#method-modifier}
 */
class MethodModifier {
    /**
     * Request methods separator.
     */
    static PIPE_SEPARATOR = '|';
    /**
     * List of permitted methods or null.
     */
    permittedValues;
    /**
     * List of restricted methods or null.
     */
    restrictedValues;
    /**
     * Constructor.
     *
     * @param methodsStr Value of the modifier.
     */
    constructor(methodsStr) {
        if (methodsStr === '') {
            throw new SyntaxError('$method modifier value cannot be empty');
        }
        const permittedMethods = [];
        const restrictedMethods = [];
        const parts = methodsStr.toUpperCase().split(MethodModifier.PIPE_SEPARATOR);
        for (let i = 0; i < parts.length; i += 1) {
            let method = parts[i].trim();
            let restricted = false;
            if (method.startsWith('~')) {
                restricted = true;
                method = method.substring(1);
            }
            if (!MethodModifier.isHTTPMethod(method)) {
                throw new SyntaxError(`Invalid $method modifier value: ${method}`);
            }
            if (restricted) {
                restrictedMethods.push(method);
            }
            else {
                permittedMethods.push(method);
            }
        }
        if (restrictedMethods.length > 0 && permittedMethods.length > 0) {
            throw new SyntaxError(`Negated values cannot be mixed with non-negated values: ${methodsStr}`);
        }
        this.restrictedValues = restrictedMethods.length > 0 ? restrictedMethods : null;
        this.permittedValues = permittedMethods.length > 0 ? permittedMethods : null;
    }
    static isHTTPMethod = (value) => value in HTTPMethod;
}

/**
 * Header modifier class.
 * The $header modifier allows matching the HTTP response
 * by a specific header with (optionally) a specific value.
 *
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#header-modifier}
 */
class HeaderModifier {
    /**
     * Colon separator.
     */
    COLON_SEPARATOR = ':';
    /**
     * Forward slash regexp marker.
     */
    FORWARD_SLASH = '/';
    /**
     * Header name to match on request.
     */
    header;
    /**
     * Header value to match on request.
     * Empty string if value is not specified, and, in that case,
     * only header name will be matched.
     */
    value;
    /**
     * Constructor.
     *
     * @param headerStr Header modifier value.
     */
    constructor(headerStr) {
        if (headerStr === '') {
            throw new SyntaxError('$header modifier value cannot be empty');
        }
        const separatorIndex = headerStr.indexOf(this.COLON_SEPARATOR);
        if (separatorIndex === -1) {
            this.header = headerStr;
            this.value = null;
            return;
        }
        this.header = headerStr.slice(0, separatorIndex);
        const rawValue = headerStr.slice(separatorIndex + 1);
        if (rawValue === '') {
            throw new SyntaxError(`Invalid $header modifier value: "${headerStr}"`);
        }
        if (rawValue.startsWith(this.FORWARD_SLASH) && rawValue.endsWith(this.FORWARD_SLASH)) {
            this.value = new RegExp(rawValue.slice(1, -1));
        }
        else {
            this.value = rawValue;
        }
    }
    /**
     * Returns header modifier value.
     *
     * @returns Header modifier value.
     */
    getHeaderModifierValue() {
        return {
            header: this.header,
            value: this.value,
        };
    }
}

/**
 * `$to` modifier class.
 * Rules with $to modifier are limited to requests made to the specified domains and their subdomains.
 *
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#to-modifier}
 */
class ToModifier {
    /**
     * Domains separator.
     */
    static PIPE_SEPARATOR = '|';
    /**
     * List of permitted domains or null.
     */
    permittedValues;
    /**
     * List of restricted domains or null.
     */
    restrictedValues;
    /**
     * Constructor.
     *
     * @param domainsStr String with domains separated by `|`.
     */
    constructor(domainsStr) {
        if (!domainsStr) {
            throw new SyntaxError('$to modifier value cannot be empty');
        }
        const permittedDomains = [];
        const restrictedDomains = [];
        const parts = domainsStr.toLowerCase().split(ToModifier.PIPE_SEPARATOR);
        for (let i = 0; i < parts.length; i += 1) {
            let domain = parts[i].trim();
            let restricted = false;
            if (domain.startsWith('~')) {
                restricted = true;
                domain = domain.substring(1);
            }
            if (domain === '') {
                throw new SyntaxError(`Empty domain specified in "${domainsStr}"`);
            }
            if (restricted) {
                restrictedDomains.push(domain);
            }
            else {
                permittedDomains.push(domain);
            }
        }
        this.restrictedValues = restrictedDomains.length > 0 ? restrictedDomains : null;
        this.permittedValues = permittedDomains.length > 0 ? permittedDomains : null;
    }
}

const PERMISSIONS_POLICY_HEADER_NAME = 'Permissions-Policy';
const COMMA_SEPARATOR = ',';
const PIPE_SEPARATOR = '|';
/**
 * Permissions modifier class.
 * Allows setting permission policies, effectively blocking specific page functionality.
 *
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#permissions-modifier}
 */
class PermissionsModifier {
    /**
     * Permission Policy directive.
     */
    permissionPolicyDirective;
    /**
     * Regular expression to apply correct separators.
     * It replaces escaped commas and pipe separators with commas.
     */
    static RE_SEPARATOR_REPLACE = new RegExp(`(\\\\${COMMA_SEPARATOR}|\\${PIPE_SEPARATOR})`, 'g');
    /**
     * Constructor.
     *
     * @param permissionPolicyStr The permission policy string to be set.
     * @param isAllowlist Indicates if the permission policy is for an allowlist.
     */
    constructor(permissionPolicyStr, isAllowlist) {
        this.permissionPolicyDirective = permissionPolicyStr
            .replace(PermissionsModifier.RE_SEPARATOR_REPLACE, COMMA_SEPARATOR);
        PermissionsModifier.validatePermissionPolicyDirective(this.permissionPolicyDirective, isAllowlist);
    }
    /**
     * Returns permission policy allowlist string.
     *
     * @returns Permission policy allowlist string.
     */
    getValue() {
        return this.permissionPolicyDirective;
    }
    /**
     * Validates permission policy directive.
     *
     * @param directive The permission policy directive to validate.
     * @param isAllowlist Indicates if the directive is for an allowlist.
     *
     * @throws SyntaxError on invalid permission policy directive.
     */
    static validatePermissionPolicyDirective(directive, isAllowlist) {
        /**
         * $permissions modifier value may be empty only in case of allowlist rule,
         * it means to disable all $permissions rules matching the rule pattern.
         */
        if (!isAllowlist && !directive) {
            throw new SyntaxError('Invalid $permissions rule: permissions directive must not be empty');
        }
    }
}

/**
 * This is the base class representing double values modifiers.
 */
class BaseValuesModifier {
    /**
     * List of permitted values or null.
     */
    permitted;
    /**
     * List of restricted values or null.
     */
    restricted;
    /**
     * Value.
     */
    value;
    /**
     * Parses the values string.
     *
     * @param values Values string.
     *
     * @throws An error if the string is empty or invalid.
     */
    constructor(values) {
        if (!values) {
            throw new SyntaxError('Modifier cannot be empty');
        }
        this.value = values;
        const permittedValues = [];
        const restrictedValues = [];
        const parts = values.split(simple_regex_Dw3J24Ss.a);
        for (let i = 0; i < parts.length; i += 1) {
            let app = parts[i];
            let restricted = false;
            if (app.startsWith('~')) {
                restricted = true;
                app = app.substring(1).trim();
            }
            if (app === '') {
                throw new SyntaxError(`Empty values specified in "${values}"`);
            }
            if (restricted) {
                restrictedValues.push(app);
            }
            else {
                permittedValues.push(app);
            }
        }
        this.restricted = restrictedValues.length > 0 ? restrictedValues : null;
        this.permitted = permittedValues.length > 0 ? permittedValues : null;
    }
    getPermitted() {
        return this.permitted;
    }
    getRestricted() {
        return this.restricted;
    }
    getValue() {
        return this.value;
    }
    match(value) {
        if (!this.restricted && !this.permitted) {
            return true;
        }
        if (this.restricted && this.restricted.includes(value)) {
            return false;
        }
        if (this.permitted) {
            return this.permitted.includes(value);
        }
        return true;
    }
}

// eslint-disable-next-line max-classes-per-file
/**
 * Netmasks class.
 */
class NetmasksCollection {
    ipv4Masks = [];
    ipv6Masks = [];
    /**
     * Returns true if any of the containing masks contains provided value.
     *
     * @param value Value to check.
     *
     * @returns True if any of the containing masks contains provided value.
     */
    contains(value) {
        if (is_ip.v4(value)) {
            return this.ipv4Masks.some((x) => (0,cidr_tools/* contains */.gR)(x, value));
        }
        return this.ipv6Masks.some((x) => (0,cidr_tools/* contains */.gR)(x, value));
    }
}
/**
 * The client modifier allows specifying clients this rule will be working for.
 * It accepts client names (not ClientIDs), IP addresses, or CIDR ranges.
 */
class ClientModifier extends BaseValuesModifier {
    permittedNetmasks;
    restrictedNetmasks;
    /**
     * Constructor.
     *
     * @param value Value of the modifier.
     */
    constructor(value) {
        super(value);
        const permitted = this.getPermitted();
        if (permitted) {
            this.permitted = ClientModifier.stripValues(permitted);
            this.permittedNetmasks = ClientModifier.parseNetmasks(this.permitted);
        }
        const restricted = this.getRestricted();
        if (restricted) {
            this.restricted = ClientModifier.stripValues(restricted);
            this.restrictedNetmasks = ClientModifier.parseNetmasks(this.restricted);
        }
    }
    /**
     * Unquotes and unescapes string.
     *
     * @param values Values to process.
     *
     * @returns Unquoted and unescaped values.
     */
    static stripValues(values) {
        return values.map((v) => {
            if ((v.startsWith('"') && v.endsWith('"'))
                || (v.startsWith('\'') && v.endsWith('\''))) {
                // eslint-disable-next-line no-param-reassign
                v = v.substr(1, v.length - 2);
            }
            return v.replace(/\\/ig, '');
        });
    }
    /**
     * Checks if this modifier matches provided params.
     *
     * @param clientName Client name.
     * @param clientIP Client IP.
     *
     * @returns True if this modifier matches provided params.
     */
    matchAny(clientName, clientIP) {
        if (this.restricted) {
            if (clientName && this.restricted.includes(clientName)) {
                return false;
            }
            if (clientIP && this.restricted.includes(clientIP)) {
                return false;
            }
            return true;
        }
        if (this.restrictedNetmasks) {
            if (clientIP && this.restrictedNetmasks.contains(clientIP)) {
                return false;
            }
            return true;
        }
        if (this.permitted) {
            if (clientName && this.permitted.includes(clientName)) {
                return true;
            }
            if (clientIP && this.permitted.includes(clientIP)) {
                return true;
            }
        }
        if (this.permittedNetmasks) {
            if (clientIP && this.permittedNetmasks.contains(clientIP)) {
                return true;
            }
        }
        return false;
    }
    /**
     * Parses netmasks from client's strings.
     *
     * @param values Values to parse.
     *
     * @returns Parsed netmasks.
     */
    static parseNetmasks(values) {
        const result = new NetmasksCollection();
        values.forEach((x) => {
            const cidrVersion = is_cidr(x);
            if (cidrVersion === 4) {
                result.ipv4Masks.push(x);
            }
            else if (cidrVersion === 6) {
                result.ipv6Masks.push(x);
            }
        });
        return result;
    }
}

/**
 * The dnsrewrite response modifier allows replacing the content of the response
 * to the DNS request for the matching hosts.
 *
 * TODO: This modifier is not yet implemented.
 *
 * @see {@link https://github.com/AdguardTeam/AdGuardHome/wiki/Hosts-Blocklists#dnsrewrite}
 */
class DnsRewriteModifier {
    /**
     * Value.
     */
    value;
    /**
     * Constructor.
     *
     * @param value Modifier value.
     */
    constructor(value) {
        this.value = value;
    }
    /**
     * Modifier value.
     *
     * @returns The value of the modifier.
     */
    getValue() {
        return this.value;
    }
}

/**
 * The `$dnstype` modifier allows specifying DNS request type on which this rule will be triggered.
 */
class DnsTypeModifier extends BaseValuesModifier {
    /**
     * Constructor.
     *
     * @param value The value used to initialize the modifier.
     */
    constructor(value) {
        super(value);
        if (this.permitted) {
            this.restricted = null;
        }
    }
}

/**
 * The ctag modifier allows to block domains only for specific types of DNS client tags.
 */
class CtagModifier extends BaseValuesModifier {
    /**
     * The list of allowed tags.
     */
    static ALLOWED_TAGS = [
        // By device type:
        'device_audio',
        'device_camera',
        'device_gameconsole',
        'device_laptop',
        'device_nas',
        'device_pc',
        'device_phone',
        'device_printer',
        'device_securityalarm',
        'device_tablet',
        'device_tv',
        'device_other',
        // By operating system:
        'os_android',
        'os_ios',
        'os_linux',
        'os_macos',
        'os_windows',
        'os_other',
        // By user group:
        'user_admin',
        'user_regular',
        'user_child',
    ];
    /**
     * Constructor.
     *
     * @param value Value of the modifier.
     */
    constructor(value) {
        super(value);
        this.validate();
    }
    /**
     * Validates tag values.
     */
    validate() {
        if (!this.getValue()) {
            throw new Error('Invalid rule: Ctag modifier must not be empty');
        }
        const tags = this.permitted ? this.permitted : this.restricted;
        if (tags && tags.some((x) => !CtagModifier.ALLOWED_TAGS.includes(x))) {
            throw new Error('Invalid rule: Invalid ctag modifier');
        }
    }
}

/* eslint-disable no-param-reassign */
/**
 * Counts the number of set bits (1s) in a 32-bit number using Hamming Weight (SWAR) method.
 *
 * @param a Number to count bits in.
 *
 * @returns The number of bits set to 1.
 */
function getBitCount(a) {
    a -= ((a >>> 1) & 0x55555555);
    a = (a & 0x33333333) + ((a >>> 2) & 0x33333333);
    a = (a + (a >>> 4)) & 0x0F0F0F0F;
    a += (a >>> 8);
    a += (a >>> 16);
    return a & 0x3F;
}
/**
 * Count the number of bits enabled in a number based on a bit mask.
 *
 * @param base Base number to check.
 * @param mask Mask to apply.
 *
 * @returns Number of bits set in `base & mask`.
 */
function countEnabledBits(base, mask) {
    return getBitCount(base & mask);
}

/**
 * NetworkRuleOption is the enumeration of various rule options.
 * In order to save memory, we store some options as a flag.
 *
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#basic-rule-modifiers}
 */
var NetworkRuleOption;
(function (NetworkRuleOption) {
    /**
     * No value is set. Syntax sugar to simplify code.
     */
    NetworkRuleOption[NetworkRuleOption["NotSet"] = 0] = "NotSet";
    /**
     * $third-party modifier.
     */
    NetworkRuleOption[NetworkRuleOption["ThirdParty"] = 1] = "ThirdParty";
    /**
     * $match-case modifier.
     */
    NetworkRuleOption[NetworkRuleOption["MatchCase"] = 2] = "MatchCase";
    /**
     * $important modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Important"] = 4] = "Important";
    // Allowlist rules modifiers
    // Each of them can disable part of the functionality
    /**
     * $elemhide modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Elemhide"] = 8] = "Elemhide";
    /**
     * $generichide modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Generichide"] = 16] = "Generichide";
    /**
     * $specifichide modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Specifichide"] = 32] = "Specifichide";
    /**
     * $genericblock modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Genericblock"] = 64] = "Genericblock";
    /**
     * $jsinject modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Jsinject"] = 128] = "Jsinject";
    /**
     * $urlblock modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Urlblock"] = 256] = "Urlblock";
    /**
     * $content modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Content"] = 512] = "Content";
    /**
     * $extension modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Extension"] = 1024] = "Extension";
    /**
     * $stealth modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Stealth"] = 2048] = "Stealth";
    // Other modifiers
    /**
     * $popup modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Popup"] = 4096] = "Popup";
    /**
     * $csp modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Csp"] = 8192] = "Csp";
    /**
     * $replace modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Replace"] = 16384] = "Replace";
    /**
     * $cookie modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Cookie"] = 32768] = "Cookie";
    /**
     * $redirect modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Redirect"] = 65536] = "Redirect";
    /**
     * $badfilter modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Badfilter"] = 131072] = "Badfilter";
    /**
     * $removeparam modifier.
     */
    NetworkRuleOption[NetworkRuleOption["RemoveParam"] = 262144] = "RemoveParam";
    /**
     * $removeheader modifier.
     */
    NetworkRuleOption[NetworkRuleOption["RemoveHeader"] = 524288] = "RemoveHeader";
    /**
     * $jsonprune modifier.
     */
    NetworkRuleOption[NetworkRuleOption["JsonPrune"] = 1048576] = "JsonPrune";
    /**
     * $hls modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Hls"] = 2097152] = "Hls";
    // Compatibility dependent
    /**
     * $network modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Network"] = 4194304] = "Network";
    /**
     * Dns modifiers.
     */
    NetworkRuleOption[NetworkRuleOption["Client"] = 8388608] = "Client";
    NetworkRuleOption[NetworkRuleOption["DnsRewrite"] = 16777216] = "DnsRewrite";
    NetworkRuleOption[NetworkRuleOption["DnsType"] = 33554432] = "DnsType";
    NetworkRuleOption[NetworkRuleOption["Ctag"] = 67108864] = "Ctag";
    /**
     * $method modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Method"] = 134217728] = "Method";
    /**
     * $to modifier.
     */
    NetworkRuleOption[NetworkRuleOption["To"] = 268435456] = "To";
    /**
     * $permissions modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Permissions"] = 536870912] = "Permissions";
    /**
     * $header modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Header"] = 1073741824] = "Header";
})(NetworkRuleOption || (NetworkRuleOption = {}));
/**
 * NetworkRuleOptions is the enumeration of various rule options groups
 * needed for validation.
 */
var NetworkRuleGroupOptions;
(function (NetworkRuleGroupOptions) {
    /**
     * Allowlist-only modifiers.
     */
    NetworkRuleGroupOptions[NetworkRuleGroupOptions["AllowlistOnly"] = 4088] = "AllowlistOnly";
    /**
     * Options supported by host-level network rules.
     */
    NetworkRuleGroupOptions[NetworkRuleGroupOptions["OptionHostLevelRules"] = 125960196] = "OptionHostLevelRules";
    /**
     * Cosmetic option modifiers.
     */
    NetworkRuleGroupOptions[NetworkRuleGroupOptions["CosmeticOption"] = 696] = "CosmeticOption";
    /**
     * Removeparam compatible modifiers.
     *
     * $removeparam rules are compatible only with content type modifiers ($subdocument, $script, $stylesheet, etc)
     * except $document (using by default) and this list of modifiers.
     */
    NetworkRuleGroupOptions[NetworkRuleGroupOptions["RemoveParamCompatibleOptions"] = 393223] = "RemoveParamCompatibleOptions";
    /**
     * Removeheader compatible modifiers.
     *
     * $removeheader rules are compatible only with content type modifiers ($subdocument, $script, $stylesheet, etc)
     * except $document (using by default) and this list of modifiers.
     */
    NetworkRuleGroupOptions[NetworkRuleGroupOptions["RemoveHeaderCompatibleOptions"] = 1074397191] = "RemoveHeaderCompatibleOptions";
    /**
     * Permissions compatible modifiers.
     *
     * $permissions is compatible with the limited list of modifiers: $domain, $important, and $subdocument.
     */
    NetworkRuleGroupOptions[NetworkRuleGroupOptions["PermissionsCompatibleOptions"] = 537001988] = "PermissionsCompatibleOptions";
    /**
     * Header compatible modifiers.
     *
     * $header is compatible with the limited list of modifiers: $csp and $removeheader (on response headers).
     */
    NetworkRuleGroupOptions[NetworkRuleGroupOptions["HeaderCompatibleOptions"] = 1074405380] = "HeaderCompatibleOptions";
})(NetworkRuleGroupOptions || (NetworkRuleGroupOptions = {}));
/**
 * Basic network filtering rule.
 *
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#basic-rules}
 */
class NetworkRule {
    ruleIndex;
    filterListId;
    allowlist;
    pattern;
    /**
     * Domains in denyallow modifier providing exceptions for permitted domains.
     *
     * @see {@link https://github.com/AdguardTeam/CoreLibs/issues/1304}
     */
    denyAllowDomains = null;
    /**
     * Flag with all enabled rule options.
     */
    enabledOptions = NetworkRuleOption.NotSet;
    /**
     * Flag with all disabled rule options.
     */
    disabledOptions = NetworkRuleOption.NotSet;
    /**
     * Flag with all permitted request types.
     */
    permittedRequestTypes = request_type/* RequestType */.Y.NotSet;
    /**
     * Flag with all restricted request types.
     */
    restrictedRequestTypes = request_type/* RequestType */.Y.NotSet;
    /**
     * Rule Advanced modifier.
     */
    advancedModifier = null;
    /**
     * Rule Domain modifier.
     */
    domainModifier = null;
    /**
     * Rule App modifier.
     */
    appModifier = null;
    /**
     * Rule Method modifier.
     */
    methodModifier = null;
    /**
     * Rule header modifier.
     */
    headerModifier = null;
    /**
     * Rule To modifier.
     */
    toModifier = null;
    /**
     * Rule Stealth modifier.
     */
    stealthModifier = null;
    /**
     * Options used by the rule, regardless of whether they are enabled or disabled.
     */
    usedOptionNames = new Set();
    /**
     * Rule priority, which is needed when the engine has to choose between
     * several rules matching the query. This value is calculated based on
     * the rule modifiers enabled or disabled and rounded up
     * to the smallest integer greater than or equal to the calculated weight
     * in the {@link calculatePriorityWeight}.
     *
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-1
     */
    priorityWeight = 1;
    /**
     * Rules with base modifiers, from category 1, each of them adds 1
     * to the weight of the rule.
     *
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-1
     */
    static CATEGORY_1_OPTIONS_MASK = NetworkRuleOption.ThirdParty
        | NetworkRuleOption.MatchCase
        | NetworkRuleOption.DnsRewrite;
    /**
     * The priority weight used in {@link calculatePriorityWeight} for rules
     * with permitted request types and methods.
     * The value 50 is chosen in order to cover (with a margin) all possible
     * combinations and variations of rules from categories with a lower
     * priority (each of them adds 1 to the rule priority).
     *
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-2
     */
    static CategoryTwoWeight = 50;
    /**
     * The priority weight used in {@link calculatePriorityWeight} for rules
     * with allowed domains.
     * The value 100 is chosen to cover all possible combinations and variations
     * of rules from categories with a lower priority, for example a rule with
     * one allowed query type will get priority 100 (50 + 50/1), but for allowed
     * domains with any number of domains we will get at least 101 (for 100
     * domains: 100 + 100/100; for 200 100 + 100/200; or even for 10000:
     * 100 + 100/10000) because the resulting weight is rounded up.
     *
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-3
     */
    static CategoryThreeWeight = 100;
    /**
     * The priority weight used in {@link calculatePriorityWeight}
     * for $redirect rules.
     *
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-6
     */
    static CategoryFourWeight = 10 ** 3;
    /**
     * The priority weight used in {@link calculatePriorityWeight} for rules
     * with specific exceptions.
     *
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-4
     */
    static CategoryFiveWeight = 10 ** 4;
    /**
     * Rules with specific exclusions, from category 4, each of them adds
     * {@link SpecificExceptionsWeight} to the weight of the rule.
     *
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-4
     */
    static SPECIFIC_EXCLUSIONS_MASK = NetworkRuleOption.Elemhide
        | NetworkRuleOption.Generichide
        | NetworkRuleOption.Specifichide
        | NetworkRuleOption.Content
        | NetworkRuleOption.Urlblock
        | NetworkRuleOption.Genericblock
        | NetworkRuleOption.Jsinject
        | NetworkRuleOption.Extension;
    /**
     * The priority weight used in {@link calculatePriorityWeight} for rules
     * with allowlist mark '@@'.
     *
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-5
     */
    static CategorySixWeight = 10 ** 5;
    /**
     * The priority weight used in {@link calculatePriorityWeight}
     * for $important rules.
     *
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-7
     */
    static CategorySevenWeight = 10 ** 6;
    /**
     * Separates the rule pattern from the list of modifiers.
     *
     * ```
     * rule = ["@@"] pattern [ "$" modifiers ]
     * modifiers = [modifier0, modifier1[, ...[, modifierN]]]
     * ```
     */
    static OPTIONS_DELIMITER = network_rule_options/* OPTIONS_DELIMITER */.rE;
    /**
     * A marker that is used in rules of exception.
     * To turn off filtering for a request, start your rule with this marker.
     */
    static MASK_ALLOWLIST = network_rule_options/* MASK_ALLOWLIST */.$4;
    /**
     * Mark that negates options.
     */
    static NOT_MARK = network_rule_options/* NOT_MARK */.IA;
    /**
     * Rule options.
     */
    static OPTIONS = network_rule_options/* NETWORK_RULE_OPTIONS */.RM;
    /**
     * Rule options that can be negated.
     */
    static NEGATABLE_OPTIONS = new Set([
        // General options
        NetworkRule.OPTIONS.FIRST_PARTY,
        NetworkRule.OPTIONS.THIRD_PARTY,
        NetworkRule.OPTIONS.MATCH_CASE,
        NetworkRule.OPTIONS.DOCUMENT,
        NetworkRule.OPTIONS.DOC,
        // Content type options
        NetworkRule.OPTIONS.SCRIPT,
        NetworkRule.OPTIONS.STYLESHEET,
        NetworkRule.OPTIONS.SUBDOCUMENT,
        NetworkRule.OPTIONS.OBJECT,
        NetworkRule.OPTIONS.IMAGE,
        NetworkRule.OPTIONS.XMLHTTPREQUEST,
        NetworkRule.OPTIONS.MEDIA,
        NetworkRule.OPTIONS.FONT,
        NetworkRule.OPTIONS.WEBSOCKET,
        NetworkRule.OPTIONS.OTHER,
        NetworkRule.OPTIONS.PING,
        // Dns modifiers
        NetworkRule.OPTIONS.EXTENSION,
    ]);
    /**
     * Advanced option modifier names.
     */
    static ADVANCED_OPTIONS = new Set([
        NetworkRule.OPTIONS.CSP,
        NetworkRule.OPTIONS.REPLACE,
        NetworkRule.OPTIONS.COOKIE,
        NetworkRule.OPTIONS.REDIRECT,
        NetworkRule.OPTIONS.REDIRECTRULE,
        NetworkRule.OPTIONS.REMOVEPARAM,
        NetworkRule.OPTIONS.REMOVEHEADER,
        NetworkRule.OPTIONS.PERMISSIONS,
        NetworkRule.OPTIONS.CLIENT,
        NetworkRule.OPTIONS.DNSREWRITE,
        NetworkRule.OPTIONS.DNSTYPE,
        NetworkRule.OPTIONS.CTAG,
    ]);
    // TODO: Remove .getText() completely
    ruleText;
    // TODO: Remove .getText() completely
    /**
     * Returns the rule text.
     *
     * @returns The rule text.
     */
    getText() {
        return this.ruleText;
    }
    /**
     * Returns the rule index.
     *
     * @returns Rule index.
     */
    getIndex() {
        return this.ruleIndex;
    }
    /**
     * Returns the identifier of the filter from which the rule was received.
     *
     * @returns Identifier of the filter from which the rule was received.
     */
    getFilterListId() {
        return this.filterListId;
    }
    /**
     * Returns all options that are used in the rule, regardless of whether they are
     * enabled or disabled.
     *
     * @returns Set of option names.
     */
    getUsedOptionNames() {
        return this.usedOptionNames;
    }
    /**
     * Each rule has its own priority, which is necessary when several rules
     * match the request and the filtering system needs to select one of them.
     * Priority is measured as a positive integer.
     * In the case of a conflict between two rules with the same priority value,
     * it is not specified which one of them will be chosen.
     *
     * @returns Rule priority.
     */
    getPriorityWeight() {
        return this.priorityWeight;
    }
    /**
     * Returns rule pattern,
     * which currently is used only in the rule validator module.
     *
     * @returns Rule pattern.
     */
    getPattern() {
        return this.pattern.pattern;
    }
    /**
     * Returns `true` if the rule is "allowlist", e.g. if it disables other
     * rules when the pattern matches the request.
     *
     * @returns True if the rule is an allowlist rule.
     */
    isAllowlist() {
        return this.allowlist;
    }
    /**
     * Checks if the rule is a document-level allowlist rule with $urlblock or
     * $genericblock or $content.
     * This means that the rule is supposed to disable or modify blocking
     * of the page sub-requests.
     * For instance, `@@||example.org^$urlblock` unblocks all sub-requests.
     *
     * @returns True if the rule is a document-level allowlist rule with specific modifiers.
     */
    isDocumentLevelAllowlistRule() {
        if (!this.isAllowlist()) {
            return false;
        }
        return this.isOptionEnabled(NetworkRuleOption.Urlblock)
            || this.isOptionEnabled(NetworkRuleOption.Genericblock)
            || this.isOptionEnabled(NetworkRuleOption.Content);
    }
    /**
     * Checks if the rule completely disables filtering.
     *
     * @returns True if the rule completely disables filtering.
     */
    isFilteringDisabled() {
        if (!this.isAllowlist()) {
            return false;
        }
        return this.isOptionEnabled(NetworkRuleOption.Elemhide)
            && this.isOptionEnabled(NetworkRuleOption.Content)
            && this.isOptionEnabled(NetworkRuleOption.Urlblock)
            && this.isOptionEnabled(NetworkRuleOption.Jsinject);
    }
    /**
     * The longest part of pattern without any special characters.
     * It is used to improve the matching performance.
     *
     * @returns The longest part of the pattern without any special characters.
     */
    getShortcut() {
        return this.pattern.shortcut;
    }
    /**
     * Gets list of permitted domains.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#domain-modifier}
     *
     * @returns List of permitted domains or null if none.
     */
    getPermittedDomains() {
        if (this.domainModifier) {
            return this.domainModifier.getPermittedDomains();
        }
        return null;
    }
    /**
     * Gets list of restricted domains.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#domain-modifier}
     *
     * @returns List of restricted domains or null if none.
     */
    getRestrictedDomains() {
        if (this.domainModifier) {
            return this.domainModifier.getRestrictedDomains();
        }
        return null;
    }
    /**
     * Gets list of denyAllow domains.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#denyallow-modifier}
     *
     * @returns List of denyAllow domains or null if none.
     */
    getDenyAllowDomains() {
        return this.denyAllowDomains;
    }
    /**
     * Get list of permitted $to domains.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#to-modifier}
     *
     * @returns List of permitted $to domains or null if none.
     */
    getPermittedToDomains() {
        if (this.toModifier) {
            return this.toModifier.permittedValues;
        }
        return null;
    }
    /**
     * Get list of restricted $to domains.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#to-modifier}
     *
     * @returns List of restricted $to domains or null if none.
     */
    getRestrictedToDomains() {
        if (this.toModifier) {
            return this.toModifier.restrictedValues;
        }
        return null;
    }
    /**
     * Gets list of permitted domains.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#app}
     *
     * @returns List of permitted domains or null if none.
     */
    getPermittedApps() {
        if (this.appModifier) {
            return this.appModifier.permittedApps;
        }
        return null;
    }
    /**
     * Gets list of restricted domains.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#app}
     *
     * @returns List of restricted domains or null if none.
     */
    getRestrictedApps() {
        if (this.appModifier) {
            return this.appModifier.restrictedApps;
        }
        return null;
    }
    /**
     * Gets list of permitted methods.
     *
     * @see {@link https://kb.adguard.com/general/how-to-create-your-own-ad-filters#method-modifier}
     *
     * @returns List of permitted methods or null if none.
     */
    getRestrictedMethods() {
        if (this.methodModifier) {
            return this.methodModifier.restrictedValues;
        }
        return null;
    }
    /**
     * Gets list of restricted methods.
     *
     * @see {@link https://kb.adguard.com/general/how-to-create-your-own-ad-filters#method-modifier}
     *
     * @returns List of restricted methods or null if none.
     */
    getPermittedMethods() {
        if (this.methodModifier) {
            return this.methodModifier.permittedValues;
        }
        return null;
    }
    /**
     * Flag with all permitted request types.
     * The value {@link RequestType.NotSet} here means "all request types are allowed".
     *
     * @returns The flag with all permitted request types.
     */
    getPermittedRequestTypes() {
        return this.permittedRequestTypes;
    }
    /**
     * Flag with all restricted request types.
     * The value {@link RequestType.NotSet} here means "no type of request is restricted".
     *
     * @returns The flag with all restricted request types.
     */
    getRestrictedRequestTypes() {
        return this.restrictedRequestTypes;
    }
    /**
     * Advanced modifier.
     *
     * @returns The advanced modifier or null if none.
     */
    getAdvancedModifier() {
        return this.advancedModifier;
    }
    /**
     * Stealth modifier.
     *
     * @returns The stealth modifier or null if none.
     */
    getStealthModifier() {
        return this.stealthModifier;
    }
    /**
     * Advanced modifier value.
     *
     * @returns The advanced modifier value or null if none.
     */
    getAdvancedModifierValue() {
        return this.advancedModifier && this.advancedModifier.getValue();
    }
    /**
     * Retrieves the header modifier value.
     *
     * @returns The header modifier value or null if none.
     */
    getHeaderModifierValue() {
        if (!this.headerModifier) {
            return null;
        }
        return this.headerModifier.getHeaderModifierValue();
    }
    /**
     * Returns true if rule's pattern is a regular expression.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#regexp-support}
     *
     * @returns True if the rule pattern is a regular expression.
     */
    isRegexRule() {
        return (this.getPattern().startsWith(simple_regex_Dw3J24Ss.S.MASK_REGEX_RULE)
            && this.getPattern().endsWith(simple_regex_Dw3J24Ss.S.MASK_REGEX_RULE));
    }
    /**
     * Checks if this filtering rule matches the specified request.
     *
     * @param request Request to check.
     * @param useShortcut The flag to use this rule shortcut.
     *
     * @returns True if the rule matches the request.
     *
     * In case we use Trie in lookup table, we don't need to use shortcut cause we already check if request's url
     * includes full rule shortcut.
     */
    match(request, useShortcut = true) {
        // Regex rules should not be tested by shortcut
        if (useShortcut && !this.matchShortcut(request)) {
            return false;
        }
        if (this.isOptionEnabled(NetworkRuleOption.Method) && !this.matchMethod(request.method)) {
            return false;
        }
        if (this.isOptionEnabled(NetworkRuleOption.ThirdParty) && !request.thirdParty) {
            return false;
        }
        if (this.isOptionDisabled(NetworkRuleOption.ThirdParty) && request.thirdParty) {
            return false;
        }
        if (!this.matchRequestType(request.requestType)) {
            return false;
        }
        if (!this.matchDomainModifier(request)) {
            return false;
        }
        if (this.isOptionEnabled(NetworkRuleOption.RemoveParam)
            || this.isOptionEnabled(NetworkRuleOption.Permissions)) {
            if (!this.matchRequestTypeExplicit(request.requestType)) {
                return false;
            }
        }
        if (!this.matchDenyAllowDomains(request.hostname)) {
            return false;
        }
        if (this.isOptionEnabled(NetworkRuleOption.To) && !this.matchToModifier(request.hostname)) {
            return false;
        }
        if (!this.matchDnsType(request.dnsType)) {
            return false;
        }
        if (!this.matchClientTags(request.clientTags)) {
            return false;
        }
        if (!this.matchClient(request.clientName, request.clientIP)) {
            return false;
        }
        return this.pattern.matchPattern(request, true);
    }
    /**
     * Simply checks if shortcut is a substring of the URL.
     *
     * @param request Request to check.
     *
     * @returns True if the shortcut is a substring of the URL.
     */
    matchShortcut(request) {
        return request.urlLowercase.indexOf(this.getShortcut()) >= 0;
    }
    /**
     * Check if request matches domain modifier by request referrer (general case) or by request target.
     *
     * In some cases the $domain modifier can match not only the referrer domain, but also the target domain.
     * This happens when the following is true (1 AND ((2 AND 3) OR 4):
     *
     * 1) The request has $document request type (not subdocument)
     * 2) The rule's pattern doesn't match any particular domain(s)
     * 3) The rule's pattern doesn't contain regular expressions
     * 4) The $domain modifier contains only excluded domains (e.g., $domain=~example.org|~example.com).
     *
     * When all these conditions are met, the domain modifier will match both the referrer domain and the target domain.
     *
     * @see {@link https://github.com/AdguardTeam/tsurlfilter/issues/45}
     *
     * @param request The request to check.
     *
     * @returns True if the rule matches the domain modifier.
     */
    matchDomainModifier(request) {
        if (!this.domainModifier) {
            return true;
        }
        const { domainModifier } = this;
        const isDocumentType = request.requestType === request_type/* RequestType */.Y.Document;
        const hasOnlyExcludedDomains = !domainModifier.hasPermittedDomains()
            && domainModifier.hasRestrictedDomains();
        const patternIsRegex = this.isRegexRule();
        const patternIsDomainSpecific = this.pattern.isPatternDomainSpecific();
        const matchesTargetByPatternCondition = !patternIsRegex && !patternIsDomainSpecific;
        if (isDocumentType && (hasOnlyExcludedDomains || matchesTargetByPatternCondition)) {
            // check if matches source hostname if exists or if matches target hostname
            return (request.sourceHostname && domainModifier.matchDomain(request.sourceHostname))
                || domainModifier.matchDomain(request.hostname);
        }
        return domainModifier.matchDomain(request.sourceHostname || '');
    }
    /**
     * Checks if the filtering rule is allowed on this domain.
     *
     * @param domain The request's domain.
     *
     * @returns True if the rule must be applied to the request.
     */
    matchDenyAllowDomains(domain) {
        if (!this.denyAllowDomains) {
            return true;
        }
        if (this.denyAllowDomains.length > 0) {
            if (DomainModifier.isDomainOrSubdomainOfAny(domain, this.denyAllowDomains)) {
                return false;
            }
        }
        return true;
    }
    /**
     * Checks if the request domain matches the specified conditions.
     *
     * @param domain The request's domain.
     *
     * @returns True if the request domain matches the permitted domains and does not match the restricted domains.
     */
    matchToModifier(domain) {
        if (!this.toModifier) {
            return true;
        }
        /**
         * The request's domain must be either explicitly permitted or not be included
         * in the list of restricted domains for the rule to apply.
         */
        const permittedDomains = this.getPermittedToDomains();
        const restrictedDomains = this.getRestrictedToDomains();
        let matches = false;
        if (permittedDomains) {
            matches = DomainModifier.isDomainOrSubdomainOfAny(domain, permittedDomains);
        }
        if (restrictedDomains) {
            matches = !DomainModifier.isDomainOrSubdomainOfAny(domain, restrictedDomains);
        }
        return matches;
    }
    /**
     * Return `true` if this rule matches with the tags associated with a client.
     *
     * @param clientTags Client tags.
     *
     * @returns True if the rule matches the client tags.
     */
    matchClientTags(clientTags) {
        const advancedModifier = this.getAdvancedModifier();
        if (!advancedModifier || !(advancedModifier instanceof CtagModifier)) {
            return true;
        }
        if (!clientTags) {
            return false;
        }
        const cTagsModifier = advancedModifier;
        return clientTags.every((x) => cTagsModifier.match(x));
    }
    /**
     * Returns TRUE if the rule matches with the specified client.
     *
     * @param clientName The name of the client.
     * @param clientIP The IP address of the client.
     *
     * @returns True if the rule matches the client.
     */
    matchClient(clientName, clientIP) {
        const advancedModifier = this.getAdvancedModifier();
        if (!advancedModifier || !(advancedModifier instanceof ClientModifier)) {
            return true;
        }
        if (!clientName && !clientIP) {
            return false;
        }
        const modifier = advancedModifier;
        return modifier.matchAny(clientName, clientIP);
    }
    /**
     * Return `true` if this rule matches with the request DNS type.
     *
     * @param dnstype The DNS type to check.
     *
     * @returns True if the rule matches the DNS type.
     */
    matchDnsType(dnstype) {
        const advancedModifier = this.getAdvancedModifier();
        if (!advancedModifier || !(advancedModifier instanceof DnsTypeModifier)) {
            return true;
        }
        if (!dnstype) {
            return false;
        }
        const modifier = advancedModifier;
        return modifier.match(dnstype);
    }
    /**
     * Checks if the request's type matches the rule properties.
     *
     * @param requestType Request type to check.
     *
     * @returns True if the rule must be applied to the request.
     */
    matchRequestType(requestType) {
        if (this.permittedRequestTypes !== request_type/* RequestType */.Y.NotSet) {
            if ((this.permittedRequestTypes & requestType) !== requestType) {
                return false;
            }
        }
        if (this.restrictedRequestTypes !== request_type/* RequestType */.Y.NotSet) {
            if ((this.restrictedRequestTypes & requestType) === requestType) {
                return false;
            }
        }
        return true;
    }
    /**
     * In case of $removeparam, $permissions modifier,
     * we only allow it to target other content types if the rule has an explicit content-type modifier.
     *
     * @param requestType Request type to check.
     *
     * @returns True if the rule must be applied to the request.
     */
    matchRequestTypeExplicit(requestType) {
        if (this.permittedRequestTypes === request_type/* RequestType */.Y.NotSet
            && this.restrictedRequestTypes === request_type/* RequestType */.Y.NotSet
            && requestType !== request_type/* RequestType */.Y.Document
            && requestType !== request_type/* RequestType */.Y.SubDocument) {
            return false;
        }
        return this.matchRequestType(requestType);
    }
    /**
     * Checks if request's method matches with the rule.
     *
     * @param method Request's method.
     *
     * @returns True, if rule must be applied to the request.
     */
    matchMethod(method) {
        if (!method || !MethodModifier.isHTTPMethod(method)) {
            return false;
        }
        /**
         * Request's method must be either explicitly
         * permitted or not be included in list of restricted methods
         * for the rule to apply.
         */
        const permittedMethods = this.getPermittedMethods();
        if (permittedMethods?.includes(method)) {
            return true;
        }
        const restrictedMethods = this.getRestrictedMethods();
        return !!restrictedMethods && !restrictedMethods.includes(method);
    }
    /**
     * Checks if request's response headers matches with
     * the rule's $header modifier value.
     *
     * @param responseHeadersItems Request's response headers.
     *
     * @returns True, if rule must be applied to the request.
     */
    matchResponseHeaders(responseHeadersItems) {
        if (!responseHeadersItems || responseHeadersItems.length === 0) {
            return false;
        }
        const ruleData = this.getHeaderModifierValue();
        if (!ruleData) {
            return false;
        }
        const { header: ruleHeaderName, value: ruleHeaderValue, } = ruleData;
        return responseHeadersItems.some((responseHeadersItem) => {
            const { name: responseHeaderName, value: responseHeaderValue, } = responseHeadersItem;
            // Header name matching is case-insensitive
            if (ruleHeaderName.toLowerCase() !== responseHeaderName.toLowerCase()) {
                return false;
            }
            if (ruleHeaderValue === null) {
                return true;
            }
            // Unlike header name, header value matching is case-sensitive
            if (typeof ruleHeaderValue === 'string') {
                return ruleHeaderValue === responseHeaderValue;
            }
            if (responseHeaderValue && ruleHeaderValue instanceof RegExp) {
                return ruleHeaderValue.test(responseHeaderValue);
            }
            return false;
        });
    }
    /**
     * Checks if a network rule is too general.
     *
     * @param node AST node of the network rule.
     *
     * @returns True if the rule is too general.
     */
    static isTooGeneral(node) {
        return !(node.modifiers?.children?.length) && node.pattern.value.length < 4;
    }
    /**
     * Creates an instance of the {@link NetworkRule}.
     * It parses this rule and extracts the rule pattern (see {@link SimpleRegex}),
     * and rule modifiers.
     *
     * @param node AST node of the network rule.
     * @param filterListId ID of the filter list this rule belongs to.
     * @param ruleIndex Line start index in the source filter list; it will be used to find the original rule text
     * in the filtering log when a rule is applied. Default value is {@link RULE_INDEX_NONE} which means that
     * the rule does not have source index.
     *
     * @throws Error if it fails to parse the rule.
     */
    constructor(node, filterListId, ruleIndex = RULE_INDEX_NONE) {
        this.ruleIndex = ruleIndex;
        // TODO: Remove this completely
        this.ruleText = rule_generator/* RuleGenerator */.u.generate(node);
        this.filterListId = filterListId;
        this.allowlist = node.exception;
        const pattern = node.pattern.value;
        if (pattern && (0,simple_regex_Dw3J24Ss.h)(pattern)) {
            throw new SyntaxError('Rule has spaces, seems to be an host rule');
        }
        if (node.modifiers?.children?.length) {
            this.loadOptions(node.modifiers);
        }
        if (NetworkRule.isTooGeneral(node)) {
            throw new SyntaxError(`Rule is too general: ${rule_generator/* RuleGenerator */.u.generate(node)}`);
        }
        this.calculatePriorityWeight();
        this.pattern = new Pattern(pattern, this.isOptionEnabled(NetworkRuleOption.MatchCase));
    }
    /**
     * Parses the options string and saves them.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#basic-rules-modifiers}
     *
     * @param options Modifier list node.
     *
     * @throws An error if there is an unsupported modifier.
     */
    loadOptions(options) {
        for (const option of options.children) {
            let value = simple_regex_Dw3J24Ss.E;
            if (option.value && option.value.value) {
                value = option.value.value;
            }
            this.loadOption(option.name.value, value, option.exception);
            this.usedOptionNames.add(option.name.value);
        }
        this.validateOptions();
    }
    /**
     * Returns true if rule contains (enabled or disabled) specified option.
     * Please note, that options have three state: enabled, disabled, undefined.
     *
     * @param option Rule option to check.
     *
     * @returns True if rule contains (enabled or disabled) specified option.
     */
    hasOption(option) {
        return this.isOptionEnabled(option) || this.isOptionDisabled(option);
    }
    /**
     * Returns true if rule has at least one cosmetic option enabled.
     *
     * @returns True if the rule has at least one cosmetic option enabled.
     */
    hasCosmeticOption() {
        return (this.enabledOptions & NetworkRuleGroupOptions.CosmeticOption) !== 0;
    }
    /**
     * Returns true if the specified option is enabled.
     * Please note, that options have three state: enabled, disabled, undefined.
     *
     * @param option Rule option to check.
     *
     * @returns True if the specified option is enabled.
     */
    isOptionEnabled(option) {
        return (this.enabledOptions & option) === option;
    }
    /**
     * Returns true if one and only option is enabled.
     *
     * @param option Rule option to check.
     *
     * @returns True if the specified option is enabled.
     */
    isSingleOptionEnabled(option) {
        return this.enabledOptions === option;
    }
    /**
     * Returns true if the specified option is disabled.
     * Please note, that options have three state: enabled, disabled, undefined.
     *
     * @param option Rule option to check.
     *
     * @returns True if the specified option is disabled.
     */
    isOptionDisabled(option) {
        return (this.disabledOptions & option) === option;
    }
    /**
     * Checks if the rule has higher priority that the specified rule:
     * `allowlist + $important` > `$important` > `redirect` > `allowlist` > `basic rules`.
     *
     * @param r Rule to compare with.
     *
     * @returns True if the rule has higher priority than `r`.
     */
    isHigherPriority(r) {
        return this.priorityWeight > r.priorityWeight;
    }
    /**
     * Returns true if the rule is considered "generic"
     * "generic" means that the rule is not restricted to a limited set of domains
     * Please note that it might be forbidden on some domains, though.
     *
     * @returns True if the rule is considered "generic".
     */
    isGeneric() {
        return !this.domainModifier?.hasPermittedDomains();
    }
    /**
     * Returns true if this rule negates the specified rule.
     * Only makes sense when this rule has a `badfilter` modifier.
     *
     * @param specifiedRule Rule to check.
     *
     * @returns True if this rule negates the specified rule.
     */
    negatesBadfilter(specifiedRule) {
        if (!this.isOptionEnabled(NetworkRuleOption.Badfilter)) {
            return false;
        }
        if (this.allowlist !== specifiedRule.allowlist) {
            return false;
        }
        if (this.pattern.pattern !== specifiedRule.pattern.pattern) {
            return false;
        }
        if (this.permittedRequestTypes !== specifiedRule.permittedRequestTypes) {
            return false;
        }
        if (this.restrictedRequestTypes !== specifiedRule.restrictedRequestTypes) {
            return false;
        }
        if ((this.enabledOptions ^ NetworkRuleOption.Badfilter) !== specifiedRule.enabledOptions) {
            return false;
        }
        if (this.disabledOptions !== specifiedRule.disabledOptions) {
            return false;
        }
        if (!(0,simple_regex_Dw3J24Ss.b)(this.getRestrictedDomains(), specifiedRule.getRestrictedDomains())) {
            return false;
        }
        if (!(0,simple_regex_Dw3J24Ss.c)(this.getPermittedDomains(), specifiedRule.getPermittedDomains())) {
            return false;
        }
        return true;
    }
    /**
     * Checks if this rule can be used for hosts-level blocking.
     *
     * @returns True if the rule can be used for hosts-level blocking.
     */
    isHostLevelNetworkRule() {
        if (this.domainModifier?.hasPermittedDomains() || this.domainModifier?.hasRestrictedDomains()) {
            return false;
        }
        if (this.permittedRequestTypes !== 0 && this.restrictedRequestTypes !== 0) {
            return false;
        }
        if (this.disabledOptions !== NetworkRuleOption.NotSet) {
            return false;
        }
        if (this.enabledOptions !== NetworkRuleOption.NotSet) {
            return ((this.enabledOptions
                & NetworkRuleGroupOptions.OptionHostLevelRules)
                | (this.enabledOptions
                    ^ NetworkRuleGroupOptions.OptionHostLevelRules)) === NetworkRuleGroupOptions.OptionHostLevelRules;
        }
        return true;
    }
    /**
     * Enables or disables the specified option.
     *
     * @param option Option to enable or disable.
     * @param enabled True to enable, false to disable.
     * @param skipRestrictions Skip options allowlist/blacklist restrictions.
     *
     * @throws An error if the option we're trying to enable cannot be.
     * For instance, you cannot enable $elemhide for blacklist rules.
     */
    setOptionEnabled(option, enabled, skipRestrictions = false) {
        if (!skipRestrictions) {
            if (!this.allowlist && (option & NetworkRuleGroupOptions.AllowlistOnly) === option) {
                throw new SyntaxError(`Modifier ${NetworkRuleOption[option]} cannot be used in blacklist rule`);
            }
        }
        if (enabled) {
            this.enabledOptions |= option;
        }
        else {
            this.disabledOptions |= option;
        }
    }
    /**
     * Permits or forbids the specified request type.
     * "Permits" means that the rule will match **only** the types that are permitted.
     * "Restricts" means that the rule will match **all but restricted**.
     *
     * @param requestType Request type.
     * @param permitted True if it's permitted (whic).
     */
    setRequestType(requestType, permitted) {
        if (permitted) {
            this.permittedRequestTypes |= requestType;
        }
        else {
            this.restrictedRequestTypes |= requestType;
        }
    }
    /**
     * Sets and validates exceptionally allowed domains presented in $denyallow modifier.
     *
     * @param optionValue Denyallow modifier value.
     */
    setDenyAllowDomains(optionValue) {
        const domainModifier = new DomainModifier(optionValue, PIPE_SEPARATOR$1);
        if (domainModifier.restrictedDomains && domainModifier.restrictedDomains.length > 0) {
            throw new SyntaxError('Invalid modifier: $denyallow domains cannot be negated');
        }
        if (domainModifier.permittedDomains) {
            if (domainModifier.permittedDomains.some(DomainModifier.isWildcardOrRegexDomain)) {
                throw new SyntaxError('Invalid modifier: $denyallow does not support wildcards and regex domains');
            }
        }
        this.denyAllowDomains = domainModifier.permittedDomains;
    }
    /**
     * Loads the specified modifier.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#basic-rules-modifiers}
     *
     * @param optionName Modifier name.
     * @param optionValue Modifier value.
     * @param exception True if the modifier is negated.
     *
     * @throws An error if there is an unsupported modifier.
     */
    loadOption(optionName, optionValue, exception = false) {
        const { OPTIONS, NEGATABLE_OPTIONS } = NetworkRule;
        if (optionName.startsWith(OPTIONS.NOOP)) {
            /**
             * A noop modifier does nothing and can be used to increase some rules readability.
             * It consists of the sequence of underscore characters (_) of any length
             * and can appear in a rule as many times as it's needed.
             */
            if (!optionName.split(OPTIONS.NOOP).some((s) => !!s)) {
                return;
            }
        }
        // TODO: Speed up this by creating a map from names to bit mask positions
        if (exception && !NEGATABLE_OPTIONS.has(optionName)) {
            throw new SyntaxError(`Invalid modifier: '${optionName}' cannot be negated`);
        }
        switch (optionName) {
            // General options
            // $first-party, $~first-party
            case OPTIONS.FIRST_PARTY:
                this.setOptionEnabled(NetworkRuleOption.ThirdParty, exception);
                break;
            // $third-party, $~third-party
            case OPTIONS.THIRD_PARTY:
                this.setOptionEnabled(NetworkRuleOption.ThirdParty, !exception);
                break;
            // $match-case, $~match-case
            case OPTIONS.MATCH_CASE:
                this.setOptionEnabled(NetworkRuleOption.MatchCase, !exception);
                break;
            // $important
            case OPTIONS.IMPORTANT:
                this.setOptionEnabled(NetworkRuleOption.Important, true);
                break;
            // $domain
            case OPTIONS.DOMAIN:
                this.domainModifier = new DomainModifier(optionValue, PIPE_SEPARATOR$1);
                break;
            // $denyallow
            case OPTIONS.DENYALLOW:
                this.setDenyAllowDomains(optionValue);
                break;
            // $method modifier
            case OPTIONS.METHOD: {
                this.setOptionEnabled(NetworkRuleOption.Method, true);
                this.methodModifier = new MethodModifier(optionValue);
                break;
            }
            // $header modifier
            case OPTIONS.HEADER:
                this.setOptionEnabled(NetworkRuleOption.Header, true);
                this.headerModifier = new HeaderModifier(optionValue);
                break;
            // $to modifier
            case OPTIONS.TO: {
                this.setOptionEnabled(NetworkRuleOption.To, true);
                this.toModifier = new ToModifier(optionValue);
                break;
            }
            // Document-level allowlist rules
            // $elemhide
            case OPTIONS.ELEMHIDE:
                this.setOptionEnabled(NetworkRuleOption.Elemhide, true);
                this.setRequestType(request_type/* RequestType */.Y.Document, true);
                this.setRequestType(request_type/* RequestType */.Y.SubDocument, true);
                break;
            // $generichide
            case OPTIONS.GENERICHIDE:
                this.setOptionEnabled(NetworkRuleOption.Generichide, true);
                this.setRequestType(request_type/* RequestType */.Y.Document, true);
                this.setRequestType(request_type/* RequestType */.Y.SubDocument, true);
                break;
            // $specifichide
            case OPTIONS.SPECIFICHIDE:
                this.setOptionEnabled(NetworkRuleOption.Specifichide, true);
                this.setRequestType(request_type/* RequestType */.Y.Document, true);
                this.setRequestType(request_type/* RequestType */.Y.SubDocument, true);
                break;
            // $genericblock
            case OPTIONS.GENERICBLOCK:
                this.setOptionEnabled(NetworkRuleOption.Genericblock, true);
                this.setRequestType(request_type/* RequestType */.Y.Document, true);
                this.setRequestType(request_type/* RequestType */.Y.SubDocument, true);
                break;
            // $jsinject
            case OPTIONS.JSINJECT:
                this.setOptionEnabled(NetworkRuleOption.Jsinject, true);
                this.setRequestType(request_type/* RequestType */.Y.Document, true);
                this.setRequestType(request_type/* RequestType */.Y.SubDocument, true);
                break;
            // $urlblock
            case OPTIONS.URLBLOCK:
                this.setOptionEnabled(NetworkRuleOption.Urlblock, true);
                this.setRequestType(request_type/* RequestType */.Y.Document, true);
                this.setRequestType(request_type/* RequestType */.Y.SubDocument, true);
                break;
            // $content
            case OPTIONS.CONTENT:
                this.setOptionEnabled(NetworkRuleOption.Content, true);
                this.setRequestType(request_type/* RequestType */.Y.Document, true);
                this.setRequestType(request_type/* RequestType */.Y.SubDocument, true);
                break;
            // $document, $doc / $~document, $~doc
            case OPTIONS.DOCUMENT:
            case OPTIONS.DOC:
                if (exception) {
                    this.setRequestType(request_type/* RequestType */.Y.Document, false);
                    break;
                }
                this.setRequestType(request_type/* RequestType */.Y.Document, true);
                // In the case of allowlist rules $document implicitly includes
                // all these modifiers: `$content`, `$elemhide`, `$jsinject`,
                // `$urlblock`.
                if (this.isAllowlist()) {
                    this.setOptionEnabled(NetworkRuleOption.Elemhide, true, true);
                    this.setOptionEnabled(NetworkRuleOption.Jsinject, true, true);
                    this.setOptionEnabled(NetworkRuleOption.Urlblock, true, true);
                    this.setOptionEnabled(NetworkRuleOption.Content, true, true);
                }
                break;
            // $stealth
            case OPTIONS.STEALTH:
                this.setOptionEnabled(NetworkRuleOption.Stealth, true);
                this.stealthModifier = new StealthModifier(optionValue);
                break;
            // $popup
            case OPTIONS.POPUP:
                this.setOptionEnabled(NetworkRuleOption.Popup, true);
                break;
            // Content type options
            // $script, $~script
            case OPTIONS.SCRIPT:
                this.setRequestType(request_type/* RequestType */.Y.Script, !exception);
                break;
            // $stylesheet, $~stylesheet
            case OPTIONS.STYLESHEET:
                this.setRequestType(request_type/* RequestType */.Y.Stylesheet, !exception);
                break;
            // $subdocument, $~subdocument
            case OPTIONS.SUBDOCUMENT:
                this.setRequestType(request_type/* RequestType */.Y.SubDocument, !exception);
                break;
            // $object, $~object
            case OPTIONS.OBJECT:
                this.setRequestType(request_type/* RequestType */.Y.Object, !exception);
                break;
            // $image, $~image
            case OPTIONS.IMAGE:
                this.setRequestType(request_type/* RequestType */.Y.Image, !exception);
                break;
            // $xmlhttprequest, $~xmlhttprequest
            case OPTIONS.XMLHTTPREQUEST:
                this.setRequestType(request_type/* RequestType */.Y.XmlHttpRequest, !exception);
                break;
            // $media, $~media
            case OPTIONS.MEDIA:
                this.setRequestType(request_type/* RequestType */.Y.Media, !exception);
                break;
            // $font, $~font
            case OPTIONS.FONT:
                this.setRequestType(request_type/* RequestType */.Y.Font, !exception);
                break;
            // $websocket, $~websocket
            case OPTIONS.WEBSOCKET:
                this.setRequestType(request_type/* RequestType */.Y.WebSocket, !exception);
                break;
            // $other, $~other
            case OPTIONS.OTHER:
                this.setRequestType(request_type/* RequestType */.Y.Other, !exception);
                break;
            // $ping, $~ping
            case OPTIONS.PING:
                this.setRequestType(request_type/* RequestType */.Y.Ping, !exception);
                break;
            // Special modifiers
            // $badfilter
            case OPTIONS.BADFILTER:
                this.setOptionEnabled(NetworkRuleOption.Badfilter, true);
                break;
            // $csp
            case OPTIONS.CSP:
                this.setOptionEnabled(NetworkRuleOption.Csp, true);
                this.advancedModifier = new CspModifier(optionValue, this.isAllowlist());
                break;
            // $replace
            case OPTIONS.REPLACE:
                this.setOptionEnabled(NetworkRuleOption.Replace, true);
                this.advancedModifier = new ReplaceModifier(optionValue);
                break;
            // $cookie
            case OPTIONS.COOKIE:
                this.setOptionEnabled(NetworkRuleOption.Cookie, true);
                this.advancedModifier = new CookieModifier(optionValue);
                break;
            // $redirect
            case OPTIONS.REDIRECT:
                this.setOptionEnabled(NetworkRuleOption.Redirect, true);
                this.advancedModifier = new RedirectModifier(optionValue, this.isAllowlist());
                break;
            // $redirect-rule
            case OPTIONS.REDIRECTRULE:
                this.setOptionEnabled(NetworkRuleOption.Redirect, true);
                this.advancedModifier = new RedirectModifier(optionValue, this.isAllowlist(), true);
                break;
            // $removeparam
            case OPTIONS.REMOVEPARAM:
                this.setOptionEnabled(NetworkRuleOption.RemoveParam, true);
                this.advancedModifier = new RemoveParamModifier(optionValue);
                break;
            // $removeheader
            case OPTIONS.REMOVEHEADER:
                this.setOptionEnabled(NetworkRuleOption.RemoveHeader, true);
                this.advancedModifier = new RemoveHeaderModifier(optionValue, this.isAllowlist());
                break;
            // $permissions
            case OPTIONS.PERMISSIONS:
                this.setOptionEnabled(NetworkRuleOption.Permissions, true);
                this.advancedModifier = new PermissionsModifier(optionValue, this.isAllowlist());
                break;
            // $jsonprune
            // simple validation of jsonprune rules for compiler
            // https://github.com/AdguardTeam/FiltersCompiler/issues/168
            case OPTIONS.JSONPRUNE:
                if (isCompatibleWith(CompatibilityTypes.Extension)) {
                    throw new SyntaxError('Extension does not support $jsonprune modifier yet');
                }
                this.setOptionEnabled(NetworkRuleOption.JsonPrune, true);
                // TODO: should be properly implemented later
                // https://github.com/AdguardTeam/tsurlfilter/issues/71
                break;
            // $hls
            // simple validation of hls rules for compiler
            // https://github.com/AdguardTeam/FiltersCompiler/issues/169
            case OPTIONS.HLS:
                if (isCompatibleWith(CompatibilityTypes.Extension)) {
                    throw new SyntaxError('Extension does not support $hls modifier yet');
                }
                this.setOptionEnabled(NetworkRuleOption.Hls, true);
                // TODO: should be properly implemented later
                // https://github.com/AdguardTeam/tsurlfilter/issues/72
                break;
            // $referrerpolicy
            // simple validation of referrerpolicy rules for compiler
            // https://github.com/AdguardTeam/FiltersCompiler/issues/191
            case OPTIONS.REFERRERPOLICY:
                if (isCompatibleWith(CompatibilityTypes.Extension)) {
                    throw new SyntaxError('Extension does not support $referrerpolicy modifier');
                }
                // do nothing as $referrerpolicy is supported by CoreLibs-based apps only.
                // it is needed for proper rule conversion performed by FiltersCompiler
                // so rules with $referrerpolicy modifier is not marked as invalid
                break;
            // Dns modifiers
            // $client
            case OPTIONS.CLIENT:
                if (isCompatibleWith(CompatibilityTypes.Extension)) {
                    throw new SyntaxError('Extension doesn\'t support $client modifier');
                }
                this.setOptionEnabled(NetworkRuleOption.Client, true);
                this.advancedModifier = new ClientModifier(optionValue);
                break;
            // $dnsrewrite
            case OPTIONS.DNSREWRITE:
                if (isCompatibleWith(CompatibilityTypes.Extension)) {
                    throw new SyntaxError('Extension doesn\'t support $dnsrewrite modifier');
                }
                this.setOptionEnabled(NetworkRuleOption.DnsRewrite, true);
                this.advancedModifier = new DnsRewriteModifier(optionValue);
                break;
            // $dnstype
            case OPTIONS.DNSTYPE:
                if (isCompatibleWith(CompatibilityTypes.Extension)) {
                    throw new SyntaxError('Extension doesn\'t support $dnstype modifier');
                }
                this.setOptionEnabled(NetworkRuleOption.DnsType, true);
                this.advancedModifier = new DnsTypeModifier(optionValue);
                break;
            // $ctag
            case OPTIONS.CTAG:
                if (isCompatibleWith(CompatibilityTypes.Extension)) {
                    throw new SyntaxError('Extension doesn\'t support $ctag modifier');
                }
                this.setOptionEnabled(NetworkRuleOption.Ctag, true);
                this.advancedModifier = new CtagModifier(optionValue);
                break;
            // $app
            case OPTIONS.APP:
                if (isCompatibleWith(CompatibilityTypes.Extension)) {
                    throw new SyntaxError('Extension doesn\'t support $app modifier');
                }
                this.appModifier = new AppModifier(optionValue);
                break;
            // $network
            case OPTIONS.NETWORK:
                if (isCompatibleWith(CompatibilityTypes.Extension)) {
                    throw new SyntaxError('Extension doesn\'t support $network modifier');
                }
                this.setOptionEnabled(NetworkRuleOption.Network, true);
                break;
            // $extension, $~extension
            case OPTIONS.EXTENSION:
                if (isCompatibleWith(CompatibilityTypes.Extension)) {
                    throw new SyntaxError('Extension doesn\'t support $extension modifier');
                }
                this.setOptionEnabled(NetworkRuleOption.Extension, !exception);
                break;
            // $all
            case OPTIONS.ALL:
                if (this.isAllowlist()) {
                    throw new SyntaxError('Rule with $all modifier can not be allowlist rule');
                }
                // Set all request types
                Object.values(request_type/* RequestType */.Y).forEach((type) => {
                    this.setRequestType(type, true);
                });
                this.setOptionEnabled(NetworkRuleOption.Popup, true);
                break;
            // $empty and $mp4
            // Deprecated in favor of $redirect
            case OPTIONS.EMPTY:
            case OPTIONS.MP4:
                // Do nothing.
                break;
            default: {
                // clear empty values
                const modifierView = [optionName, optionValue]
                    .filter((i) => i)
                    .join('=');
                throw new SyntaxError(`Unknown modifier: ${modifierView}`);
            }
        }
    }
    /**
     * To calculate priority, we've categorized modifiers into different groups.
     * These groups are ranked based on their priority, from lowest to highest.
     * A modifier that significantly narrows the scope of a rule adds more
     * weight to its total priority. Conversely, if a rule applies to a broader
     * range of requests, its priority decreases.
     *
     * It's worth noting that there are cases where a single-parameter modifier
     * has a higher priority than multi-parameter ones. For instance, in
     * the case of `$domain=example.com|example.org`, a rule that includes two
     * domains has a slightly broader effective area than a rule with one
     * specified domain, therefore its priority is lower.
     *
     * The base priority weight of any rule is 1. If the calculated priority
     * is a floating-point number, it will be **rounded up** to the smallest
     * integer greater than or equal to the calculated weight.
     *
     * @see {@link NetworkRule.PermittedRequestTypeWeight}
     * @see {@link NetworkRule.PermittedDomainWeight}
     * @see {@link NetworkRule.SpecificExceptionsWeight}
     * @see {@link NetworkRule.AllowlistRuleWeight}
     * @see {@link NetworkRule.RedirectRuleWeight}
     * @see {@link NetworkRule.ImportantRuleWeight}
     * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-counting}
     */
    calculatePriorityWeight() {
        // Base modifiers, category 1.
        this.priorityWeight += countEnabledBits(this.enabledOptions, NetworkRule.CATEGORY_1_OPTIONS_MASK);
        this.priorityWeight += countEnabledBits(this.disabledOptions, NetworkRule.CATEGORY_1_OPTIONS_MASK);
        /**
         * When dealing with a negated domain, app, method, or content-type,
         * we add a point for the existence of the modifier itself, regardless
         * of the quantity of negated domains or content-types. This is because
         * the rule's scope is already infinitely broad. Put simply,
         * by prohibiting multiple domains, content-types, methods or apps,
         * the scope of the rule becomes only minimally smaller.
         */
        if (this.denyAllowDomains && this.denyAllowDomains.length > 0) {
            this.priorityWeight += 1;
        }
        const { domainModifier } = this;
        if (domainModifier?.hasRestrictedDomains()) {
            this.priorityWeight += 1;
        }
        if (this.methodModifier?.restrictedValues && this.methodModifier.restrictedValues.length > 0) {
            this.priorityWeight += 1;
        }
        if (this.restrictedRequestTypes !== request_type/* RequestType */.Y.NotSet) {
            this.priorityWeight += 1;
        }
        // $to modifier is basically a replacement for a regular expression
        // See https://github.com/AdguardTeam/KnowledgeBase/pull/196#discussion_r1221401215
        if (this.toModifier) {
            this.priorityWeight += 1;
        }
        /**
         * Category 2: permitted request types, methods, headers, $popup.
         * Specified content-types add `50 + 50 / number_of_content_types`,
         * for example: `||example.com^$image,script` will add
         * `50 + 50 / 2 = 50 + 25 = 75` to the total weight of the rule.
         * The `$popup` also belongs to this category, because it implicitly
         * adds the modifier `$document`.
         * Similarly, specific exceptions add `$document,subdocument`.
         *
         * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-2}
         */
        if (this.permittedRequestTypes !== request_type/* RequestType */.Y.NotSet) {
            const numberOfPermittedRequestTypes = getBitCount(this.permittedRequestTypes);
            // More permitted request types mean less priority weight.
            const relativeWeight = NetworkRule.CategoryTwoWeight / numberOfPermittedRequestTypes;
            this.priorityWeight += NetworkRule.CategoryTwoWeight + relativeWeight;
        }
        if (this.methodModifier?.permittedValues && this.methodModifier.permittedValues.length > 0) {
            // More permitted request methods mean less priority weight.
            const relativeWeight = NetworkRule.CategoryTwoWeight / this.methodModifier.permittedValues.length;
            this.priorityWeight += NetworkRule.CategoryTwoWeight + relativeWeight;
        }
        if (this.headerModifier) {
            // $header modifier in the rule adds 50
            this.priorityWeight += NetworkRule.CategoryTwoWeight;
        }
        /**
         * Category 3: permitted domains.
         * Specified domains through `$domain` and specified applications
         * through `$app` add `100 + 100 / number_domains (or number_applications)`,
         * for example:
         * `||example.com^$domain=example.com|example.org|example.net`
         * will add `100 + 100 / 3 = 134.3 = 134` or
         * `||example.com^$app=org.example.app1|org.example.app2`
         * will add `100 + 100 / 2 = 151`.
         */
        if (domainModifier?.hasPermittedDomains()) {
            // More permitted domains mean less priority weight.
            const relativeWeight = NetworkRule.CategoryThreeWeight / domainModifier.getPermittedDomains().length;
            this.priorityWeight += NetworkRule.CategoryThreeWeight + relativeWeight;
        }
        // Category 4: redirect rules.
        if (this.isOptionEnabled(NetworkRuleOption.Redirect)) {
            this.priorityWeight += NetworkRule.CategoryFourWeight;
        }
        // Category 5: specific exceptions.
        this.priorityWeight += NetworkRule.CategoryFiveWeight * countEnabledBits(this.enabledOptions, NetworkRule.SPECIFIC_EXCLUSIONS_MASK);
        // Category 6: allowlist rules.
        if (this.isAllowlist()) {
            this.priorityWeight += NetworkRule.CategorySixWeight;
        }
        // Category 7: important rules.
        if (this.isOptionEnabled(NetworkRuleOption.Important)) {
            this.priorityWeight += NetworkRule.CategorySevenWeight;
        }
        // Round up to avoid overlap between different categories of rules.
        this.priorityWeight = Math.ceil(this.priorityWeight);
    }
    /**
     * Validates rule options.
     */
    validateOptions() {
        if (this.advancedModifier instanceof RemoveParamModifier) {
            this.validateRemoveParamRule();
        }
        else if (this.advancedModifier instanceof RemoveHeaderModifier) {
            this.validateRemoveHeaderRule();
        }
        else if (this.advancedModifier instanceof PermissionsModifier) {
            this.validatePermissionsRule();
        }
        else if (this.headerModifier instanceof HeaderModifier) {
            this.validateHeaderRule();
        }
        else if (this.toModifier !== null) {
            this.validateToRule();
        }
        else if (this.denyAllowDomains !== null) {
            this.validateDenyallowRule();
        }
    }
    /**
     * $header rules are not compatible with any other
     * modifiers except for $important, $csp, $removeheader, $badfilter.
     * The rules with any other modifiers are considered invalid and will be discarded.
     */
    validateHeaderRule() {
        if ((this.enabledOptions | NetworkRuleGroupOptions.HeaderCompatibleOptions)
            !== NetworkRuleGroupOptions.HeaderCompatibleOptions) {
            throw new SyntaxError('$header rules are not compatible with some other modifiers');
        }
        if (this.advancedModifier && this.isOptionEnabled(NetworkRuleOption.RemoveHeader)) {
            const removeHeaderValue = this.getAdvancedModifierValue();
            if (!removeHeaderValue || removeHeaderValue.includes('request:')) {
                const message = '$header rules are only compatible with response headers removal of $removeheader.';
                throw new SyntaxError(message);
            }
        }
    }
    /**
     * $permissions rules are not compatible with any other
     * modifiers except $domain, $important, and $subdocument.
     * The rules with any other modifiers are considered invalid and will be discarded.
     */
    validatePermissionsRule() {
        if ((this.enabledOptions | NetworkRuleGroupOptions.PermissionsCompatibleOptions)
            !== NetworkRuleGroupOptions.PermissionsCompatibleOptions) {
            throw new SyntaxError('$permissions rules are not compatible with some other modifiers');
        }
    }
    /**
     * $removeparam rules are not compatible with any other modifiers except $domain,
     * $third-party, $app, $important, $match-case and permitted content type modifiers ($script, $stylesheet, etc).
     * The rules with any other modifiers are considered invalid and will be discarded.
     */
    validateRemoveParamRule() {
        if ((this.enabledOptions | NetworkRuleGroupOptions.RemoveParamCompatibleOptions)
            !== NetworkRuleGroupOptions.RemoveParamCompatibleOptions) {
            throw new SyntaxError('$removeparam rules are not compatible with some other modifiers');
        }
    }
    /**
     * $removeheader rules are not compatible with any other modifiers except $domain,
     * $third-party, $app, $important, $match-case and permitted content type modifiers ($script, $stylesheet, etc).
     * The rules with any other modifiers are considered invalid and will be discarded.
     */
    validateRemoveHeaderRule() {
        if ((this.enabledOptions | NetworkRuleGroupOptions.RemoveHeaderCompatibleOptions)
            !== NetworkRuleGroupOptions.RemoveHeaderCompatibleOptions) {
            throw new SyntaxError('$removeheader rules are not compatible with some other modifiers');
        }
        if (this.headerModifier && this.isOptionEnabled(NetworkRuleOption.Header)) {
            const removeHeaderValue = this.getAdvancedModifierValue();
            if (!removeHeaderValue || removeHeaderValue.includes('request:')) {
                const message = 'Request headers removal of $removeheaders is not compatible with $header rules.';
                throw new SyntaxError(message);
            }
        }
    }
    /**
     * $to rules are not compatible $denyallow - these rules considered invalid
     * and will be discarded.
     */
    validateToRule() {
        if (this.denyAllowDomains) {
            throw new SyntaxError('modifier $to is not compatible with $denyallow modifier');
        }
    }
    /**
     * $denyallow rules are not compatible $to - these rules considered invalid
     * and will be discarded.
     */
    validateDenyallowRule() {
        if (this.toModifier) {
            throw new SyntaxError('modifier $to is not compatible with $denyallow modifier');
        }
    }
}

/**
 * MatchingResult contains all the rules matching a web request, and provides methods
 * that define how a web request should be processed.
 */
class MatchingResult {
    /**
     * BasicRule - a rule matching the request.
     * It could lead to one of the following:
     * block the request
     * unblock the request (a regular allowlist rule or a document-level allowlist rule)
     * modify the way cosmetic rules work for this request
     * modify the response (see $redirect rules).
     */
    basicRule;
    /**
     * Rule matching the request's referrer and having on of the following modifiers:
     * - $document — this one basically disables everything;
     * - $urlblock — disables network-level rules (not cosmetic);
     * - $genericblock — disables generic network-level rules.
     *
     * Other document-level modifiers like $jsinject or $content will be ignored here as they don't do anything.
     */
    documentRule;
    /**
     * Set of rules modifying the response's content-security-policy
     * See $csp modifier.
     */
    cspRules;
    /**
     * Set of rules modifying the request's and response's cookies
     * See $cookie modifier.
     */
    cookieRules;
    /**
     * Set of rules modifying the response's content
     * See $replace modifier.
     */
    replaceRules;
    /**
     * Set of rules redirecting request
     * See $redirect and $redirect-rule modifiers.
     */
    redirectRules;
    /**
     * RemoveParam rules - a set of rules modifying url query parameters
     * See $removeparam modifier.
     */
    removeParamRules;
    /**
     * RemoveHeader rules - a set of rules modifying headers
     * See $removeheader modifier.
     */
    removeHeaderRules;
    /**
     * Permissions rules - a set of rules modifying permissions policy
     * See $permissions modifier.
     */
    permissionsRules;
    /**
     * Headers rules - a set of rules for blocking rules by headers.
     */
    headerRules;
    /**
     * Stealth rules - a set of allowlist rules with $stealth modifier,
     * that negates stealth mode features.
     *
     * Note that the stealth rule can be received from both rules and sourceRules.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#stealth-modifier}
     */
    stealthRules;
    /**
     * CosmeticExceptionRule - a rule that disables cosmetic rules for the document or subdocument.
     * It is moved to it's own filed to not interfere with applying network blocking rules.
     */
    cosmeticExceptionRule;
    /**
     * PopupRule - this is a rule that specified which way should be used
     * to blocking document request: close the tab or open dummy blocking page.
     * We should store it separately from other blocking rules, because $popup
     * has an intersection by use cases with $all.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#popup-modifier}
     */
    popupRule;
    /**
     * Creates an instance of the MatchingResult struct and fills it with the rules.
     *
     * @param rules A list of network rules that match the request.
     * @param sourceRule A rule that matches the document that is a source
     * of the request, i.e. document-level exclusions.
     */
    constructor(rules, sourceRule) {
        this.basicRule = null;
        this.documentRule = null;
        this.cspRules = null;
        this.cookieRules = null;
        this.replaceRules = null;
        this.removeParamRules = null;
        this.removeHeaderRules = null;
        this.redirectRules = null;
        this.stealthRules = null;
        this.permissionsRules = null;
        this.headerRules = null;
        this.popupRule = null;
        this.cosmeticExceptionRule = null;
        // eslint-disable-next-line no-param-reassign
        rules = MatchingResult.removeBadfilterRules(rules);
        if (sourceRule) {
            this.documentRule = sourceRule;
        }
        // Second - check if blocking rules (generic or all of them) are allowed
        // generic blocking rules are allowed by default
        let genericAllowed = true;
        // basic blocking rules are allowed by default
        let basicAllowed = true;
        if (this.documentRule) {
            if (this.documentRule.isOptionEnabled(NetworkRuleOption.Urlblock)) {
                basicAllowed = false;
            }
            else if (this.documentRule.isOptionEnabled(NetworkRuleOption.Genericblock)) {
                genericAllowed = false;
            }
        }
        // Iterate through the list of rules and fill the MatchingResult
        for (const rule of rules) {
            if (rule.hasCosmeticOption()) {
                if (!this.cosmeticExceptionRule || rule.isHigherPriority(this.cosmeticExceptionRule)) {
                    this.cosmeticExceptionRule = rule;
                }
                /**
                 * Some rules include both cosmetic options and network modifiers,
                 * and affect both network and cosmetic engines matching.
                 *
                 * Such rules should also compete for `basicRule` slot down below,
                 * e.g `@@||example.org$document` and `@@||nhk.or.jp^$content`.
                 *
                 * Cosmetic options rules that don't contain such modifiers should only affect cosmetic engine.
                 */
                if (!rule.isOptionEnabled(NetworkRuleOption.Urlblock)
                    && !rule.isOptionEnabled(NetworkRuleOption.Genericblock)
                    && !rule.isOptionEnabled(NetworkRuleOption.Content)) {
                    continue;
                }
            }
            if (rule.isOptionEnabled(NetworkRuleOption.Cookie)) {
                (this.cookieRules ??= []).push(rule);
                continue;
            }
            if (rule.isOptionEnabled(NetworkRuleOption.Replace)) {
                (this.replaceRules ??= []).push(rule);
                continue;
            }
            if (rule.isOptionEnabled(NetworkRuleOption.RemoveParam)) {
                (this.removeParamRules ??= []).push(rule);
                continue;
            }
            if (rule.isOptionEnabled(NetworkRuleOption.RemoveHeader)) {
                (this.removeHeaderRules ??= []).push(rule);
                continue;
            }
            if (rule.isOptionEnabled(NetworkRuleOption.Redirect)) {
                (this.redirectRules ??= []).push(rule);
                continue;
            }
            if (rule.isOptionEnabled(NetworkRuleOption.Csp)) {
                (this.cspRules ??= []).push(rule);
                continue;
            }
            if (rule.isOptionEnabled(NetworkRuleOption.Stealth)) {
                (this.stealthRules ??= []).push(rule);
                continue;
            }
            if (rule.isOptionEnabled(NetworkRuleOption.Permissions)) {
                (this.permissionsRules ??= []).push(rule);
                continue;
            }
            if (rule.isOptionEnabled(NetworkRuleOption.Header)) {
                (this.headerRules ??= []).push(rule);
                continue;
            }
            if (rule.isOptionEnabled(NetworkRuleOption.Popup)
                // This check needed to split $all rules from $popup rules
                && (rule.getPermittedRequestTypes() & request_type/* RequestType */.Y.Document) !== request_type/* RequestType */.Y.Document) {
                this.popupRule = rule;
                continue;
            }
            // Check blocking rules against $genericblock / $urlblock
            if (!rule.isAllowlist() && this.documentRule?.isHigherPriority(rule)) {
                if (!basicAllowed) {
                    continue;
                }
                if (!genericAllowed && rule.isGeneric()) {
                    continue;
                }
            }
            if (!this.basicRule || rule.isHigherPriority(this.basicRule)) {
                this.basicRule = rule;
            }
        }
    }
    /**
     * Returns popup rule.
     *
     * @returns The popup rule or null if not found.
     */
    getPopupRule() {
        return this.popupRule;
    }
    /**
     * GetBasicResult returns a rule that should be applied to the web request.
     *
     * Possible outcomes are:
     * - returns nil -- allow the request;
     * - returns an allowlist rule -- allow the request;
     * - returns a blocking rule -- block the request;
     * - returns a redirect rule -- redirect the request.
     *
     * @returns Basic result rule.
     */
    getBasicResult() {
        let basic = this.basicRule;
        // e.g. @@||example.com^$generichide
        if (this.cosmeticExceptionRule && (!basic || this.cosmeticExceptionRule.isHigherPriority(basic))) {
            return this.cosmeticExceptionRule;
        }
        if (!basic) {
            // Only document-level frame rule would be returned as a basic result,
            // cause only those rules could block or modify page sub-requests.
            // Other frame rules (generichide, elemhide etc) will be used in getCosmeticOption function.
            if (this.documentRule && this.documentRule.isDocumentLevelAllowlistRule()) {
                basic = this.documentRule;
            }
        }
        // https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#replace-modifier
        // https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-extra
        // $replace rules have a higher priority than other basic rules (including exception rules).
        // So if a request corresponds to two different rules one of which has the $replace modifier,
        // this rule will be applied.
        if (this.replaceRules) {
            const isReplaceOrContent = basic?.isOptionEnabled(NetworkRuleOption.Replace)
                || basic?.isOptionEnabled(NetworkRuleOption.Content);
            // If basic rule is an exception with $replace or $content modifier,
            // then basic rule will disable $replace rules.
            if (basic?.isAllowlist() && isReplaceOrContent) {
                return basic;
            }
            // Otherwise null is returned to allow the request, because we need
            // to get response first to then apply the $replace rules to
            // the response.
            return null;
        }
        // Redirect rules have a high priority
        // https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#redirect-modifier
        // https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-6
        const redirectRule = this.getRedirectRule();
        if (redirectRule && (!basic || !basic.isHigherPriority(redirectRule))) {
            return redirectRule;
        }
        if (!basic) {
            return this.popupRule;
        }
        return basic;
    }
    /**
     * Returns a single stealth rule, that is corresponding to the given option.
     * If no option is given, returns a rule that disables stealth completely if any.
     *
     * @param stealthOption Stealth option name.
     *
     * @returns Stealth rule or null.
     */
    getStealthRule(stealthOption) {
        if (!this.stealthRules) {
            return null;
        }
        return this.stealthRules.find((r) => {
            const stealthModifier = r.getStealthModifier();
            if (!stealthModifier) {
                logger.debug(`Stealth rule without stealth modifier: ${r}`);
                return false;
            }
            if (stealthOption) {
                return stealthModifier.hasStealthOption(stealthOption);
            }
            // $stealth rules without values are globally disabling stealth mode
            return !stealthModifier.hasValues();
        }) ?? null;
    }
    /**
     * Returns a single rule with $header modifier,
     * that should be applied to the web request, if any.
     *
     * Function is intended to be called on onHeadersReceived event as an alternative to getBasicResult,
     * it returns only a blocking or allowlist rule without modifiers which could modify the request.
     * Request modifying rules with $header modifier are handled in a corresponding service.
     *
     * TODO: filterAdvancedModifierRules may not be optimal for sorting rules with $header modifier,
     * as $header is not an advanced modifier.
     *
     * @param responseHeaders Response headers.
     *
     * @returns Header result rule or null.
     */
    getResponseHeadersResult(responseHeaders) {
        if (!responseHeaders || responseHeaders.length === 0) {
            return null;
        }
        const { basicRule, documentRule } = this;
        let { headerRules } = this;
        if (!headerRules) {
            return null;
        }
        if (!basicRule) {
            if (documentRule && documentRule.isDocumentLevelAllowlistRule()) {
                return null;
            }
        }
        else if (basicRule.isAllowlist()) {
            return null;
        }
        headerRules = headerRules.filter((rule) => rule.matchResponseHeaders(responseHeaders));
        // Handle allowlist rules with $header modifier,
        // filtering out blocking rules which are allowlisted
        const rules = MatchingResult.filterAdvancedModifierRules(headerRules, (bRule) => ((aRule) => {
            const bHeaderData = bRule.getHeaderModifierValue();
            const aHeaderData = aRule.getHeaderModifierValue();
            return bHeaderData?.header === aHeaderData?.header
                && bHeaderData?.value?.toString() === aHeaderData?.value?.toString();
        }));
        return MatchingResult.getHighestPriorityRule(rules);
    }
    /**
     * Returns a bit-flag with the list of cosmetic options.
     *
     * @returns Cosmetic option mask.
     */
    getCosmeticOption() {
        const { basicRule, documentRule, cosmeticExceptionRule } = this;
        let rule = cosmeticExceptionRule || basicRule;
        // We choose a non-empty rule and the one of the two with the higher
        // priority in order to accurately calculate cosmetic options.
        if ((!rule && documentRule) || (rule && documentRule?.isHigherPriority(rule))) {
            rule = documentRule;
        }
        if (!rule || !rule.isAllowlist()) {
            return CosmeticOption.CosmeticOptionAll;
        }
        let option = CosmeticOption.CosmeticOptionAll;
        if (rule.isOptionEnabled(NetworkRuleOption.Elemhide)) {
            option ^= CosmeticOption.CosmeticOptionGenericCSS;
            option ^= CosmeticOption.CosmeticOptionSpecificCSS;
        }
        if (rule.isOptionEnabled(NetworkRuleOption.Generichide)) {
            option ^= CosmeticOption.CosmeticOptionGenericCSS;
        }
        if (rule.isOptionEnabled(NetworkRuleOption.Specifichide)) {
            option ^= CosmeticOption.CosmeticOptionSpecificCSS;
        }
        if (rule.isOptionEnabled(NetworkRuleOption.Jsinject)) {
            option ^= CosmeticOption.CosmeticOptionJS;
        }
        if (rule.isOptionEnabled(NetworkRuleOption.Content)) {
            option ^= CosmeticOption.CosmeticOptionHtml;
        }
        return option;
    }
    /**
     * Return an array of replace rules.
     *
     * @returns An array of replace rules.
     */
    getReplaceRules() {
        if (!this.replaceRules) {
            return [];
        }
        // TODO: Look up for allowlist $content rule
        return MatchingResult.filterAdvancedModifierRules(this.replaceRules, (rule) => ((x) => x.getAdvancedModifierValue() === rule.getAdvancedModifierValue()));
    }
    /**
     * Filters array of rules according to allowlist rules contained.
     * Empty advanced modifier allowlists everything.
     *
     * This function result will be called for testing if rule `x` allowlists rule `r`.
     *
     * @param rules Array of rules.
     * @param allowlistPredicate Allowlist criteria.
     *
     * @returns Filtered array of rules.
     */
    static filterAdvancedModifierRules(rules, allowlistPredicate) {
        const blockingRules = [];
        const allowlistRules = [];
        for (const rule of rules) {
            if (rule.isAllowlist()) {
                allowlistRules.push(rule);
            }
            else {
                blockingRules.push(rule);
            }
        }
        if (blockingRules.length === 0) {
            return [];
        }
        if (allowlistRules.length === 0) {
            return blockingRules;
        }
        if (allowlistRules.length > 0) {
            const allowlistRuleWithEmptyOption = allowlistRules
                .find((allowlistRule) => allowlistRule.getAdvancedModifierValue() === '');
            const result = [];
            blockingRules.forEach((blockRule) => {
                if (allowlistRuleWithEmptyOption
                    && !blockRule.isHigherPriority(allowlistRuleWithEmptyOption)) {
                    result.push(allowlistRuleWithEmptyOption);
                    return;
                }
                const allowlistingRule = allowlistRules.find((a) => {
                    return !blockRule.isHigherPriority(a) && allowlistPredicate.call(this, blockRule)(a);
                });
                if (allowlistingRule) {
                    result.push(allowlistingRule);
                }
                else {
                    result.push(blockRule);
                }
            });
            return result.filter((item, pos) => result.indexOf(item) === pos);
        }
        return blockingRules;
    }
    /**
     * Returns an array of csp rules.
     *
     * @returns An array of csp rules.
     */
    getCspRules() {
        if (!this.cspRules) {
            return [];
        }
        const blockingRules = [];
        const allowlistedRulesByDirective = new Map();
        for (const rule of this.cspRules) {
            if (rule.isAllowlist()) {
                if (!rule.getAdvancedModifierValue()) { // Global allowlist rule
                    return [rule];
                }
                MatchingResult.putWithPriority(rule, undefined, allowlistedRulesByDirective);
            }
            else {
                blockingRules.push(rule);
            }
        }
        const rulesByDirective = new Map();
        // Collect allowlist and blocking CSP rules in one array
        blockingRules.forEach((rule) => {
            if (rule.getAdvancedModifierValue()) {
                const allowlistRule = allowlistedRulesByDirective.get(rule.getAdvancedModifierValue());
                MatchingResult.putWithPriority(rule, allowlistRule, rulesByDirective);
            }
        });
        return Array.from(rulesByDirective.values());
    }
    /**
     * Checks if a network rule is sub document rule.
     *
     * @param rule Rule to check.
     *
     * @returns `true` if the rule is sub document rule.
     */
    static isSubDocumentRule(rule) {
        return (rule.getPermittedRequestTypes() & request_type/* RequestType */.Y.SubDocument) === request_type/* RequestType */.Y.SubDocument;
    }
    /**
     * Returns an array of permission policy rules.
     *
     * @returns An array of permission policy rules.
     */
    getPermissionsPolicyRules() {
        if (!this.permissionsRules) {
            return [];
        }
        const allowlistRules = [];
        const blockingRules = [];
        let globalAllowlistRule = null;
        let globalSubDocAllowlistRule = null;
        for (let i = 0; i < this.permissionsRules.length; i += 1) {
            const rule = this.permissionsRules[i];
            if (rule.isAllowlist()) {
                // Global allowlist rule, where $permissions modifier doesn't have a value
                if (!rule.getAdvancedModifierValue()) {
                    if (MatchingResult.isSubDocumentRule(rule)) {
                        if (!globalSubDocAllowlistRule) {
                            // e.g. @@||example.com^$subdocument,permissions
                            globalSubDocAllowlistRule = rule;
                        }
                    }
                    else if (!globalAllowlistRule) {
                        // e.g. @@||example.com^$permissions
                        globalAllowlistRule = rule;
                    }
                }
                else {
                    allowlistRules.push(rule);
                }
            }
            else {
                blockingRules.push(rule);
            }
        }
        if (globalAllowlistRule) {
            return [globalAllowlistRule];
        }
        const result = new Set();
        blockingRules.forEach((rule) => {
            if (MatchingResult.isSubDocumentRule(rule) && globalSubDocAllowlistRule) {
                result.add(globalSubDocAllowlistRule);
                return;
            }
            const allowlistRule = allowlistRules.find((a) => !rule.isHigherPriority(a) && rule.getAdvancedModifierValue() === a.getAdvancedModifierValue()
                && MatchingResult.isSubDocumentRule(a) === MatchingResult.isSubDocumentRule(rule));
            if (allowlistRule) {
                result.add(allowlistRule);
            }
            else {
                result.add(rule);
            }
        });
        return Array.from(result);
    }
    /**
     * Returns a redirect rule or null if redirect rules are empty.
     * $redirect-rule is only returned if there's a blocking rule also matching
     * this request.
     *
     * @returns Redirect rule or null if not found.
     */
    getRedirectRule() {
        if (!this.redirectRules) {
            return null;
        }
        // Apply allowlist $redirect rules.
        let result = MatchingResult.filterAdvancedModifierRules(this.redirectRules, (rule) => ((x) => x.getAdvancedModifierValue() === rule.getAdvancedModifierValue()));
        // Filters only not allowlist rules.
        result = result.filter((r) => !r.isAllowlist());
        // Splits $redirect and $redirect-rule into separate arrays.
        const conditionalRedirectRules = [];
        const allWeatherRedirectRules = [];
        result.forEach((rule) => {
            const redirectModifier = rule.getAdvancedModifier();
            if (redirectModifier.isRedirectingOnlyBlocked) {
                conditionalRedirectRules.push(rule);
            }
            else {
                allWeatherRedirectRules.push(rule);
            }
        });
        if (allWeatherRedirectRules.length > 0) {
            return MatchingResult.getHighestPriorityRule(allWeatherRedirectRules);
        }
        if (conditionalRedirectRules.length > 0 && this.basicRule && !this.basicRule.isAllowlist()) {
            return MatchingResult.getHighestPriorityRule(conditionalRedirectRules);
        }
        return null;
    }
    /**
     * Returns an array of cookie rules.
     *
     * @returns An array of cookie rules.
     */
    getCookieRules() {
        if (!this.cookieRules) {
            return [];
        }
        const basic = this.getBasicResult();
        if (basic?.isAllowlist() && basic.isOptionEnabled(NetworkRuleOption.Urlblock)) {
            return [];
        }
        const allowlistPredicate = (rule) => ((allowlistRule) => {
            const allowlistRuleCookieModifier = allowlistRule.getAdvancedModifier();
            const ruleCookieModifier = rule.getAdvancedModifier();
            if (allowlistRule.getAdvancedModifierValue() === rule.getAdvancedModifierValue()) {
                return true;
            }
            // Matches by cookie name
            if (allowlistRuleCookieModifier.matches(ruleCookieModifier.getCookieName())) {
                return true;
            }
            return false;
        });
        let filtered = MatchingResult.filterAdvancedModifierRules(this.cookieRules, allowlistPredicate);
        // Cookie rule may also be disabled by a stealth rule with corresponding `1p-cookie` or `3p-cookie` value
        // If corresponding $stealth rule is found, such cookie rule does not get into resulting array
        filtered = filtered.filter((cookieRule) => {
            if (cookieRule.getFilterListId() !== STEALTH_MODE_FILTER_ID) {
                return true;
            }
            if (cookieRule.isOptionEnabled(NetworkRuleOption.ThirdParty)) {
                return !this.getStealthRule(StealthOptionName.ThirdPartyCookies);
            }
            return !this.getStealthRule(StealthOptionName.FirstPartyCookies);
        });
        return filtered.concat([...this.cookieRules.filter((r) => r.isAllowlist())]);
    }
    /**
     * Returns an array of removeparam rules.
     *
     * @returns Array of removeparam rules.
     */
    getRemoveParamRules() {
        if (!this.removeParamRules) {
            return [];
        }
        return MatchingResult.filterAdvancedModifierRules(this.removeParamRules, 
        // eslint-disable-next-line arrow-body-style
        (rule) => ((x) => {
            return x.isHigherPriority(rule) && x.getAdvancedModifierValue() === rule.getAdvancedModifierValue();
        }));
    }
    /**
     * Returns an array of removeheader rules.
     *
     * @returns An array of removeheader rules.
     */
    getRemoveHeaderRules() {
        if (!this.removeHeaderRules) {
            return [];
        }
        if (this.basicRule
            && this.basicRule.isAllowlist()
            && this.basicRule.isOptionEnabled(NetworkRuleOption.Urlblock)) {
            return [];
        }
        return MatchingResult.filterAdvancedModifierRules(this.removeHeaderRules, (rule) => ((x) => x.getAdvancedModifierValue() === rule.getAdvancedModifierValue()));
    }
    /**
     * Decides which rule should be put into the given map.
     * Compares priorities of the two given rules with the equal CSP directive and the rule that may already in the map.
     *
     * @param rule CSP rule (not null).
     * @param allowlistRule CSP allowlist rule (may be null).
     * @param map Rules mapped by csp directive.
     */
    // eslint-disable-next-line max-len
    static putWithPriority(rule, allowlistRule, map) {
        const cspDirective = rule.getAdvancedModifierValue();
        const currentRule = cspDirective ? map.get(cspDirective) : null;
        let newRule = rule;
        if (currentRule && !rule.isHigherPriority(currentRule)) {
            newRule = currentRule;
        }
        if (allowlistRule && allowlistRule.isHigherPriority(newRule)) {
            newRule = allowlistRule;
        }
        map.set(cspDirective, newRule);
    }
    /**
     * Looks if there are any matching $badfilter rules and removes
     * matching bad filters from the array (see the $badfilter description for more info).
     *
     * @param rules Rules to filter.
     *
     * @returns Filtered rules.
     */
    static removeBadfilterRules(rules) {
        const badfilterRules = [];
        for (const rule of rules) {
            if (rule.isOptionEnabled(NetworkRuleOption.Badfilter)) {
                badfilterRules.push(rule);
            }
        }
        if (badfilterRules.length > 0) {
            return rules.filter((rule) => {
                if (rule.isOptionEnabled(NetworkRuleOption.Badfilter)) {
                    return false;
                }
                const isRuleNegated = badfilterRules.some((badfilter) => badfilter.negatesBadfilter(rule));
                return !isRuleNegated;
            });
        }
        return rules;
    }
    /**
     * Returns the highest priority rule from the given array.
     *
     * @param rules Array of network rules.
     *
     * @returns Hightest priority rule or null if the array is empty.
     */
    static getHighestPriorityRule(rules) {
        if (rules.length === 0) {
            return null;
        }
        return rules.sort((a, b) => (b.isHigherPriority(a) ? 1 : -1))[0];
    }
}

/**
 * Prefix tree implementation.
 */
class TrieNode {
    /**
     * This node's children could be
     * - undefined in case of no children
     * - an instance of TrieNode in case of lonely child
     * - a map where key is a character code and value is it's trie node.
     */
    children;
    /**
     * Character code of this TrieNode.
     */
    code;
    /**
     * Data, attached to this trie node. When trie traversal is being done,
     * data from all trie nodes is collected.
     */
    data;
    /**
     * Creates an instance of a TrieNode with the specified char code.
     *
     * @param code The character code for this TrieNode.
     */
    constructor(code) {
        this.code = code;
    }
    /**
     * Attaches data to this TrieNode.
     *
     * @param data The data to attach to this TrieNode.
     */
    attach(data) {
        if (!this.data) {
            this.data = [];
        }
        this.data.push(data);
    }
    /**
     * Adds the specified string to the Trie and attaches data to it.
     *
     * @param str String to add.
     * @param data Data to attach to the leaf node.
     */
    add(str, data) {
        // eslint-disable-next-line @typescript-eslint/no-this-alias
        let root = this;
        for (let i = 0; i < str.length; i += 1) {
            const c = str.charCodeAt(i);
            let next = root.getChild(c);
            if (!next) {
                next = root.addChild(c);
            }
            root = next;
        }
        root.attach(data);
    }
    /**
     * Traverses this TrieNode and it's children using the specified search string.
     * This method collects all the data that's attached on the way and returns as
     * a result.
     *
     * @param str String to check.
     * @param start Index in str where to start traversing from.
     *
     * @returns An array of numbers collected from the trie nodes.
     */
    traverse(str, start) {
        const result = [];
        // eslint-disable-next-line @typescript-eslint/no-this-alias
        let current = this;
        for (let i = start; i < str.length; i += 1) {
            const c = str.charCodeAt(i);
            const next = current.getChild(c);
            if (!next) {
                break;
            }
            if (next.data) {
                result.push(...next.data);
            }
            current = next;
        }
        return result;
    }
    /**
     * Traverses this TrieNode and it's children using the specified search string and all substrings.
     *
     * @param str String to check.
     * @param len Max length to check.
     *
     * @returns Array of numbers collected from the trie nodes.
     */
    traverseAll(str, len) {
        const data = [];
        for (let i = 0; i <= len; i += 1) {
            const result = this.traverse(str, i);
            if (result) {
                data.push(...result);
            }
        }
        return data;
    }
    /**
     * Returns a child node with the specified character code or
     * undefined if not found.
     *
     * @param code Character code.
     *
     * @returns Child node or undefined.
     */
    getChild(code) {
        const { children } = this;
        if (!children) {
            return undefined;
        }
        if (children instanceof TrieNode) {
            if (children.code === code) {
                return children;
            }
            return undefined;
        }
        return children.get(code);
    }
    /**
     * Adds a new child node with the specified character code.
     *
     * @param code Character code.
     *
     * @returns The newly created TrieNode.
     */
    addChild(code) {
        const node = new TrieNode(code);
        if (!this.children) {
            this.children = node;
        }
        else if (this.children instanceof TrieNode) {
            const oldNode = this.children;
            this.children = new Map();
            this.children.set(oldNode.code, oldNode);
            this.children.set(code, node);
        }
        else {
            this.children.set(code, node);
        }
        return node;
    }
}

/**
 * Look up table with underlying prefix tree.
 */
class TrieLookupTable {
    /**
     * Count of rules added to this lookup table.
     */
    rulesCount = 0;
    /**
     * Storage for the network filtering rules.
     */
    ruleStorage;
    /**
     * Trie that stores rules' shortcuts.
     */
    trie;
    /**
     * Creates a new instance of the TrieLookupTable.
     *
     * @param storage Rules storage. We store "rule indexes" in the lookup table which
     * can be used to retrieve the full rules from the storage.
     */
    constructor(storage) {
        this.ruleStorage = storage;
        this.trie = new TrieNode(0);
    }
    /**
     * Finds all matching rules from the shortcuts lookup table.
     *
     * @param request Request to check.
     *
     * @returns Array of matching rules.
     */
    matchAll(request) {
        const rulesIndexes = this.traverse(request);
        return this.matchRules(request, rulesIndexes);
    }
    /**
     * Tries to add the rule to the lookup table.
     * Returns true if it was added.
     *
     * @param rule Rule to add.
     * @param storageIdx Index of the rule in the storage.
     *
     * @returns True if the rule was added.
     */
    addRule(rule, storageIdx) {
        const shortcut = rule.getShortcut();
        if (!shortcut || TrieLookupTable.isAnyURLShortcut(shortcut)
            || shortcut.length < simple_regex_Dw3J24Ss.S.MIN_SHORTCUT_LENGTH) {
            return false;
        }
        this.trie.add(shortcut, storageIdx);
        this.rulesCount += 1;
        return true;
    }
    /**
     * Returns total rules count.
     *
     * @returns Total rules count.
     */
    getRulesCount() {
        return this.rulesCount;
    }
    /**
     * For specified request finds matching rules from rules indexes array.
     *
     * @param request Request to check.
     * @param rulesIndexes Array of rules indexes.
     *
     * @returns Array of matching rules.
     */
    matchRules(request, rulesIndexes) {
        if (!rulesIndexes) {
            return [];
        }
        const result = [];
        for (let j = 0; j < rulesIndexes.length; j += 1) {
            const idx = rulesIndexes[j];
            const rule = this.ruleStorage.retrieveNetworkRule(idx);
            if (rule && rule.match(request, false)) {
                result.push(rule);
            }
        }
        return result;
    }
    /**
     * Traverses trie.
     *
     * @param request Request to check.
     *
     * @returns Array of numbers collected from the trie nodes.
     */
    traverse(request) {
        return this.trie.traverseAll(request.urlLowercase, request.urlLowercase.length);
    }
    /**
     * Checks if the rule potentially matches too many URLs.
     * We'd better use another type of lookup table for this kind of rules.
     *
     * @param shortcut Shortcut to check.
     *
     * @returns True if the rule potentially matches too many URLs.
     */
    static isAnyURLShortcut(shortcut) {
        // The numbers are basically ("PROTO://".length + 1)
        if (shortcut.length < 6 && shortcut.indexOf('ws:') === 0) {
            return true;
        }
        if (shortcut.length < 7 && shortcut.indexOf('|ws') === 0) {
            return true;
        }
        if (shortcut.length < 9 && shortcut.indexOf('http') === 0) {
            return true;
        }
        return !!(shortcut.length < 10 && shortcut.indexOf('|http') === 0);
    }
}

/**
 * Domain lookup table. Key is the domain name hash.
 */
class DomainsLookupTable {
    /**
     * Count of rules added to this lookup table.
     */
    rulesCount = 0;
    /**
     * Domain lookup table. Key is the domain name hash.
     */
    domainsLookupTable = new Map();
    /**
     * Storage for the network filtering rules.
     */
    ruleStorage;
    /**
     * Creates a new instance.
     *
     * @param storage Rules storage. We store "rule indexes" in the lookup table which
     * can be used to retrieve the full rules from the storage.
     */
    constructor(storage) {
        this.ruleStorage = storage;
    }
    /**
     * Implements the ILookupTable interface for DomainsLookupTable.
     *
     * @param rule Rule to add.
     * @param storageIdx Index of the rule in the storage.
     *
     * @returns True if the rule was added.
     */
    addRule(rule, storageIdx) {
        const permittedDomains = rule.getPermittedDomains();
        if (!permittedDomains || permittedDomains.length === 0) {
            return false;
        }
        if (permittedDomains.some(DomainModifier.isWildcardOrRegexDomain)) {
            return false;
        }
        permittedDomains.forEach((domain) => {
            const hash = (0,simple_regex_Dw3J24Ss.f)(domain);
            // Add the rule to the lookup table
            let rulesIndexes = this.domainsLookupTable.get(hash);
            if (!rulesIndexes) {
                rulesIndexes = [];
            }
            rulesIndexes.push(storageIdx);
            this.domainsLookupTable.set(hash, rulesIndexes);
        });
        this.rulesCount += 1;
        return true;
    }
    /**
     * Implements the ILookupTable interface method.
     *
     * @returns The count of rules added to this lookup table.
     */
    getRulesCount() {
        return this.rulesCount;
    }
    /**
     * Implements the ILookupTable interface method.
     *
     * @param request Request to check.
     *
     * @returns Array of matching network rules.
     */
    matchAll(request) {
        const result = [];
        if (!request.sourceHostname) {
            return result;
        }
        const domains = request.subdomains;
        if (request.hostname !== request.sourceHostname) {
            domains.push(...request.sourceSubdomains);
        }
        for (let i = 0; i < domains.length; i += 1) {
            const hash = (0,simple_regex_Dw3J24Ss.f)(domains[i]);
            const rulesIndexes = this.domainsLookupTable.get(hash);
            if (rulesIndexes) {
                for (let j = 0; j < rulesIndexes.length; j += 1) {
                    const rule = this.ruleStorage.retrieveNetworkRule(rulesIndexes[j]);
                    if (rule && rule.match(request)) {
                        result.push(rule);
                    }
                }
            }
        }
        return result;
    }
}

/**
 * Hostname lookup table.
 * For specific kind of rules like '||hostname^' and '||hostname/path' more simple algorithm with hashes is faster.
 */
class HostnameLookupTable {
    /**
     * Count of rules added to this lookup table.
     */
    rulesCount = 0;
    /**
     * Domain lookup table. Key is the domain name hash.
     */
    hostnameLookupTable = new Map();
    /**
     * Storage for the network filtering rules.
     */
    ruleStorage;
    /**
     * Creates a new instance.
     *
     * @param storage Rules storage. We store "rule indexes" in the lookup table which
     * can be used to retrieve the full rules from the storage.
     */
    constructor(storage) {
        this.ruleStorage = storage;
    }
    /**
     * Implements the ILookupTable interface for DomainsLookupTable.
     *
     * @param rule Rule to add.
     * @param storageIdx Index of the rule in the storage.
     *
     * @returns True if the rule was added.
     */
    addRule(rule, storageIdx) {
        const pattern = rule.getPattern();
        let hostname = '';
        // Pattern: '||example.org^'
        if (pattern.startsWith(simple_regex_Dw3J24Ss.S.MASK_START_URL) && pattern.endsWith(simple_regex_Dw3J24Ss.S.MASK_SEPARATOR)) {
            hostname = pattern.slice(simple_regex_Dw3J24Ss.S.MASK_START_URL.length, pattern.length - simple_regex_Dw3J24Ss.S.MASK_SEPARATOR.length);
        }
        // Pattern: '||example.org/path'
        if (pattern.startsWith(simple_regex_Dw3J24Ss.S.MASK_START_URL) && pattern.indexOf(simple_regex_Dw3J24Ss.S.MASK_BACKSLASH) !== -1) {
            const end = pattern.indexOf(simple_regex_Dw3J24Ss.S.MASK_BACKSLASH);
            hostname = pattern.slice(simple_regex_Dw3J24Ss.S.MASK_START_URL.length, end);
        }
        if (!HostnameLookupTable.isValidHostname(hostname)) {
            return false;
        }
        const hash = (0,simple_regex_Dw3J24Ss.f)(hostname);
        let rulesIndexes = this.hostnameLookupTable.get(hash);
        if (!rulesIndexes) {
            rulesIndexes = new Array();
            this.hostnameLookupTable.set(hash, rulesIndexes);
        }
        rulesIndexes.push(storageIdx);
        this.rulesCount += 1;
        return true;
    }
    /**
     * Implements the ILookupTable interface method.
     *
     * @returns The count of rules added to this lookup table.
     */
    getRulesCount() {
        return this.rulesCount;
    }
    /**
     * Implements the ILookupTable interface method.
     *
     * @param request The request to match against.
     *
     * @returns An array of matching network rules.
     */
    matchAll(request) {
        const result = [];
        const domains = request.subdomains;
        for (let i = 0; i < domains.length; i += 1) {
            const hash = (0,simple_regex_Dw3J24Ss.f)(domains[i]);
            const rulesIndexes = this.hostnameLookupTable.get(hash);
            if (rulesIndexes) {
                for (let j = 0; j < rulesIndexes.length; j += 1) {
                    const rule = this.ruleStorage.retrieveNetworkRule(rulesIndexes[j]);
                    if (rule && rule.match(request)) {
                        result.push(rule);
                    }
                }
            }
        }
        return result;
    }
    /**
     * Checks if this hostname string is valid.
     *
     * @param hostname Hostname to check.
     *
     * @returns True if the hostname is valid.
     */
    static isValidHostname(hostname) {
        if (!hostname) {
            return false;
        }
        if (hostname.indexOf(simple_regex_Dw3J24Ss.S.MASK_ANY_CHARACTER) !== -1) {
            return false;
        }
        if (hostname.indexOf('.') < 0 || hostname.endsWith('.')) {
            return false;
        }
        return true;
    }
}

/**
 * Sequence scan lookup table of rules for which we could not find a shortcut
 * and could not place it to the shortcuts lookup table.
 * In common case of rule there is always a way to just check a rule.match().
 */
class SeqScanLookupTable {
    /**
     * Count of rules added to this lookup table.
     */
    rulesCount = 0;
    /**
     * Rules for which we could not find a shortcut and could not place it to the shortcuts lookup table.
     */
    rules = [];
    /**
     * Implements the ILookupTable interface for SeqScanLookupTable.
     *
     * @param rule Rule to add.
     *
     * @returns True if the rule was added.
     */
    addRule(rule) {
        if (!this.rules.includes(rule)) {
            this.rules.push(rule);
            this.rulesCount += 1;
            return true;
        }
        return false;
    }
    /**
     * Implements the ILookupTable interface method.
     *
     * @returns Count of rules added to this lookup table.
     */
    getRulesCount() {
        return this.rulesCount;
    }
    /**
     * Implements the ILookupTable interface method.
     *
     * @param request Request to check.
     *
     * @returns Array of matching rules.
     */
    matchAll(request) {
        const result = [];
        for (let i = 0; i < this.rules.length; i += 1) {
            const r = this.rules[i];
            if (r.match(request)) {
                result.push(r);
            }
        }
        return result;
    }
}

/**
 * NetworkEngine is the engine that supports quick search over network rules.
 */
class NetworkEngine {
    /**
     * Count of rules added to the engine.
     */
    rulesCount;
    /**
     * Storage for the network filtering rules.
     */
    ruleStorage;
    /**
     * Domain lookup table. Key is the domain name hash.
     */
    domainsLookupTable;
    /**
     * Lookup table that relies on the rule shortcuts to speed up the search.
     */
    shortcutsLookupTable;
    /**
     * Lookup table for rules like `||hostname^` or `||hostname/path`.
     */
    hostnameLookupTable;
    /**
     * Rules for which we could not find a shortcut and could not place it to the shortcuts lookup table.
     */
    seqScanLookupTable;
    /**
     * Builds an instance of the network engine.
     *
     * @param storage An object for a rules storage.
     * @param skipStorageScan Create an instance without storage scanning.
     */
    constructor(storage, skipStorageScan = false) {
        this.ruleStorage = storage;
        this.rulesCount = 0;
        this.domainsLookupTable = new DomainsLookupTable(storage);
        this.hostnameLookupTable = new HostnameLookupTable(storage);
        this.shortcutsLookupTable = new TrieLookupTable(storage);
        this.seqScanLookupTable = new SeqScanLookupTable();
        if (skipStorageScan) {
            return;
        }
        const scanner = this.ruleStorage.createRuleStorageScanner(ScannerType.NetworkRules);
        while (scanner.scan()) {
            const indexedRule = scanner.getRule();
            if (indexedRule
                && indexedRule.rule instanceof NetworkRule) {
                this.addRule(indexedRule.rule, indexedRule.index);
            }
        }
    }
    /**
     * Match searches over all filtering rules loaded to the engine.
     * It returns rule if a match was found alongside the matching rule.
     *
     * @param request Request to check.
     *
     * @returns Rule matching request or null if no match was found.
     */
    match(request) {
        const networkRules = this.matchAll(request);
        if (networkRules.length === 0) {
            return null;
        }
        const result = new MatchingResult(networkRules, null);
        return result.getBasicResult();
    }
    /**
     * Finds all rules matching the specified request regardless of the rule types
     * It will find both allowlist and blacklist rules.
     *
     * @param request Request to check.
     *
     * @returns Array of matching rules.
     */
    matchAll(request) {
        // First check by shortcuts
        const result = this.hostnameLookupTable.matchAll(request);
        result.push(...(this.shortcutsLookupTable.matchAll(request)));
        result.push(...(this.domainsLookupTable.matchAll(request)));
        result.push(...(this.seqScanLookupTable.matchAll(request)));
        return result;
    }
    /**
     * Adds rule to the network engine.
     *
     * @param rule Rule to add.
     * @param storageIdx Storage index of the rule.
     */
    addRule(rule, storageIdx) {
        if (!this.hostnameLookupTable.addRule(rule, storageIdx)) {
            if (!this.shortcutsLookupTable.addRule(rule, storageIdx)) {
                if (!this.domainsLookupTable.addRule(rule, storageIdx)) {
                    this.seqScanLookupTable.addRule(rule, storageIdx);
                }
            }
        }
        this.rulesCount += 1;
    }
}

/**
 * Implements a host rule.
 *
 * HostRule is a structure for simple host-level rules (i.e. /etc/hosts syntax).
 * More details: http://man7.org/linux/man-pages/man5/hosts.5.html.
 * It also supports "just domain" syntax. In this case, the IP will be set to `0.0.0.0`.
 *
 * Rules syntax looks like this.
 * ```
 * IP_address canonical_hostname [aliases...]
 * ```
 *
 * Examples:
 * `192.168.1.13 bar.mydomain.org bar` -- ipv4
 * `ff02::1 ip6-allnodes` -- ipv6
 * `::1 localhost ip6-localhost ip6-loopback` -- ipv6 aliases
 * `example.org` -- "just domain" syntax.
 *
 * @returns True if this rule can be used on the specified hostname.
 */
class HostRule {
    ruleIndex;
    filterListId;
    hostnames = [];
    ip = '';
    invalid = false;
    /**
     * Constructor.
     *
     * Parses the rule and creates a new HostRule instance.
     *
     * @param node Original rule text.
     * @param filterListId ID of the filter list this rule belongs to.
     * @param ruleIndex Index of the rule.
     *
     * @throws Error if it fails to parse the rule.
     */
    constructor(node, filterListId, ruleIndex = RULE_INDEX_NONE) {
        this.ruleIndex = ruleIndex;
        this.filterListId = filterListId;
        this.ip = node.ip.value;
        if (node.hostnames.children.length === 0) {
            this.invalid = true;
            return;
        }
        this.hostnames = node.hostnames.children.map((hostname) => hostname.value);
    }
    /**
     * Match returns true if this rule can be used on the specified hostname.
     *
     * @param hostname Hostname to check.
     *
     * @returns True if the hostname matches one of the hostnames in the rule.
     */
    match(hostname) {
        return this.hostnames.includes(hostname);
    }
    /**
     * Returns list id.
     *
     * @returns The filter list ID.
     */
    getFilterListId() {
        return this.filterListId;
    }
    /**
     * Returns rule index.
     *
     * @returns The rule index.
     */
    getIndex() {
        return this.ruleIndex;
    }
    /**
     * Returns ip address.
     *
     * @returns IP address.
     */
    getIp() {
        return this.ip;
    }
    /**
     * Returns hostnames.
     *
     * @returns Array of hostnames.
     */
    getHostnames() {
        return this.hostnames;
    }
    /**
     * Checks if the rule is invalid.
     *
     * @returns True if the rule is invalid.
     */
    isInvalid() {
        return this.invalid;
    }
}

/**
 * Request represents a web request with all it's necessary properties.
 */
class Request {
    /**
     * Max url length for matching
     * Some urls are really long and slow down matching, so we cut them to this length.
     */
    static MAX_URL_MATCH_LENGTH = 2000;
    /**
     * Request type.
     */
    requestType;
    /**
     * True if request is third-party.
     * Third-party basically means that Domain != SourceDomain.
     * It can be null in the case when there is no sourceUrl at all.
     */
    thirdParty;
    /**
     * Original request URL.
     */
    url;
    /**
     * Request identifier.
     */
    requestId;
    /**
     * Status code.
     */
    statusCode;
    /**
     * Method name.
     */
    method;
    /**
     * Request tab identifier.
     */
    tabId;
    /**
     * The same request URL, but in lower case and shortened.
     * It is necessary to use lower-cased URL in several places,
     * that's why we keep it in the object.
     */
    urlLowercase;
    /**
     * Request's hostname.
     */
    hostname;
    /**
     * Request's domain (eTLD+1).
     */
    domain;
    /**
     * Source URL. Can be empty.
     */
    sourceUrl;
    /**
     * Source hostname. Can be empty.
     */
    sourceHostname;
    /**
     * Source domain (eTLD+1). Can be empty.
     */
    sourceDomain;
    /**
     * The request is for a given Hostname, and not for a URL, and we don't really know what protocol it is.
     * This can be true for DNS requests, or for HTTP CONNECT, or SNI matching.
     */
    isHostnameRequest = false;
    /**
     * List of subdomains parsed from hostname.
     */
    subdomains;
    /**
     * List of source subdomains parsed from source hostname.
     */
    sourceSubdomains;
    /**
     * List of client tags.
     */
    clientTags;
    /**
     * DNS type.
     */
    dnsType;
    /**
     * Client name.
     */
    clientName;
    /**
     * Client IP.
     */
    clientIP;
    /**
     * Creates an instance of a Request.
     *
     * @param url Request URL.
     * @param sourceUrl Source URL.
     * @param requestType Request type.
     * @param method Request method.
     *
     * @throws
     */
    constructor(url, sourceUrl, requestType, method) {
        if (typeof url !== 'string' || !isHttpOrWsRequest(url)) {
            throw new TypeError(`Invalid request url: ${url}`);
        }
        this.url = url;
        this.requestType = requestType;
        this.method = method;
        this.urlLowercase = Request.compactUrl(url).toLowerCase();
        this.sourceUrl = Request.compactUrl(sourceUrl);
        const tldResult = (0,es6/* parse */.qg)(url);
        // We suppose that request always has a hostname and a domain.
        this.hostname = tldResult.hostname;
        this.domain = tldResult.domain;
        this.subdomains = Request.getSubdomains(tldResult);
        let sourceTldResult;
        if (sourceUrl) {
            sourceTldResult = (0,es6/* parse */.qg)(sourceUrl);
            this.sourceHostname = sourceTldResult.hostname;
            this.sourceDomain = sourceTldResult.domain;
            this.sourceSubdomains = Request.getSubdomains(sourceTldResult);
        }
        else {
            this.sourceHostname = null;
            this.sourceDomain = null;
            this.sourceSubdomains = [];
        }
        if (this.sourceDomain) {
            this.thirdParty = this.domain !== this.sourceDomain;
        }
        else if (sourceTldResult && sourceTldResult.isIp) {
            this.thirdParty = this.hostname !== this.sourceHostname;
        }
        else {
            this.thirdParty = null;
        }
    }
    /**
     * We cut the url in performance purposes.
     *
     * @param url The URL to be compacted.
     *
     * @returns The compacted URL or null if the input URL is null.
     */
    static compactUrl(url) {
        let compacted = url;
        if (compacted && compacted.length > Request.MAX_URL_MATCH_LENGTH) {
            compacted = compacted.substring(0, Request.MAX_URL_MATCH_LENGTH);
        }
        return compacted;
    }
    /**
     * Splits subdomains and returns all subdomains (including the hostname itself).
     *
     * @param tldResult Result of `tldts.parse()`.
     *
     * @returns Array of subdomains.
     */
    static getSubdomains(tldResult) {
        const { domain, hostname, subdomain, publicSuffix, } = tldResult;
        const subdomainsResult = [];
        if (!domain) {
            if (hostname) {
                subdomainsResult.push(hostname);
                return subdomainsResult;
            }
            return [];
        }
        if (publicSuffix) {
            subdomainsResult.push(publicSuffix);
            // Extract subdomains from complex suffixes
            // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2037
            // https://github.com/AdguardTeam/tsurlfilter/issues/57
            for (let i = 0; i < publicSuffix.length; i += 1) {
                if (publicSuffix[i] === '.') {
                    subdomainsResult.push(publicSuffix.slice(i + 1));
                }
            }
        }
        subdomainsResult.push(domain);
        if (!subdomain) {
            return subdomainsResult;
        }
        const parts = subdomain.split('.');
        let incrementDomain = domain;
        for (let i = parts.length - 1; i >= 0; i -= 1) {
            incrementDomain = `${parts[i]}.${incrementDomain}`;
            subdomainsResult.push(incrementDomain);
        }
        return subdomainsResult;
    }
}

/**
 * DnsResult contains a network rule and host rules matching request.
 */
class DnsResult {
    /**
     * BasicRule - a network rule matching the request.
     */
    basicRule = null;
    /**
     * Host rules.
     */
    hostRules = [];
}

/**
 * DNSEngine combines host rules and network rules and is supposed to quickly find
 * matching rules for hostnames.
 * First, it looks over network rules and returns first rule found.
 * Then, if nothing found, it looks up the host rules.
 */
class DnsEngine {
    /**
     * Count of rules added to the engine.
     */
    rulesCount;
    /**
     * Storage.
     */
    ruleStorage;
    /**
     * Lookup table. Key is the hostname hash.
     */
    lookupTable;
    /**
     * Network engine instance.
     */
    networkEngine;
    /**
     * Builds an instance of dns engine.
     *
     * @param storage Rule storage.
     */
    constructor(storage) {
        this.ruleStorage = storage;
        this.rulesCount = 0;
        this.lookupTable = new Map();
        this.networkEngine = new NetworkEngine(storage, true);
        const scanner = this.ruleStorage.createRuleStorageScanner(ScannerType.HostRules);
        while (scanner.scan()) {
            const indexedRule = scanner.getRule();
            if (indexedRule) {
                if (indexedRule.rule instanceof HostRule) {
                    this.addRule(indexedRule.rule, indexedRule.index);
                }
                else if (indexedRule.rule instanceof NetworkRule
                    && indexedRule.rule.isHostLevelNetworkRule()) {
                    this.networkEngine.addRule(indexedRule.rule, indexedRule.index);
                }
            }
        }
    }
    /**
     * Match searches over all filtering and host rules loaded to the engine.
     *
     * @param hostname To check.
     *
     * @returns Dns result object.
     */
    match(hostname) {
        const result = new DnsResult();
        if (!hostname) {
            return result;
        }
        const url = `http://${hostname}/`;
        const request = new Request(url, url, RequestType.Document);
        request.isHostnameRequest = true;
        const networkRule = this.networkEngine.match(request);
        if (networkRule) {
            // Network rules always have higher priority
            result.basicRule = networkRule;
            return result;
        }
        const hash = fastHash(hostname);
        const rulesIndexes = this.lookupTable.get(hash);
        if (rulesIndexes) {
            for (let j = 0; j < rulesIndexes.length; j += 1) {
                const rule = this.ruleStorage.retrieveHostRule(rulesIndexes[j]);
                if (rule && rule.match(hostname)) {
                    result.hostRules.push(rule);
                }
            }
        }
        return result;
    }
    /**
     * Adds rule to engine.
     *
     * @param rule Rule to add.
     * @param storageIdx Storage index of the rule.
     */
    addRule(rule, storageIdx) {
        rule.getHostnames().forEach((hostname) => {
            const hash = fastHash(hostname);
            // Add the rule to the lookup table
            let rulesIndexes = this.lookupTable.get(hash);
            if (!rulesIndexes) {
                rulesIndexes = [];
            }
            rulesIndexes.push(storageIdx);
            this.lookupTable.set(hash, rulesIndexes);
        });
        this.rulesCount += 1;
    }
}

/* eslint-disable no-await-in-loop */
/* eslint-disable no-promise-executor-return */
/**
 * Engine represents the filtering engine with all the loaded rules.
 */
class Engine {
    /**
     * Request's cache size
     * Used as both source rules and others limit.
     * The value is based on benchmark runs.
     */
    static REQUEST_CACHE_SIZE = 500;
    /**
     * Basic filtering rules engine.
     */
    networkEngine;
    /**
     * Cosmetic rules engine.
     */
    cosmeticEngine;
    /**
     * Rules storage.
     */
    ruleStorage;
    /**
     * Request results cache.
     */
    resultCache;
    /**
     * Creates an instance of an Engine
     * Parses the filtering rules and creates a filtering engine of them.
     *
     * @param ruleStorage Storage.
     * @param skipStorageScan Create an instance without storage scanning.
     *
     * @throws
     */
    constructor(ruleStorage, skipStorageScan = false) {
        this.ruleStorage = ruleStorage;
        this.networkEngine = new NetworkEngine(ruleStorage, skipStorageScan);
        this.cosmeticEngine = new CosmeticEngine(ruleStorage, skipStorageScan);
        this.resultCache = new esm/* LRUCache */.q({ max: Engine.REQUEST_CACHE_SIZE });
    }
    /**
     * Loads rules to engine.
     */
    loadRules() {
        const scanner = this.ruleStorage.createRuleStorageScanner(ScannerType.NetworkRules | ScannerType.CosmeticRules);
        while (scanner.scan()) {
            this.addRule(scanner.getRule());
        }
    }
    /**
     * Async loads rules to engine.
     *
     * @param chunkSize Size of rules chunk to load at a time.
     */
    async loadRulesAsync(chunkSize) {
        const scanner = this.ruleStorage.createRuleStorageScanner(ScannerType.NetworkRules | ScannerType.CosmeticRules);
        let counter = 0;
        while (scanner.scan()) {
            counter += 1;
            if (counter >= chunkSize) {
                counter = 0;
                /**
                 * In some cases UI thread becomes blocked while adding rules to engine,
                 * that't why we create filter rules using chunks of the specified length
                 * Rules creation is rather slow operation so we should
                 * use setTimeout calls to give UI thread some time.
                 */
                await new Promise((resolve) => setTimeout(resolve, 1));
            }
            this.addRule(scanner.getRule());
        }
    }
    /**
     * Matches the specified request against the filtering engine and returns the matching result.
     *
     * @param request Request to check.
     * @param frameRule Source document rule or null.
     *
     * @returns Matching result.
     */
    matchRequest(request, frameRule = null) {
        let cacheKey = `${request.url}#${request.sourceHostname}#${request.requestType}`;
        if (request.method) {
            cacheKey += `#${request.method}`;
        }
        /**
         * Add frame url text to the key to avoid caching,
         * because allowlist rules are not stored in the engine. AG-12694.
         */
        if (frameRule) {
            cacheKey += `#${frameRule.getIndex()}`;
        }
        const res = this.resultCache.get(cacheKey);
        if (res) {
            return res;
        }
        const networkRules = this.networkEngine.matchAll(request);
        const result = new MatchingResult(networkRules, frameRule);
        this.resultCache.set(cacheKey, result);
        return result;
    }
    /**
     * Matches current frame and returns document-level allowlist rule if found.
     *
     * @param frameUrl The URL of the frame to match.
     *
     * @returns Document-level allowlist rule if found, otherwise null.
     */
    matchFrame(frameUrl) {
        const sourceRequest = new Request(frameUrl, '', request_type/* RequestType */.Y.Document);
        let sourceRules = this.networkEngine.matchAll(sourceRequest);
        sourceRules = MatchingResult.removeBadfilterRules(sourceRules);
        let result = null;
        sourceRules.forEach((r) => {
            if (r.isDocumentLevelAllowlistRule()) {
                if (!result || r.isHigherPriority(result)) {
                    result = r;
                }
            }
        });
        return result;
    }
    /**
     * Gets cosmetic result for the specified hostname and cosmetic options.
     *
     * @param request Host to check.
     * @param option Mask of enabled cosmetic types.
     *
     * @returns Cosmetic result.
     */
    getCosmeticResult(request, option) {
        return this.cosmeticEngine.match(request, option);
    }
    /**
     * Gets rules count.
     *
     * @returns The total number of rules.
     */
    getRulesCount() {
        return this.networkEngine.rulesCount + this.cosmeticEngine.rulesCount;
    }
    /**
     * Adds rules to engines.
     *
     * @param indexedRule Rule to add.
     */
    addRule(indexedRule) {
        if (indexedRule) {
            if (indexedRule.rule instanceof NetworkRule) {
                this.networkEngine.addRule(indexedRule.rule, indexedRule.index);
            }
            else if (indexedRule.rule instanceof CosmeticRule) {
                this.cosmeticEngine.addRule(indexedRule.rule, indexedRule.index);
            }
        }
    }
    /**
     * Retrieves a rule node by its filter list identifier and rule index.
     *
     * If there's no rule by that index or the rule structure is invalid, it will return null.
     *
     * @param filterId Filter list identifier.
     * @param ruleIndex Rule index.
     *
     * @returns Rule node or `null`.
     */
    retrieveRuleNode(filterId, ruleIndex) {
        return this.ruleStorage.retrieveRuleNode(filterId, ruleIndex);
    }
}

/**
 * Source map.
 *
 * @note Since serialized rule nodes are not store original rule text, we need this source map between the
 * serialized filter list and the raw filter list.
 */
const filterListSourceMapValidator = lib/* record */.g1(
/**
 * Rule start index in the converted list's byte buffer.
 */
lib/* string */.Yj(), 
/**
 * Rule start index in the raw converted list.
 */
lib/* number */.ai());

/**
 * Helper function to get the rule source text from the source string by its line start index.
 *
 * @param lineStartIndex Rule start index.
 * @param source Raw filter list source.
 *
 * @returns Rule string or null if the rule couldn't be found.
 */
const getRuleSourceText = (lineStartIndex, source) => {
    // note: checking for LF is enough, because we transform source before storing it, and it's always LF
    let [lineEndIndex] = (0,simple_regex_Dw3J24Ss.d)(source, lineStartIndex);
    // If the line end index is not found, we assume that the rule is the last line in the source.
    if (lineEndIndex === -1) {
        lineEndIndex = source.length;
    }
    // If the rule start index is equal to or greater than the rule end index, we return null,
    // and the rule is considered not found.
    if (lineStartIndex >= lineEndIndex) {
        return null;
    }
    const ruleSourceText = source.slice(lineStartIndex, lineEndIndex);
    // WARNING!
    // Potential memory leak mitigation for substring operation due to V8 optimizations:
    // When extracting a substring with rule.slice(), there's a concern in some JS environments
    // that the resulting substring might retain a hidden reference to the entire original 'rule' string.
    // This could prevent the garbage collector (GC) from freeing the memory allocated for filter rules.
    // This hidden reference occurs because the substring might not create a new string but rather
    // a view into the original, keeping it in memory longer than necessary.
    // And we receive a memory leak here because we store parsed tags from first N lines of the filter rules
    // which have references to the original large string with filter rules.
    // To ensure that the original large string can be garbage collected, and only the necessary
    // substring is retained, we explicitly force a copy of the substring via split and join,
    // thereby breaking the direct reference to the original string and allowing the GC to free the memory
    // for filter rules when they are no longer in use.
    return ruleSourceText.split('').join('');
};
/**
 * Helper function to get the rule source index (line start index in the source) from the source map by the rule index.
 *
 * @param ruleIdx Rule index.
 * @param sourceMap Source map.
 *
 * @returns Rule source index or RULE_INDEX_NONE (-1).
 *
 * @note Similar to `Array.prototype.indexOf`, we return -1 if the rule index is not found.
 */
const getRuleSourceIndex = (ruleIdx, sourceMap) => {
    return sourceMap[ruleIdx] ?? RULE_INDEX_NONE;
};

/**
 * BufferReader is a class responsible for reading content from serialized rules.
 */
class BufferReader {
    /**
     * Input byte buffer.
     */
    buffer;
    /**
     * Current position of the reader.
     */
    currentIndex = 0;
    /**
     * Constructor of a BufferReader.
     *
     * @param buffer Uint8Array that contains a UTF-8 encoded string.
     */
    constructor(buffer) {
        this.buffer = buffer;
        this.currentIndex = this.buffer.currentOffset;
    }
    /**
     * Reads the next line in the buffer.
     *
     * @returns Text or null on end.
     */
    readNext() {
        // If the next byte is 0, it means that there's nothing to read.
        if (this.buffer.peekUint8() === 0) {
            return null;
        }
        let ruleNode;
        rule_deserializer/* RuleDeserializer */.Y.deserialize(this.buffer, ruleNode = {});
        this.currentIndex = this.buffer.currentOffset;
        if (ruleNode.category) {
            return ruleNode;
        }
        return null;
    }
    /**
     * Returns the current position of this reader or -1 if there's nothing to
     * read.
     *
     * @returns - The current position or -1 if there's nothing to read.
     */
    getCurrentPos() {
        return this.currentIndex;
    }
    /** @inheritdoc */
    getDataLength() {
        return this.buffer.capacity;
    }
}

/**
 * List identifier max value.
 * We use "number" type for storage indexes, so we have some limits for list
 * identifiers.
 * We use line number for rule index, so if we save 11 ranks for rules, then we
 * have 6 ranks left for list ids. Check RuleStorageScanner class for more info.
 */
const LIST_ID_MAX_VALUE = 10 ** 6;

/**
 * Helper function to create an allowlist rule node for a given domain.
 *
 * @param domain Domain to create an allowlist rule for.
 *
 * @returns Allowlist rule node or null.
 */
const createAllowlistRuleNode = (domain) => {
    const domainToUse = domain.startsWith('www.') ? domain.substring(4) : domain;
    if (!domainToUse) {
        return null;
    }
    let pattern;
    // Special case: Wildcard TLD + N domain
    if (domainToUse.startsWith('*.')) {
        pattern = `${simple_regex_Dw3J24Ss.S.MASK_START_URL}${domainToUse.slice(2)}`;
    }
    else {
        // In other cases we use regexp to match domain and it`s 'www' subdomain strictly.
        let regexp = '';
        // transform allowlist domain special characters
        for (let i = 0; i < domainToUse.length; i += 1) {
            const char = domainToUse[i];
            // transform wildcard to regexp equivalent
            if (char === '*') {
                regexp += '.*';
                // escape domain separator
            }
            else if (char === '.') {
                regexp += String.raw `\.`;
            }
            else {
                regexp += char;
            }
        }
        pattern = String.raw `///(www\.)?${regexp}/`;
    }
    const node = {
        category: nodes/* RuleCategory */.$O.Network,
        type: nodes/* NetworkRuleType */.vY.NetworkRule,
        syntax: adblockers/* AdblockSyntax */.Y.Common,
        exception: true,
        pattern: {
            type: 'Value',
            value: pattern,
        },
        modifiers: {
            type: 'ModifierList',
            children: [
                {
                    type: 'Modifier',
                    name: {
                        type: 'Value',
                        value: 'document',
                    },
                },
                {
                    type: 'Modifier',
                    name: {
                        type: 'Value',
                        value: 'important',
                    },
                },
            ],
        },
    };
    return node;
};

/**
 * Rule builder class.
 */
class RuleFactory {
    /**
     * Creates rule of suitable class from text string
     * It returns null if the line is empty or if it is a comment.
     *
     * TODO: Pack `ignore*` parameters and `silent` into one object with flags.
     *
     * @param node Rule node.
     * @param filterListId List id.
     * @param ruleIndex Line start index in the source filter list; it will be used to find the original rule text
     * in the filtering log when a rule is applied. Default value is {@link RULE_INDEX_NONE} which means that
     * the rule does not have source index.
     * @param ignoreNetwork Do not create network rules.
     * @param ignoreCosmetic Do not create cosmetic rules.
     * @param ignoreHost Do not create host rules.
     * @param silent Log the error for `true`, otherwise throw an exception on
     * a rule creation.
     *
     * @returns IRule object or null.
     *
     * @throws Error when `silent` flag is passed as false on rule creation error.
     */
    static createRule(node, filterListId, ruleIndex = RULE_INDEX_NONE, ignoreNetwork = false, ignoreCosmetic = false, ignoreHost = true, silent = true) {
        try {
            switch (node.category) {
                case nodes/* RuleCategory */.$O.Invalid:
                case nodes/* RuleCategory */.$O.Empty:
                case nodes/* RuleCategory */.$O.Comment:
                    return null;
                case nodes/* RuleCategory */.$O.Cosmetic:
                    if (ignoreCosmetic) {
                        return null;
                    }
                    return new CosmeticRule(node, filterListId, ruleIndex);
                case nodes/* RuleCategory */.$O.Network:
                    if (node.type === nodes/* NetworkRuleType */.vY.HostRule) {
                        if (ignoreHost) {
                            return null;
                        }
                        return new HostRule(node, filterListId, ruleIndex);
                    }
                    if (ignoreNetwork) {
                        return null;
                    }
                    return new NetworkRule(node, filterListId, ruleIndex);
                default:
                    // should not happen in normal operation
                    return null;
            }
        }
        catch (e) {
            let msg = `"${getErrorMessage(e)}" in the rule: `;
            try {
                msg += `"${rule_generator/* RuleGenerator */.u.generate(node)}"`;
            }
            catch (generateError) {
                msg += `"${JSON.stringify(node)}" (generate error: ${getErrorMessage(generateError)})`;
            }
            if (silent) {
                logger.info(`Error: ${msg}`);
            }
            else {
                throw new Error(msg);
            }
        }
        return null;
    }
    /**
     * Creates allowlist rule for domain.
     *
     * @param domain Domain name.
     * @param filterListId List id.
     * @param ruleIndex Line start index in the source filter list.
     *
     * @returns Allowlist rule or null.
     */
    static createAllowlistRule(domain, filterListId, ruleIndex = RULE_INDEX_NONE) {
        const node = createAllowlistRuleNode(domain);
        if (!node) {
            return null;
        }
        return new NetworkRule(node, filterListId, ruleIndex);
    }
}

/**
 * Rule scanner provides the functionality for reading rules from a filter list.
 */
// TODO: Change string filter list to byte buffer.
class RuleScanner {
    /**
     * Filter list ID.
     */
    listId;
    /**
     * True if we should ignore cosmetic rules.
     */
    ignoreCosmetic;
    /**
     * True if we should ignore javascript cosmetic rules.
     */
    ignoreJS;
    /**
     * True if we should ignore unsafe rules, like $removeheader.
     */
    ignoreUnsafe;
    /**
     * True if we should ignore network rules.
     */
    ignoreNetwork;
    /**
     * True if we should ignore host filtering rules.
     */
    ignoreHost;
    /**
     * Underlying reader object.
     */
    reader;
    /**
     * Current rule.
     */
    currentRule = null;
    /**
     * Index of the beginning of the current rule (basically, a line number).
     */
    currentRuleIndex = 0;
    /**
     * Constructor of a RuleScanner object.
     *
     * @param reader Source of the filtering rules.
     * @param listId Filter list ID.
     * @param configuration Scanner configuration object.
     */
    constructor(reader, listId, configuration) {
        this.reader = reader;
        this.listId = listId;
        this.ignoreCosmetic = !!configuration.ignoreCosmetic
            || ((configuration.scannerType & ScannerType.CosmeticRules) !== ScannerType.CosmeticRules);
        this.ignoreNetwork = (configuration.scannerType & ScannerType.NetworkRules) !== ScannerType.NetworkRules;
        this.ignoreHost = (configuration.scannerType & ScannerType.HostRules) !== ScannerType.HostRules;
        this.ignoreJS = !!configuration.ignoreJS;
        this.ignoreUnsafe = !!configuration.ignoreUnsafe;
    }
    /**
     * Scan advances the RuleScanner to the next rule, which will then be
     * available through the getRule() method.
     *
     * @returns - False when the scan stops, either by reaching the end of the
     * input or an error. If there's a rule available, returns true.
     */
    scan() {
        let lineIndex = this.reader.getCurrentPos();
        let line = this.readNext();
        while (line) {
            if (!this.isIgnored(line)) {
                const rule = RuleFactory.createRule(line, this.listId, lineIndex, this.ignoreNetwork, this.ignoreCosmetic, this.ignoreHost);
                this.currentRule = rule;
                this.currentRuleIndex = lineIndex;
                return true;
            }
            lineIndex = this.reader.getCurrentPos();
            line = this.readNext();
        }
        return false;
    }
    /**
     * @returns - The most recent rule generated by a call to scan(), and the
     * index of this rule's text.
     */
    getRule() {
        if (this.currentRule) {
            return new IndexedRule(this.currentRule, this.currentRuleIndex);
        }
        return null;
    }
    /**
     * Get filter list id.
     *
     * @returns List id.
     */
    getListId() {
        return this.listId;
    }
    /**
     * Get the length of the data read by the scanner.
     *
     * @returns Data length.
     */
    getDataLength() {
        return this.reader.getDataLength();
    }
    /**
     * Reads the next line and returns it.
     *
     * @returns - Next line string or null.
     */
    readNext() {
        return this.reader.readNext();
    }
    /**
     * Checks if the rule should be ignored by this scanner.
     *
     * @param rule Rule to check.
     *
     * @returns - True if the rule should be ignored.
     */
    isIgnored(rule) {
        if (!this.ignoreCosmetic && !this.ignoreJS && !this.ignoreUnsafe) {
            return false;
        }
        if (rule.category === nodes/* RuleCategory */.$O.Cosmetic) {
            if (this.ignoreCosmetic) {
                return true;
            }
            // Ignore JS type rules.
            // TODO: in the future we may allow CSS rules and Scriptlets (except
            // for "trusted" scriptlets).
            if (this.ignoreJS
                && (rule.type === nodes/* CosmeticRuleType */.k9.JsInjectionRule
                    || rule.type === nodes/* CosmeticRuleType */.k9.ScriptletInjectionRule)) {
                return true;
            }
        }
        if (this.ignoreUnsafe) {
            if (rule.category === nodes/* RuleCategory */.$O.Network && rule.type === nodes/* NetworkRuleType */.vY.NetworkRule) {
                if (rule.modifiers?.children?.some((modifier) => NetworkRule.ADVANCED_OPTIONS.has(modifier.name.value))) {
                    return true;
                }
            }
        }
        return false;
    }
}

/**
 * BufferRuleList represents a string-based rule list. It keeps the original
 * rule list as a byte array with UTF-8 encoded characters. This approach
 * allows saving on the memory used by tsurlfilter compared to StringRuleList.
 */
class BufferRuleList {
    /**
     * Rule list ID.
     */
    id;
    /**
     * String with filtering rules (one per line) encoded as a
     * UTF-8 array.
     */
    rulesBuffer;
    /**
     * Whether to ignore cosmetic rules or not.
     */
    ignoreCosmetic;
    /**
     * Whether to ignore javascript cosmetic rules or not.
     */
    ignoreJS;
    /**
     * Whether to ignore unsafe (e.g. $removeheader) rules or not.
     */
    ignoreUnsafe;
    /**
     * Source map for the filter list.
     */
    sourceMap;
    /**
     * Text decoder that is used to read strings from the internal buffer of
     * UTF-8 encoded characters.
     */
    static decoder = new TextDecoder('utf-8');
    /**
     * Constructor of BufferRuleList.
     *
     * @param listId List identifier.
     * @param inputRules String with filtering rules (one per line).
     * @param ignoreCosmetic (Optional) True to ignore cosmetic rules.
     * @param ignoreJS (Optional) True to ignore JS rules.
     * @param ignoreUnsafe (Optional) True to ignore unsafe rules.
     * @param sourceMap (Optional) Source map for the filter list.
     */
    constructor(listId, inputRules, ignoreCosmetic, ignoreJS, ignoreUnsafe, sourceMap) {
        if (listId >= LIST_ID_MAX_VALUE) {
            throw new Error(`Invalid list identifier, it must be less than ${LIST_ID_MAX_VALUE}`);
        }
        this.id = listId;
        this.rulesBuffer = new input_byte_buffer/* InputByteBuffer */.N(inputRules);
        this.ignoreCosmetic = !!ignoreCosmetic;
        this.ignoreJS = !!ignoreJS;
        this.ignoreUnsafe = !!ignoreUnsafe;
        this.sourceMap = sourceMap ?? {};
    }
    /**
     * Close does nothing as here's nothing to close in the BufferRuleList.
     */
    // eslint-disable-next-line class-methods-use-this
    close() {
        // Empty
    }
    /**
     * @returns The rule list identifier.
     */
    getId() {
        return this.id;
    }
    /**
     * Creates a new rules scanner that reads the list contents.
     *
     * @param scannerType The type of scanner to create.
     *
     * @returns Scanner object.
     */
    newScanner(scannerType) {
        const reader = new BufferReader(this.rulesBuffer.createCopyWithOffset(0));
        return new RuleScanner(reader, this.id, {
            scannerType,
            ignoreCosmetic: this.ignoreCosmetic,
            ignoreJS: this.ignoreJS,
            ignoreUnsafe: this.ignoreUnsafe,
        });
    }
    /**
     * Retrieves a rule node by its index.
     *
     * If there's no rule by that index or the rule is invalid, it will return
     * null.
     *
     * @param ruleIdx Rule index.
     *
     * @returns Rule node or `null`.
     */
    retrieveRuleNode(ruleIdx) {
        try {
            const ruleNode = {};
            const copy = this.rulesBuffer.createCopyWithOffset(ruleIdx);
            rule_deserializer/* RuleDeserializer */.Y.deserialize(copy, ruleNode);
            return ruleNode;
        }
        catch (e) {
            // fall through
        }
        return null;
    }
    /**
     * @inheritdoc
     */
    retrieveRuleSourceIndex(ruleIdx) {
        return getRuleSourceIndex(ruleIdx, this.sourceMap);
    }
}

// TODO: Consider moving this file to the `@adguard/agtree` package
/**
 * AGTree parser options for the preprocessor.
 */
const PREPROCESSOR_AGTREE_OPTIONS = {
    ...options/* defaultParserOptions */.n,
    includeRaws: false,
    isLocIncluded: false,
    ignoreComments: false,
    // TODO: Add support for host rules + in the converter
    parseHostRules: false,
};
/**
 * Utility class for pre-processing filter lists before they are used by the AdGuard filtering engine.
 *
 * Concept:
 *
 * Right after a filter list is downloaded, we iterate over its rules and do the following:
 *   1. Parse rule text to AST (Abstract Syntax Tree) (if possible).
 *   2. Convert rule node to AdGuard format (if possible / needed).
 *
 * During this conversion, we also produce two maps:
 *    - Source map:     For performance reasons, we don't store the original rule text in the AST.
 *                      We store AST in a binary serialized format.
 *                      This source map is used to map the rule start index from the serialized filter list to
 *                      its start index in the raw filter list (converted filter list). This is needed to show
 *                      the exact applied rule in the filtering log. This rule text maybe a converted rule,
 *                      but in this case, we can get its original rule text from the conversion map
 *                      (for filtering engine, only the converted filter list is needed).
 *    - Conversion map: Maps the converted rule text to its original rule text. This is needed to show the
 *                      original rule text in the filtering log if a converted rule is applied.
 */
class FilterListPreprocessor {
    /**
     * Processes the raw filter list and converts it to the AdGuard format.
     *
     * @param filterList Raw filter list to convert.
     * @param parseHosts If true, the preprocessor will parse host rules.
     *
     * @returns A {@link PreprocessedFilterList} object which contains the converted filter list,
     * the mapping between the original and converted rules, and the source map.
     */
    static preprocess(filterList, parseHosts = false) {
        const filterListLength = filterList.length;
        const sourceMap = {};
        const conversionMap = {};
        const rawFilterList = [];
        const convertedFilterList = new OutputByteBuffer();
        const firstLineBreakData = (0,simple_regex_Dw3J24Ss.d)(filterList);
        let inputOffset = 0;
        let outputOffset = 0;
        let previousLineBreak = firstLineBreakData[1] > 0
            ? filterList.slice(firstLineBreakData[0], firstLineBreakData[0] + firstLineBreakData[1])
            : simple_regex_Dw3J24Ss.L;
        while (inputOffset < filterListLength) {
            const [lineBreakIndex, lineBreakLength] = (0,simple_regex_Dw3J24Ss.d)(filterList, inputOffset);
            const ruleText = filterList.slice(inputOffset, lineBreakIndex);
            const lineBreak = filterList.slice(lineBreakIndex, lineBreakIndex + lineBreakLength);
            // parse and convert can throw an error, so we need to catch them
            try {
                const ruleNode = rule_parser/* RuleParser */.G.parse(ruleText, {
                    ...PREPROCESSOR_AGTREE_OPTIONS,
                    parseHostRules: parseHosts,
                });
                if (ruleNode.category === nodes/* RuleCategory */.$O.Empty || ruleNode.category === nodes/* RuleCategory */.$O.Comment) {
                    // Add empty lines and comments as is to the converted filter list,
                    // but not to the output byte buffer / source map.
                    rawFilterList.push(ruleText);
                    rawFilterList.push(lineBreak);
                    outputOffset += ruleText.length + lineBreakLength;
                    inputOffset = lineBreakIndex + lineBreakLength;
                    previousLineBreak = lineBreak;
                    continue;
                }
                const conversionResult = rule/* RuleConverter */.b.convertToAdg(ruleNode);
                if (conversionResult.isConverted) {
                    // Maybe the rule is the last line without a line break in the input filter list
                    // but we need to convert it to multiple rules.
                    // In this case, we should use the last used line break before the conversion.
                    const convertedRulesLineBreak = lineBreakLength > 0 ? lineBreak : previousLineBreak;
                    const numberOfConvertedRules = conversionResult.result.length;
                    // Note: 1 rule can be converted to multiple rules
                    for (let i = 0; i < conversionResult.result.length; i += 1) {
                        const convertedRuleNode = conversionResult.result[i];
                        // In this case we should generate the rule text from the AST, because its converted,
                        // i.e. it's not the same as the original rule text.
                        const convertedRuleText = rule_generator/* RuleGenerator */.u.generate(convertedRuleNode);
                        rawFilterList.push(convertedRuleText);
                        rawFilterList.push(i === numberOfConvertedRules - 1 ? lineBreak : convertedRulesLineBreak);
                        const bufferOffset = convertedFilterList.currentOffset;
                        // Store the converted rules and the mapping between the original and converted rules
                        conversionMap[outputOffset] = ruleText;
                        sourceMap[bufferOffset] = outputOffset;
                        RuleSerializer.serialize(convertedRuleNode, convertedFilterList);
                        outputOffset += convertedRuleText.length + (i === numberOfConvertedRules - 1
                            ? lineBreakLength
                            : convertedRulesLineBreak.length);
                    }
                }
                else {
                    // If the rule is not converted, we should store the original rule text in the raw filter list.
                    rawFilterList.push(ruleText);
                    rawFilterList.push(lineBreak);
                    const bufferOffset = convertedFilterList.currentOffset;
                    // Store the converted rules and the mapping between the original and converted rules
                    sourceMap[bufferOffset] = outputOffset;
                    RuleSerializer.serialize(ruleNode, convertedFilterList);
                    outputOffset += ruleText.length + lineBreakLength;
                }
            }
            catch (error) {
                // TODO: Integrate Logger library to be able to set log level AG-40234
                // Log issues just as an info AG-37460
                logger.info(`Failed to process rule: '${ruleText}' due to ${getErrorMessage(error)}`);
                // Add invalid rules as is to the converted filter list,
                // but not to the output byte buffer / source map.
                rawFilterList.push(ruleText);
                rawFilterList.push(lineBreak);
                outputOffset += ruleText.length + lineBreakLength;
            }
            // Move to the next line
            inputOffset = lineBreakIndex + lineBreakLength;
            previousLineBreak = lineBreak;
        }
        return {
            filterList: convertedFilterList.getChunks(),
            rawFilterList: rawFilterList.join(simple_regex_Dw3J24Ss.E),
            conversionMap,
            sourceMap,
        };
    }
    /**
     * A "lightweight" version of the preprocess method. This method is necessary because, in the rulesets,
     * we store the converted raw list and the conversion map, but not the entire preprocessed filter list.
     * This method helps us regenerate the serialized filter list and the source map fields with less overhead
     * compared to the full preprocess method.
     *
     * @param preprocessedFilterList Preprocessed filter list,
     * which contains the raw filter list and the conversion map.
     * @param parseHosts If true, the preprocessor will parse host rules.
     *
     * @returns Preprocessed filter list with the "filterList" and "sourceMap" fields.
     */
    static preprocessLightweight(preprocessedFilterList, parseHosts = false) {
        const { rawFilterList, conversionMap } = preprocessedFilterList;
        const { length } = rawFilterList;
        const sourceMap = {};
        const filterList = new OutputByteBuffer();
        let inputOffset = 0;
        let outputOffset = 0;
        while (inputOffset < length) {
            const [lineBreakIndex, lineBreakLength] = (0,simple_regex_Dw3J24Ss.d)(rawFilterList, inputOffset);
            const ruleText = rawFilterList.slice(inputOffset, lineBreakIndex);
            try {
                const ruleNode = rule_parser/* RuleParser */.G.parse(ruleText, {
                    ...PREPROCESSOR_AGTREE_OPTIONS,
                    parseHostRules: parseHosts,
                });
                // Ignore empty lines and comments from the binary filter list
                if (ruleNode.category !== nodes/* RuleCategory */.$O.Empty && ruleNode.category !== nodes/* RuleCategory */.$O.Comment) {
                    const bufferOffset = filterList.currentOffset;
                    sourceMap[bufferOffset] = outputOffset;
                    RuleSerializer.serialize(ruleNode, filterList);
                }
            }
            catch (error) {
                // TODO: Integrate Logger library to be able to set log level AG-40234
                // Log issues just as an info AG-37460
                logger.info(`Failed to process rule: '${ruleText}' due to ${getErrorMessage(error)}`);
            }
            outputOffset += ruleText.length + lineBreakLength;
            // Move to the next line
            inputOffset = lineBreakIndex + lineBreakLength;
        }
        return {
            // TODO: consider returning an empty array if the filter list is empty
            filterList: filterList.getChunks(),
            rawFilterList,
            conversionMap,
            sourceMap,
        };
    }
    /**
     * Gets the original filter list text from the preprocessed filter list.
     *
     * @param preprocessedFilterList Preprocessed filter list.
     *
     * @returns Original filter list text.
     */
    static getOriginalFilterListText(preprocessedFilterList) {
        const { rawFilterList, conversionMap } = preprocessedFilterList;
        const { length } = rawFilterList;
        const result = [];
        let offset = 0;
        let prevLineStart = -1;
        let lineBreakIndex = -1;
        let lineBreakLength = 0;
        while (offset < length) {
            [lineBreakIndex, lineBreakLength] = (0,simple_regex_Dw3J24Ss.d)(rawFilterList, offset);
            const lineBreak = rawFilterList.slice(lineBreakIndex, lineBreakIndex + lineBreakLength);
            const originalRule = conversionMap[offset];
            // One rule can be converted to multiple rules - in this case we should put the original rule text only once
            // If there is such a case, these rules follow one after the other
            if (!(originalRule && originalRule === conversionMap[prevLineStart])) {
                result.push(originalRule ?? rawFilterList.slice(offset, lineBreakIndex));
                result.push(lineBreak);
            }
            prevLineStart = offset;
            offset = lineBreakIndex + lineBreakLength;
        }
        // Add an empty rule if final new line is present
        if (lineBreakLength > 0) {
            result.push(simple_regex_Dw3J24Ss.E);
        }
        return result.join(simple_regex_Dw3J24Ss.E);
    }
    /**
     * Gets the original rules from the preprocessed filter list.
     *
     * @param preprocessedFilterList Preprocessed filter list.
     *
     * @returns Array of original rules.
     */
    static getOriginalRules(preprocessedFilterList) {
        const { rawFilterList, conversionMap } = preprocessedFilterList;
        const { length } = rawFilterList;
        const result = [];
        let offset = 0;
        let prevLineStart = -1;
        let lineBreakIndex = -1;
        let lineBreakLength = 0;
        while (offset < length) {
            [lineBreakIndex, lineBreakLength] = (0,simple_regex_Dw3J24Ss.d)(rawFilterList, offset);
            const originalRule = conversionMap[offset];
            // One rule can be converted to multiple rules - in this case we should put the original rule text only once
            // If there is such a case, these rules follow one after the other
            if (!(originalRule && originalRule === conversionMap[prevLineStart])) {
                result.push(originalRule ?? rawFilterList.slice(offset, lineBreakIndex));
            }
            prevLineStart = offset;
            offset = lineBreakIndex + lineBreakLength;
        }
        // Add an empty rule if final new line is present
        if (lineBreakLength > 0) {
            result.push(simple_regex_Dw3J24Ss.E);
        }
        return result;
    }
    /**
     * Creates an empty preprocessed filter list.
     *
     * @returns An empty preprocessed filter list.
     *
     * @note It gives the same result as the {@link preprocess} method with an empty filter list:
     * ```ts
     * FilterListPreprocessor.preprocess('');
     * ```
     */
    static createEmptyPreprocessedFilterList() {
        // Note: need to use OutputByteBuffer, because it writes the schema version to the buffer
        const buffer = new OutputByteBuffer();
        return {
            // TODO: consider returning an empty array
            filterList: buffer.getChunks(),
            rawFilterList: '',
            conversionMap: {},
            sourceMap: {},
        };
    }
}

/**
 * Validator for filter list conversion map.
 *
 * @note This is only needed to show the original rule text in the filtering log if a converted rule is applied.
 */
const filterListConversionMapValidator = lib/* record */.g1(
/**
 * Converted rule line start offset.
 */
lib/* string */.Yj(), 
/**
 * Original rule text.
 */
lib/* string */.Yj());
/**
 * Validator for filter list chunks.
 */
const filterListChunksValidator = lib/* array */.YO(lib/* custom */.Ie((val) => val instanceof Uint8Array));
/**
 * Validator for preprocessed filter list.
 */
const preprocessedFilterListValidator = lib/* object */.Ik({
    /**
     * Raw processed filter list.
     */
    rawFilterList: lib/* string */.Yj(),
    /**
     * Processed filter list, but in a serialized form.
     */
    filterList: filterListChunksValidator,
    /**
     * Map of converted rules to original rules.
     */
    conversionMap: filterListConversionMapValidator,
    /**
     * Source map.
     */
    sourceMap: filterListSourceMapValidator,
});

/**
 * RuleStorageScanner scans multiple RuleScanner instances.
 * The storage index is built from the rule position in the list
 * + cumulative offset value of filter lists.
 */
class RuleStorageScanner {
    /**
     * Current scanner.
     */
    currentScanner = null;
    /**
     * Index of the current scanner.
     */
    currentScannerIdx = -1;
    /**
     * Rule position in the concatenated filter lists data.
     */
    storageOffset = 0;
    /**
     * Constructor.
     *
     * @param scanners List of scanners.
     */
    constructor(scanners) {
        this.scanners = scanners;
        this.listOffsetEntriesCursor = 0;
        this.listOffsetKeys = new Int32Array(scanners.length);
        this.listOffsetValues = new Uint32Array(scanners.length);
    }
    /**
     * Scan advances the RuleStorageScanner to the next rule, which will then be available
     * through the Rule method. It returns false when the scan stops, either by
     * reaching the end of the input or an error.
     *
     * @returns True if there is some result.
     */
    scan() {
        const scannersLength = this.scanners.length;
        if (scannersLength === 0) {
            return false;
        }
        if (!this.currentScanner) {
            this.currentScannerIdx = 0;
            this.currentScanner = this.scanners[this.currentScannerIdx];
            this.setListOffset(this.currentScanner.getListId(), this.storageOffset);
        }
        while (this.currentScannerIdx < scannersLength) {
            if (this.currentScanner.scan()) {
                return true;
            }
            // Accumulate the length of the current scanner before moving to the next one
            this.storageOffset += this.currentScanner.getDataLength();
            // Move to the next scanner
            this.currentScannerIdx += 1;
            // Check if there's a next scanner
            if (this.currentScannerIdx < this.scanners.length) {
                this.currentScanner = this.scanners[this.currentScannerIdx];
                this.setListOffset(this.currentScanner.getListId(), this.storageOffset);
            }
        }
        return false;
    }
    /**
     * Rule returns the most recent rule generated by a call to Scan, and the index of this rule.
     * See ruleListIdxToStorageIdx for more information on what this index is.
     *
     * @returns The most recent rule and its index, or null if no rule is available.
     */
    getRule() {
        if (!this.currentScanner) {
            return null;
        }
        const rule = this.currentScanner.getRule();
        if (!rule) {
            return null;
        }
        const offset = this.getListOffset(rule.rule.getFilterListId());
        const index = offset + rule.index;
        return new IndexedStorageRule(rule.rule, index);
    }
    /**
     * Match storage index with range of filter list offset
     * and return list id and local filter list position.
     *
     * @param storageIdx Rule position in concatenated filter lists data.
     *
     * @returns Tuple of list id and local filter list position.
     */
    getIds(storageIdx) {
        const listOffsetEntriesLength = this.listOffsetKeys.length;
        if (listOffsetEntriesLength === 1) {
            return [this.listOffsetKeys[0], storageIdx - this.listOffsetValues[0]];
        }
        for (let i = 0; i < listOffsetEntriesLength - 1; i += 1) {
            const offset = this.listOffsetValues[i];
            const nextOffset = this.listOffsetValues[i + 1];
            if (storageIdx >= offset && storageIdx < nextOffset) {
                return [this.listOffsetKeys[i], storageIdx - offset];
            }
        }
        return [
            this.listOffsetKeys[listOffsetEntriesLength - 1],
            storageIdx - this.listOffsetValues[listOffsetEntriesLength - 1],
        ];
    }
    /**
     * Push listID and offset to the {@link listOffsetEntries}.
     *
     * @param listId Filter list id.
     * @param offset Filter list offset position in the storage.
     */
    setListOffset(listId, offset) {
        this.listOffsetKeys[this.listOffsetEntriesCursor] = listId;
        this.listOffsetValues[this.listOffsetEntriesCursor] = offset;
        this.listOffsetEntriesCursor += 1;
    }
    /**
     * Gets filter list offset by list id.
     *
     * @param listId Filter list id.
     *
     * @returns Offset position in the storage.
     *
     * @throws Error if listId is not found.
     */
    getListOffset(listId) {
        const idx = this.listOffsetKeys.indexOf(listId);
        if (idx !== -1) {
            return this.listOffsetValues[idx];
        }
        throw new Error(`listId ${listId} not found in the storage`);
    }
}

/**
 * RuleStorage is an abstraction that combines several rule lists
 * It can be scanned using RuleStorageScanner, and also it allows
 * retrieving rules by its index.
 *
 * The idea is to keep rules in a serialized format (even original format in the case of FileRuleList)
 * and create them in a lazy manner only when we really need them. When the filtering engine is
 * being initialized, we need to scan the rule lists once in order to fill up the lookup tables.
 * We use rule indexes as a unique rule identifier instead of the rule itself.
 * The rule is created (see RetrieveRule) only when there's a chance that it's needed.
 *
 * Rule index is an int64 value that actually consists of two int32 values:
 * One is the rule list identifier, and the second is the index of the rule inside of that list.
 */
class RuleStorage {
    /**
     * Lists is an array of rules lists which can be accessed using this RuleStorage.
     */
    lists;
    /**
     * Map with rule lists. Map key is the list ID.
     */
    listsMap;
    /**
     * Cache with the rules which are stored inside this cache instance..
     */
    cache;
    /**
     * Constructor.
     *
     * @param lists Rule lists array.
     *
     * @throws Error on duplicate lists.
     */
    constructor(lists) {
        this.lists = lists;
        this.listsMap = new Map();
        this.cache = new Map();
        this.lists.forEach((list) => {
            const filterListId = list.getId();
            if (this.listsMap.get(filterListId)) {
                throw new Error(`Duplicate list ID: ${filterListId}`);
            }
            this.listsMap.set(filterListId, list);
        });
    }
    /**
     * Retrieves a rule node by its filter list identifier and rule index.
     *
     * If there's no rule by that index or the rule structure is invalid, it will return null.
     *
     * @param filterId Filter list identifier.
     * @param ruleIndex Rule index.
     *
     * @returns Rule node or `null`.
     */
    retrieveRuleNode(filterId, ruleIndex) {
        if (!this.listsMap.has(filterId)) {
            return null;
        }
        return this.listsMap.get(filterId).retrieveRuleNode(ruleIndex);
    }
    /**
     * Creates a new instance of RuleStorageScanner.
     * It can be used to read and parse all the storage contents.
     *
     * @param scannerType The type of scanner to create.
     *
     * @returns Scanner instance.
     */
    createRuleStorageScanner(scannerType) {
        const scanners = this.lists.map((list) => list.newScanner(scannerType));
        this.scanner = new RuleStorageScanner(scanners);
        return this.scanner;
    }
    /**
     * Looks for the filtering rule in this storage.
     *
     * @param storageIdx The lookup index that you can get from the rule storage scanner.
     * @param ignoreHost Rules could be retrieved as host rules.
     *
     * @returns The rule or null if not found or an error occurs.
     */
    retrieveRule(storageIdx, ignoreHost = true) {
        const rule = this.cache.get(storageIdx);
        if (rule) {
            return rule;
        }
        const [listId, ruleId] = this.scanner.getIds(storageIdx);
        const list = this.listsMap.get(listId);
        if (!list) {
            logger.warn(`Failed to retrieve list ${listId}, should not happen in normal operation`);
            return null;
        }
        const ruleNode = list.retrieveRuleNode(ruleId);
        if (!ruleNode) {
            logger.warn(`Failed to retrieve rule ${ruleId}, should not happen in normal operation`);
            return null;
        }
        const result = RuleFactory.createRule(ruleNode, listId, ruleId, false, false, ignoreHost);
        if (result) {
            this.cache.set(storageIdx, result);
        }
        return result;
    }
    /**
     * Retrieves a network rule from the storage.
     *
     * @param storageIdx Storage index of the rule.
     *
     * @returns The rule or nil in any other case (not found or error).
     */
    retrieveNetworkRule(storageIdx) {
        const rule = this.retrieveRule(storageIdx);
        if (!rule) {
            return null;
        }
        if (rule instanceof NetworkRule) {
            return rule;
        }
        return null;
    }
    /**
     * Retrieves a host rule from the storage.
     *
     * @param storageIdx Storage index of the rule.
     *
     * @returns The rule or nil in any other case (not found or error).
     */
    retrieveHostRule(storageIdx) {
        const rule = this.retrieveRule(storageIdx, false);
        if (!rule) {
            return null;
        }
        if (rule instanceof HostRule) {
            return rule;
        }
        return null;
    }
    /**
     * Returns the size of the cache.
     *
     * @returns The size of the cache.
     */
    getCacheSize() {
        return this.cache.size;
    }
}

const FILTER_PREFIX = 'filter_';
/**
 * Extracts the filter ID from a given filter name.
 *
 * @param filterName The filter name in the format `filter_{filterId}.txt`.
 *
 * @returns The extracted filter ID, or null if the filter name does not match the expected format.
 */
const getIdFromFilterName = (filterName) => {
    const match = filterName.match(new RegExp(`${FILTER_PREFIX}(\\d+)\\.txt`));
    if (!match) {
        return null;
    }
    return parseInt(match[1], 10);
};

/**
 * Fetches a resource from the given URL and returns its content as text.
 *
 * @param url The URL of the resource to fetch.
 *
 * @returns A promise that resolves to the fetched content as a string.
 *
 * @throws If the request fails.
 */
const fetchExtensionResourceText = async (url) => {
    return fetch(url).then((response) => response.text());
};

/**
 * Creates a list of allowlist rules for a given list ID and domains.
 *
 * @param listId List ID.
 * @param domains List of domains to create allowlist rules for.
 *
 * @returns BufferRuleList instance.
 */
const createAllowlistRuleList = (listId, domains) => {
    const buffer = new OutputByteBuffer();
    domains.forEach((domain) => {
        const rule = createAllowlistRuleNode(domain);
        if (rule) {
            RuleSerializer.serialize(rule, buffer);
        }
    });
    return new BufferRuleList(listId, buffer.getChunks());
};

/**
 * Module with miscellaneous syntax utils exposed in API.
 */
class RuleSyntaxUtils {
    static DUMMY_FILTER_ID = 0;
    /**
     * Checks if rule can be matched by domain.
     *
     * @param node Rule node.
     * @param domain Domain to check.
     *
     * @returns True if the rule can be matched by the domain, false otherwise.
     */
    static isRuleForDomain(node, domain) {
        const rule = RuleFactory.createRule(node, this.DUMMY_FILTER_ID);
        if (!rule) {
            return false;
        }
        const permittedDomains = rule.getPermittedDomains();
        return !!permittedDomains
            && DomainModifier.isDomainOrSubdomainOfAny(domain, permittedDomains);
    }
    /**
     * Checks if rule can be matched by URL.
     *
     * @param node Rule node.
     * @param url URL to check.
     *
     * @returns True if the rule can be matched by the URL, false otherwise.
     */
    static isRuleForUrl(node, url) {
        const domain = (0,es6/* getHostname */.EW)(url);
        if (!domain) {
            return false;
        }
        return this.isRuleForDomain(node, domain);
    }
}




/***/ }),

/***/ 95892:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   $4: () => (/* binding */ MASK_ALLOWLIST),
/* harmony export */   IA: () => (/* binding */ NOT_MARK),
/* harmony export */   RM: () => (/* binding */ NETWORK_RULE_OPTIONS),
/* harmony export */   rE: () => (/* binding */ OPTIONS_DELIMITER)
/* harmony export */ });
/* unused harmony export ESCAPE_CHARACTER */
const NETWORK_RULE_OPTIONS = {
    THIRD_PARTY: 'third-party',
    FIRST_PARTY: 'first-party',
    MATCH_CASE: 'match-case',
    IMPORTANT: 'important',
    DOMAIN: 'domain',
    DENYALLOW: 'denyallow',
    ELEMHIDE: 'elemhide',
    GENERICHIDE: 'generichide',
    SPECIFICHIDE: 'specifichide',
    GENERICBLOCK: 'genericblock',
    JSINJECT: 'jsinject',
    URLBLOCK: 'urlblock',
    CONTENT: 'content',
    DOCUMENT: 'document',
    DOC: 'doc',
    STEALTH: 'stealth',
    POPUP: 'popup',
    EMPTY: 'empty',
    MP4: 'mp4',
    SCRIPT: 'script',
    STYLESHEET: 'stylesheet',
    SUBDOCUMENT: 'subdocument',
    OBJECT: 'object',
    IMAGE: 'image',
    XMLHTTPREQUEST: 'xmlhttprequest',
    MEDIA: 'media',
    FONT: 'font',
    WEBSOCKET: 'websocket',
    OTHER: 'other',
    PING: 'ping',
    BADFILTER: 'badfilter',
    CSP: 'csp',
    REPLACE: 'replace',
    COOKIE: 'cookie',
    REDIRECT: 'redirect',
    REDIRECTRULE: 'redirect-rule',
    REMOVEPARAM: 'removeparam',
    REMOVEHEADER: 'removeheader',
    JSONPRUNE: 'jsonprune',
    HLS: 'hls',
    REFERRERPOLICY: 'referrerpolicy',
    APP: 'app',
    NETWORK: 'network',
    EXTENSION: 'extension',
    NOOP: '_',
    CLIENT: 'client',
    DNSREWRITE: 'dnsrewrite',
    DNSTYPE: 'dnstype',
    CTAG: 'ctag',
    HEADER: 'header',
    METHOD: 'method',
    TO: 'to',
    PERMISSIONS: 'permissions',
    ALL: 'all',
};
const OPTIONS_DELIMITER = '$';
const MASK_ALLOWLIST = '@@';
const NOT_MARK = '~';
const ESCAPE_CHARACTER = '\\';




/***/ }),

/***/ 55712:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Y: () => (/* binding */ RequestType)
/* harmony export */ });
/**
 * RequestType is the request types enumeration.
 * Important: the enumeration is marked as const to avoid side effects when
 * importing it into an extension.
 */
const RequestType = {
    /**
     * No value is set. Syntax sugar to simplify code.
     */
    NotSet: 0,
    /**
     * Main frame.
     */
    Document: 1,
    /**
     * (iframe) $subdocument.
     */
    SubDocument: 2, // 1 << 1
    /**
     * (javascript, etc) $script.
     */
    Script: 4, // 1 << 2
    /**
     * (css) $stylesheet.
     */
    Stylesheet: 8, // 1 << 3
    /**
     * (flash, etc) $object.
     */
    Object: 16, // 1 << 4
    /**
     * (any image) $image.
     */
    Image: 32, // 1 << 5
    /**
     * (ajax/fetch) $xmlhttprequest.
     */
    XmlHttpRequest: 64, // 1 << 6
    /**
     * (video/music) $media.
     */
    Media: 128, // 1 << 7
    /**
     * (any custom font) $font.
     */
    Font: 256, // 1 << 8
    /**
     * (a websocket connection) $websocket.
     */
    WebSocket: 512, // 1 << 9
    /**
     * (navigator.sendBeacon()) $ping.
     */
    Ping: 1024, // 1 << 10
    /**
     * Csp_report.
     */
    CspReport: 2048, // 1 << 11
    /**
     * Any other request type.
     */
    Other: 4096, // 1 << 12
};




/***/ }),

/***/ 12389:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   E: () => (/* binding */ EMPTY_STRING),
/* harmony export */   L: () => (/* binding */ LF),
/* harmony export */   S: () => (/* binding */ SimpleRegex),
/* harmony export */   W: () => (/* binding */ WILDCARD),
/* harmony export */   a: () => (/* binding */ SEPARATOR),
/* harmony export */   b: () => (/* binding */ stringArraysEquals),
/* harmony export */   c: () => (/* binding */ stringArraysHaveIntersection),
/* harmony export */   d: () => (/* binding */ findNextLineBreakIndex),
/* harmony export */   f: () => (/* binding */ fastHash),
/* harmony export */   h: () => (/* binding */ hasSpaces),
/* harmony export */   i: () => (/* binding */ isString),
/* harmony export */   s: () => (/* binding */ splitByDelimiterWithEscapeCharacter),
/* harmony export */   u: () => (/* binding */ unescapeChar)
/* harmony export */ });
/* unused harmony exports e, g, j, k, l, m, n, o, r */
var ErrorStatusCodes;
(function (ErrorStatusCodes) {
    ErrorStatusCodes[ErrorStatusCodes["ComplexRegex"] = 1001] = "ComplexRegex";
    ErrorStatusCodes[ErrorStatusCodes["RuleLimit"] = 1002] = "RuleLimit";
    ErrorStatusCodes[ErrorStatusCodes["RegexpRuleLimit"] = 1003] = "RegexpRuleLimit";
    ErrorStatusCodes[ErrorStatusCodes["RemoveparamRegexpIsNotSupported"] = 1004] = "RemoveparamRegexpIsNotSupported";
    ErrorStatusCodes[ErrorStatusCodes["RemoveparamInversionIsNotSupported"] = 1005] = "RemoveparamInversionIsNotSupported";
})(ErrorStatusCodes || (ErrorStatusCodes = {}));
const EMPTY_STRING = '';
const SEPARATOR = '|';
const SPACE = ' ';
const WILDCARD = '*';
const LF = '\n';
const CR = '\r';
const FF = '\f';

/**
 * Splits the string by the delimiter, ignoring escaped delimiters
 * and without tokenizing.
 * Works for plain strings that don't include string representation of
 * complex entities, e.g $replace modifier values.
 *
 * @param string String to split.
 * @param delimiter Delimiter.
 * @param escapeCharacter Escape character.
 * @param preserveEmptyTokens If true, preserve empty parts.
 * @param shouldUnescape If true, unescape characters.
 *
 * @returns Array of string parts.
 */
function splitByDelimiterWithEscapeCharacter(string, delimiter, escapeCharacter, preserveEmptyTokens, shouldUnescape = true) {
    if (!string) {
        return [];
    }
    if (string.startsWith(delimiter)) {
        // eslint-disable-next-line no-param-reassign
        string = string.substring(1);
    }
    let words = [];
    if (!string.includes(escapeCharacter)) {
        words = string.split(delimiter);
        if (!preserveEmptyTokens) {
            words = words.filter((word) => !!word);
        }
        return words;
    }
    let chars = [];
    const makeWord = () => {
        const word = chars.join('');
        words.push(word);
        chars = [];
    };
    for (let i = 0; i < string.length; i += 1) {
        const char = string.charAt(i);
        const isLastChar = i === (string.length - 1);
        if (char === delimiter) {
            const isEscapedChar = i > 0 && string[i - 1] === escapeCharacter;
            if (isEscapedChar) {
                if (shouldUnescape) {
                    chars.splice(chars.length - 1, 1);
                }
                chars.push(char);
            }
            else {
                makeWord();
            }
            if (isLastChar) {
                makeWord();
            }
        }
        else if (isLastChar) {
            chars.push(char);
            makeWord();
        }
        else {
            chars.push(char);
        }
    }
    if (!preserveEmptyTokens) {
        words = words.filter((word) => !!word);
    }
    return words;
}
/**
 * Checks if the specified string starts with a substr at the specified index.
 *
 * @param str String to check.
 * @param startIndex Index to start checking from.
 * @param substr Substring to check.
 *
 * @returns Boolean true if it does start.
 */
function startsAtIndexWith(str, startIndex, substr) {
    if (str.length - startIndex < substr.length) {
        return false;
    }
    for (let i = 0; i < substr.length; i += 1) {
        if (str.charAt(startIndex + i) !== substr.charAt(i)) {
            return false;
        }
    }
    return true;
}
/**
 * Checks if `str` has unquoted `substr`.
 *
 * @param str String to check.
 * @param substr Substring to check.
 *
 * @returns True if str has unquoted substr.
 */
function hasUnquotedSubstring(str, substr) {
    const quotes = ['"', "'", '/'];
    if (!str.includes(substr)) {
        return false;
    }
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    if (indexOfAny(str, quotes) === -1) {
        return true;
    }
    const stack = [];
    for (let i = 0; i < str.length; i += 1) {
        const cursor = str[i];
        if (stack.length === 0) {
            if (startsAtIndexWith(str, i, substr)) {
                return true;
            }
        }
        if (quotes.indexOf(cursor) >= 0
            && (i === 0 || str[i - 1] !== '\\')) {
            const last = stack.pop();
            if (!last) {
                stack.push(cursor);
            }
            else if (last !== cursor) {
                stack.push(last);
                stack.push(cursor);
            }
        }
    }
    return false;
}
/**
 * `djb2` hash algorithm.
 *
 * NOTE: This version uses some bit operands to exclude overflow MAX_SAFE_INTEGER
 * (and moreover, exclude overflow 2^32).
 *
 * @see {@link https://gist.github.com/eplawless/52813b1d8ad9af510d85?permalink_comment_id=3367765#gistcomment-3367765}
 *
 * @param str String to get hash.
 *
 * @returns Hash.
 */
function fastHash(str) {
    if (str.length === 0) {
        return 0;
    }
    // A magic constant that gives good distribution.
    let hash = 5381;
    for (let i = 0; i < str.length; i += 1) {
        hash = hash * 33 ^ str.charCodeAt(i);
    }
    return hash >>> 0;
}
/**
 * `djb2` hash algorithm with sign bit masked off to fit 31 bits.
 *
 * @param str String to get hash.
 *
 * @returns Hash from 0 to 2^31-1.
 */
function fastHash31(str) {
    // Mask off sign bit to keep value in range [0, ..., 2^31‑1].
    return fastHash(str) & 0x7fffffff;
}
/**
 * Look for any symbol from "chars" array starting at "start" index or from the start of the string.
 *
 * @param str   String to search.
 * @param chars Chars to search for.
 * @param start Start index (optional, inclusive).
 *
 * @returns Int Index of the element found or -1 if not.
 */
function indexOfAny(str, chars, start = 0) {
    if (str.length <= start) {
        return -1;
    }
    for (let i = start; i < str.length; i += 1) {
        const c = str.charAt(i);
        if (chars.indexOf(c) > -1) {
            return i;
        }
    }
    return -1;
}
/**
 * Replaces all occurrences of find with replace in str.
 *
 * @param str The string in which to replace all occurrences of the find string.
 * @param find The substring to find in the string.
 * @param replace The substring to replace the find string with.
 *
 * @returns The string with all occurrences of find replaced by replace.
 */
function replaceAll(str, find, replace) {
    if (!str) {
        return str;
    }
    return str.split(find).join(replace);
}
/**
 * Checks if arrays are equal.
 *
 * @param left Array.
 * @param right Array.
 *
 * @returns {boolean} True on equality.
 */
function stringArraysEquals(left, right) {
    if (!left || !right) {
        return !left && !right;
    }
    if (left.length !== right.length) {
        return false;
    }
    for (let i = 0; i < left.length; i += 1) {
        if (left[i] !== right[i]) {
            return false;
        }
    }
    return true;
}
/**
 * Checks if arrays have an intersection.
 *
 * @param left Array.
 * @param right Array.
 *
 * @returns {boolean} True on equality.
 */
function stringArraysHaveIntersection(left, right) {
    if (!left || !right) {
        return true;
    }
    for (let i = 0; i < left.length; i += 1) {
        if (right.includes(left[i])) {
            return true;
        }
    }
    return false;
}
/**
 * Checks if string contains spaces.
 *
 * @param str String to check.
 *
 * @returns `true` if string contains spaces, `false` otherwise.
 */
function hasSpaces(str) {
    return str.includes(SPACE);
}
/**
 * Check if the given value is a string.
 *
 * @param value Value to check.
 *
 * @returns `true` if value is a string, `false` otherwise.
 */
function isString(value) {
    return typeof value === 'string';
}
/**
 * Unescapes the specified character in the string.
 *
 * @param str String to escape.
 * @param char Character to escape.
 *
 * @returns The string with the specified character unescaped.
 */
function unescapeChar(str, char) {
    return str.replace(`\\${char}`, char);
}
/**
 * Finds the next line break index in the string starting from the specified index.
 * Supports LF, CR, FF and CRLF line breaks.
 *
 * @param str String to search in.
 * @param startIndex  Start index. Default is 0.
 *
 * @returns A tuple with the line break index and the line break length.
 * If the line break is not found, returns the string length and 0.
 */
function findNextLineBreakIndex(str, startIndex = 0) {
    const { length } = str;
    let offset = startIndex;
    while (offset < length) {
        const char = str[offset];
        if (char === LF || char === FF) {
            return [offset, 1];
        }
        if (char === CR) {
            return str[offset + 1] === LF ? [offset, 2] : [offset, 1];
        }
        offset += 1;
    }
    return [length, 0];
}
/**
 * Finds the next occurrence of a specified character in a string that is not preceded by an escape (`\`).
 *
 * @param str The input string to search within.
 * @param char The character to find in the string.
 * @param [startIndex] The index to start searching from.
 *
 * @returns The index of the next unescaped occurrence of the character, or the length of the string if not found.
 */
const findNextUnescapedIndex = (str, char, startIndex = 0) => {
    let i = str.indexOf(char, startIndex);
    while (i !== -1 && str[i - 1] === '\\') {
        i = str.indexOf(char, i + 1);
    }
    return i === -1 ? str.length : i;
};
/**
 * Determines whether a given Unicode code point corresponds to a numeric digit (0-9).
 *
 * @param codePoint The Unicode code point to check.
 *
 * @returns `true` if the code point represents a numeric character (0-9), otherwise `false`.
 */
const isNumber = (codePoint) => {
    return codePoint >= 48 && codePoint <= 57;
};
/**
 * Determines whether a given Unicode code point corresponds to an alphabetical letter (a-z, A-Z).
 *
 * @param codePoint The Unicode code point to check.
 *
 * @returns `true` if the code point represents an alphabetic character, otherwise `false`.
 */
const isAlpha = (codePoint) => {
    const codePointLower = codePoint | 0x20;
    return codePointLower >= 97 && codePointLower <= 122;
};
/**
 * Determines whether a given Unicode code point corresponds to an alphanumeric character (a-z, A-Z, 0-9).
 *
 * @param codePoint The Unicode code point to check.
 *
 * @returns `true` if the code point represents an alphanumeric character, otherwise `false`.
 */
const isAlphaNumeric = (codePoint) => {
    return isAlpha(codePoint) || isNumber(codePoint);
};

/* eslint-disable prefer-regex-literals */
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
// should be escaped . * + ? ^ $ { } ( ) | [ ] / \
// except of * | ^
const specialCharacters = ['.', '+', '?', '$', '{', '}', '(', ')', '[', ']', '/', '\\'];
const reSpecialCharacters = new RegExp(`[${specialCharacters.join('\\')}]`, 'g');
const reSpecialCharactersFull = /[.*+?^${}()|[\]\\]/g;
const reEscapedSpecialCharactersFull = /\\[.*+?^${}()|[\]\\]/g;
const protocolMarker = String.raw `:\/\/`;
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#using_special_characters_in_strings
const escapeSequence = {
    n: '\n',
    r: '\r',
    t: '\t',
    b: '\b',
    f: '\f',
    v: '\v',
};
/**
 * Class with static helper methods for working with basic filtering rules patterns.
 *
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#basic-rules}
 *
 * @returns The escaped string.
 */
class SimpleRegex {
    /**
     * Matching the beginning of an address. With this character you don't
     * have to specify a particular protocol and subdomain in address mask.
     * It means, `||` stands for `http://*.`, `https://*.`, `ws://*.`, `wss://*.` at once.
     */
    static MASK_START_URL = '||';
    /**
     * REGEX_START_URL corresponds to MASK_START_URL.
     */
    static REGEX_START_URL = '^(http|https|ws|wss)://([a-z0-9-_.]+\\.)?';
    /**
     * A pointer to the beginning or the end of address. The value depends on the
     * character placement in the mask. For example, a rule `swf|` corresponds
     * to `http://example.com/annoyingflash.swf`, but not to `http://example.com/swf/index.html`.
     * `|http://example.org` corresponds to `http://example.org`,
     * but not to `http://domain.com?url=http://example.org`.
     */
    static MASK_PIPE = '|';
    /**
     * REGEX_END_STRING corresponds to MASK_PIPE if it is in the end of a pattern.
     */
    static REGEX_END_STRING = '$';
    /**
     * REGEX_START_STRING corresponds to MASK_PIPE if it is in the beginning of a pattern.
     */
    static REGEX_START_STRING = '^';
    /**
     * Separator character mark. Separator character is any character,
     * but a letter, a digit, or one of the following: _ - .
     */
    static MASK_SEPARATOR = '^';
    /**
     * REGEX_SEPARATOR corresponds to MASK_SEPARATOR.
     */
    static REGEX_SEPARATOR = '([^ a-zA-Z0-9.%_-]|$)';
    /**
     * This is a wildcard character. It is used to represent "any set of characters".
     * This can also be an empty string or a string of any length.
     */
    static MASK_ANY_CHARACTER = '*';
    /**
     * Path separator.
     */
    static MASK_BACKSLASH = '/';
    /**
     * REGEX_ANY_CHARACTER corresponds to MASK_ANY_CHARACTER.
     */
    static REGEX_ANY_CHARACTER = '.*';
    /**
     * Enclose regex in two backslashes to mark a regex rule.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#regular-expressions-support}
     */
    static MASK_REGEX_RULE = '/';
    /**
     *  Regex for matching special characters in modifier regex pattern.
     */
    static reModifierPatternSpecialCharacters = /[[\],\\]/g;
    /**
     * Regex for matching escaped special characters in modifier regex pattern.
     */
    static reModifierPatternEscapedSpecialCharacters = /\\[[\],\\]/g;
    /**
     * If string starts with exclamation mark "!" we consider it as comment.
     */
    static MASK_COMMENT = '!';
    /**
     * Min length of rule shortcut
     * This value has been picked as a result of performance experiments.
     */
    static MIN_SHORTCUT_LENGTH = 3;
    /**
     * Min length of generic rule shortcut.
     */
    static MIN_GENERIC_RULE_LENGTH = 4;
    /**
     * Regex with basic matching pattern special characters.
     */
    static rePatternSpecialCharacters = new RegExp('[*^|]');
    /**
     * Extracts the shortcut from the rule's pattern.
     * Shortcut is the longest substring of the pattern that does not contain
     * any special characters.
     *
     * Please note, that the shortcut is always lower-case!
     *
     * @param pattern Network rule's pattern.
     *
     * @returns The shortcut or the empty string if we could not extract any.
     */
    static extractShortcut(pattern) {
        if (pattern.startsWith(this.MASK_REGEX_RULE) && pattern.endsWith(this.MASK_REGEX_RULE)) {
            return this.extractRegexpShortcut(pattern);
        }
        return this.extractBasicShortcut(pattern);
    }
    /**
     * Searches for the longest substring of the pattern that
     * does not contain any special characters: `*`, `^`, `|`.
     *
     * @param pattern Network rule's pattern.
     *
     * @returns The shortcut or the empty string.
     */
    static extractBasicShortcut(pattern) {
        let longest = '';
        const parts = pattern.split(this.rePatternSpecialCharacters);
        for (const part of parts) {
            if (part.length > longest.length) {
                longest = part;
            }
        }
        return (longest || '').toLowerCase();
    }
    /**
     * Extracts the longest substring from the provided regex pattern that does not
     * contain any special regex symbols or constructs that invalidate it for use
     * as a quick match shortcut.
     * The pattern is expected to be enclosed in forward slashes (e.g., `/example/`),
     * and may optionally contain a protocol marker (`://`),
     * which is ignored to prevent trivial matches like "http".
     *
     * This method discards many complex regex features (e.g., groups, character
     * classes, certain escaped sequences) when forming the shortcut, and always
     * returns the result in lower-case. If no valid substring is found, it returns
     * an empty string.
     *
     * @param pattern The input regex pattern, including the enclosing slashes.
     * For example: `/https?:\\/\\/example\\.com/`.
     *
     * @returns The longest valid substring usable as a shortcut, or an empty string if none is found.
     */
    static extractRegexpShortcut(pattern) {
        const { length } = pattern;
        if (!pattern
            // length should be at least 3: "/x/", "//" does not make sense
            || length < 3
            // regex pattern should start and end with '/'
            || pattern[0] !== '/'
            || pattern[length - 1] !== '/') {
            return '';
        }
        const protocolIndex = pattern.indexOf(protocolMarker);
        /**
         * `i` is our primary index into the pattern;
         * we skip the initial `/` or jump after the protocol marker `://`.
         */
        let i = protocolIndex !== -1
            ? protocolIndex + protocolMarker.length
            : 1;
        let longestToken = '';
        let longestTokenInGroup = '';
        let currentToken = '';
        /**
         * Resets `currentToken` and updates `longestTokenInGroup` if `currentToken` is longer.
         */
        const resetCurrentToken = () => {
            if (currentToken.length > longestTokenInGroup.length) {
                longestTokenInGroup = currentToken;
            }
            currentToken = '';
        };
        /**
         * Resets `longestTokenInGroup` and updates `longestToken` if `longestTokenInGroup` is longer.
         */
        const resetGroupToken = () => {
            if (longestTokenInGroup.length > longestToken.length) {
                longestToken = longestTokenInGroup;
            }
            longestTokenInGroup = '';
        };
        /**
         * Track parenthesis group nesting.
         */
        let groupBalance = 0;
        /**
         * Skip everything up to the closing parenthesis for the current group
         * (including nested groups).
         * This method moves `i` to the position of the closing parenthesis.
         */
        const ignoreCurrentGroup = () => {
            // Ignoring group means we should drop the current token
            currentToken = '';
            longestTokenInGroup = '';
            const startBalance = groupBalance;
            while (i < length) {
                // If `(` is not escaped, increment group count
                if (pattern[i] === '(' && pattern[i - 1] !== '\\') {
                    groupBalance += 1;
                }
                // If `)` is not escaped, decrement group count
                if (pattern[i] === ')' && pattern[i - 1] !== '\\') {
                    groupBalance -= 1;
                    // Once we return to the level before this group started, stop
                    if (groupBalance < startBalance) {
                        break;
                    }
                }
                i += 1;
            }
        };
        while (i < length) {
            const char = pattern[i];
            // 1) Handle escaped sequences
            if (char === '\\') {
                // Skip the backslash
                i += 1;
                const escaped = pattern[i];
                switch (escaped) {
                    // Ignore predefined character classes: \d, \D, \s, \S, \w, \W
                    case 'd':
                    case 'D':
                    case 's':
                    case 'S':
                    case 'w':
                    case 'W':
                    // Ignore special characters: \t, \r, \n, \v, \f, \b, \0
                    // eslint-disable-next-line no-fallthrough
                    case 't':
                    case 'r':
                    case 'n':
                    case 'v':
                    case 'f':
                    case 'b':
                    case '0':
                        resetCurrentToken();
                        i += 1;
                        continue;
                    // Ignore control characters: \cX — control character X
                    case 'c':
                        resetCurrentToken();
                        // skip 'c' and the following character
                        i += 2;
                        continue;
                    // Ignore \xhh
                    case 'x':
                        resetCurrentToken();
                        // skip 'x' and the following 2 characters
                        i += 3;
                        continue;
                    // Ignore \uhhhh
                    case 'u':
                        resetCurrentToken();
                        // skip 'u' and the following 4 characters
                        i += 5;
                        continue;
                    // Ignore named backreference: \k<...>
                    case 'k':
                        resetCurrentToken();
                        // skip 'k'
                        i += 1;
                        if (pattern[i] === '<') {
                            // Skip until the closing '>'
                            i = findNextUnescapedIndex(pattern, '>', i) + 1;
                        }
                        continue;
                    // Special case: add escaped '.' or '/' to the current token
                    case '.':
                    case '/':
                        currentToken += escaped;
                        i += 1;
                        continue;
                    default:
                        resetCurrentToken();
                        i += 1;
                        continue;
                }
            }
            // 2) Handle "regular" characters (i.e., not after a backslash)
            switch (char) {
                // Ignore custom character classes, like [xyz], [^xyz], [\b], [a-z], etc.
                case '[':
                    resetCurrentToken();
                    i = findNextUnescapedIndex(pattern, ']', i) + 1;
                    continue;
                // Ignore disjunctions (alternations), like a|b|c
                // Note: shortcut should be present in all possible tested strings,
                // this is why we ignore disjunctions
                case '|':
                    ignoreCurrentGroup();
                    continue;
                // Ignore specific quantifiers, like x{n}, x{n,}, x{n,m}
                case '{':
                    resetCurrentToken();
                    i = findNextUnescapedIndex(pattern, '}', i) + 1;
                    continue;
                // Handle group open
                case '(':
                    resetCurrentToken();
                    resetGroupToken();
                    groupBalance += 1;
                    // Skip `(`
                    i += 1;
                    // Ignore negative lookahead: (?!...) and negative lookbehind: (?<!...)
                    // Negative lookbehind and lookahead contain data that should not be present in the tested strings,
                    // this is why we ignore them
                    if (pattern.indexOf('?!', i) === i || pattern.indexOf('?<!', i) === i) {
                        ignoreCurrentGroup();
                    }
                    // Ignore name section from named groups: (?<...>
                    if (pattern.indexOf('?<', i) === i) {
                        // Skip until the closing '>'
                        i = findNextUnescapedIndex(pattern, '>', i + 2) + 1;
                    }
                    continue;
                // Handle group close
                case ')':
                    resetCurrentToken();
                    resetGroupToken();
                    groupBalance -= 1;
                    // Skip `)`
                    i += 1;
                    continue;
                // Handle special regex symbols: . * + ? ^ $ /
                case '.':
                case '*':
                case '+':
                case '?':
                case '^':
                case '$':
                case '/':
                    resetCurrentToken();
                    i += 1;
                    continue;
                default:
                    // For performance, let's check if it's a valid token char
                    // Note: isValidRegexpShortcutChar checks for alphanumeric or
                    // escaped '.' or '/'
                    if (isAlphaNumeric(char.charCodeAt(0))) {
                        currentToken += char;
                    }
                    else {
                        // If it's not a valid char for a shortcut, reset
                        resetCurrentToken();
                    }
                    i += 1;
                    break;
            }
        }
        // Finalize the last token
        resetCurrentToken();
        resetGroupToken();
        return longestToken.toLowerCase();
    }
    /**
     * PatternToRegexp is a helper method for creating regular expressions from the simple
     * wildcard-based syntax which is used in basic filters.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#basic-rules}
     *
     * @param pattern Basic rule pattern.
     *
     * @returns Regular expression.
     */
    static patternToRegexp(pattern) {
        if (pattern === this.MASK_START_URL
            || pattern === this.MASK_PIPE
            || pattern === this.MASK_ANY_CHARACTER
            || pattern === '') {
            return this.REGEX_ANY_CHARACTER;
        }
        if (pattern.startsWith(this.MASK_REGEX_RULE) && pattern.endsWith(this.MASK_REGEX_RULE)) {
            // This is a regex rule, just remove the regex markers
            return pattern.substring(this.MASK_REGEX_RULE.length, pattern.length - this.MASK_REGEX_RULE.length);
        }
        // Escape special characters except of * | ^
        let regex = pattern.replace(reSpecialCharacters, '\\$&');
        // Now escape "|" characters but avoid escaping them in the special places
        if (regex.startsWith(this.MASK_START_URL)) {
            regex = regex.substring(0, this.MASK_START_URL.length)
                + replaceAll(regex.substring(this.MASK_START_URL.length, regex.length - this.MASK_PIPE.length), this.MASK_PIPE, `\\${this.MASK_PIPE}`)
                + regex.substring(regex.length - this.MASK_PIPE.length);
        }
        else {
            regex = regex.substring(0, this.MASK_PIPE.length)
                + replaceAll(regex.substring(this.MASK_PIPE.length, regex.length - this.MASK_PIPE.length), this.MASK_PIPE, `\\${this.MASK_PIPE}`)
                + regex.substring(regex.length - this.MASK_PIPE.length);
        }
        // Replace special URL masks
        regex = replaceAll(regex, this.MASK_ANY_CHARACTER, this.REGEX_ANY_CHARACTER);
        regex = replaceAll(regex, this.MASK_SEPARATOR, this.REGEX_SEPARATOR);
        // Replace start URL and pipes
        if (regex.startsWith(this.MASK_START_URL)) {
            regex = this.REGEX_START_URL + regex.substring(this.MASK_START_URL.length);
        }
        else if (regex.startsWith(this.MASK_PIPE)) {
            regex = this.REGEX_START_STRING + regex.substring(this.MASK_PIPE.length);
        }
        if (regex.endsWith(this.MASK_PIPE)) {
            regex = regex.substring(0, regex.length - this.MASK_PIPE.length) + this.REGEX_END_STRING;
        }
        return regex;
    }
    /**
     * Creates RegExp object from string in '/reg_exp/gi' format.
     *
     * @param str The string to escape.
     *
     * @returns The created RegExp object.
     */
    static patternFromString(str) {
        const parts = splitByDelimiterWithEscapeCharacter(str, '/', '\\', true);
        let modifiers = (parts[1] || '');
        if (modifiers.indexOf('g') < 0) {
            modifiers += 'g';
        }
        return new RegExp(parts[0], modifiers);
    }
    /**
     * Escapes characters with special meaning inside a regular expression.
     *
     * @param str The string to escape.
     * @param searchPattern Pattern for detecting special characters. Optional.
     *
     * @returns The escaped string.
     */
    static escapeRegexSpecials(str, searchPattern = reSpecialCharactersFull) {
        return str.replace(searchPattern, '\\$&');
    }
    /**
     * Unescapes characters with special meaning inside a regular expression.
     *
     * @param str The string to unescape.
     * @param searchPattern Pattern for detecting special characters. Optional.
     *
     * @returns The unescaped string.
     */
    static unescapeRegexSpecials(str, searchPattern = reEscapedSpecialCharactersFull) {
        return str.replace(searchPattern, (match) => match.substring(1));
    }
    /**
     * Check if pattern is Regex.
     *
     * @param str The string to check.
     *
     * @returns True if the string is a regex pattern, false otherwise.
     */
    static isRegexPattern(str) {
        return str.startsWith('/') && str.endsWith('/');
    }
    /**
     * Unescapes special characters in a string.
     *
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#using_special_characters_in_strings}
     *
     * @param str The string to unescape.
     *
     * @returns The unescaped string.
     */
    static unescapeSpecials(str) {
        const keys = Object.keys(escapeSequence).join('|');
        const regex = new RegExp(`\\\\(${keys})`, 'g');
        return str.replace(regex, (match, group) => {
            return escapeSequence[group];
        });
    }
}




/***/ }),

/***/ 47562:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  gR: () => (/* binding */ contains)
});

// UNUSED EXPORTS: default, exclude, expand, isIP, merge, normalize, overlap, parse

;// ./node_modules/.pnpm/ip-regex@5.0.0/node_modules/ip-regex/index.js
const word = '[a-fA-F\\d:]';

const boundry = options => options && options.includeBoundaries
	? `(?:(?<=\\s|^)(?=${word})|(?<=${word})(?=\\s|$))`
	: '';

const v4 = '(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}';

const v6segment = '[a-fA-F\\d]{1,4}';

const v6 = `
(?:
(?:${v6segment}:){7}(?:${v6segment}|:)|                                    // 1:2:3:4:5:6:7::  1:2:3:4:5:6:7:8
(?:${v6segment}:){6}(?:${v4}|:${v6segment}|:)|                             // 1:2:3:4:5:6::    1:2:3:4:5:6::8   1:2:3:4:5:6::8  1:2:3:4:5:6::1.2.3.4
(?:${v6segment}:){5}(?::${v4}|(?::${v6segment}){1,2}|:)|                   // 1:2:3:4:5::      1:2:3:4:5::7:8   1:2:3:4:5::8    1:2:3:4:5::7:1.2.3.4
(?:${v6segment}:){4}(?:(?::${v6segment}){0,1}:${v4}|(?::${v6segment}){1,3}|:)| // 1:2:3:4::        1:2:3:4::6:7:8   1:2:3:4::8      1:2:3:4::6:7:1.2.3.4
(?:${v6segment}:){3}(?:(?::${v6segment}){0,2}:${v4}|(?::${v6segment}){1,4}|:)| // 1:2:3::          1:2:3::5:6:7:8   1:2:3::8        1:2:3::5:6:7:1.2.3.4
(?:${v6segment}:){2}(?:(?::${v6segment}){0,3}:${v4}|(?::${v6segment}){1,5}|:)| // 1:2::            1:2::4:5:6:7:8   1:2::8          1:2::4:5:6:7:1.2.3.4
(?:${v6segment}:){1}(?:(?::${v6segment}){0,4}:${v4}|(?::${v6segment}){1,6}|:)| // 1::              1::3:4:5:6:7:8   1::8            1::3:4:5:6:7:1.2.3.4
(?::(?:(?::${v6segment}){0,5}:${v4}|(?::${v6segment}){1,7}|:))             // ::2:3:4:5:6:7:8  ::2:3:4:5:6:7:8  ::8             ::1.2.3.4
)(?:%[0-9a-zA-Z]{1,})?                                             // %eth0            %1
`.replace(/\s*\/\/.*$/gm, '').replace(/\n/g, '').trim();

// Pre-compile only the exact regexes because adding a global flag make regexes stateful
const v46Exact = new RegExp(`(?:^${v4}$)|(?:^${v6}$)`);
const v4exact = new RegExp(`^${v4}$`);
const v6exact = new RegExp(`^${v6}$`);

const ipRegex = options => options && options.exact
	? v46Exact
	: new RegExp(`(?:${boundry(options)}${v4}${boundry(options)})|(?:${boundry(options)}${v6}${boundry(options)})`, 'g');

ipRegex.v4 = options => options && options.exact ? v4exact : new RegExp(`${boundry(options)}${v4}${boundry(options)}`, 'g');
ipRegex.v6 = options => options && options.exact ? v6exact : new RegExp(`${boundry(options)}${v6}${boundry(options)}`, 'g');

/* harmony default export */ const ip_regex = (ipRegex);

;// ./node_modules/.pnpm/cidr-regex@4.0.3/node_modules/cidr-regex/index.js


const defaultOpts = {exact: false};
const v4str = `${ip_regex.v4().source}\\/(3[0-2]|[12]?[0-9])`;
const v6str = `${ip_regex.v6().source}\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])`;

// pre-compile only the exact regexes as global flag makes regex objects stateful
const cidr_regex_v4exact = new RegExp(`^${v4str}$`);
const cidr_regex_v6exact = new RegExp(`^${v6str}$`);
const v46exact = new RegExp(`(?:^${v4str}$)|(?:^${v6str}$)`);

const cidrRegex = ({exact} = defaultOpts) => exact ? v46exact : new RegExp(`(?:${v4str})|(?:${v6str})`, "g");
const cidr_regex_v4 = cidrRegex.v4 = ({exact} = defaultOpts) => exact ? cidr_regex_v4exact : new RegExp(v4str, "g");
const cidr_regex_v6 = cidrRegex.v6 = ({exact} = defaultOpts) => exact ? cidr_regex_v6exact : new RegExp(v6str, "g");
/* harmony default export */ const cidr_regex = (cidrRegex);

// EXTERNAL MODULE: ./node_modules/.pnpm/string-natural-compare@3.0.1/node_modules/string-natural-compare/natural-compare.js
var natural_compare = __webpack_require__(34156);
;// ./node_modules/.pnpm/ip-bigint@7.3.0/node_modules/ip-bigint/index.js
const max4 = 2n ** 32n - 1n;
const max6 = 2n ** 128n - 1n;

function parseIp(ip) {
  const version = ipVersion(ip);
  if (!version) throw new Error(`Invalid IP address: ${ip}`);

  let number = 0n;
  let exp = 0n;
  const res = Object.create(null);

  if (version === 4) {
    for (const n of ip.split(".").map(BigInt).reverse()) {
      number += n * (2n ** exp);
      exp += 8n;
    }
  } else {
    if (ip.includes(".")) {
      res.ipv4mapped = true;
      ip = ip.split(":").map(part => {
        if (part.includes(".")) {
          const digits = part.split(".").map(str => Number(str).toString(16).padStart(2, "0"));
          return `${digits[0]}${digits[1]}:${digits[2]}${digits[3]}`;
        } else {
          return part;
        }
      }).join(":");
    }

    if (ip.includes("%")) {
      let scopeid;
      [, ip, scopeid] = /(.+)%(.+)/.exec(ip);
      res.scopeid = scopeid;
    }

    const parts = ip.split(":");
    const index = parts.indexOf("");

    if (index !== -1) {
      while (parts.length < 8) {
        parts.splice(index, 0, "");
      }
    }

    for (const n of parts.map(part => BigInt(parseInt(part || 0, 16))).reverse()) {
      number += n * (2n ** exp);
      exp += 16n;
    }
  }

  res.number = number;
  res.version = version;
  return res;
}

function stringifyIp({number, version, ipv4mapped, scopeid} = {}, {compress = true, hexify = false} = {}) {
  if (typeof number !== "bigint") throw new Error(`Expected a BigInt`);
  if (![4, 6].includes(version)) throw new Error(`Invalid version: ${version}`);
  if (number < 0n || number > (version === 4 ? max4 : max6)) throw new Error(`Invalid number: ${number}`);

  let step = version === 4 ? 24n : 112n;
  const stepReduction = version === 4 ? 8n : 16n;
  let remain = number;
  const parts = [];

  while (step > 0n) {
    const divisor = 2n ** step;
    parts.push(remain / divisor);
    remain = number % divisor;
    step -= stepReduction;
  }
  parts.push(remain);

  if (version === 4) {
    return parts.join(".");
  } else {
    let ip = "";
    if (ipv4mapped && !hexify) {
      for (const [index, num] of parts.entries()) {
        if (index < 6) {
          ip += `${num.toString(16)}:`;
        } else {
          ip += `${String(num >> 8n)}.${String(num & 255n)}${index === 6 ? "." : ""}`;
        }
      }
      if (compress) {
        ip = compressIPv6(ip.split(":"));
      }
    } else {
      if (compress) {
        ip = compressIPv6(parts.map(n => n.toString(16)));
      } else {
        ip = parts.map(n => n.toString(16)).join(":");
      }
    }

    if (scopeid) {
      ip = `${ip}%${scopeid}`;
    }

    return ip;
  }
}

function normalizeIp(ip, {compress = true, hexify = false} = {}) {
  return stringifyIp(parseIp(ip), {compress, hexify});
}

// take the longest or first sequence of "0" segments and replace it with "::"
function compressIPv6(parts) {
  let longest, current;
  for (const [index, part] of parts.entries()) {
    if (part === "0") {
      if (!current) {
        current = new Set([index]);
      } else {
        current.add(index);
      }
    } else {
      if (current) {
        if (!longest) {
          longest = current;
        } else if (current.size > longest.size) {
          longest = current;
        }
        current = null;
      }
    }
  }
  if ((!longest && current) || (current && current.size > longest.size)) {
    longest = current;
  }

  for (const index of longest || []) {
    parts[index] = ":";
  }

  return parts.filter(Boolean).join(":").replace(/:{2,}/, "::");
}

function ipVersion(ip) {
  return ip.includes(":") ? 6 : ip.includes(".") ? 4 : 0;
}

;// ./node_modules/.pnpm/cidr-tools@6.4.2/node_modules/cidr-tools/index.js





const bits = {
  4: 32,
  6: 128,
};

const uniq = arr => Array.from(new Set(arr));

function isIP(ip) {
  if (ip_regex.v4({exact: true}).test(ip)) return 4;
  if (ip_regex.v6({exact: true}).test(ip)) return 6;
  return 0;
}

function isCidr(ip) {
  if (cidr_regex.v4({exact: true}).test(ip)) return 4;
  if (cidr_regex.v6({exact: true}).test(ip)) return 6;
  return 0;
}

function doNormalize(cidr, {compress = true, hexify = false} = {}) {
  const {start, prefix, single, version} = parse(cidr);
  if (!single) { // cidr
    // set network address to first address
    const ip = normalizeIp(stringifyIp({number: start, version}), {compress, hexify});
    return `${ip}/${prefix}`;
  } else { // single ip
    return normalizeIp(cidr, {compress, hexify});
  }
}

function normalize(cidr, {compress = true, hexify = false} = {}) {
  if (Array.isArray(cidr)) {
    return cidr.map(entry => normalize(entry, {compress, hexify}));
  } else {
    return doNormalize(cidr, {compress, hexify});
  }
}

function parse(str) {
  const cidrVersion = isCidr(str);
  const parsed = Object.create(null);
  parsed.single = false;

  if (cidrVersion) {
    parsed.cidr = str;
    parsed.version = cidrVersion;
  } else {
    const version = isIP(str);
    if (version) {
      parsed.cidr = `${str}/${bits[version]}`;
      parsed.version = version;
      parsed.single = true;
    } else {
      throw new Error(`Network is not a CIDR or IP: ${str}`);
    }
  }

  const [ip, prefix] = parsed.cidr.split("/");
  parsed.prefix = prefix;
  const {number, version} = parseIp(ip);
  const numBits = bits[version];
  const ipBits = number.toString(2).padStart(numBits, "0");
  const prefixLen = Number(numBits - prefix);
  const startBits = ipBits.substring(0, numBits - prefixLen);
  parsed.start = BigInt(`0b${startBits}${"0".repeat(prefixLen)}`);
  parsed.end = BigInt(`0b${startBits}${"1".repeat(prefixLen)}`);
  return parsed;
}

// returns whether networks fully or partially overlap
function doNetsOverlap(a, b) {
  //    aaa
  // bbb
  if (a.start > b.end) return false; // a starts after b

  // aaa
  //    bbb
  if (b.start > a.end) return false; // b starts after a

  return true;
}

// returns whether network a fully contains network b;
function netContains(a, b) {
  //  aaa
  // bbbb
  if (b.start < a.start) return false; // a starts after b

  // aaa
  // bbbb
  if (b.end > a.end) return false; // b starts after a

  return true;
}

// exclude b from a and return remainder cidrs
function excludeNets(a, b, v) {
  const parts = [];

  // compareTo returns negative if left is less than right

  //       aaa
  //   bbb
  //   aaa
  //       bbb
  if (a.start > b.end || a.end < b.start) {
    return [a.cidr];
  }

  //   aaa
  //   bbb
  if (a.start === b.start && a.end === b.end) {
    return [];
  }

  //   aa
  //  bbbb
  if (a.start > b.start && a.end < b.end) {
    return [];
  }

  // aaaa
  //   bbbb
  // aaaa
  //   bb
  if (a.start < b.start && a.end <= b.end) {
    parts.push({start: a.start, end: b.start - 1n});
  }

  //    aaa
  //   bbb
  //   aaaa
  //   bbb
  if (a.start >= b.start && a.end > b.end) {
    parts.push({start: b.end + 1n, end: a.end});
  }

  //  aaaa
  //   bb
  if (a.start < b.start && a.end > b.end) {
    parts.push(
      {start: a.start, end: b.start - 1n},
      {start: b.end + 1n, end: a.end},
    );
  }

  const remaining = [];
  for (const part of parts) {
    for (const subpart of subparts(part)) {
      remaining.push(formatPart(subpart, v));
    }
  }

  return merge(remaining);
}

function biggestPowerOfTwo(num) {
  if (num === 0n) return 0n;
  return 2n ** BigInt(String(num.toString(2).length - 1));
}

function subparts(part) {
  // special case for when part is length 1
  if ((part.end - part.start) === 1n) {
    if (part.end % 2n === 0n) {
      return [{start: part.start, end: part.start}, {start: part.end, end: part.end}];
    } else {
      return [{start: part.start, end: part.end}];
    }
  }

  const size = diff(part.end, part.start);
  let biggest = biggestPowerOfTwo(size);

  let start, end;
  if (size === biggest && part.start + size === part.end) {
    return [part];
  } else if (part.start % biggest === 0n) {
    // start is matching on the size-defined boundary - ex: 0-12, use 0-8
    start = part.start;
    end = start + biggest - 1n;
  } else {
    start = (part.end / biggest) * biggest;

    // start is not matching on the size-defined boundary - 4-16, use 8-16
    if ((start + biggest - 1n) > part.end) {
      // divide will floor to nearest integer
      start = ((part.end / biggest) - 1n) * biggest;

      while (start < part.start) {
        biggest /= 2n;
        start = ((part.end / biggest) - 1n) * biggest;
      }

      end = start + biggest - 1n;
    } else {
      start = (part.end / biggest) * biggest;
      end = start + biggest - 1n;
    }
  }

  let parts = [{start, end}];

  // additional subnets on left side
  if (start !== part.start) {
    parts = parts.concat(subparts({start: part.start, end: start - 1n}));
  }

  // additional subnets on right side
  if (end !== part.end) {
    parts = parts.concat(subparts({start: end + 1n, end: part.end}));
  }

  return parts;
}

function diff(a, b) {
  if (typeof a !== "bigint") a = BigInt(a);
  if (typeof b !== "bigint") b = BigInt(b);
  a += 1n;
  return a - b;
}

function formatPart(part, v) {
  const ip = normalize(stringifyIp({
    number: BigInt(part.start.toString()),
    version: v,
  }));
  const zeroes = diff(part.end, part.start).toString(2);
  const prefix = bits[v] - (zeroes.match(/0/g) || []).length;
  return `${ip}/${prefix}`;
}

function mapNets(nets) {
  const maps = {4: {}, 6: {}};
  for (const {start, end, version: v} of nets) {
    if (!maps[v][start]) maps[v][start] = {};
    if (!maps[v][end]) maps[v][end] = {};

    if (maps[v][start].start) {
      maps[v][start].start += 1;
    } else {
      maps[v][start].start = 1;
    }

    if (maps[v][end].end) {
      maps[v][end].end += 1;
    } else {
      maps[v][end].end = 1;
    }
  }
  return maps;
}

function merge(nets) {
  nets = uniq((Array.isArray(nets) ? nets : [nets]).map(parse));
  const maps = mapNets(nets);

  const merged = {4: [], 6: []};
  const start = {4: null, 6: null};
  const end = {4: null, 6: null};

  for (const v of [4, 6]) {
    const numbers = Object.keys(maps[v]).sort(natural_compare);
    let depth = 0;

    for (const [index, number] of numbers.entries()) {
      const marker = maps[v][number];

      if (start[v] === null && marker.start) {
        start[v] = BigInt(number);
      }
      if (marker.end) {
        end[v] = BigInt(number);
      }

      if (marker.start) depth += marker.start;
      if (marker.end) depth -= marker.end;

      if (marker.end && depth === 0 && ((numbers[index + 1] - numbers[index]) > 1)) {
        for (const sub of subparts({start: start[v], end: end[v]})) {
          merged[v].push(formatPart(sub, v));
        }
        start[v] = null;
        end[v] = null;
      } else if (index === (numbers.length - 1)) {
        for (const sub of subparts({start: start[v], end: end[v]})) {
          merged[v].push(formatPart(sub, v));
        }
      }
    }
  }

  return [...merged[4].sort(natural_compare), ...merged[6].sort(natural_compare)];
}

function exclude(basenets, exclnets) {
  basenets = uniq(Array.isArray(basenets) ? basenets : [basenets]);
  exclnets = uniq(Array.isArray(exclnets) ? exclnets : [exclnets]);

  basenets = merge(basenets);
  exclnets = merge(exclnets);

  const bases = {4: [], 6: []};
  const excls = {4: [], 6: []};

  for (const basenet of basenets) {
    bases[isCidr(basenet)].push(basenet);
  }

  for (const exclnet of exclnets) {
    excls[isCidr(exclnet)].push(exclnet);
  }

  for (const v of [4, 6]) {
    for (const exclcidr of excls[v]) {
      for (const [index, basecidr] of bases[v].entries()) {
        const base = parse(basecidr);
        const excl = parse(exclcidr);
        const remainders = excludeNets(base, excl, v);
        if (base.cidr !== remainders.toString()) {
          bases[v] = bases[v].concat(remainders);
          bases[v].splice(index, 1);
        }
      }
    }
  }

  return bases[4].concat(bases[6]);
}

function expand(nets) {
  nets = uniq(Array.isArray(nets) ? nets : [nets]);

  const ips = [];
  for (const net of merge(nets)) {
    const {start, end, version} = parse(net);
    for (let number = start; number <= end; number++) {
      ips.push(stringifyIp({number, version}));
    }
  }
  return ips.map(normalize);
}

function overlap(a, b) {
  const aNets = uniq(Array.isArray(a) ? a : [a]);
  const bNets = uniq(Array.isArray(b) ? b : [b]);

  for (const a of aNets) {
    const aParsed = parse(a);
    for (const b of bNets) {
      const bParsed = parse(b);

      // version mismatch
      if (aParsed.version !== bParsed.version) {
        continue;
      }

      if (doNetsOverlap(aParsed, bParsed)) {
        return true;
      }
    }
  }

  return false;
}

function contains(a, b) {
  const aNets = uniq(Array.isArray(a) ? a : [a]);
  const bNets = uniq(Array.isArray(b) ? b : [b]);

  const numExpected = bNets.length;
  let numFound = 0;
  for (const a of aNets) {
    const aParsed = parse(a);
    for (const b of bNets) {
      const bParsed = parse(b);

      // version mismatch
      if (aParsed.version !== bParsed.version) {
        continue;
      }

      if (netContains(aParsed, bParsed)) {
        numFound++;
        continue;
      }
    }
  }

  return numFound === numExpected;
}

/* harmony default export */ const cidr_tools = ({
  merge,
  exclude,
  expand,
  overlap,
  contains,
  normalize,
  parse,
});


/***/ }),

/***/ 38037:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   q: () => (/* binding */ LRUCache)
/* harmony export */ });
/**
 * @module LRUCache
 */
const perf = typeof performance === 'object' &&
    performance &&
    typeof performance.now === 'function'
    ? performance
    : Date;
const warned = new Set();
/* c8 ignore start */
const PROCESS = (typeof process === 'object' && !!process ? process : {});
/* c8 ignore start */
const emitWarning = (msg, type, code, fn) => {
    typeof PROCESS.emitWarning === 'function'
        ? PROCESS.emitWarning(msg, type, code, fn)
        : console.error(`[${code}] ${type}: ${msg}`);
};
let AC = globalThis.AbortController;
let AS = globalThis.AbortSignal;
/* c8 ignore start */
if (typeof AC === 'undefined') {
    //@ts-ignore
    AS = class AbortSignal {
        onabort;
        _onabort = [];
        reason;
        aborted = false;
        addEventListener(_, fn) {
            this._onabort.push(fn);
        }
    };
    //@ts-ignore
    AC = class AbortController {
        constructor() {
            warnACPolyfill();
        }
        signal = new AS();
        abort(reason) {
            if (this.signal.aborted)
                return;
            //@ts-ignore
            this.signal.reason = reason;
            //@ts-ignore
            this.signal.aborted = true;
            //@ts-ignore
            for (const fn of this.signal._onabort) {
                fn(reason);
            }
            this.signal.onabort?.(reason);
        }
    };
    let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1';
    const warnACPolyfill = () => {
        if (!printACPolyfillWarning)
            return;
        printACPolyfillWarning = false;
        emitWarning('AbortController is not defined. If using lru-cache in ' +
            'node 14, load an AbortController polyfill from the ' +
            '`node-abort-controller` package. A minimal polyfill is ' +
            'provided for use by LRUCache.fetch(), but it should not be ' +
            'relied upon in other contexts (eg, passing it to other APIs that ' +
            'use AbortController/AbortSignal might have undesirable effects). ' +
            'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill);
    };
}
/* c8 ignore stop */
const shouldWarn = (code) => !warned.has(code);
const TYPE = Symbol('type');
const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
/* c8 ignore start */
// This is a little bit ridiculous, tbh.
// The maximum array length is 2^32-1 or thereabouts on most JS impls.
// And well before that point, you're caching the entire world, I mean,
// that's ~32GB of just integers for the next/prev links, plus whatever
// else to hold that many keys and values.  Just filling the memory with
// zeroes at init time is brutal when you get that big.
// But why not be complete?
// Maybe in the future, these limits will have expanded.
const getUintArray = (max) => !isPosInt(max)
    ? null
    : max <= Math.pow(2, 8)
        ? Uint8Array
        : max <= Math.pow(2, 16)
            ? Uint16Array
            : max <= Math.pow(2, 32)
                ? Uint32Array
                : max <= Number.MAX_SAFE_INTEGER
                    ? ZeroArray
                    : null;
/* c8 ignore stop */
class ZeroArray extends Array {
    constructor(size) {
        super(size);
        this.fill(0);
    }
}
class Stack {
    heap;
    length;
    // private constructor
    static #constructing = false;
    static create(max) {
        const HeapCls = getUintArray(max);
        if (!HeapCls)
            return [];
        Stack.#constructing = true;
        const s = new Stack(max, HeapCls);
        Stack.#constructing = false;
        return s;
    }
    constructor(max, HeapCls) {
        /* c8 ignore start */
        if (!Stack.#constructing) {
            throw new TypeError('instantiate Stack using Stack.create(n)');
        }
        /* c8 ignore stop */
        this.heap = new HeapCls(max);
        this.length = 0;
    }
    push(n) {
        this.heap[this.length++] = n;
    }
    pop() {
        return this.heap[--this.length];
    }
}
/**
 * Default export, the thing you're using this module to get.
 *
 * The `K` and `V` types define the key and value types, respectively. The
 * optional `FC` type defines the type of the `context` object passed to
 * `cache.fetch()` and `cache.memo()`.
 *
 * Keys and values **must not** be `null` or `undefined`.
 *
 * All properties from the options object (with the exception of `max`,
 * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are
 * added as normal public members. (The listed options are read-only getters.)
 *
 * Changing any of these will alter the defaults for subsequent method calls.
 */
class LRUCache {
    // options that cannot be changed without disaster
    #max;
    #maxSize;
    #dispose;
    #disposeAfter;
    #fetchMethod;
    #memoMethod;
    /**
     * {@link LRUCache.OptionsBase.ttl}
     */
    ttl;
    /**
     * {@link LRUCache.OptionsBase.ttlResolution}
     */
    ttlResolution;
    /**
     * {@link LRUCache.OptionsBase.ttlAutopurge}
     */
    ttlAutopurge;
    /**
     * {@link LRUCache.OptionsBase.updateAgeOnGet}
     */
    updateAgeOnGet;
    /**
     * {@link LRUCache.OptionsBase.updateAgeOnHas}
     */
    updateAgeOnHas;
    /**
     * {@link LRUCache.OptionsBase.allowStale}
     */
    allowStale;
    /**
     * {@link LRUCache.OptionsBase.noDisposeOnSet}
     */
    noDisposeOnSet;
    /**
     * {@link LRUCache.OptionsBase.noUpdateTTL}
     */
    noUpdateTTL;
    /**
     * {@link LRUCache.OptionsBase.maxEntrySize}
     */
    maxEntrySize;
    /**
     * {@link LRUCache.OptionsBase.sizeCalculation}
     */
    sizeCalculation;
    /**
     * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
     */
    noDeleteOnFetchRejection;
    /**
     * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
     */
    noDeleteOnStaleGet;
    /**
     * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
     */
    allowStaleOnFetchAbort;
    /**
     * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
     */
    allowStaleOnFetchRejection;
    /**
     * {@link LRUCache.OptionsBase.ignoreFetchAbort}
     */
    ignoreFetchAbort;
    // computed properties
    #size;
    #calculatedSize;
    #keyMap;
    #keyList;
    #valList;
    #next;
    #prev;
    #head;
    #tail;
    #free;
    #disposed;
    #sizes;
    #starts;
    #ttls;
    #hasDispose;
    #hasFetchMethod;
    #hasDisposeAfter;
    /**
     * Do not call this method unless you need to inspect the
     * inner workings of the cache.  If anything returned by this
     * object is modified in any way, strange breakage may occur.
     *
     * These fields are private for a reason!
     *
     * @internal
     */
    static unsafeExposeInternals(c) {
        return {
            // properties
            starts: c.#starts,
            ttls: c.#ttls,
            sizes: c.#sizes,
            keyMap: c.#keyMap,
            keyList: c.#keyList,
            valList: c.#valList,
            next: c.#next,
            prev: c.#prev,
            get head() {
                return c.#head;
            },
            get tail() {
                return c.#tail;
            },
            free: c.#free,
            // methods
            isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
            backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context),
            moveToTail: (index) => c.#moveToTail(index),
            indexes: (options) => c.#indexes(options),
            rindexes: (options) => c.#rindexes(options),
            isStale: (index) => c.#isStale(index),
        };
    }
    // Protected read-only members
    /**
     * {@link LRUCache.OptionsBase.max} (read-only)
     */
    get max() {
        return this.#max;
    }
    /**
     * {@link LRUCache.OptionsBase.maxSize} (read-only)
     */
    get maxSize() {
        return this.#maxSize;
    }
    /**
     * The total computed size of items in the cache (read-only)
     */
    get calculatedSize() {
        return this.#calculatedSize;
    }
    /**
     * The number of items stored in the cache (read-only)
     */
    get size() {
        return this.#size;
    }
    /**
     * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
     */
    get fetchMethod() {
        return this.#fetchMethod;
    }
    get memoMethod() {
        return this.#memoMethod;
    }
    /**
     * {@link LRUCache.OptionsBase.dispose} (read-only)
     */
    get dispose() {
        return this.#dispose;
    }
    /**
     * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
     */
    get disposeAfter() {
        return this.#disposeAfter;
    }
    constructor(options) {
        const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options;
        if (max !== 0 && !isPosInt(max)) {
            throw new TypeError('max option must be a nonnegative integer');
        }
        const UintArray = max ? getUintArray(max) : Array;
        if (!UintArray) {
            throw new Error('invalid max value: ' + max);
        }
        this.#max = max;
        this.#maxSize = maxSize;
        this.maxEntrySize = maxEntrySize || this.#maxSize;
        this.sizeCalculation = sizeCalculation;
        if (this.sizeCalculation) {
            if (!this.#maxSize && !this.maxEntrySize) {
                throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize');
            }
            if (typeof this.sizeCalculation !== 'function') {
                throw new TypeError('sizeCalculation set to non-function');
            }
        }
        if (memoMethod !== undefined &&
            typeof memoMethod !== 'function') {
            throw new TypeError('memoMethod must be a function if defined');
        }
        this.#memoMethod = memoMethod;
        if (fetchMethod !== undefined &&
            typeof fetchMethod !== 'function') {
            throw new TypeError('fetchMethod must be a function if specified');
        }
        this.#fetchMethod = fetchMethod;
        this.#hasFetchMethod = !!fetchMethod;
        this.#keyMap = new Map();
        this.#keyList = new Array(max).fill(undefined);
        this.#valList = new Array(max).fill(undefined);
        this.#next = new UintArray(max);
        this.#prev = new UintArray(max);
        this.#head = 0;
        this.#tail = 0;
        this.#free = Stack.create(max);
        this.#size = 0;
        this.#calculatedSize = 0;
        if (typeof dispose === 'function') {
            this.#dispose = dispose;
        }
        if (typeof disposeAfter === 'function') {
            this.#disposeAfter = disposeAfter;
            this.#disposed = [];
        }
        else {
            this.#disposeAfter = undefined;
            this.#disposed = undefined;
        }
        this.#hasDispose = !!this.#dispose;
        this.#hasDisposeAfter = !!this.#disposeAfter;
        this.noDisposeOnSet = !!noDisposeOnSet;
        this.noUpdateTTL = !!noUpdateTTL;
        this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
        this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
        this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
        this.ignoreFetchAbort = !!ignoreFetchAbort;
        // NB: maxEntrySize is set to maxSize if it's set
        if (this.maxEntrySize !== 0) {
            if (this.#maxSize !== 0) {
                if (!isPosInt(this.#maxSize)) {
                    throw new TypeError('maxSize must be a positive integer if specified');
                }
            }
            if (!isPosInt(this.maxEntrySize)) {
                throw new TypeError('maxEntrySize must be a positive integer if specified');
            }
            this.#initializeSizeTracking();
        }
        this.allowStale = !!allowStale;
        this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
        this.updateAgeOnGet = !!updateAgeOnGet;
        this.updateAgeOnHas = !!updateAgeOnHas;
        this.ttlResolution =
            isPosInt(ttlResolution) || ttlResolution === 0
                ? ttlResolution
                : 1;
        this.ttlAutopurge = !!ttlAutopurge;
        this.ttl = ttl || 0;
        if (this.ttl) {
            if (!isPosInt(this.ttl)) {
                throw new TypeError('ttl must be a positive integer if specified');
            }
            this.#initializeTTLTracking();
        }
        // do not allow completely unbounded caches
        if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
            throw new TypeError('At least one of max, maxSize, or ttl is required');
        }
        if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
            const code = 'LRU_CACHE_UNBOUNDED';
            if (shouldWarn(code)) {
                warned.add(code);
                const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' +
                    'result in unbounded memory consumption.';
                emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache);
            }
        }
    }
    /**
     * Return the number of ms left in the item's TTL. If item is not in cache,
     * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.
     */
    getRemainingTTL(key) {
        return this.#keyMap.has(key) ? Infinity : 0;
    }
    #initializeTTLTracking() {
        const ttls = new ZeroArray(this.#max);
        const starts = new ZeroArray(this.#max);
        this.#ttls = ttls;
        this.#starts = starts;
        this.#setItemTTL = (index, ttl, start = perf.now()) => {
            starts[index] = ttl !== 0 ? start : 0;
            ttls[index] = ttl;
            if (ttl !== 0 && this.ttlAutopurge) {
                const t = setTimeout(() => {
                    if (this.#isStale(index)) {
                        this.#delete(this.#keyList[index], 'expire');
                    }
                }, ttl + 1);
                // unref() not supported on all platforms
                /* c8 ignore start */
                if (t.unref) {
                    t.unref();
                }
                /* c8 ignore stop */
            }
        };
        this.#updateItemAge = index => {
            starts[index] = ttls[index] !== 0 ? perf.now() : 0;
        };
        this.#statusTTL = (status, index) => {
            if (ttls[index]) {
                const ttl = ttls[index];
                const start = starts[index];
                /* c8 ignore next */
                if (!ttl || !start)
                    return;
                status.ttl = ttl;
                status.start = start;
                status.now = cachedNow || getNow();
                const age = status.now - start;
                status.remainingTTL = ttl - age;
            }
        };
        // debounce calls to perf.now() to 1s so we're not hitting
        // that costly call repeatedly.
        let cachedNow = 0;
        const getNow = () => {
            const n = perf.now();
            if (this.ttlResolution > 0) {
                cachedNow = n;
                const t = setTimeout(() => (cachedNow = 0), this.ttlResolution);
                // not available on all platforms
                /* c8 ignore start */
                if (t.unref) {
                    t.unref();
                }
                /* c8 ignore stop */
            }
            return n;
        };
        this.getRemainingTTL = key => {
            const index = this.#keyMap.get(key);
            if (index === undefined) {
                return 0;
            }
            const ttl = ttls[index];
            const start = starts[index];
            if (!ttl || !start) {
                return Infinity;
            }
            const age = (cachedNow || getNow()) - start;
            return ttl - age;
        };
        this.#isStale = index => {
            const s = starts[index];
            const t = ttls[index];
            return !!t && !!s && (cachedNow || getNow()) - s > t;
        };
    }
    // conditionally set private methods related to TTL
    #updateItemAge = () => { };
    #statusTTL = () => { };
    #setItemTTL = () => { };
    /* c8 ignore stop */
    #isStale = () => false;
    #initializeSizeTracking() {
        const sizes = new ZeroArray(this.#max);
        this.#calculatedSize = 0;
        this.#sizes = sizes;
        this.#removeItemSize = index => {
            this.#calculatedSize -= sizes[index];
            sizes[index] = 0;
        };
        this.#requireSize = (k, v, size, sizeCalculation) => {
            // provisionally accept background fetches.
            // actual value size will be checked when they return.
            if (this.#isBackgroundFetch(v)) {
                return 0;
            }
            if (!isPosInt(size)) {
                if (sizeCalculation) {
                    if (typeof sizeCalculation !== 'function') {
                        throw new TypeError('sizeCalculation must be a function');
                    }
                    size = sizeCalculation(v, k);
                    if (!isPosInt(size)) {
                        throw new TypeError('sizeCalculation return invalid (expect positive integer)');
                    }
                }
                else {
                    throw new TypeError('invalid size value (must be positive integer). ' +
                        'When maxSize or maxEntrySize is used, sizeCalculation ' +
                        'or size must be set.');
                }
            }
            return size;
        };
        this.#addItemSize = (index, size, status) => {
            sizes[index] = size;
            if (this.#maxSize) {
                const maxSize = this.#maxSize - sizes[index];
                while (this.#calculatedSize > maxSize) {
                    this.#evict(true);
                }
            }
            this.#calculatedSize += sizes[index];
            if (status) {
                status.entrySize = size;
                status.totalCalculatedSize = this.#calculatedSize;
            }
        };
    }
    #removeItemSize = _i => { };
    #addItemSize = (_i, _s, _st) => { };
    #requireSize = (_k, _v, size, sizeCalculation) => {
        if (size || sizeCalculation) {
            throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache');
        }
        return 0;
    };
    *#indexes({ allowStale = this.allowStale } = {}) {
        if (this.#size) {
            for (let i = this.#tail; true;) {
                if (!this.#isValidIndex(i)) {
                    break;
                }
                if (allowStale || !this.#isStale(i)) {
                    yield i;
                }
                if (i === this.#head) {
                    break;
                }
                else {
                    i = this.#prev[i];
                }
            }
        }
    }
    *#rindexes({ allowStale = this.allowStale } = {}) {
        if (this.#size) {
            for (let i = this.#head; true;) {
                if (!this.#isValidIndex(i)) {
                    break;
                }
                if (allowStale || !this.#isStale(i)) {
                    yield i;
                }
                if (i === this.#tail) {
                    break;
                }
                else {
                    i = this.#next[i];
                }
            }
        }
    }
    #isValidIndex(index) {
        return (index !== undefined &&
            this.#keyMap.get(this.#keyList[index]) === index);
    }
    /**
     * Return a generator yielding `[key, value]` pairs,
     * in order from most recently used to least recently used.
     */
    *entries() {
        for (const i of this.#indexes()) {
            if (this.#valList[i] !== undefined &&
                this.#keyList[i] !== undefined &&
                !this.#isBackgroundFetch(this.#valList[i])) {
                yield [this.#keyList[i], this.#valList[i]];
            }
        }
    }
    /**
     * Inverse order version of {@link LRUCache.entries}
     *
     * Return a generator yielding `[key, value]` pairs,
     * in order from least recently used to most recently used.
     */
    *rentries() {
        for (const i of this.#rindexes()) {
            if (this.#valList[i] !== undefined &&
                this.#keyList[i] !== undefined &&
                !this.#isBackgroundFetch(this.#valList[i])) {
                yield [this.#keyList[i], this.#valList[i]];
            }
        }
    }
    /**
     * Return a generator yielding the keys in the cache,
     * in order from most recently used to least recently used.
     */
    *keys() {
        for (const i of this.#indexes()) {
            const k = this.#keyList[i];
            if (k !== undefined &&
                !this.#isBackgroundFetch(this.#valList[i])) {
                yield k;
            }
        }
    }
    /**
     * Inverse order version of {@link LRUCache.keys}
     *
     * Return a generator yielding the keys in the cache,
     * in order from least recently used to most recently used.
     */
    *rkeys() {
        for (const i of this.#rindexes()) {
            const k = this.#keyList[i];
            if (k !== undefined &&
                !this.#isBackgroundFetch(this.#valList[i])) {
                yield k;
            }
        }
    }
    /**
     * Return a generator yielding the values in the cache,
     * in order from most recently used to least recently used.
     */
    *values() {
        for (const i of this.#indexes()) {
            const v = this.#valList[i];
            if (v !== undefined &&
                !this.#isBackgroundFetch(this.#valList[i])) {
                yield this.#valList[i];
            }
        }
    }
    /**
     * Inverse order version of {@link LRUCache.values}
     *
     * Return a generator yielding the values in the cache,
     * in order from least recently used to most recently used.
     */
    *rvalues() {
        for (const i of this.#rindexes()) {
            const v = this.#valList[i];
            if (v !== undefined &&
                !this.#isBackgroundFetch(this.#valList[i])) {
                yield this.#valList[i];
            }
        }
    }
    /**
     * Iterating over the cache itself yields the same results as
     * {@link LRUCache.entries}
     */
    [Symbol.iterator]() {
        return this.entries();
    }
    /**
     * A String value that is used in the creation of the default string
     * description of an object. Called by the built-in method
     * `Object.prototype.toString`.
     */
    [Symbol.toStringTag] = 'LRUCache';
    /**
     * Find a value for which the supplied fn method returns a truthy value,
     * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.
     */
    find(fn, getOptions = {}) {
        for (const i of this.#indexes()) {
            const v = this.#valList[i];
            const value = this.#isBackgroundFetch(v)
                ? v.__staleWhileFetching
                : v;
            if (value === undefined)
                continue;
            if (fn(value, this.#keyList[i], this)) {
                return this.get(this.#keyList[i], getOptions);
            }
        }
    }
    /**
     * Call the supplied function on each item in the cache, in order from most
     * recently used to least recently used.
     *
     * `fn` is called as `fn(value, key, cache)`.
     *
     * If `thisp` is provided, function will be called in the `this`-context of
     * the provided object, or the cache if no `thisp` object is provided.
     *
     * Does not update age or recenty of use, or iterate over stale values.
     */
    forEach(fn, thisp = this) {
        for (const i of this.#indexes()) {
            const v = this.#valList[i];
            const value = this.#isBackgroundFetch(v)
                ? v.__staleWhileFetching
                : v;
            if (value === undefined)
                continue;
            fn.call(thisp, value, this.#keyList[i], this);
        }
    }
    /**
     * The same as {@link LRUCache.forEach} but items are iterated over in
     * reverse order.  (ie, less recently used items are iterated over first.)
     */
    rforEach(fn, thisp = this) {
        for (const i of this.#rindexes()) {
            const v = this.#valList[i];
            const value = this.#isBackgroundFetch(v)
                ? v.__staleWhileFetching
                : v;
            if (value === undefined)
                continue;
            fn.call(thisp, value, this.#keyList[i], this);
        }
    }
    /**
     * Delete any stale entries. Returns true if anything was removed,
     * false otherwise.
     */
    purgeStale() {
        let deleted = false;
        for (const i of this.#rindexes({ allowStale: true })) {
            if (this.#isStale(i)) {
                this.#delete(this.#keyList[i], 'expire');
                deleted = true;
            }
        }
        return deleted;
    }
    /**
     * Get the extended info about a given entry, to get its value, size, and
     * TTL info simultaneously. Returns `undefined` if the key is not present.
     *
     * Unlike {@link LRUCache#dump}, which is designed to be portable and survive
     * serialization, the `start` value is always the current timestamp, and the
     * `ttl` is a calculated remaining time to live (negative if expired).
     *
     * Always returns stale values, if their info is found in the cache, so be
     * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})
     * if relevant.
     */
    info(key) {
        const i = this.#keyMap.get(key);
        if (i === undefined)
            return undefined;
        const v = this.#valList[i];
        const value = this.#isBackgroundFetch(v)
            ? v.__staleWhileFetching
            : v;
        if (value === undefined)
            return undefined;
        const entry = { value };
        if (this.#ttls && this.#starts) {
            const ttl = this.#ttls[i];
            const start = this.#starts[i];
            if (ttl && start) {
                const remain = ttl - (perf.now() - start);
                entry.ttl = remain;
                entry.start = Date.now();
            }
        }
        if (this.#sizes) {
            entry.size = this.#sizes[i];
        }
        return entry;
    }
    /**
     * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
     * passed to {@link LRUCache#load}.
     *
     * The `start` fields are calculated relative to a portable `Date.now()`
     * timestamp, even if `performance.now()` is available.
     *
     * Stale entries are always included in the `dump`, even if
     * {@link LRUCache.OptionsBase.allowStale} is false.
     *
     * Note: this returns an actual array, not a generator, so it can be more
     * easily passed around.
     */
    dump() {
        const arr = [];
        for (const i of this.#indexes({ allowStale: true })) {
            const key = this.#keyList[i];
            const v = this.#valList[i];
            const value = this.#isBackgroundFetch(v)
                ? v.__staleWhileFetching
                : v;
            if (value === undefined || key === undefined)
                continue;
            const entry = { value };
            if (this.#ttls && this.#starts) {
                entry.ttl = this.#ttls[i];
                // always dump the start relative to a portable timestamp
                // it's ok for this to be a bit slow, it's a rare operation.
                const age = perf.now() - this.#starts[i];
                entry.start = Math.floor(Date.now() - age);
            }
            if (this.#sizes) {
                entry.size = this.#sizes[i];
            }
            arr.unshift([key, entry]);
        }
        return arr;
    }
    /**
     * Reset the cache and load in the items in entries in the order listed.
     *
     * The shape of the resulting cache may be different if the same options are
     * not used in both caches.
     *
     * The `start` fields are assumed to be calculated relative to a portable
     * `Date.now()` timestamp, even if `performance.now()` is available.
     */
    load(arr) {
        this.clear();
        for (const [key, entry] of arr) {
            if (entry.start) {
                // entry.start is a portable timestamp, but we may be using
                // node's performance.now(), so calculate the offset, so that
                // we get the intended remaining TTL, no matter how long it's
                // been on ice.
                //
                // it's ok for this to be a bit slow, it's a rare operation.
                const age = Date.now() - entry.start;
                entry.start = perf.now() - age;
            }
            this.set(key, entry.value, entry);
        }
    }
    /**
     * Add a value to the cache.
     *
     * Note: if `undefined` is specified as a value, this is an alias for
     * {@link LRUCache#delete}
     *
     * Fields on the {@link LRUCache.SetOptions} options param will override
     * their corresponding values in the constructor options for the scope
     * of this single `set()` operation.
     *
     * If `start` is provided, then that will set the effective start
     * time for the TTL calculation. Note that this must be a previous
     * value of `performance.now()` if supported, or a previous value of
     * `Date.now()` if not.
     *
     * Options object may also include `size`, which will prevent
     * calling the `sizeCalculation` function and just use the specified
     * number if it is a positive integer, and `noDisposeOnSet` which
     * will prevent calling a `dispose` function in the case of
     * overwrites.
     *
     * If the `size` (or return value of `sizeCalculation`) for a given
     * entry is greater than `maxEntrySize`, then the item will not be
     * added to the cache.
     *
     * Will update the recency of the entry.
     *
     * If the value is `undefined`, then this is an alias for
     * `cache.delete(key)`. `undefined` is never stored in the cache.
     */
    set(k, v, setOptions = {}) {
        if (v === undefined) {
            this.delete(k);
            return this;
        }
        const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions;
        let { noUpdateTTL = this.noUpdateTTL } = setOptions;
        const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
        // if the item doesn't fit, don't do anything
        // NB: maxEntrySize set to maxSize by default
        if (this.maxEntrySize && size > this.maxEntrySize) {
            if (status) {
                status.set = 'miss';
                status.maxEntrySizeExceeded = true;
            }
            // have to delete, in case something is there already.
            this.#delete(k, 'set');
            return this;
        }
        let index = this.#size === 0 ? undefined : this.#keyMap.get(k);
        if (index === undefined) {
            // addition
            index = (this.#size === 0
                ? this.#tail
                : this.#free.length !== 0
                    ? this.#free.pop()
                    : this.#size === this.#max
                        ? this.#evict(false)
                        : this.#size);
            this.#keyList[index] = k;
            this.#valList[index] = v;
            this.#keyMap.set(k, index);
            this.#next[this.#tail] = index;
            this.#prev[index] = this.#tail;
            this.#tail = index;
            this.#size++;
            this.#addItemSize(index, size, status);
            if (status)
                status.set = 'add';
            noUpdateTTL = false;
        }
        else {
            // update
            this.#moveToTail(index);
            const oldVal = this.#valList[index];
            if (v !== oldVal) {
                if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
                    oldVal.__abortController.abort(new Error('replaced'));
                    const { __staleWhileFetching: s } = oldVal;
                    if (s !== undefined && !noDisposeOnSet) {
                        if (this.#hasDispose) {
                            this.#dispose?.(s, k, 'set');
                        }
                        if (this.#hasDisposeAfter) {
                            this.#disposed?.push([s, k, 'set']);
                        }
                    }
                }
                else if (!noDisposeOnSet) {
                    if (this.#hasDispose) {
                        this.#dispose?.(oldVal, k, 'set');
                    }
                    if (this.#hasDisposeAfter) {
                        this.#disposed?.push([oldVal, k, 'set']);
                    }
                }
                this.#removeItemSize(index);
                this.#addItemSize(index, size, status);
                this.#valList[index] = v;
                if (status) {
                    status.set = 'replace';
                    const oldValue = oldVal && this.#isBackgroundFetch(oldVal)
                        ? oldVal.__staleWhileFetching
                        : oldVal;
                    if (oldValue !== undefined)
                        status.oldValue = oldValue;
                }
            }
            else if (status) {
                status.set = 'update';
            }
        }
        if (ttl !== 0 && !this.#ttls) {
            this.#initializeTTLTracking();
        }
        if (this.#ttls) {
            if (!noUpdateTTL) {
                this.#setItemTTL(index, ttl, start);
            }
            if (status)
                this.#statusTTL(status, index);
        }
        if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
            const dt = this.#disposed;
            let task;
            while ((task = dt?.shift())) {
                this.#disposeAfter?.(...task);
            }
        }
        return this;
    }
    /**
     * Evict the least recently used item, returning its value or
     * `undefined` if cache is empty.
     */
    pop() {
        try {
            while (this.#size) {
                const val = this.#valList[this.#head];
                this.#evict(true);
                if (this.#isBackgroundFetch(val)) {
                    if (val.__staleWhileFetching) {
                        return val.__staleWhileFetching;
                    }
                }
                else if (val !== undefined) {
                    return val;
                }
            }
        }
        finally {
            if (this.#hasDisposeAfter && this.#disposed) {
                const dt = this.#disposed;
                let task;
                while ((task = dt?.shift())) {
                    this.#disposeAfter?.(...task);
                }
            }
        }
    }
    #evict(free) {
        const head = this.#head;
        const k = this.#keyList[head];
        const v = this.#valList[head];
        if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
            v.__abortController.abort(new Error('evicted'));
        }
        else if (this.#hasDispose || this.#hasDisposeAfter) {
            if (this.#hasDispose) {
                this.#dispose?.(v, k, 'evict');
            }
            if (this.#hasDisposeAfter) {
                this.#disposed?.push([v, k, 'evict']);
            }
        }
        this.#removeItemSize(head);
        // if we aren't about to use the index, then null these out
        if (free) {
            this.#keyList[head] = undefined;
            this.#valList[head] = undefined;
            this.#free.push(head);
        }
        if (this.#size === 1) {
            this.#head = this.#tail = 0;
            this.#free.length = 0;
        }
        else {
            this.#head = this.#next[head];
        }
        this.#keyMap.delete(k);
        this.#size--;
        return head;
    }
    /**
     * Check if a key is in the cache, without updating the recency of use.
     * Will return false if the item is stale, even though it is technically
     * in the cache.
     *
     * Check if a key is in the cache, without updating the recency of
     * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set
     * to `true` in either the options or the constructor.
     *
     * Will return `false` if the item is stale, even though it is technically in
     * the cache. The difference can be determined (if it matters) by using a
     * `status` argument, and inspecting the `has` field.
     *
     * Will not update item age unless
     * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
     */
    has(k, hasOptions = {}) {
        const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
        const index = this.#keyMap.get(k);
        if (index !== undefined) {
            const v = this.#valList[index];
            if (this.#isBackgroundFetch(v) &&
                v.__staleWhileFetching === undefined) {
                return false;
            }
            if (!this.#isStale(index)) {
                if (updateAgeOnHas) {
                    this.#updateItemAge(index);
                }
                if (status) {
                    status.has = 'hit';
                    this.#statusTTL(status, index);
                }
                return true;
            }
            else if (status) {
                status.has = 'stale';
                this.#statusTTL(status, index);
            }
        }
        else if (status) {
            status.has = 'miss';
        }
        return false;
    }
    /**
     * Like {@link LRUCache#get} but doesn't update recency or delete stale
     * items.
     *
     * Returns `undefined` if the item is stale, unless
     * {@link LRUCache.OptionsBase.allowStale} is set.
     */
    peek(k, peekOptions = {}) {
        const { allowStale = this.allowStale } = peekOptions;
        const index = this.#keyMap.get(k);
        if (index === undefined ||
            (!allowStale && this.#isStale(index))) {
            return;
        }
        const v = this.#valList[index];
        // either stale and allowed, or forcing a refresh of non-stale value
        return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
    }
    #backgroundFetch(k, index, options, context) {
        const v = index === undefined ? undefined : this.#valList[index];
        if (this.#isBackgroundFetch(v)) {
            return v;
        }
        const ac = new AC();
        const { signal } = options;
        // when/if our AC signals, then stop listening to theirs.
        signal?.addEventListener('abort', () => ac.abort(signal.reason), {
            signal: ac.signal,
        });
        const fetchOpts = {
            signal: ac.signal,
            options,
            context,
        };
        const cb = (v, updateCache = false) => {
            const { aborted } = ac.signal;
            const ignoreAbort = options.ignoreFetchAbort && v !== undefined;
            if (options.status) {
                if (aborted && !updateCache) {
                    options.status.fetchAborted = true;
                    options.status.fetchError = ac.signal.reason;
                    if (ignoreAbort)
                        options.status.fetchAbortIgnored = true;
                }
                else {
                    options.status.fetchResolved = true;
                }
            }
            if (aborted && !ignoreAbort && !updateCache) {
                return fetchFail(ac.signal.reason);
            }
            // either we didn't abort, and are still here, or we did, and ignored
            const bf = p;
            if (this.#valList[index] === p) {
                if (v === undefined) {
                    if (bf.__staleWhileFetching) {
                        this.#valList[index] = bf.__staleWhileFetching;
                    }
                    else {
                        this.#delete(k, 'fetch');
                    }
                }
                else {
                    if (options.status)
                        options.status.fetchUpdated = true;
                    this.set(k, v, fetchOpts.options);
                }
            }
            return v;
        };
        const eb = (er) => {
            if (options.status) {
                options.status.fetchRejected = true;
                options.status.fetchError = er;
            }
            return fetchFail(er);
        };
        const fetchFail = (er) => {
            const { aborted } = ac.signal;
            const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
            const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
            const noDelete = allowStale || options.noDeleteOnFetchRejection;
            const bf = p;
            if (this.#valList[index] === p) {
                // if we allow stale on fetch rejections, then we need to ensure that
                // the stale value is not removed from the cache when the fetch fails.
                const del = !noDelete || bf.__staleWhileFetching === undefined;
                if (del) {
                    this.#delete(k, 'fetch');
                }
                else if (!allowStaleAborted) {
                    // still replace the *promise* with the stale value,
                    // since we are done with the promise at this point.
                    // leave it untouched if we're still waiting for an
                    // aborted background fetch that hasn't yet returned.
                    this.#valList[index] = bf.__staleWhileFetching;
                }
            }
            if (allowStale) {
                if (options.status && bf.__staleWhileFetching !== undefined) {
                    options.status.returnedStale = true;
                }
                return bf.__staleWhileFetching;
            }
            else if (bf.__returned === bf) {
                throw er;
            }
        };
        const pcall = (res, rej) => {
            const fmp = this.#fetchMethod?.(k, v, fetchOpts);
            if (fmp && fmp instanceof Promise) {
                fmp.then(v => res(v === undefined ? undefined : v), rej);
            }
            // ignored, we go until we finish, regardless.
            // defer check until we are actually aborting,
            // so fetchMethod can override.
            ac.signal.addEventListener('abort', () => {
                if (!options.ignoreFetchAbort ||
                    options.allowStaleOnFetchAbort) {
                    res(undefined);
                    // when it eventually resolves, update the cache.
                    if (options.allowStaleOnFetchAbort) {
                        res = v => cb(v, true);
                    }
                }
            });
        };
        if (options.status)
            options.status.fetchDispatched = true;
        const p = new Promise(pcall).then(cb, eb);
        const bf = Object.assign(p, {
            __abortController: ac,
            __staleWhileFetching: v,
            __returned: undefined,
        });
        if (index === undefined) {
            // internal, don't expose status.
            this.set(k, bf, { ...fetchOpts.options, status: undefined });
            index = this.#keyMap.get(k);
        }
        else {
            this.#valList[index] = bf;
        }
        return bf;
    }
    #isBackgroundFetch(p) {
        if (!this.#hasFetchMethod)
            return false;
        const b = p;
        return (!!b &&
            b instanceof Promise &&
            b.hasOwnProperty('__staleWhileFetching') &&
            b.__abortController instanceof AC);
    }
    async fetch(k, fetchOptions = {}) {
        const { 
        // get options
        allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, 
        // set options
        ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL, 
        // fetch exclusive options
        noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions;
        if (!this.#hasFetchMethod) {
            if (status)
                status.fetch = 'get';
            return this.get(k, {
                allowStale,
                updateAgeOnGet,
                noDeleteOnStaleGet,
                status,
            });
        }
        const options = {
            allowStale,
            updateAgeOnGet,
            noDeleteOnStaleGet,
            ttl,
            noDisposeOnSet,
            size,
            sizeCalculation,
            noUpdateTTL,
            noDeleteOnFetchRejection,
            allowStaleOnFetchRejection,
            allowStaleOnFetchAbort,
            ignoreFetchAbort,
            status,
            signal,
        };
        let index = this.#keyMap.get(k);
        if (index === undefined) {
            if (status)
                status.fetch = 'miss';
            const p = this.#backgroundFetch(k, index, options, context);
            return (p.__returned = p);
        }
        else {
            // in cache, maybe already fetching
            const v = this.#valList[index];
            if (this.#isBackgroundFetch(v)) {
                const stale = allowStale && v.__staleWhileFetching !== undefined;
                if (status) {
                    status.fetch = 'inflight';
                    if (stale)
                        status.returnedStale = true;
                }
                return stale ? v.__staleWhileFetching : (v.__returned = v);
            }
            // if we force a refresh, that means do NOT serve the cached value,
            // unless we are already in the process of refreshing the cache.
            const isStale = this.#isStale(index);
            if (!forceRefresh && !isStale) {
                if (status)
                    status.fetch = 'hit';
                this.#moveToTail(index);
                if (updateAgeOnGet) {
                    this.#updateItemAge(index);
                }
                if (status)
                    this.#statusTTL(status, index);
                return v;
            }
            // ok, it is stale or a forced refresh, and not already fetching.
            // refresh the cache.
            const p = this.#backgroundFetch(k, index, options, context);
            const hasStale = p.__staleWhileFetching !== undefined;
            const staleVal = hasStale && allowStale;
            if (status) {
                status.fetch = isStale ? 'stale' : 'refresh';
                if (staleVal && isStale)
                    status.returnedStale = true;
            }
            return staleVal ? p.__staleWhileFetching : (p.__returned = p);
        }
    }
    async forceFetch(k, fetchOptions = {}) {
        const v = await this.fetch(k, fetchOptions);
        if (v === undefined)
            throw new Error('fetch() returned undefined');
        return v;
    }
    memo(k, memoOptions = {}) {
        const memoMethod = this.#memoMethod;
        if (!memoMethod) {
            throw new Error('no memoMethod provided to constructor');
        }
        const { context, forceRefresh, ...options } = memoOptions;
        const v = this.get(k, options);
        if (!forceRefresh && v !== undefined)
            return v;
        const vv = memoMethod(k, v, {
            options,
            context,
        });
        this.set(k, vv, options);
        return vv;
    }
    /**
     * Return a value from the cache. Will update the recency of the cache
     * entry found.
     *
     * If the key is not found, get() will return `undefined`.
     */
    get(k, getOptions = {}) {
        const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions;
        const index = this.#keyMap.get(k);
        if (index !== undefined) {
            const value = this.#valList[index];
            const fetching = this.#isBackgroundFetch(value);
            if (status)
                this.#statusTTL(status, index);
            if (this.#isStale(index)) {
                if (status)
                    status.get = 'stale';
                // delete only if not an in-flight background fetch
                if (!fetching) {
                    if (!noDeleteOnStaleGet) {
                        this.#delete(k, 'expire');
                    }
                    if (status && allowStale)
                        status.returnedStale = true;
                    return allowStale ? value : undefined;
                }
                else {
                    if (status &&
                        allowStale &&
                        value.__staleWhileFetching !== undefined) {
                        status.returnedStale = true;
                    }
                    return allowStale ? value.__staleWhileFetching : undefined;
                }
            }
            else {
                if (status)
                    status.get = 'hit';
                // if we're currently fetching it, we don't actually have it yet
                // it's not stale, which means this isn't a staleWhileRefetching.
                // If it's not stale, and fetching, AND has a __staleWhileFetching
                // value, then that means the user fetched with {forceRefresh:true},
                // so it's safe to return that value.
                if (fetching) {
                    return value.__staleWhileFetching;
                }
                this.#moveToTail(index);
                if (updateAgeOnGet) {
                    this.#updateItemAge(index);
                }
                return value;
            }
        }
        else if (status) {
            status.get = 'miss';
        }
    }
    #connect(p, n) {
        this.#prev[n] = p;
        this.#next[p] = n;
    }
    #moveToTail(index) {
        // if tail already, nothing to do
        // if head, move head to next[index]
        // else
        //   move next[prev[index]] to next[index] (head has no prev)
        //   move prev[next[index]] to prev[index]
        // prev[index] = tail
        // next[tail] = index
        // tail = index
        if (index !== this.#tail) {
            if (index === this.#head) {
                this.#head = this.#next[index];
            }
            else {
                this.#connect(this.#prev[index], this.#next[index]);
            }
            this.#connect(this.#tail, index);
            this.#tail = index;
        }
    }
    /**
     * Deletes a key out of the cache.
     *
     * Returns true if the key was deleted, false otherwise.
     */
    delete(k) {
        return this.#delete(k, 'delete');
    }
    #delete(k, reason) {
        let deleted = false;
        if (this.#size !== 0) {
            const index = this.#keyMap.get(k);
            if (index !== undefined) {
                deleted = true;
                if (this.#size === 1) {
                    this.#clear(reason);
                }
                else {
                    this.#removeItemSize(index);
                    const v = this.#valList[index];
                    if (this.#isBackgroundFetch(v)) {
                        v.__abortController.abort(new Error('deleted'));
                    }
                    else if (this.#hasDispose || this.#hasDisposeAfter) {
                        if (this.#hasDispose) {
                            this.#dispose?.(v, k, reason);
                        }
                        if (this.#hasDisposeAfter) {
                            this.#disposed?.push([v, k, reason]);
                        }
                    }
                    this.#keyMap.delete(k);
                    this.#keyList[index] = undefined;
                    this.#valList[index] = undefined;
                    if (index === this.#tail) {
                        this.#tail = this.#prev[index];
                    }
                    else if (index === this.#head) {
                        this.#head = this.#next[index];
                    }
                    else {
                        const pi = this.#prev[index];
                        this.#next[pi] = this.#next[index];
                        const ni = this.#next[index];
                        this.#prev[ni] = this.#prev[index];
                    }
                    this.#size--;
                    this.#free.push(index);
                }
            }
        }
        if (this.#hasDisposeAfter && this.#disposed?.length) {
            const dt = this.#disposed;
            let task;
            while ((task = dt?.shift())) {
                this.#disposeAfter?.(...task);
            }
        }
        return deleted;
    }
    /**
     * Clear the cache entirely, throwing away all values.
     */
    clear() {
        return this.#clear('delete');
    }
    #clear(reason) {
        for (const index of this.#rindexes({ allowStale: true })) {
            const v = this.#valList[index];
            if (this.#isBackgroundFetch(v)) {
                v.__abortController.abort(new Error('deleted'));
            }
            else {
                const k = this.#keyList[index];
                if (this.#hasDispose) {
                    this.#dispose?.(v, k, reason);
                }
                if (this.#hasDisposeAfter) {
                    this.#disposed?.push([v, k, reason]);
                }
            }
        }
        this.#keyMap.clear();
        this.#valList.fill(undefined);
        this.#keyList.fill(undefined);
        if (this.#ttls && this.#starts) {
            this.#ttls.fill(0);
            this.#starts.fill(0);
        }
        if (this.#sizes) {
            this.#sizes.fill(0);
        }
        this.#head = 0;
        this.#tail = 0;
        this.#free.length = 0;
        this.#calculatedSize = 0;
        this.#size = 0;
        if (this.#hasDisposeAfter && this.#disposed) {
            const dt = this.#disposed;
            let task;
            while ((task = dt?.shift())) {
                this.#disposeAfter?.(...task);
            }
        }
    }
}


/***/ }),

/***/ 93300:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   yu: () => (/* binding */ fromZodError)
/* harmony export */ });
/* unused harmony exports ValidationError, createMessageBuilder, errorMap, fromError, fromZodIssue, isValidationError, isValidationErrorLike, isZodErrorLike, toValidationError */
/* harmony import */ var zod__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3290);
// lib/isZodErrorLike.ts
function isZodErrorLike(err) {
  return err instanceof Error && err.name === "ZodError" && "issues" in err && Array.isArray(err.issues);
}

// lib/ValidationError.ts
var ValidationError = class extends Error {
  name;
  details;
  constructor(message, options) {
    super(message, options);
    this.name = "ZodValidationError";
    this.details = getIssuesFromErrorOptions(options);
  }
  toString() {
    return this.message;
  }
};
function getIssuesFromErrorOptions(options) {
  if (options) {
    const cause = options.cause;
    if (isZodErrorLike(cause)) {
      return cause.issues;
    }
  }
  return [];
}

// lib/isValidationError.ts
function isValidationError(err) {
  return err instanceof ValidationError;
}

// lib/isValidationErrorLike.ts
function isValidationErrorLike(err) {
  return err instanceof Error && err.name === "ZodValidationError";
}

// lib/fromZodIssue.ts


// lib/MessageBuilder.ts


// lib/utils/NonEmptyArray.ts
function isNonEmptyArray(value) {
  return value.length !== 0;
}

// lib/utils/joinPath.ts
var identifierRegex = /[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u;
function joinPath(path) {
  if (path.length === 1) {
    return path[0].toString();
  }
  return path.reduce((acc, item) => {
    if (typeof item === "number") {
      return acc + "[" + item.toString() + "]";
    }
    if (item.includes('"')) {
      return acc + '["' + escapeQuotes(item) + '"]';
    }
    if (!identifierRegex.test(item)) {
      return acc + '["' + item + '"]';
    }
    const separator = acc.length === 0 ? "" : ".";
    return acc + separator + item;
  }, "");
}
function escapeQuotes(str) {
  return str.replace(/"/g, '\\"');
}

// lib/config.ts
var ISSUE_SEPARATOR = "; ";
var MAX_ISSUES_IN_MESSAGE = 99;
var PREFIX = "Validation error";
var PREFIX_SEPARATOR = ": ";
var UNION_SEPARATOR = ", or ";

// lib/MessageBuilder.ts
function createMessageBuilder(props = {}) {
  const {
    issueSeparator = ISSUE_SEPARATOR,
    unionSeparator = UNION_SEPARATOR,
    prefixSeparator = PREFIX_SEPARATOR,
    prefix = PREFIX,
    includePath = true,
    maxIssuesInMessage = MAX_ISSUES_IN_MESSAGE
  } = props;
  return (issues) => {
    const message = issues.slice(0, maxIssuesInMessage).map(
      (issue) => getMessageFromZodIssue({
        issue,
        issueSeparator,
        unionSeparator,
        includePath
      })
    ).join(issueSeparator);
    return prefixMessage(message, prefix, prefixSeparator);
  };
}
function getMessageFromZodIssue(props) {
  const { issue, issueSeparator, unionSeparator, includePath } = props;
  if (issue.code === zod__WEBPACK_IMPORTED_MODULE_0__/* .ZodIssueCode */ .eq.invalid_union) {
    return issue.unionErrors.reduce((acc, zodError) => {
      const newIssues = zodError.issues.map(
        (issue2) => getMessageFromZodIssue({
          issue: issue2,
          issueSeparator,
          unionSeparator,
          includePath
        })
      ).join(issueSeparator);
      if (!acc.includes(newIssues)) {
        acc.push(newIssues);
      }
      return acc;
    }, []).join(unionSeparator);
  }
  if (issue.code === zod__WEBPACK_IMPORTED_MODULE_0__/* .ZodIssueCode */ .eq.invalid_arguments) {
    return [
      issue.message,
      ...issue.argumentsError.issues.map(
        (issue2) => getMessageFromZodIssue({
          issue: issue2,
          issueSeparator,
          unionSeparator,
          includePath
        })
      )
    ].join(issueSeparator);
  }
  if (issue.code === zod__WEBPACK_IMPORTED_MODULE_0__/* .ZodIssueCode */ .eq.invalid_return_type) {
    return [
      issue.message,
      ...issue.returnTypeError.issues.map(
        (issue2) => getMessageFromZodIssue({
          issue: issue2,
          issueSeparator,
          unionSeparator,
          includePath
        })
      )
    ].join(issueSeparator);
  }
  if (includePath && isNonEmptyArray(issue.path)) {
    if (issue.path.length === 1) {
      const identifier = issue.path[0];
      if (typeof identifier === "number") {
        return `${issue.message} at index ${identifier}`;
      }
    }
    return `${issue.message} at "${joinPath(issue.path)}"`;
  }
  return issue.message;
}
function prefixMessage(message, prefix, prefixSeparator) {
  if (prefix !== null) {
    if (message.length > 0) {
      return [prefix, message].join(prefixSeparator);
    }
    return prefix;
  }
  if (message.length > 0) {
    return message;
  }
  return PREFIX;
}

// lib/fromZodIssue.ts
function fromZodIssue(issue, options = {}) {
  const messageBuilder = createMessageBuilderFromOptions(options);
  const message = messageBuilder([issue]);
  return new ValidationError(message, { cause: new zod2.ZodError([issue]) });
}
function createMessageBuilderFromOptions(options) {
  if ("messageBuilder" in options) {
    return options.messageBuilder;
  }
  return createMessageBuilder(options);
}

// lib/errorMap.ts
var errorMap = (issue, ctx) => {
  const error = fromZodIssue({
    ...issue,
    // fallback to the default error message
    // when issue does not have a message
    message: issue.message ?? ctx.defaultError
  });
  return {
    message: error.message
  };
};

// lib/fromZodError.ts
function fromZodError(zodError, options = {}) {
  if (!isZodErrorLike(zodError)) {
    throw new TypeError(
      `Invalid zodError param; expected instance of ZodError. Did you mean to use the "${fromError.name}" method instead?`
    );
  }
  return fromZodErrorWithoutRuntimeCheck(zodError, options);
}
function fromZodErrorWithoutRuntimeCheck(zodError, options = {}) {
  const zodIssues = zodError.errors;
  let message;
  if (isNonEmptyArray(zodIssues)) {
    const messageBuilder = createMessageBuilderFromOptions2(options);
    message = messageBuilder(zodIssues);
  } else {
    message = zodError.message;
  }
  return new ValidationError(message, { cause: zodError });
}
function createMessageBuilderFromOptions2(options) {
  if ("messageBuilder" in options) {
    return options.messageBuilder;
  }
  return createMessageBuilder(options);
}

// lib/toValidationError.ts
var toValidationError = (options = {}) => (err) => {
  if (isZodErrorLike(err)) {
    return fromZodErrorWithoutRuntimeCheck(err, options);
  }
  if (err instanceof Error) {
    return new ValidationError(err.message, { cause: err });
  }
  return new ValidationError("Unknown error");
};

// lib/fromError.ts
function fromError(err, options = {}) {
  return toValidationError(options)(err);
}

//# sourceMappingURL=index.mjs.map

/***/ }),

/***/ 69509:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Ay: () => (/* binding */ z),
/* harmony export */   G: () => (/* binding */ ZodError),
/* harmony export */   eq: () => (/* binding */ ZodIssueCode)
/* harmony export */ });
/* unused harmony exports BRAND, DIRTY, EMPTY_PATH, INVALID, NEVER, OK, ParseStatus, Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodBranded, ZodCatch, ZodDate, ZodDefault, ZodDiscriminatedUnion, ZodEffects, ZodEnum, ZodFirstPartyTypeKind, ZodFunction, ZodIntersection, ZodLazy, ZodLiteral, ZodMap, ZodNaN, ZodNativeEnum, ZodNever, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodParsedType, ZodPipeline, ZodPromise, ZodRecord, ZodSchema, ZodSet, ZodString, ZodSymbol, ZodTransformer, ZodTuple, ZodType, ZodUndefined, ZodUnion, ZodUnknown, ZodVoid, addIssueToContext, any, array, bigint, boolean, coerce, custom, date, defaultErrorMap, discriminatedUnion, effect, enum, function, getErrorMap, getParsedType, instanceof, intersection, isAborted, isAsync, isDirty, isValid, late, lazy, literal, makeIssue, map, nan, nativeEnum, never, null, nullable, number, object, objectUtil, oboolean, onumber, optional, ostring, pipeline, preprocess, promise, quotelessJson, record, set, setErrorMap, strictObject, string, symbol, transformer, tuple, undefined, union, unknown, util, void, z */
var util;
(function (util) {
    util.assertEqual = (val) => val;
    function assertIs(_arg) { }
    util.assertIs = assertIs;
    function assertNever(_x) {
        throw new Error();
    }
    util.assertNever = assertNever;
    util.arrayToEnum = (items) => {
        const obj = {};
        for (const item of items) {
            obj[item] = item;
        }
        return obj;
    };
    util.getValidEnumValues = (obj) => {
        const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
        const filtered = {};
        for (const k of validKeys) {
            filtered[k] = obj[k];
        }
        return util.objectValues(filtered);
    };
    util.objectValues = (obj) => {
        return util.objectKeys(obj).map(function (e) {
            return obj[e];
        });
    };
    util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
        ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
        : (object) => {
            const keys = [];
            for (const key in object) {
                if (Object.prototype.hasOwnProperty.call(object, key)) {
                    keys.push(key);
                }
            }
            return keys;
        };
    util.find = (arr, checker) => {
        for (const item of arr) {
            if (checker(item))
                return item;
        }
        return undefined;
    };
    util.isInteger = typeof Number.isInteger === "function"
        ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
        : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
    function joinValues(array, separator = " | ") {
        return array
            .map((val) => (typeof val === "string" ? `'${val}'` : val))
            .join(separator);
    }
    util.joinValues = joinValues;
    util.jsonStringifyReplacer = (_, value) => {
        if (typeof value === "bigint") {
            return value.toString();
        }
        return value;
    };
})(util || (util = {}));
var objectUtil;
(function (objectUtil) {
    objectUtil.mergeShapes = (first, second) => {
        return {
            ...first,
            ...second, // second overwrites first
        };
    };
})(objectUtil || (objectUtil = {}));
const ZodParsedType = util.arrayToEnum([
    "string",
    "nan",
    "number",
    "integer",
    "float",
    "boolean",
    "date",
    "bigint",
    "symbol",
    "function",
    "undefined",
    "null",
    "array",
    "object",
    "unknown",
    "promise",
    "void",
    "never",
    "map",
    "set",
]);
const getParsedType = (data) => {
    const t = typeof data;
    switch (t) {
        case "undefined":
            return ZodParsedType.undefined;
        case "string":
            return ZodParsedType.string;
        case "number":
            return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
        case "boolean":
            return ZodParsedType.boolean;
        case "function":
            return ZodParsedType.function;
        case "bigint":
            return ZodParsedType.bigint;
        case "symbol":
            return ZodParsedType.symbol;
        case "object":
            if (Array.isArray(data)) {
                return ZodParsedType.array;
            }
            if (data === null) {
                return ZodParsedType.null;
            }
            if (data.then &&
                typeof data.then === "function" &&
                data.catch &&
                typeof data.catch === "function") {
                return ZodParsedType.promise;
            }
            if (typeof Map !== "undefined" && data instanceof Map) {
                return ZodParsedType.map;
            }
            if (typeof Set !== "undefined" && data instanceof Set) {
                return ZodParsedType.set;
            }
            if (typeof Date !== "undefined" && data instanceof Date) {
                return ZodParsedType.date;
            }
            return ZodParsedType.object;
        default:
            return ZodParsedType.unknown;
    }
};

const ZodIssueCode = util.arrayToEnum([
    "invalid_type",
    "invalid_literal",
    "custom",
    "invalid_union",
    "invalid_union_discriminator",
    "invalid_enum_value",
    "unrecognized_keys",
    "invalid_arguments",
    "invalid_return_type",
    "invalid_date",
    "invalid_string",
    "too_small",
    "too_big",
    "invalid_intersection_types",
    "not_multiple_of",
    "not_finite",
]);
const quotelessJson = (obj) => {
    const json = JSON.stringify(obj, null, 2);
    return json.replace(/"([^"]+)":/g, "$1:");
};
class ZodError extends Error {
    constructor(issues) {
        super();
        this.issues = [];
        this.addIssue = (sub) => {
            this.issues = [...this.issues, sub];
        };
        this.addIssues = (subs = []) => {
            this.issues = [...this.issues, ...subs];
        };
        const actualProto = new.target.prototype;
        if (Object.setPrototypeOf) {
            // eslint-disable-next-line ban/ban
            Object.setPrototypeOf(this, actualProto);
        }
        else {
            this.__proto__ = actualProto;
        }
        this.name = "ZodError";
        this.issues = issues;
    }
    get errors() {
        return this.issues;
    }
    format(_mapper) {
        const mapper = _mapper ||
            function (issue) {
                return issue.message;
            };
        const fieldErrors = { _errors: [] };
        const processError = (error) => {
            for (const issue of error.issues) {
                if (issue.code === "invalid_union") {
                    issue.unionErrors.map(processError);
                }
                else if (issue.code === "invalid_return_type") {
                    processError(issue.returnTypeError);
                }
                else if (issue.code === "invalid_arguments") {
                    processError(issue.argumentsError);
                }
                else if (issue.path.length === 0) {
                    fieldErrors._errors.push(mapper(issue));
                }
                else {
                    let curr = fieldErrors;
                    let i = 0;
                    while (i < issue.path.length) {
                        const el = issue.path[i];
                        const terminal = i === issue.path.length - 1;
                        if (!terminal) {
                            curr[el] = curr[el] || { _errors: [] };
                            // if (typeof el === "string") {
                            //   curr[el] = curr[el] || { _errors: [] };
                            // } else if (typeof el === "number") {
                            //   const errorArray: any = [];
                            //   errorArray._errors = [];
                            //   curr[el] = curr[el] || errorArray;
                            // }
                        }
                        else {
                            curr[el] = curr[el] || { _errors: [] };
                            curr[el]._errors.push(mapper(issue));
                        }
                        curr = curr[el];
                        i++;
                    }
                }
            }
        };
        processError(this);
        return fieldErrors;
    }
    toString() {
        return this.message;
    }
    get message() {
        return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
    }
    get isEmpty() {
        return this.issues.length === 0;
    }
    flatten(mapper = (issue) => issue.message) {
        const fieldErrors = {};
        const formErrors = [];
        for (const sub of this.issues) {
            if (sub.path.length > 0) {
                fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
                fieldErrors[sub.path[0]].push(mapper(sub));
            }
            else {
                formErrors.push(mapper(sub));
            }
        }
        return { formErrors, fieldErrors };
    }
    get formErrors() {
        return this.flatten();
    }
}
ZodError.create = (issues) => {
    const error = new ZodError(issues);
    return error;
};

const errorMap = (issue, _ctx) => {
    let message;
    switch (issue.code) {
        case ZodIssueCode.invalid_type:
            if (issue.received === ZodParsedType.undefined) {
                message = "Required";
            }
            else {
                message = `Expected ${issue.expected}, received ${issue.received}`;
            }
            break;
        case ZodIssueCode.invalid_literal:
            message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
            break;
        case ZodIssueCode.unrecognized_keys:
            message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
            break;
        case ZodIssueCode.invalid_union:
            message = `Invalid input`;
            break;
        case ZodIssueCode.invalid_union_discriminator:
            message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
            break;
        case ZodIssueCode.invalid_enum_value:
            message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
            break;
        case ZodIssueCode.invalid_arguments:
            message = `Invalid function arguments`;
            break;
        case ZodIssueCode.invalid_return_type:
            message = `Invalid function return type`;
            break;
        case ZodIssueCode.invalid_date:
            message = `Invalid date`;
            break;
        case ZodIssueCode.invalid_string:
            if (typeof issue.validation === "object") {
                if ("includes" in issue.validation) {
                    message = `Invalid input: must include "${issue.validation.includes}"`;
                    if (typeof issue.validation.position === "number") {
                        message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
                    }
                }
                else if ("startsWith" in issue.validation) {
                    message = `Invalid input: must start with "${issue.validation.startsWith}"`;
                }
                else if ("endsWith" in issue.validation) {
                    message = `Invalid input: must end with "${issue.validation.endsWith}"`;
                }
                else {
                    util.assertNever(issue.validation);
                }
            }
            else if (issue.validation !== "regex") {
                message = `Invalid ${issue.validation}`;
            }
            else {
                message = "Invalid";
            }
            break;
        case ZodIssueCode.too_small:
            if (issue.type === "array")
                message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
            else if (issue.type === "string")
                message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
            else if (issue.type === "number")
                message = `Number must be ${issue.exact
                    ? `exactly equal to `
                    : issue.inclusive
                        ? `greater than or equal to `
                        : `greater than `}${issue.minimum}`;
            else if (issue.type === "date")
                message = `Date must be ${issue.exact
                    ? `exactly equal to `
                    : issue.inclusive
                        ? `greater than or equal to `
                        : `greater than `}${new Date(Number(issue.minimum))}`;
            else
                message = "Invalid input";
            break;
        case ZodIssueCode.too_big:
            if (issue.type === "array")
                message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
            else if (issue.type === "string")
                message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
            else if (issue.type === "number")
                message = `Number must be ${issue.exact
                    ? `exactly`
                    : issue.inclusive
                        ? `less than or equal to`
                        : `less than`} ${issue.maximum}`;
            else if (issue.type === "bigint")
                message = `BigInt must be ${issue.exact
                    ? `exactly`
                    : issue.inclusive
                        ? `less than or equal to`
                        : `less than`} ${issue.maximum}`;
            else if (issue.type === "date")
                message = `Date must be ${issue.exact
                    ? `exactly`
                    : issue.inclusive
                        ? `smaller than or equal to`
                        : `smaller than`} ${new Date(Number(issue.maximum))}`;
            else
                message = "Invalid input";
            break;
        case ZodIssueCode.custom:
            message = `Invalid input`;
            break;
        case ZodIssueCode.invalid_intersection_types:
            message = `Intersection results could not be merged`;
            break;
        case ZodIssueCode.not_multiple_of:
            message = `Number must be a multiple of ${issue.multipleOf}`;
            break;
        case ZodIssueCode.not_finite:
            message = "Number must be finite";
            break;
        default:
            message = _ctx.defaultError;
            util.assertNever(issue);
    }
    return { message };
};

let overrideErrorMap = errorMap;
function setErrorMap(map) {
    overrideErrorMap = map;
}
function getErrorMap() {
    return overrideErrorMap;
}

const makeIssue = (params) => {
    const { data, path, errorMaps, issueData } = params;
    const fullPath = [...path, ...(issueData.path || [])];
    const fullIssue = {
        ...issueData,
        path: fullPath,
    };
    let errorMessage = "";
    const maps = errorMaps
        .filter((m) => !!m)
        .slice()
        .reverse();
    for (const map of maps) {
        errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
    }
    return {
        ...issueData,
        path: fullPath,
        message: issueData.message || errorMessage,
    };
};
const EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
    const issue = makeIssue({
        issueData: issueData,
        data: ctx.data,
        path: ctx.path,
        errorMaps: [
            ctx.common.contextualErrorMap,
            ctx.schemaErrorMap,
            getErrorMap(),
            errorMap, // then global default map
        ].filter((x) => !!x),
    });
    ctx.common.issues.push(issue);
}
class ParseStatus {
    constructor() {
        this.value = "valid";
    }
    dirty() {
        if (this.value === "valid")
            this.value = "dirty";
    }
    abort() {
        if (this.value !== "aborted")
            this.value = "aborted";
    }
    static mergeArray(status, results) {
        const arrayValue = [];
        for (const s of results) {
            if (s.status === "aborted")
                return INVALID;
            if (s.status === "dirty")
                status.dirty();
            arrayValue.push(s.value);
        }
        return { status: status.value, value: arrayValue };
    }
    static async mergeObjectAsync(status, pairs) {
        const syncPairs = [];
        for (const pair of pairs) {
            syncPairs.push({
                key: await pair.key,
                value: await pair.value,
            });
        }
        return ParseStatus.mergeObjectSync(status, syncPairs);
    }
    static mergeObjectSync(status, pairs) {
        const finalObject = {};
        for (const pair of pairs) {
            const { key, value } = pair;
            if (key.status === "aborted")
                return INVALID;
            if (value.status === "aborted")
                return INVALID;
            if (key.status === "dirty")
                status.dirty();
            if (value.status === "dirty")
                status.dirty();
            if (typeof value.value !== "undefined" || pair.alwaysSet) {
                finalObject[key.value] = value.value;
            }
        }
        return { status: status.value, value: finalObject };
    }
}
const INVALID = Object.freeze({
    status: "aborted",
});
const DIRTY = (value) => ({ status: "dirty", value });
const OK = (value) => ({ status: "valid", value });
const isAborted = (x) => x.status === "aborted";
const isDirty = (x) => x.status === "dirty";
const isValid = (x) => x.status === "valid";
const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;

var errorUtil;
(function (errorUtil) {
    errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
    errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
})(errorUtil || (errorUtil = {}));

class ParseInputLazyPath {
    constructor(parent, value, path, key) {
        this._cachedPath = [];
        this.parent = parent;
        this.data = value;
        this._path = path;
        this._key = key;
    }
    get path() {
        if (!this._cachedPath.length) {
            if (this._key instanceof Array) {
                this._cachedPath.push(...this._path, ...this._key);
            }
            else {
                this._cachedPath.push(...this._path, this._key);
            }
        }
        return this._cachedPath;
    }
}
const handleResult = (ctx, result) => {
    if (isValid(result)) {
        return { success: true, data: result.value };
    }
    else {
        if (!ctx.common.issues.length) {
            throw new Error("Validation failed but no issues detected.");
        }
        return {
            success: false,
            get error() {
                if (this._error)
                    return this._error;
                const error = new ZodError(ctx.common.issues);
                this._error = error;
                return this._error;
            },
        };
    }
};
function processCreateParams(params) {
    if (!params)
        return {};
    const { errorMap, invalid_type_error, required_error, description } = params;
    if (errorMap && (invalid_type_error || required_error)) {
        throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
    }
    if (errorMap)
        return { errorMap: errorMap, description };
    const customMap = (iss, ctx) => {
        if (iss.code !== "invalid_type")
            return { message: ctx.defaultError };
        if (typeof ctx.data === "undefined") {
            return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError };
        }
        return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError };
    };
    return { errorMap: customMap, description };
}
class ZodType {
    constructor(def) {
        /** Alias of safeParseAsync */
        this.spa = this.safeParseAsync;
        this._def = def;
        this.parse = this.parse.bind(this);
        this.safeParse = this.safeParse.bind(this);
        this.parseAsync = this.parseAsync.bind(this);
        this.safeParseAsync = this.safeParseAsync.bind(this);
        this.spa = this.spa.bind(this);
        this.refine = this.refine.bind(this);
        this.refinement = this.refinement.bind(this);
        this.superRefine = this.superRefine.bind(this);
        this.optional = this.optional.bind(this);
        this.nullable = this.nullable.bind(this);
        this.nullish = this.nullish.bind(this);
        this.array = this.array.bind(this);
        this.promise = this.promise.bind(this);
        this.or = this.or.bind(this);
        this.and = this.and.bind(this);
        this.transform = this.transform.bind(this);
        this.brand = this.brand.bind(this);
        this.default = this.default.bind(this);
        this.catch = this.catch.bind(this);
        this.describe = this.describe.bind(this);
        this.pipe = this.pipe.bind(this);
        this.isNullable = this.isNullable.bind(this);
        this.isOptional = this.isOptional.bind(this);
    }
    get description() {
        return this._def.description;
    }
    _getType(input) {
        return getParsedType(input.data);
    }
    _getOrReturnCtx(input, ctx) {
        return (ctx || {
            common: input.parent.common,
            data: input.data,
            parsedType: getParsedType(input.data),
            schemaErrorMap: this._def.errorMap,
            path: input.path,
            parent: input.parent,
        });
    }
    _processInputParams(input) {
        return {
            status: new ParseStatus(),
            ctx: {
                common: input.parent.common,
                data: input.data,
                parsedType: getParsedType(input.data),
                schemaErrorMap: this._def.errorMap,
                path: input.path,
                parent: input.parent,
            },
        };
    }
    _parseSync(input) {
        const result = this._parse(input);
        if (isAsync(result)) {
            throw new Error("Synchronous parse encountered promise.");
        }
        return result;
    }
    _parseAsync(input) {
        const result = this._parse(input);
        return Promise.resolve(result);
    }
    parse(data, params) {
        const result = this.safeParse(data, params);
        if (result.success)
            return result.data;
        throw result.error;
    }
    safeParse(data, params) {
        var _a;
        const ctx = {
            common: {
                issues: [],
                async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
                contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
            },
            path: (params === null || params === void 0 ? void 0 : params.path) || [],
            schemaErrorMap: this._def.errorMap,
            parent: null,
            data,
            parsedType: getParsedType(data),
        };
        const result = this._parseSync({ data, path: ctx.path, parent: ctx });
        return handleResult(ctx, result);
    }
    async parseAsync(data, params) {
        const result = await this.safeParseAsync(data, params);
        if (result.success)
            return result.data;
        throw result.error;
    }
    async safeParseAsync(data, params) {
        const ctx = {
            common: {
                issues: [],
                contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
                async: true,
            },
            path: (params === null || params === void 0 ? void 0 : params.path) || [],
            schemaErrorMap: this._def.errorMap,
            parent: null,
            data,
            parsedType: getParsedType(data),
        };
        const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
        const result = await (isAsync(maybeAsyncResult)
            ? maybeAsyncResult
            : Promise.resolve(maybeAsyncResult));
        return handleResult(ctx, result);
    }
    refine(check, message) {
        const getIssueProperties = (val) => {
            if (typeof message === "string" || typeof message === "undefined") {
                return { message };
            }
            else if (typeof message === "function") {
                return message(val);
            }
            else {
                return message;
            }
        };
        return this._refinement((val, ctx) => {
            const result = check(val);
            const setError = () => ctx.addIssue({
                code: ZodIssueCode.custom,
                ...getIssueProperties(val),
            });
            if (typeof Promise !== "undefined" && result instanceof Promise) {
                return result.then((data) => {
                    if (!data) {
                        setError();
                        return false;
                    }
                    else {
                        return true;
                    }
                });
            }
            if (!result) {
                setError();
                return false;
            }
            else {
                return true;
            }
        });
    }
    refinement(check, refinementData) {
        return this._refinement((val, ctx) => {
            if (!check(val)) {
                ctx.addIssue(typeof refinementData === "function"
                    ? refinementData(val, ctx)
                    : refinementData);
                return false;
            }
            else {
                return true;
            }
        });
    }
    _refinement(refinement) {
        return new ZodEffects({
            schema: this,
            typeName: ZodFirstPartyTypeKind.ZodEffects,
            effect: { type: "refinement", refinement },
        });
    }
    superRefine(refinement) {
        return this._refinement(refinement);
    }
    optional() {
        return ZodOptional.create(this, this._def);
    }
    nullable() {
        return ZodNullable.create(this, this._def);
    }
    nullish() {
        return this.nullable().optional();
    }
    array() {
        return ZodArray.create(this, this._def);
    }
    promise() {
        return ZodPromise.create(this, this._def);
    }
    or(option) {
        return ZodUnion.create([this, option], this._def);
    }
    and(incoming) {
        return ZodIntersection.create(this, incoming, this._def);
    }
    transform(transform) {
        return new ZodEffects({
            ...processCreateParams(this._def),
            schema: this,
            typeName: ZodFirstPartyTypeKind.ZodEffects,
            effect: { type: "transform", transform },
        });
    }
    default(def) {
        const defaultValueFunc = typeof def === "function" ? def : () => def;
        return new ZodDefault({
            ...processCreateParams(this._def),
            innerType: this,
            defaultValue: defaultValueFunc,
            typeName: ZodFirstPartyTypeKind.ZodDefault,
        });
    }
    brand() {
        return new ZodBranded({
            typeName: ZodFirstPartyTypeKind.ZodBranded,
            type: this,
            ...processCreateParams(this._def),
        });
    }
    catch(def) {
        const catchValueFunc = typeof def === "function" ? def : () => def;
        return new ZodCatch({
            ...processCreateParams(this._def),
            innerType: this,
            catchValue: catchValueFunc,
            typeName: ZodFirstPartyTypeKind.ZodCatch,
        });
    }
    describe(description) {
        const This = this.constructor;
        return new This({
            ...this._def,
            description,
        });
    }
    pipe(target) {
        return ZodPipeline.create(this, target);
    }
    isOptional() {
        return this.safeParse(undefined).success;
    }
    isNullable() {
        return this.safeParse(null).success;
    }
}
const cuidRegex = /^c[^\s-]{8,}$/i;
const cuid2Regex = /^[a-z][a-z0-9]*$/;
const ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/;
const uuidRegex = /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
// from https://stackoverflow.com/a/46181/1550155
// old version: too slow, didn't support unicode
// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
//old email regex
// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
// eslint-disable-next-line
const emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
const emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u;
const ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/;
const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
// Adapted from https://stackoverflow.com/a/3143231
const datetimeRegex = (args) => {
    if (args.precision) {
        if (args.offset) {
            return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
        }
        else {
            return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`);
        }
    }
    else if (args.precision === 0) {
        if (args.offset) {
            return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
        }
        else {
            return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`);
        }
    }
    else {
        if (args.offset) {
            return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
        }
        else {
            return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`);
        }
    }
};
function isValidIP(ip, version) {
    if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
        return true;
    }
    if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
        return true;
    }
    return false;
}
class ZodString extends ZodType {
    constructor() {
        super(...arguments);
        this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), {
            validation,
            code: ZodIssueCode.invalid_string,
            ...errorUtil.errToObj(message),
        });
        /**
         * @deprecated Use z.string().min(1) instead.
         * @see {@link ZodString.min}
         */
        this.nonempty = (message) => this.min(1, errorUtil.errToObj(message));
        this.trim = () => new ZodString({
            ...this._def,
            checks: [...this._def.checks, { kind: "trim" }],
        });
        this.toLowerCase = () => new ZodString({
            ...this._def,
            checks: [...this._def.checks, { kind: "toLowerCase" }],
        });
        this.toUpperCase = () => new ZodString({
            ...this._def,
            checks: [...this._def.checks, { kind: "toUpperCase" }],
        });
    }
    _parse(input) {
        if (this._def.coerce) {
            input.data = String(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.string) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.string,
                received: ctx.parsedType,
            }
            //
            );
            return INVALID;
        }
        const status = new ParseStatus();
        let ctx = undefined;
        for (const check of this._def.checks) {
            if (check.kind === "min") {
                if (input.data.length < check.value) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_small,
                        minimum: check.value,
                        type: "string",
                        inclusive: true,
                        exact: false,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "max") {
                if (input.data.length > check.value) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_big,
                        maximum: check.value,
                        type: "string",
                        inclusive: true,
                        exact: false,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "length") {
                const tooBig = input.data.length > check.value;
                const tooSmall = input.data.length < check.value;
                if (tooBig || tooSmall) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    if (tooBig) {
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.too_big,
                            maximum: check.value,
                            type: "string",
                            inclusive: true,
                            exact: true,
                            message: check.message,
                        });
                    }
                    else if (tooSmall) {
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.too_small,
                            minimum: check.value,
                            type: "string",
                            inclusive: true,
                            exact: true,
                            message: check.message,
                        });
                    }
                    status.dirty();
                }
            }
            else if (check.kind === "email") {
                if (!emailRegex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "email",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "emoji") {
                if (!emojiRegex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "emoji",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "uuid") {
                if (!uuidRegex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "uuid",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "cuid") {
                if (!cuidRegex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "cuid",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "cuid2") {
                if (!cuid2Regex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "cuid2",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "ulid") {
                if (!ulidRegex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "ulid",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "url") {
                try {
                    new URL(input.data);
                }
                catch (_a) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "url",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "regex") {
                check.regex.lastIndex = 0;
                const testResult = check.regex.test(input.data);
                if (!testResult) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "regex",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "trim") {
                input.data = input.data.trim();
            }
            else if (check.kind === "includes") {
                if (!input.data.includes(check.value, check.position)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.invalid_string,
                        validation: { includes: check.value, position: check.position },
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "toLowerCase") {
                input.data = input.data.toLowerCase();
            }
            else if (check.kind === "toUpperCase") {
                input.data = input.data.toUpperCase();
            }
            else if (check.kind === "startsWith") {
                if (!input.data.startsWith(check.value)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.invalid_string,
                        validation: { startsWith: check.value },
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "endsWith") {
                if (!input.data.endsWith(check.value)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.invalid_string,
                        validation: { endsWith: check.value },
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "datetime") {
                const regex = datetimeRegex(check);
                if (!regex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.invalid_string,
                        validation: "datetime",
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "ip") {
                if (!isValidIP(input.data, check.version)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "ip",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else {
                util.assertNever(check);
            }
        }
        return { status: status.value, value: input.data };
    }
    _addCheck(check) {
        return new ZodString({
            ...this._def,
            checks: [...this._def.checks, check],
        });
    }
    email(message) {
        return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
    }
    url(message) {
        return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
    }
    emoji(message) {
        return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
    }
    uuid(message) {
        return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
    }
    cuid(message) {
        return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
    }
    cuid2(message) {
        return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
    }
    ulid(message) {
        return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
    }
    ip(options) {
        return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
    }
    datetime(options) {
        var _a;
        if (typeof options === "string") {
            return this._addCheck({
                kind: "datetime",
                precision: null,
                offset: false,
                message: options,
            });
        }
        return this._addCheck({
            kind: "datetime",
            precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
            offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
            ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
        });
    }
    regex(regex, message) {
        return this._addCheck({
            kind: "regex",
            regex: regex,
            ...errorUtil.errToObj(message),
        });
    }
    includes(value, options) {
        return this._addCheck({
            kind: "includes",
            value: value,
            position: options === null || options === void 0 ? void 0 : options.position,
            ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
        });
    }
    startsWith(value, message) {
        return this._addCheck({
            kind: "startsWith",
            value: value,
            ...errorUtil.errToObj(message),
        });
    }
    endsWith(value, message) {
        return this._addCheck({
            kind: "endsWith",
            value: value,
            ...errorUtil.errToObj(message),
        });
    }
    min(minLength, message) {
        return this._addCheck({
            kind: "min",
            value: minLength,
            ...errorUtil.errToObj(message),
        });
    }
    max(maxLength, message) {
        return this._addCheck({
            kind: "max",
            value: maxLength,
            ...errorUtil.errToObj(message),
        });
    }
    length(len, message) {
        return this._addCheck({
            kind: "length",
            value: len,
            ...errorUtil.errToObj(message),
        });
    }
    get isDatetime() {
        return !!this._def.checks.find((ch) => ch.kind === "datetime");
    }
    get isEmail() {
        return !!this._def.checks.find((ch) => ch.kind === "email");
    }
    get isURL() {
        return !!this._def.checks.find((ch) => ch.kind === "url");
    }
    get isEmoji() {
        return !!this._def.checks.find((ch) => ch.kind === "emoji");
    }
    get isUUID() {
        return !!this._def.checks.find((ch) => ch.kind === "uuid");
    }
    get isCUID() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid");
    }
    get isCUID2() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid2");
    }
    get isULID() {
        return !!this._def.checks.find((ch) => ch.kind === "ulid");
    }
    get isIP() {
        return !!this._def.checks.find((ch) => ch.kind === "ip");
    }
    get minLength() {
        let min = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "min") {
                if (min === null || ch.value > min)
                    min = ch.value;
            }
        }
        return min;
    }
    get maxLength() {
        let max = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "max") {
                if (max === null || ch.value < max)
                    max = ch.value;
            }
        }
        return max;
    }
}
ZodString.create = (params) => {
    var _a;
    return new ZodString({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodString,
        coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
        ...processCreateParams(params),
    });
};
// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
function floatSafeRemainder(val, step) {
    const valDecCount = (val.toString().split(".")[1] || "").length;
    const stepDecCount = (step.toString().split(".")[1] || "").length;
    const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
    const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
    const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
    return (valInt % stepInt) / Math.pow(10, decCount);
}
class ZodNumber extends ZodType {
    constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
        this.step = this.multipleOf;
    }
    _parse(input) {
        if (this._def.coerce) {
            input.data = Number(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.number) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.number,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        let ctx = undefined;
        const status = new ParseStatus();
        for (const check of this._def.checks) {
            if (check.kind === "int") {
                if (!util.isInteger(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.invalid_type,
                        expected: "integer",
                        received: "float",
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "min") {
                const tooSmall = check.inclusive
                    ? input.data < check.value
                    : input.data <= check.value;
                if (tooSmall) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_small,
                        minimum: check.value,
                        type: "number",
                        inclusive: check.inclusive,
                        exact: false,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "max") {
                const tooBig = check.inclusive
                    ? input.data > check.value
                    : input.data >= check.value;
                if (tooBig) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_big,
                        maximum: check.value,
                        type: "number",
                        inclusive: check.inclusive,
                        exact: false,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "multipleOf") {
                if (floatSafeRemainder(input.data, check.value) !== 0) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.not_multiple_of,
                        multipleOf: check.value,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "finite") {
                if (!Number.isFinite(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.not_finite,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else {
                util.assertNever(check);
            }
        }
        return { status: status.value, value: input.data };
    }
    gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
    }
    gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
    }
    lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
    }
    lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
    }
    setLimit(kind, value, inclusive, message) {
        return new ZodNumber({
            ...this._def,
            checks: [
                ...this._def.checks,
                {
                    kind,
                    value,
                    inclusive,
                    message: errorUtil.toString(message),
                },
            ],
        });
    }
    _addCheck(check) {
        return new ZodNumber({
            ...this._def,
            checks: [...this._def.checks, check],
        });
    }
    int(message) {
        return this._addCheck({
            kind: "int",
            message: errorUtil.toString(message),
        });
    }
    positive(message) {
        return this._addCheck({
            kind: "min",
            value: 0,
            inclusive: false,
            message: errorUtil.toString(message),
        });
    }
    negative(message) {
        return this._addCheck({
            kind: "max",
            value: 0,
            inclusive: false,
            message: errorUtil.toString(message),
        });
    }
    nonpositive(message) {
        return this._addCheck({
            kind: "max",
            value: 0,
            inclusive: true,
            message: errorUtil.toString(message),
        });
    }
    nonnegative(message) {
        return this._addCheck({
            kind: "min",
            value: 0,
            inclusive: true,
            message: errorUtil.toString(message),
        });
    }
    multipleOf(value, message) {
        return this._addCheck({
            kind: "multipleOf",
            value: value,
            message: errorUtil.toString(message),
        });
    }
    finite(message) {
        return this._addCheck({
            kind: "finite",
            message: errorUtil.toString(message),
        });
    }
    safe(message) {
        return this._addCheck({
            kind: "min",
            inclusive: true,
            value: Number.MIN_SAFE_INTEGER,
            message: errorUtil.toString(message),
        })._addCheck({
            kind: "max",
            inclusive: true,
            value: Number.MAX_SAFE_INTEGER,
            message: errorUtil.toString(message),
        });
    }
    get minValue() {
        let min = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "min") {
                if (min === null || ch.value > min)
                    min = ch.value;
            }
        }
        return min;
    }
    get maxValue() {
        let max = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "max") {
                if (max === null || ch.value < max)
                    max = ch.value;
            }
        }
        return max;
    }
    get isInt() {
        return !!this._def.checks.find((ch) => ch.kind === "int" ||
            (ch.kind === "multipleOf" && util.isInteger(ch.value)));
    }
    get isFinite() {
        let max = null, min = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "finite" ||
                ch.kind === "int" ||
                ch.kind === "multipleOf") {
                return true;
            }
            else if (ch.kind === "min") {
                if (min === null || ch.value > min)
                    min = ch.value;
            }
            else if (ch.kind === "max") {
                if (max === null || ch.value < max)
                    max = ch.value;
            }
        }
        return Number.isFinite(min) && Number.isFinite(max);
    }
}
ZodNumber.create = (params) => {
    return new ZodNumber({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodNumber,
        coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
        ...processCreateParams(params),
    });
};
class ZodBigInt extends ZodType {
    constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
    }
    _parse(input) {
        if (this._def.coerce) {
            input.data = BigInt(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.bigint) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.bigint,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        let ctx = undefined;
        const status = new ParseStatus();
        for (const check of this._def.checks) {
            if (check.kind === "min") {
                const tooSmall = check.inclusive
                    ? input.data < check.value
                    : input.data <= check.value;
                if (tooSmall) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_small,
                        type: "bigint",
                        minimum: check.value,
                        inclusive: check.inclusive,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "max") {
                const tooBig = check.inclusive
                    ? input.data > check.value
                    : input.data >= check.value;
                if (tooBig) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_big,
                        type: "bigint",
                        maximum: check.value,
                        inclusive: check.inclusive,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "multipleOf") {
                if (input.data % check.value !== BigInt(0)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.not_multiple_of,
                        multipleOf: check.value,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else {
                util.assertNever(check);
            }
        }
        return { status: status.value, value: input.data };
    }
    gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
    }
    gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
    }
    lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
    }
    lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
    }
    setLimit(kind, value, inclusive, message) {
        return new ZodBigInt({
            ...this._def,
            checks: [
                ...this._def.checks,
                {
                    kind,
                    value,
                    inclusive,
                    message: errorUtil.toString(message),
                },
            ],
        });
    }
    _addCheck(check) {
        return new ZodBigInt({
            ...this._def,
            checks: [...this._def.checks, check],
        });
    }
    positive(message) {
        return this._addCheck({
            kind: "min",
            value: BigInt(0),
            inclusive: false,
            message: errorUtil.toString(message),
        });
    }
    negative(message) {
        return this._addCheck({
            kind: "max",
            value: BigInt(0),
            inclusive: false,
            message: errorUtil.toString(message),
        });
    }
    nonpositive(message) {
        return this._addCheck({
            kind: "max",
            value: BigInt(0),
            inclusive: true,
            message: errorUtil.toString(message),
        });
    }
    nonnegative(message) {
        return this._addCheck({
            kind: "min",
            value: BigInt(0),
            inclusive: true,
            message: errorUtil.toString(message),
        });
    }
    multipleOf(value, message) {
        return this._addCheck({
            kind: "multipleOf",
            value,
            message: errorUtil.toString(message),
        });
    }
    get minValue() {
        let min = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "min") {
                if (min === null || ch.value > min)
                    min = ch.value;
            }
        }
        return min;
    }
    get maxValue() {
        let max = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "max") {
                if (max === null || ch.value < max)
                    max = ch.value;
            }
        }
        return max;
    }
}
ZodBigInt.create = (params) => {
    var _a;
    return new ZodBigInt({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodBigInt,
        coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
        ...processCreateParams(params),
    });
};
class ZodBoolean extends ZodType {
    _parse(input) {
        if (this._def.coerce) {
            input.data = Boolean(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.boolean) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.boolean,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        return OK(input.data);
    }
}
ZodBoolean.create = (params) => {
    return new ZodBoolean({
        typeName: ZodFirstPartyTypeKind.ZodBoolean,
        coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
        ...processCreateParams(params),
    });
};
class ZodDate extends ZodType {
    _parse(input) {
        if (this._def.coerce) {
            input.data = new Date(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.date) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.date,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        if (isNaN(input.data.getTime())) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_date,
            });
            return INVALID;
        }
        const status = new ParseStatus();
        let ctx = undefined;
        for (const check of this._def.checks) {
            if (check.kind === "min") {
                if (input.data.getTime() < check.value) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_small,
                        message: check.message,
                        inclusive: true,
                        exact: false,
                        minimum: check.value,
                        type: "date",
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "max") {
                if (input.data.getTime() > check.value) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_big,
                        message: check.message,
                        inclusive: true,
                        exact: false,
                        maximum: check.value,
                        type: "date",
                    });
                    status.dirty();
                }
            }
            else {
                util.assertNever(check);
            }
        }
        return {
            status: status.value,
            value: new Date(input.data.getTime()),
        };
    }
    _addCheck(check) {
        return new ZodDate({
            ...this._def,
            checks: [...this._def.checks, check],
        });
    }
    min(minDate, message) {
        return this._addCheck({
            kind: "min",
            value: minDate.getTime(),
            message: errorUtil.toString(message),
        });
    }
    max(maxDate, message) {
        return this._addCheck({
            kind: "max",
            value: maxDate.getTime(),
            message: errorUtil.toString(message),
        });
    }
    get minDate() {
        let min = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "min") {
                if (min === null || ch.value > min)
                    min = ch.value;
            }
        }
        return min != null ? new Date(min) : null;
    }
    get maxDate() {
        let max = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "max") {
                if (max === null || ch.value < max)
                    max = ch.value;
            }
        }
        return max != null ? new Date(max) : null;
    }
}
ZodDate.create = (params) => {
    return new ZodDate({
        checks: [],
        coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
        typeName: ZodFirstPartyTypeKind.ZodDate,
        ...processCreateParams(params),
    });
};
class ZodSymbol extends ZodType {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.symbol) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.symbol,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        return OK(input.data);
    }
}
ZodSymbol.create = (params) => {
    return new ZodSymbol({
        typeName: ZodFirstPartyTypeKind.ZodSymbol,
        ...processCreateParams(params),
    });
};
class ZodUndefined extends ZodType {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.undefined) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.undefined,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        return OK(input.data);
    }
}
ZodUndefined.create = (params) => {
    return new ZodUndefined({
        typeName: ZodFirstPartyTypeKind.ZodUndefined,
        ...processCreateParams(params),
    });
};
class ZodNull extends ZodType {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.null) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.null,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        return OK(input.data);
    }
}
ZodNull.create = (params) => {
    return new ZodNull({
        typeName: ZodFirstPartyTypeKind.ZodNull,
        ...processCreateParams(params),
    });
};
class ZodAny extends ZodType {
    constructor() {
        super(...arguments);
        // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
        this._any = true;
    }
    _parse(input) {
        return OK(input.data);
    }
}
ZodAny.create = (params) => {
    return new ZodAny({
        typeName: ZodFirstPartyTypeKind.ZodAny,
        ...processCreateParams(params),
    });
};
class ZodUnknown extends ZodType {
    constructor() {
        super(...arguments);
        // required
        this._unknown = true;
    }
    _parse(input) {
        return OK(input.data);
    }
}
ZodUnknown.create = (params) => {
    return new ZodUnknown({
        typeName: ZodFirstPartyTypeKind.ZodUnknown,
        ...processCreateParams(params),
    });
};
class ZodNever extends ZodType {
    _parse(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.never,
            received: ctx.parsedType,
        });
        return INVALID;
    }
}
ZodNever.create = (params) => {
    return new ZodNever({
        typeName: ZodFirstPartyTypeKind.ZodNever,
        ...processCreateParams(params),
    });
};
class ZodVoid extends ZodType {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.undefined) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.void,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        return OK(input.data);
    }
}
ZodVoid.create = (params) => {
    return new ZodVoid({
        typeName: ZodFirstPartyTypeKind.ZodVoid,
        ...processCreateParams(params),
    });
};
class ZodArray extends ZodType {
    _parse(input) {
        const { ctx, status } = this._processInputParams(input);
        const def = this._def;
        if (ctx.parsedType !== ZodParsedType.array) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.array,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        if (def.exactLength !== null) {
            const tooBig = ctx.data.length > def.exactLength.value;
            const tooSmall = ctx.data.length < def.exactLength.value;
            if (tooBig || tooSmall) {
                addIssueToContext(ctx, {
                    code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
                    minimum: (tooSmall ? def.exactLength.value : undefined),
                    maximum: (tooBig ? def.exactLength.value : undefined),
                    type: "array",
                    inclusive: true,
                    exact: true,
                    message: def.exactLength.message,
                });
                status.dirty();
            }
        }
        if (def.minLength !== null) {
            if (ctx.data.length < def.minLength.value) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.too_small,
                    minimum: def.minLength.value,
                    type: "array",
                    inclusive: true,
                    exact: false,
                    message: def.minLength.message,
                });
                status.dirty();
            }
        }
        if (def.maxLength !== null) {
            if (ctx.data.length > def.maxLength.value) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.too_big,
                    maximum: def.maxLength.value,
                    type: "array",
                    inclusive: true,
                    exact: false,
                    message: def.maxLength.message,
                });
                status.dirty();
            }
        }
        if (ctx.common.async) {
            return Promise.all([...ctx.data].map((item, i) => {
                return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
            })).then((result) => {
                return ParseStatus.mergeArray(status, result);
            });
        }
        const result = [...ctx.data].map((item, i) => {
            return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
        });
        return ParseStatus.mergeArray(status, result);
    }
    get element() {
        return this._def.type;
    }
    min(minLength, message) {
        return new ZodArray({
            ...this._def,
            minLength: { value: minLength, message: errorUtil.toString(message) },
        });
    }
    max(maxLength, message) {
        return new ZodArray({
            ...this._def,
            maxLength: { value: maxLength, message: errorUtil.toString(message) },
        });
    }
    length(len, message) {
        return new ZodArray({
            ...this._def,
            exactLength: { value: len, message: errorUtil.toString(message) },
        });
    }
    nonempty(message) {
        return this.min(1, message);
    }
}
ZodArray.create = (schema, params) => {
    return new ZodArray({
        type: schema,
        minLength: null,
        maxLength: null,
        exactLength: null,
        typeName: ZodFirstPartyTypeKind.ZodArray,
        ...processCreateParams(params),
    });
};
function deepPartialify(schema) {
    if (schema instanceof ZodObject) {
        const newShape = {};
        for (const key in schema.shape) {
            const fieldSchema = schema.shape[key];
            newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
        }
        return new ZodObject({
            ...schema._def,
            shape: () => newShape,
        });
    }
    else if (schema instanceof ZodArray) {
        return new ZodArray({
            ...schema._def,
            type: deepPartialify(schema.element),
        });
    }
    else if (schema instanceof ZodOptional) {
        return ZodOptional.create(deepPartialify(schema.unwrap()));
    }
    else if (schema instanceof ZodNullable) {
        return ZodNullable.create(deepPartialify(schema.unwrap()));
    }
    else if (schema instanceof ZodTuple) {
        return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
    }
    else {
        return schema;
    }
}
class ZodObject extends ZodType {
    constructor() {
        super(...arguments);
        this._cached = null;
        /**
         * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
         * If you want to pass through unknown properties, use `.passthrough()` instead.
         */
        this.nonstrict = this.passthrough;
        // extend<
        //   Augmentation extends ZodRawShape,
        //   NewOutput extends util.flatten<{
        //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
        //       ? Augmentation[k]["_output"]
        //       : k extends keyof Output
        //       ? Output[k]
        //       : never;
        //   }>,
        //   NewInput extends util.flatten<{
        //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
        //       ? Augmentation[k]["_input"]
        //       : k extends keyof Input
        //       ? Input[k]
        //       : never;
        //   }>
        // >(
        //   augmentation: Augmentation
        // ): ZodObject<
        //   extendShape<T, Augmentation>,
        //   UnknownKeys,
        //   Catchall,
        //   NewOutput,
        //   NewInput
        // > {
        //   return new ZodObject({
        //     ...this._def,
        //     shape: () => ({
        //       ...this._def.shape(),
        //       ...augmentation,
        //     }),
        //   }) as any;
        // }
        /**
         * @deprecated Use `.extend` instead
         *  */
        this.augment = this.extend;
    }
    _getCached() {
        if (this._cached !== null)
            return this._cached;
        const shape = this._def.shape();
        const keys = util.objectKeys(shape);
        return (this._cached = { shape, keys });
    }
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.object) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.object,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        const { status, ctx } = this._processInputParams(input);
        const { shape, keys: shapeKeys } = this._getCached();
        const extraKeys = [];
        if (!(this._def.catchall instanceof ZodNever &&
            this._def.unknownKeys === "strip")) {
            for (const key in ctx.data) {
                if (!shapeKeys.includes(key)) {
                    extraKeys.push(key);
                }
            }
        }
        const pairs = [];
        for (const key of shapeKeys) {
            const keyValidator = shape[key];
            const value = ctx.data[key];
            pairs.push({
                key: { status: "valid", value: key },
                value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
                alwaysSet: key in ctx.data,
            });
        }
        if (this._def.catchall instanceof ZodNever) {
            const unknownKeys = this._def.unknownKeys;
            if (unknownKeys === "passthrough") {
                for (const key of extraKeys) {
                    pairs.push({
                        key: { status: "valid", value: key },
                        value: { status: "valid", value: ctx.data[key] },
                    });
                }
            }
            else if (unknownKeys === "strict") {
                if (extraKeys.length > 0) {
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.unrecognized_keys,
                        keys: extraKeys,
                    });
                    status.dirty();
                }
            }
            else if (unknownKeys === "strip") ;
            else {
                throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
            }
        }
        else {
            // run catchall validation
            const catchall = this._def.catchall;
            for (const key of extraKeys) {
                const value = ctx.data[key];
                pairs.push({
                    key: { status: "valid", value: key },
                    value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)
                    ),
                    alwaysSet: key in ctx.data,
                });
            }
        }
        if (ctx.common.async) {
            return Promise.resolve()
                .then(async () => {
                const syncPairs = [];
                for (const pair of pairs) {
                    const key = await pair.key;
                    syncPairs.push({
                        key,
                        value: await pair.value,
                        alwaysSet: pair.alwaysSet,
                    });
                }
                return syncPairs;
            })
                .then((syncPairs) => {
                return ParseStatus.mergeObjectSync(status, syncPairs);
            });
        }
        else {
            return ParseStatus.mergeObjectSync(status, pairs);
        }
    }
    get shape() {
        return this._def.shape();
    }
    strict(message) {
        errorUtil.errToObj;
        return new ZodObject({
            ...this._def,
            unknownKeys: "strict",
            ...(message !== undefined
                ? {
                    errorMap: (issue, ctx) => {
                        var _a, _b, _c, _d;
                        const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
                        if (issue.code === "unrecognized_keys")
                            return {
                                message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,
                            };
                        return {
                            message: defaultError,
                        };
                    },
                }
                : {}),
        });
    }
    strip() {
        return new ZodObject({
            ...this._def,
            unknownKeys: "strip",
        });
    }
    passthrough() {
        return new ZodObject({
            ...this._def,
            unknownKeys: "passthrough",
        });
    }
    // const AugmentFactory =
    //   <Def extends ZodObjectDef>(def: Def) =>
    //   <Augmentation extends ZodRawShape>(
    //     augmentation: Augmentation
    //   ): ZodObject<
    //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
    //     Def["unknownKeys"],
    //     Def["catchall"]
    //   > => {
    //     return new ZodObject({
    //       ...def,
    //       shape: () => ({
    //         ...def.shape(),
    //         ...augmentation,
    //       }),
    //     }) as any;
    //   };
    extend(augmentation) {
        return new ZodObject({
            ...this._def,
            shape: () => ({
                ...this._def.shape(),
                ...augmentation,
            }),
        });
    }
    /**
     * Prior to zod@1.0.12 there was a bug in the
     * inferred type of merged objects. Please
     * upgrade if you are experiencing issues.
     */
    merge(merging) {
        const merged = new ZodObject({
            unknownKeys: merging._def.unknownKeys,
            catchall: merging._def.catchall,
            shape: () => ({
                ...this._def.shape(),
                ...merging._def.shape(),
            }),
            typeName: ZodFirstPartyTypeKind.ZodObject,
        });
        return merged;
    }
    // merge<
    //   Incoming extends AnyZodObject,
    //   Augmentation extends Incoming["shape"],
    //   NewOutput extends {
    //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
    //       ? Augmentation[k]["_output"]
    //       : k extends keyof Output
    //       ? Output[k]
    //       : never;
    //   },
    //   NewInput extends {
    //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
    //       ? Augmentation[k]["_input"]
    //       : k extends keyof Input
    //       ? Input[k]
    //       : never;
    //   }
    // >(
    //   merging: Incoming
    // ): ZodObject<
    //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
    //   Incoming["_def"]["unknownKeys"],
    //   Incoming["_def"]["catchall"],
    //   NewOutput,
    //   NewInput
    // > {
    //   const merged: any = new ZodObject({
    //     unknownKeys: merging._def.unknownKeys,
    //     catchall: merging._def.catchall,
    //     shape: () =>
    //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
    //     typeName: ZodFirstPartyTypeKind.ZodObject,
    //   }) as any;
    //   return merged;
    // }
    setKey(key, schema) {
        return this.augment({ [key]: schema });
    }
    // merge<Incoming extends AnyZodObject>(
    //   merging: Incoming
    // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
    // ZodObject<
    //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
    //   Incoming["_def"]["unknownKeys"],
    //   Incoming["_def"]["catchall"]
    // > {
    //   // const mergedShape = objectUtil.mergeShapes(
    //   //   this._def.shape(),
    //   //   merging._def.shape()
    //   // );
    //   const merged: any = new ZodObject({
    //     unknownKeys: merging._def.unknownKeys,
    //     catchall: merging._def.catchall,
    //     shape: () =>
    //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
    //     typeName: ZodFirstPartyTypeKind.ZodObject,
    //   }) as any;
    //   return merged;
    // }
    catchall(index) {
        return new ZodObject({
            ...this._def,
            catchall: index,
        });
    }
    pick(mask) {
        const shape = {};
        util.objectKeys(mask).forEach((key) => {
            if (mask[key] && this.shape[key]) {
                shape[key] = this.shape[key];
            }
        });
        return new ZodObject({
            ...this._def,
            shape: () => shape,
        });
    }
    omit(mask) {
        const shape = {};
        util.objectKeys(this.shape).forEach((key) => {
            if (!mask[key]) {
                shape[key] = this.shape[key];
            }
        });
        return new ZodObject({
            ...this._def,
            shape: () => shape,
        });
    }
    /**
     * @deprecated
     */
    deepPartial() {
        return deepPartialify(this);
    }
    partial(mask) {
        const newShape = {};
        util.objectKeys(this.shape).forEach((key) => {
            const fieldSchema = this.shape[key];
            if (mask && !mask[key]) {
                newShape[key] = fieldSchema;
            }
            else {
                newShape[key] = fieldSchema.optional();
            }
        });
        return new ZodObject({
            ...this._def,
            shape: () => newShape,
        });
    }
    required(mask) {
        const newShape = {};
        util.objectKeys(this.shape).forEach((key) => {
            if (mask && !mask[key]) {
                newShape[key] = this.shape[key];
            }
            else {
                const fieldSchema = this.shape[key];
                let newField = fieldSchema;
                while (newField instanceof ZodOptional) {
                    newField = newField._def.innerType;
                }
                newShape[key] = newField;
            }
        });
        return new ZodObject({
            ...this._def,
            shape: () => newShape,
        });
    }
    keyof() {
        return createZodEnum(util.objectKeys(this.shape));
    }
}
ZodObject.create = (shape, params) => {
    return new ZodObject({
        shape: () => shape,
        unknownKeys: "strip",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params),
    });
};
ZodObject.strictCreate = (shape, params) => {
    return new ZodObject({
        shape: () => shape,
        unknownKeys: "strict",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params),
    });
};
ZodObject.lazycreate = (shape, params) => {
    return new ZodObject({
        shape,
        unknownKeys: "strip",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params),
    });
};
class ZodUnion extends ZodType {
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        const options = this._def.options;
        function handleResults(results) {
            // return first issue-free validation if it exists
            for (const result of results) {
                if (result.result.status === "valid") {
                    return result.result;
                }
            }
            for (const result of results) {
                if (result.result.status === "dirty") {
                    // add issues from dirty option
                    ctx.common.issues.push(...result.ctx.common.issues);
                    return result.result;
                }
            }
            // return invalid
            const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_union,
                unionErrors,
            });
            return INVALID;
        }
        if (ctx.common.async) {
            return Promise.all(options.map(async (option) => {
                const childCtx = {
                    ...ctx,
                    common: {
                        ...ctx.common,
                        issues: [],
                    },
                    parent: null,
                };
                return {
                    result: await option._parseAsync({
                        data: ctx.data,
                        path: ctx.path,
                        parent: childCtx,
                    }),
                    ctx: childCtx,
                };
            })).then(handleResults);
        }
        else {
            let dirty = undefined;
            const issues = [];
            for (const option of options) {
                const childCtx = {
                    ...ctx,
                    common: {
                        ...ctx.common,
                        issues: [],
                    },
                    parent: null,
                };
                const result = option._parseSync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: childCtx,
                });
                if (result.status === "valid") {
                    return result;
                }
                else if (result.status === "dirty" && !dirty) {
                    dirty = { result, ctx: childCtx };
                }
                if (childCtx.common.issues.length) {
                    issues.push(childCtx.common.issues);
                }
            }
            if (dirty) {
                ctx.common.issues.push(...dirty.ctx.common.issues);
                return dirty.result;
            }
            const unionErrors = issues.map((issues) => new ZodError(issues));
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_union,
                unionErrors,
            });
            return INVALID;
        }
    }
    get options() {
        return this._def.options;
    }
}
ZodUnion.create = (types, params) => {
    return new ZodUnion({
        options: types,
        typeName: ZodFirstPartyTypeKind.ZodUnion,
        ...processCreateParams(params),
    });
};
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//////////                                 //////////
//////////      ZodDiscriminatedUnion      //////////
//////////                                 //////////
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
const getDiscriminator = (type) => {
    if (type instanceof ZodLazy) {
        return getDiscriminator(type.schema);
    }
    else if (type instanceof ZodEffects) {
        return getDiscriminator(type.innerType());
    }
    else if (type instanceof ZodLiteral) {
        return [type.value];
    }
    else if (type instanceof ZodEnum) {
        return type.options;
    }
    else if (type instanceof ZodNativeEnum) {
        // eslint-disable-next-line ban/ban
        return Object.keys(type.enum);
    }
    else if (type instanceof ZodDefault) {
        return getDiscriminator(type._def.innerType);
    }
    else if (type instanceof ZodUndefined) {
        return [undefined];
    }
    else if (type instanceof ZodNull) {
        return [null];
    }
    else {
        return null;
    }
};
class ZodDiscriminatedUnion extends ZodType {
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.object,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        const discriminator = this.discriminator;
        const discriminatorValue = ctx.data[discriminator];
        const option = this.optionsMap.get(discriminatorValue);
        if (!option) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_union_discriminator,
                options: Array.from(this.optionsMap.keys()),
                path: [discriminator],
            });
            return INVALID;
        }
        if (ctx.common.async) {
            return option._parseAsync({
                data: ctx.data,
                path: ctx.path,
                parent: ctx,
            });
        }
        else {
            return option._parseSync({
                data: ctx.data,
                path: ctx.path,
                parent: ctx,
            });
        }
    }
    get discriminator() {
        return this._def.discriminator;
    }
    get options() {
        return this._def.options;
    }
    get optionsMap() {
        return this._def.optionsMap;
    }
    /**
     * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
     * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
     * have a different value for each object in the union.
     * @param discriminator the name of the discriminator property
     * @param types an array of object schemas
     * @param params
     */
    static create(discriminator, options, params) {
        // Get all the valid discriminator values
        const optionsMap = new Map();
        // try {
        for (const type of options) {
            const discriminatorValues = getDiscriminator(type.shape[discriminator]);
            if (!discriminatorValues) {
                throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
            }
            for (const value of discriminatorValues) {
                if (optionsMap.has(value)) {
                    throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
                }
                optionsMap.set(value, type);
            }
        }
        return new ZodDiscriminatedUnion({
            typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
            discriminator,
            options,
            optionsMap,
            ...processCreateParams(params),
        });
    }
}
function mergeValues(a, b) {
    const aType = getParsedType(a);
    const bType = getParsedType(b);
    if (a === b) {
        return { valid: true, data: a };
    }
    else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
        const bKeys = util.objectKeys(b);
        const sharedKeys = util
            .objectKeys(a)
            .filter((key) => bKeys.indexOf(key) !== -1);
        const newObj = { ...a, ...b };
        for (const key of sharedKeys) {
            const sharedValue = mergeValues(a[key], b[key]);
            if (!sharedValue.valid) {
                return { valid: false };
            }
            newObj[key] = sharedValue.data;
        }
        return { valid: true, data: newObj };
    }
    else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
        if (a.length !== b.length) {
            return { valid: false };
        }
        const newArray = [];
        for (let index = 0; index < a.length; index++) {
            const itemA = a[index];
            const itemB = b[index];
            const sharedValue = mergeValues(itemA, itemB);
            if (!sharedValue.valid) {
                return { valid: false };
            }
            newArray.push(sharedValue.data);
        }
        return { valid: true, data: newArray };
    }
    else if (aType === ZodParsedType.date &&
        bType === ZodParsedType.date &&
        +a === +b) {
        return { valid: true, data: a };
    }
    else {
        return { valid: false };
    }
}
class ZodIntersection extends ZodType {
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const handleParsed = (parsedLeft, parsedRight) => {
            if (isAborted(parsedLeft) || isAborted(parsedRight)) {
                return INVALID;
            }
            const merged = mergeValues(parsedLeft.value, parsedRight.value);
            if (!merged.valid) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_intersection_types,
                });
                return INVALID;
            }
            if (isDirty(parsedLeft) || isDirty(parsedRight)) {
                status.dirty();
            }
            return { status: status.value, value: merged.data };
        };
        if (ctx.common.async) {
            return Promise.all([
                this._def.left._parseAsync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                }),
                this._def.right._parseAsync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                }),
            ]).then(([left, right]) => handleParsed(left, right));
        }
        else {
            return handleParsed(this._def.left._parseSync({
                data: ctx.data,
                path: ctx.path,
                parent: ctx,
            }), this._def.right._parseSync({
                data: ctx.data,
                path: ctx.path,
                parent: ctx,
            }));
        }
    }
}
ZodIntersection.create = (left, right, params) => {
    return new ZodIntersection({
        left: left,
        right: right,
        typeName: ZodFirstPartyTypeKind.ZodIntersection,
        ...processCreateParams(params),
    });
};
class ZodTuple extends ZodType {
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.array) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.array,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        if (ctx.data.length < this._def.items.length) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: this._def.items.length,
                inclusive: true,
                exact: false,
                type: "array",
            });
            return INVALID;
        }
        const rest = this._def.rest;
        if (!rest && ctx.data.length > this._def.items.length) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: this._def.items.length,
                inclusive: true,
                exact: false,
                type: "array",
            });
            status.dirty();
        }
        const items = [...ctx.data]
            .map((item, itemIndex) => {
            const schema = this._def.items[itemIndex] || this._def.rest;
            if (!schema)
                return null;
            return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
        })
            .filter((x) => !!x); // filter nulls
        if (ctx.common.async) {
            return Promise.all(items).then((results) => {
                return ParseStatus.mergeArray(status, results);
            });
        }
        else {
            return ParseStatus.mergeArray(status, items);
        }
    }
    get items() {
        return this._def.items;
    }
    rest(rest) {
        return new ZodTuple({
            ...this._def,
            rest,
        });
    }
}
ZodTuple.create = (schemas, params) => {
    if (!Array.isArray(schemas)) {
        throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
    }
    return new ZodTuple({
        items: schemas,
        typeName: ZodFirstPartyTypeKind.ZodTuple,
        rest: null,
        ...processCreateParams(params),
    });
};
class ZodRecord extends ZodType {
    get keySchema() {
        return this._def.keyType;
    }
    get valueSchema() {
        return this._def.valueType;
    }
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.object,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        const pairs = [];
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        for (const key in ctx.data) {
            pairs.push({
                key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
                value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
            });
        }
        if (ctx.common.async) {
            return ParseStatus.mergeObjectAsync(status, pairs);
        }
        else {
            return ParseStatus.mergeObjectSync(status, pairs);
        }
    }
    get element() {
        return this._def.valueType;
    }
    static create(first, second, third) {
        if (second instanceof ZodType) {
            return new ZodRecord({
                keyType: first,
                valueType: second,
                typeName: ZodFirstPartyTypeKind.ZodRecord,
                ...processCreateParams(third),
            });
        }
        return new ZodRecord({
            keyType: ZodString.create(),
            valueType: first,
            typeName: ZodFirstPartyTypeKind.ZodRecord,
            ...processCreateParams(second),
        });
    }
}
class ZodMap extends ZodType {
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.map) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.map,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        const pairs = [...ctx.data.entries()].map(([key, value], index) => {
            return {
                key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
                value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])),
            };
        });
        if (ctx.common.async) {
            const finalMap = new Map();
            return Promise.resolve().then(async () => {
                for (const pair of pairs) {
                    const key = await pair.key;
                    const value = await pair.value;
                    if (key.status === "aborted" || value.status === "aborted") {
                        return INVALID;
                    }
                    if (key.status === "dirty" || value.status === "dirty") {
                        status.dirty();
                    }
                    finalMap.set(key.value, value.value);
                }
                return { status: status.value, value: finalMap };
            });
        }
        else {
            const finalMap = new Map();
            for (const pair of pairs) {
                const key = pair.key;
                const value = pair.value;
                if (key.status === "aborted" || value.status === "aborted") {
                    return INVALID;
                }
                if (key.status === "dirty" || value.status === "dirty") {
                    status.dirty();
                }
                finalMap.set(key.value, value.value);
            }
            return { status: status.value, value: finalMap };
        }
    }
}
ZodMap.create = (keyType, valueType, params) => {
    return new ZodMap({
        valueType,
        keyType,
        typeName: ZodFirstPartyTypeKind.ZodMap,
        ...processCreateParams(params),
    });
};
class ZodSet extends ZodType {
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.set) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.set,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        const def = this._def;
        if (def.minSize !== null) {
            if (ctx.data.size < def.minSize.value) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.too_small,
                    minimum: def.minSize.value,
                    type: "set",
                    inclusive: true,
                    exact: false,
                    message: def.minSize.message,
                });
                status.dirty();
            }
        }
        if (def.maxSize !== null) {
            if (ctx.data.size > def.maxSize.value) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.too_big,
                    maximum: def.maxSize.value,
                    type: "set",
                    inclusive: true,
                    exact: false,
                    message: def.maxSize.message,
                });
                status.dirty();
            }
        }
        const valueType = this._def.valueType;
        function finalizeSet(elements) {
            const parsedSet = new Set();
            for (const element of elements) {
                if (element.status === "aborted")
                    return INVALID;
                if (element.status === "dirty")
                    status.dirty();
                parsedSet.add(element.value);
            }
            return { status: status.value, value: parsedSet };
        }
        const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
        if (ctx.common.async) {
            return Promise.all(elements).then((elements) => finalizeSet(elements));
        }
        else {
            return finalizeSet(elements);
        }
    }
    min(minSize, message) {
        return new ZodSet({
            ...this._def,
            minSize: { value: minSize, message: errorUtil.toString(message) },
        });
    }
    max(maxSize, message) {
        return new ZodSet({
            ...this._def,
            maxSize: { value: maxSize, message: errorUtil.toString(message) },
        });
    }
    size(size, message) {
        return this.min(size, message).max(size, message);
    }
    nonempty(message) {
        return this.min(1, message);
    }
}
ZodSet.create = (valueType, params) => {
    return new ZodSet({
        valueType,
        minSize: null,
        maxSize: null,
        typeName: ZodFirstPartyTypeKind.ZodSet,
        ...processCreateParams(params),
    });
};
class ZodFunction extends ZodType {
    constructor() {
        super(...arguments);
        this.validate = this.implement;
    }
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.function) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.function,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        function makeArgsIssue(args, error) {
            return makeIssue({
                data: args,
                path: ctx.path,
                errorMaps: [
                    ctx.common.contextualErrorMap,
                    ctx.schemaErrorMap,
                    getErrorMap(),
                    errorMap,
                ].filter((x) => !!x),
                issueData: {
                    code: ZodIssueCode.invalid_arguments,
                    argumentsError: error,
                },
            });
        }
        function makeReturnsIssue(returns, error) {
            return makeIssue({
                data: returns,
                path: ctx.path,
                errorMaps: [
                    ctx.common.contextualErrorMap,
                    ctx.schemaErrorMap,
                    getErrorMap(),
                    errorMap,
                ].filter((x) => !!x),
                issueData: {
                    code: ZodIssueCode.invalid_return_type,
                    returnTypeError: error,
                },
            });
        }
        const params = { errorMap: ctx.common.contextualErrorMap };
        const fn = ctx.data;
        if (this._def.returns instanceof ZodPromise) {
            return OK(async (...args) => {
                const error = new ZodError([]);
                const parsedArgs = await this._def.args
                    .parseAsync(args, params)
                    .catch((e) => {
                    error.addIssue(makeArgsIssue(args, e));
                    throw error;
                });
                const result = await fn(...parsedArgs);
                const parsedReturns = await this._def.returns._def.type
                    .parseAsync(result, params)
                    .catch((e) => {
                    error.addIssue(makeReturnsIssue(result, e));
                    throw error;
                });
                return parsedReturns;
            });
        }
        else {
            return OK((...args) => {
                const parsedArgs = this._def.args.safeParse(args, params);
                if (!parsedArgs.success) {
                    throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
                }
                const result = fn(...parsedArgs.data);
                const parsedReturns = this._def.returns.safeParse(result, params);
                if (!parsedReturns.success) {
                    throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
                }
                return parsedReturns.data;
            });
        }
    }
    parameters() {
        return this._def.args;
    }
    returnType() {
        return this._def.returns;
    }
    args(...items) {
        return new ZodFunction({
            ...this._def,
            args: ZodTuple.create(items).rest(ZodUnknown.create()),
        });
    }
    returns(returnType) {
        return new ZodFunction({
            ...this._def,
            returns: returnType,
        });
    }
    implement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
    }
    strictImplement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
    }
    static create(args, returns, params) {
        return new ZodFunction({
            args: (args
                ? args
                : ZodTuple.create([]).rest(ZodUnknown.create())),
            returns: returns || ZodUnknown.create(),
            typeName: ZodFirstPartyTypeKind.ZodFunction,
            ...processCreateParams(params),
        });
    }
}
class ZodLazy extends ZodType {
    get schema() {
        return this._def.getter();
    }
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        const lazySchema = this._def.getter();
        return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
    }
}
ZodLazy.create = (getter, params) => {
    return new ZodLazy({
        getter: getter,
        typeName: ZodFirstPartyTypeKind.ZodLazy,
        ...processCreateParams(params),
    });
};
class ZodLiteral extends ZodType {
    _parse(input) {
        if (input.data !== this._def.value) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                received: ctx.data,
                code: ZodIssueCode.invalid_literal,
                expected: this._def.value,
            });
            return INVALID;
        }
        return { status: "valid", value: input.data };
    }
    get value() {
        return this._def.value;
    }
}
ZodLiteral.create = (value, params) => {
    return new ZodLiteral({
        value: value,
        typeName: ZodFirstPartyTypeKind.ZodLiteral,
        ...processCreateParams(params),
    });
};
function createZodEnum(values, params) {
    return new ZodEnum({
        values: values,
        typeName: ZodFirstPartyTypeKind.ZodEnum,
        ...processCreateParams(params),
    });
}
class ZodEnum extends ZodType {
    _parse(input) {
        if (typeof input.data !== "string") {
            const ctx = this._getOrReturnCtx(input);
            const expectedValues = this._def.values;
            addIssueToContext(ctx, {
                expected: util.joinValues(expectedValues),
                received: ctx.parsedType,
                code: ZodIssueCode.invalid_type,
            });
            return INVALID;
        }
        if (this._def.values.indexOf(input.data) === -1) {
            const ctx = this._getOrReturnCtx(input);
            const expectedValues = this._def.values;
            addIssueToContext(ctx, {
                received: ctx.data,
                code: ZodIssueCode.invalid_enum_value,
                options: expectedValues,
            });
            return INVALID;
        }
        return OK(input.data);
    }
    get options() {
        return this._def.values;
    }
    get enum() {
        const enumValues = {};
        for (const val of this._def.values) {
            enumValues[val] = val;
        }
        return enumValues;
    }
    get Values() {
        const enumValues = {};
        for (const val of this._def.values) {
            enumValues[val] = val;
        }
        return enumValues;
    }
    get Enum() {
        const enumValues = {};
        for (const val of this._def.values) {
            enumValues[val] = val;
        }
        return enumValues;
    }
    extract(values) {
        return ZodEnum.create(values);
    }
    exclude(values) {
        return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));
    }
}
ZodEnum.create = createZodEnum;
class ZodNativeEnum extends ZodType {
    _parse(input) {
        const nativeEnumValues = util.getValidEnumValues(this._def.values);
        const ctx = this._getOrReturnCtx(input);
        if (ctx.parsedType !== ZodParsedType.string &&
            ctx.parsedType !== ZodParsedType.number) {
            const expectedValues = util.objectValues(nativeEnumValues);
            addIssueToContext(ctx, {
                expected: util.joinValues(expectedValues),
                received: ctx.parsedType,
                code: ZodIssueCode.invalid_type,
            });
            return INVALID;
        }
        if (nativeEnumValues.indexOf(input.data) === -1) {
            const expectedValues = util.objectValues(nativeEnumValues);
            addIssueToContext(ctx, {
                received: ctx.data,
                code: ZodIssueCode.invalid_enum_value,
                options: expectedValues,
            });
            return INVALID;
        }
        return OK(input.data);
    }
    get enum() {
        return this._def.values;
    }
}
ZodNativeEnum.create = (values, params) => {
    return new ZodNativeEnum({
        values: values,
        typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
        ...processCreateParams(params),
    });
};
class ZodPromise extends ZodType {
    unwrap() {
        return this._def.type;
    }
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.promise &&
            ctx.common.async === false) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.promise,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        const promisified = ctx.parsedType === ZodParsedType.promise
            ? ctx.data
            : Promise.resolve(ctx.data);
        return OK(promisified.then((data) => {
            return this._def.type.parseAsync(data, {
                path: ctx.path,
                errorMap: ctx.common.contextualErrorMap,
            });
        }));
    }
}
ZodPromise.create = (schema, params) => {
    return new ZodPromise({
        type: schema,
        typeName: ZodFirstPartyTypeKind.ZodPromise,
        ...processCreateParams(params),
    });
};
class ZodEffects extends ZodType {
    innerType() {
        return this._def.schema;
    }
    sourceType() {
        return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects
            ? this._def.schema.sourceType()
            : this._def.schema;
    }
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const effect = this._def.effect || null;
        if (effect.type === "preprocess") {
            const processed = effect.transform(ctx.data);
            if (ctx.common.async) {
                return Promise.resolve(processed).then((processed) => {
                    return this._def.schema._parseAsync({
                        data: processed,
                        path: ctx.path,
                        parent: ctx,
                    });
                });
            }
            else {
                return this._def.schema._parseSync({
                    data: processed,
                    path: ctx.path,
                    parent: ctx,
                });
            }
        }
        const checkCtx = {
            addIssue: (arg) => {
                addIssueToContext(ctx, arg);
                if (arg.fatal) {
                    status.abort();
                }
                else {
                    status.dirty();
                }
            },
            get path() {
                return ctx.path;
            },
        };
        checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
        if (effect.type === "refinement") {
            const executeRefinement = (acc
            // effect: RefinementEffect<any>
            ) => {
                const result = effect.refinement(acc, checkCtx);
                if (ctx.common.async) {
                    return Promise.resolve(result);
                }
                if (result instanceof Promise) {
                    throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
                }
                return acc;
            };
            if (ctx.common.async === false) {
                const inner = this._def.schema._parseSync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                });
                if (inner.status === "aborted")
                    return INVALID;
                if (inner.status === "dirty")
                    status.dirty();
                // return value is ignored
                executeRefinement(inner.value);
                return { status: status.value, value: inner.value };
            }
            else {
                return this._def.schema
                    ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
                    .then((inner) => {
                    if (inner.status === "aborted")
                        return INVALID;
                    if (inner.status === "dirty")
                        status.dirty();
                    return executeRefinement(inner.value).then(() => {
                        return { status: status.value, value: inner.value };
                    });
                });
            }
        }
        if (effect.type === "transform") {
            if (ctx.common.async === false) {
                const base = this._def.schema._parseSync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                });
                if (!isValid(base))
                    return base;
                const result = effect.transform(base.value, checkCtx);
                if (result instanceof Promise) {
                    throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
                }
                return { status: status.value, value: result };
            }
            else {
                return this._def.schema
                    ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
                    .then((base) => {
                    if (!isValid(base))
                        return base;
                    return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
                });
            }
        }
        util.assertNever(effect);
    }
}
ZodEffects.create = (schema, effect, params) => {
    return new ZodEffects({
        schema,
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        effect,
        ...processCreateParams(params),
    });
};
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
    return new ZodEffects({
        schema,
        effect: { type: "preprocess", transform: preprocess },
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        ...processCreateParams(params),
    });
};
class ZodOptional extends ZodType {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === ZodParsedType.undefined) {
            return OK(undefined);
        }
        return this._def.innerType._parse(input);
    }
    unwrap() {
        return this._def.innerType;
    }
}
ZodOptional.create = (type, params) => {
    return new ZodOptional({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodOptional,
        ...processCreateParams(params),
    });
};
class ZodNullable extends ZodType {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === ZodParsedType.null) {
            return OK(null);
        }
        return this._def.innerType._parse(input);
    }
    unwrap() {
        return this._def.innerType;
    }
}
ZodNullable.create = (type, params) => {
    return new ZodNullable({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodNullable,
        ...processCreateParams(params),
    });
};
class ZodDefault extends ZodType {
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        let data = ctx.data;
        if (ctx.parsedType === ZodParsedType.undefined) {
            data = this._def.defaultValue();
        }
        return this._def.innerType._parse({
            data,
            path: ctx.path,
            parent: ctx,
        });
    }
    removeDefault() {
        return this._def.innerType;
    }
}
ZodDefault.create = (type, params) => {
    return new ZodDefault({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodDefault,
        defaultValue: typeof params.default === "function"
            ? params.default
            : () => params.default,
        ...processCreateParams(params),
    });
};
class ZodCatch extends ZodType {
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        // newCtx is used to not collect issues from inner types in ctx
        const newCtx = {
            ...ctx,
            common: {
                ...ctx.common,
                issues: [],
            },
        };
        const result = this._def.innerType._parse({
            data: newCtx.data,
            path: newCtx.path,
            parent: {
                ...newCtx,
            },
        });
        if (isAsync(result)) {
            return result.then((result) => {
                return {
                    status: "valid",
                    value: result.status === "valid"
                        ? result.value
                        : this._def.catchValue({
                            get error() {
                                return new ZodError(newCtx.common.issues);
                            },
                            input: newCtx.data,
                        }),
                };
            });
        }
        else {
            return {
                status: "valid",
                value: result.status === "valid"
                    ? result.value
                    : this._def.catchValue({
                        get error() {
                            return new ZodError(newCtx.common.issues);
                        },
                        input: newCtx.data,
                    }),
            };
        }
    }
    removeCatch() {
        return this._def.innerType;
    }
}
ZodCatch.create = (type, params) => {
    return new ZodCatch({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodCatch,
        catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
        ...processCreateParams(params),
    });
};
class ZodNaN extends ZodType {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.nan) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.nan,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        return { status: "valid", value: input.data };
    }
}
ZodNaN.create = (params) => {
    return new ZodNaN({
        typeName: ZodFirstPartyTypeKind.ZodNaN,
        ...processCreateParams(params),
    });
};
const BRAND = Symbol("zod_brand");
class ZodBranded extends ZodType {
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        const data = ctx.data;
        return this._def.type._parse({
            data,
            path: ctx.path,
            parent: ctx,
        });
    }
    unwrap() {
        return this._def.type;
    }
}
class ZodPipeline extends ZodType {
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.common.async) {
            const handleAsync = async () => {
                const inResult = await this._def.in._parseAsync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                });
                if (inResult.status === "aborted")
                    return INVALID;
                if (inResult.status === "dirty") {
                    status.dirty();
                    return DIRTY(inResult.value);
                }
                else {
                    return this._def.out._parseAsync({
                        data: inResult.value,
                        path: ctx.path,
                        parent: ctx,
                    });
                }
            };
            return handleAsync();
        }
        else {
            const inResult = this._def.in._parseSync({
                data: ctx.data,
                path: ctx.path,
                parent: ctx,
            });
            if (inResult.status === "aborted")
                return INVALID;
            if (inResult.status === "dirty") {
                status.dirty();
                return {
                    status: "dirty",
                    value: inResult.value,
                };
            }
            else {
                return this._def.out._parseSync({
                    data: inResult.value,
                    path: ctx.path,
                    parent: ctx,
                });
            }
        }
    }
    static create(a, b) {
        return new ZodPipeline({
            in: a,
            out: b,
            typeName: ZodFirstPartyTypeKind.ZodPipeline,
        });
    }
}
const custom = (check, params = {}, 
/*
 * @deprecated
 *
 * Pass `fatal` into the params object instead:
 *
 * ```ts
 * z.string().custom((val) => val.length > 5, { fatal: false })
 * ```
 *
 */
fatal) => {
    if (check)
        return ZodAny.create().superRefine((data, ctx) => {
            var _a, _b;
            if (!check(data)) {
                const p = typeof params === "function"
                    ? params(data)
                    : typeof params === "string"
                        ? { message: params }
                        : params;
                const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
                const p2 = typeof p === "string" ? { message: p } : p;
                ctx.addIssue({ code: "custom", ...p2, fatal: _fatal });
            }
        });
    return ZodAny.create();
};
const late = {
    object: ZodObject.lazycreate,
};
var ZodFirstPartyTypeKind;
(function (ZodFirstPartyTypeKind) {
    ZodFirstPartyTypeKind["ZodString"] = "ZodString";
    ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
    ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
    ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
    ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
    ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
    ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
    ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
    ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
    ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
    ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
    ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
    ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
    ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
    ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
    ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
    ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
    ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
    ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
    ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
    ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
    ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
    ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
    ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
    ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
    ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
    ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
    ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
    ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
    ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
    ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
    ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
    ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
    ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
    ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
const instanceOfType = (
// const instanceOfType = <T extends new (...args: any[]) => any>(
cls, params = {
    message: `Input not instance of ${cls.name}`,
}) => custom((data) => data instanceof cls, params);
const stringType = ZodString.create;
const numberType = ZodNumber.create;
const nanType = ZodNaN.create;
const bigIntType = ZodBigInt.create;
const booleanType = ZodBoolean.create;
const dateType = ZodDate.create;
const symbolType = ZodSymbol.create;
const undefinedType = ZodUndefined.create;
const nullType = ZodNull.create;
const anyType = ZodAny.create;
const unknownType = ZodUnknown.create;
const neverType = ZodNever.create;
const voidType = ZodVoid.create;
const arrayType = ZodArray.create;
const objectType = ZodObject.create;
const strictObjectType = ZodObject.strictCreate;
const unionType = ZodUnion.create;
const discriminatedUnionType = ZodDiscriminatedUnion.create;
const intersectionType = ZodIntersection.create;
const tupleType = ZodTuple.create;
const recordType = ZodRecord.create;
const mapType = ZodMap.create;
const setType = ZodSet.create;
const functionType = ZodFunction.create;
const lazyType = ZodLazy.create;
const literalType = ZodLiteral.create;
const enumType = ZodEnum.create;
const nativeEnumType = ZodNativeEnum.create;
const promiseType = ZodPromise.create;
const effectsType = ZodEffects.create;
const optionalType = ZodOptional.create;
const nullableType = ZodNullable.create;
const preprocessType = ZodEffects.createWithPreprocess;
const pipelineType = ZodPipeline.create;
const ostring = () => stringType().optional();
const onumber = () => numberType().optional();
const oboolean = () => booleanType().optional();
const coerce = {
    string: ((arg) => ZodString.create({ ...arg, coerce: true })),
    number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
    boolean: ((arg) => ZodBoolean.create({
        ...arg,
        coerce: true,
    })),
    bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
    date: ((arg) => ZodDate.create({ ...arg, coerce: true })),
};
const NEVER = INVALID;

var z = /*#__PURE__*/Object.freeze({
    __proto__: null,
    defaultErrorMap: errorMap,
    setErrorMap: setErrorMap,
    getErrorMap: getErrorMap,
    makeIssue: makeIssue,
    EMPTY_PATH: EMPTY_PATH,
    addIssueToContext: addIssueToContext,
    ParseStatus: ParseStatus,
    INVALID: INVALID,
    DIRTY: DIRTY,
    OK: OK,
    isAborted: isAborted,
    isDirty: isDirty,
    isValid: isValid,
    isAsync: isAsync,
    get util () { return util; },
    get objectUtil () { return objectUtil; },
    ZodParsedType: ZodParsedType,
    getParsedType: getParsedType,
    ZodType: ZodType,
    ZodString: ZodString,
    ZodNumber: ZodNumber,
    ZodBigInt: ZodBigInt,
    ZodBoolean: ZodBoolean,
    ZodDate: ZodDate,
    ZodSymbol: ZodSymbol,
    ZodUndefined: ZodUndefined,
    ZodNull: ZodNull,
    ZodAny: ZodAny,
    ZodUnknown: ZodUnknown,
    ZodNever: ZodNever,
    ZodVoid: ZodVoid,
    ZodArray: ZodArray,
    ZodObject: ZodObject,
    ZodUnion: ZodUnion,
    ZodDiscriminatedUnion: ZodDiscriminatedUnion,
    ZodIntersection: ZodIntersection,
    ZodTuple: ZodTuple,
    ZodRecord: ZodRecord,
    ZodMap: ZodMap,
    ZodSet: ZodSet,
    ZodFunction: ZodFunction,
    ZodLazy: ZodLazy,
    ZodLiteral: ZodLiteral,
    ZodEnum: ZodEnum,
    ZodNativeEnum: ZodNativeEnum,
    ZodPromise: ZodPromise,
    ZodEffects: ZodEffects,
    ZodTransformer: ZodEffects,
    ZodOptional: ZodOptional,
    ZodNullable: ZodNullable,
    ZodDefault: ZodDefault,
    ZodCatch: ZodCatch,
    ZodNaN: ZodNaN,
    BRAND: BRAND,
    ZodBranded: ZodBranded,
    ZodPipeline: ZodPipeline,
    custom: custom,
    Schema: ZodType,
    ZodSchema: ZodType,
    late: late,
    get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },
    coerce: coerce,
    any: anyType,
    array: arrayType,
    bigint: bigIntType,
    boolean: booleanType,
    date: dateType,
    discriminatedUnion: discriminatedUnionType,
    effect: effectsType,
    'enum': enumType,
    'function': functionType,
    'instanceof': instanceOfType,
    intersection: intersectionType,
    lazy: lazyType,
    literal: literalType,
    map: mapType,
    nan: nanType,
    nativeEnum: nativeEnumType,
    never: neverType,
    'null': nullType,
    nullable: nullableType,
    number: numberType,
    object: objectType,
    oboolean: oboolean,
    onumber: onumber,
    optional: optionalType,
    ostring: ostring,
    pipeline: pipelineType,
    preprocess: preprocessType,
    promise: promiseType,
    record: recordType,
    set: setType,
    strictObject: strictObjectType,
    string: stringType,
    symbol: symbolType,
    transformer: effectsType,
    tuple: tupleType,
    'undefined': undefinedType,
    union: unionType,
    unknown: unknownType,
    'void': voidType,
    NEVER: NEVER,
    ZodIssueCode: ZodIssueCode,
    quotelessJson: quotelessJson,
    ZodError: ZodError
});




/***/ }),

/***/ 3290:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Ay: () => (/* binding */ z),
/* harmony export */   G: () => (/* binding */ ZodError),
/* harmony export */   Ie: () => (/* binding */ custom),
/* harmony export */   Ik: () => (/* binding */ objectType),
/* harmony export */   L5: () => (/* binding */ unknownType),
/* harmony export */   YO: () => (/* binding */ arrayType),
/* harmony export */   Yj: () => (/* binding */ stringType),
/* harmony export */   ai: () => (/* binding */ numberType),
/* harmony export */   eq: () => (/* binding */ ZodIssueCode),
/* harmony export */   g1: () => (/* binding */ recordType),
/* harmony export */   z: () => (/* binding */ z)
/* harmony export */ });
/* unused harmony exports BRAND, DIRTY, EMPTY_PATH, INVALID, NEVER, OK, ParseStatus, Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodBranded, ZodCatch, ZodDate, ZodDefault, ZodDiscriminatedUnion, ZodEffects, ZodEnum, ZodFirstPartyTypeKind, ZodFunction, ZodIntersection, ZodLazy, ZodLiteral, ZodMap, ZodNaN, ZodNativeEnum, ZodNever, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodParsedType, ZodPipeline, ZodPromise, ZodReadonly, ZodRecord, ZodSchema, ZodSet, ZodString, ZodSymbol, ZodTransformer, ZodTuple, ZodType, ZodUndefined, ZodUnion, ZodUnknown, ZodVoid, addIssueToContext, any, bigint, boolean, coerce, date, datetimeRegex, defaultErrorMap, discriminatedUnion, effect, enum, function, getErrorMap, getParsedType, instanceof, intersection, isAborted, isAsync, isDirty, isValid, late, lazy, literal, makeIssue, map, nan, nativeEnum, never, null, nullable, objectUtil, oboolean, onumber, optional, ostring, pipeline, preprocess, promise, quotelessJson, set, setErrorMap, strictObject, symbol, transformer, tuple, undefined, union, util, void */
var util;
(function (util) {
    util.assertEqual = (val) => val;
    function assertIs(_arg) { }
    util.assertIs = assertIs;
    function assertNever(_x) {
        throw new Error();
    }
    util.assertNever = assertNever;
    util.arrayToEnum = (items) => {
        const obj = {};
        for (const item of items) {
            obj[item] = item;
        }
        return obj;
    };
    util.getValidEnumValues = (obj) => {
        const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
        const filtered = {};
        for (const k of validKeys) {
            filtered[k] = obj[k];
        }
        return util.objectValues(filtered);
    };
    util.objectValues = (obj) => {
        return util.objectKeys(obj).map(function (e) {
            return obj[e];
        });
    };
    util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
        ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
        : (object) => {
            const keys = [];
            for (const key in object) {
                if (Object.prototype.hasOwnProperty.call(object, key)) {
                    keys.push(key);
                }
            }
            return keys;
        };
    util.find = (arr, checker) => {
        for (const item of arr) {
            if (checker(item))
                return item;
        }
        return undefined;
    };
    util.isInteger = typeof Number.isInteger === "function"
        ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
        : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
    function joinValues(array, separator = " | ") {
        return array
            .map((val) => (typeof val === "string" ? `'${val}'` : val))
            .join(separator);
    }
    util.joinValues = joinValues;
    util.jsonStringifyReplacer = (_, value) => {
        if (typeof value === "bigint") {
            return value.toString();
        }
        return value;
    };
})(util || (util = {}));
var objectUtil;
(function (objectUtil) {
    objectUtil.mergeShapes = (first, second) => {
        return {
            ...first,
            ...second, // second overwrites first
        };
    };
})(objectUtil || (objectUtil = {}));
const ZodParsedType = util.arrayToEnum([
    "string",
    "nan",
    "number",
    "integer",
    "float",
    "boolean",
    "date",
    "bigint",
    "symbol",
    "function",
    "undefined",
    "null",
    "array",
    "object",
    "unknown",
    "promise",
    "void",
    "never",
    "map",
    "set",
]);
const getParsedType = (data) => {
    const t = typeof data;
    switch (t) {
        case "undefined":
            return ZodParsedType.undefined;
        case "string":
            return ZodParsedType.string;
        case "number":
            return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
        case "boolean":
            return ZodParsedType.boolean;
        case "function":
            return ZodParsedType.function;
        case "bigint":
            return ZodParsedType.bigint;
        case "symbol":
            return ZodParsedType.symbol;
        case "object":
            if (Array.isArray(data)) {
                return ZodParsedType.array;
            }
            if (data === null) {
                return ZodParsedType.null;
            }
            if (data.then &&
                typeof data.then === "function" &&
                data.catch &&
                typeof data.catch === "function") {
                return ZodParsedType.promise;
            }
            if (typeof Map !== "undefined" && data instanceof Map) {
                return ZodParsedType.map;
            }
            if (typeof Set !== "undefined" && data instanceof Set) {
                return ZodParsedType.set;
            }
            if (typeof Date !== "undefined" && data instanceof Date) {
                return ZodParsedType.date;
            }
            return ZodParsedType.object;
        default:
            return ZodParsedType.unknown;
    }
};

const ZodIssueCode = util.arrayToEnum([
    "invalid_type",
    "invalid_literal",
    "custom",
    "invalid_union",
    "invalid_union_discriminator",
    "invalid_enum_value",
    "unrecognized_keys",
    "invalid_arguments",
    "invalid_return_type",
    "invalid_date",
    "invalid_string",
    "too_small",
    "too_big",
    "invalid_intersection_types",
    "not_multiple_of",
    "not_finite",
]);
const quotelessJson = (obj) => {
    const json = JSON.stringify(obj, null, 2);
    return json.replace(/"([^"]+)":/g, "$1:");
};
class ZodError extends Error {
    get errors() {
        return this.issues;
    }
    constructor(issues) {
        super();
        this.issues = [];
        this.addIssue = (sub) => {
            this.issues = [...this.issues, sub];
        };
        this.addIssues = (subs = []) => {
            this.issues = [...this.issues, ...subs];
        };
        const actualProto = new.target.prototype;
        if (Object.setPrototypeOf) {
            // eslint-disable-next-line ban/ban
            Object.setPrototypeOf(this, actualProto);
        }
        else {
            this.__proto__ = actualProto;
        }
        this.name = "ZodError";
        this.issues = issues;
    }
    format(_mapper) {
        const mapper = _mapper ||
            function (issue) {
                return issue.message;
            };
        const fieldErrors = { _errors: [] };
        const processError = (error) => {
            for (const issue of error.issues) {
                if (issue.code === "invalid_union") {
                    issue.unionErrors.map(processError);
                }
                else if (issue.code === "invalid_return_type") {
                    processError(issue.returnTypeError);
                }
                else if (issue.code === "invalid_arguments") {
                    processError(issue.argumentsError);
                }
                else if (issue.path.length === 0) {
                    fieldErrors._errors.push(mapper(issue));
                }
                else {
                    let curr = fieldErrors;
                    let i = 0;
                    while (i < issue.path.length) {
                        const el = issue.path[i];
                        const terminal = i === issue.path.length - 1;
                        if (!terminal) {
                            curr[el] = curr[el] || { _errors: [] };
                            // if (typeof el === "string") {
                            //   curr[el] = curr[el] || { _errors: [] };
                            // } else if (typeof el === "number") {
                            //   const errorArray: any = [];
                            //   errorArray._errors = [];
                            //   curr[el] = curr[el] || errorArray;
                            // }
                        }
                        else {
                            curr[el] = curr[el] || { _errors: [] };
                            curr[el]._errors.push(mapper(issue));
                        }
                        curr = curr[el];
                        i++;
                    }
                }
            }
        };
        processError(this);
        return fieldErrors;
    }
    static assert(value) {
        if (!(value instanceof ZodError)) {
            throw new Error(`Not a ZodError: ${value}`);
        }
    }
    toString() {
        return this.message;
    }
    get message() {
        return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
    }
    get isEmpty() {
        return this.issues.length === 0;
    }
    flatten(mapper = (issue) => issue.message) {
        const fieldErrors = {};
        const formErrors = [];
        for (const sub of this.issues) {
            if (sub.path.length > 0) {
                fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
                fieldErrors[sub.path[0]].push(mapper(sub));
            }
            else {
                formErrors.push(mapper(sub));
            }
        }
        return { formErrors, fieldErrors };
    }
    get formErrors() {
        return this.flatten();
    }
}
ZodError.create = (issues) => {
    const error = new ZodError(issues);
    return error;
};

const errorMap = (issue, _ctx) => {
    let message;
    switch (issue.code) {
        case ZodIssueCode.invalid_type:
            if (issue.received === ZodParsedType.undefined) {
                message = "Required";
            }
            else {
                message = `Expected ${issue.expected}, received ${issue.received}`;
            }
            break;
        case ZodIssueCode.invalid_literal:
            message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
            break;
        case ZodIssueCode.unrecognized_keys:
            message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
            break;
        case ZodIssueCode.invalid_union:
            message = `Invalid input`;
            break;
        case ZodIssueCode.invalid_union_discriminator:
            message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
            break;
        case ZodIssueCode.invalid_enum_value:
            message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
            break;
        case ZodIssueCode.invalid_arguments:
            message = `Invalid function arguments`;
            break;
        case ZodIssueCode.invalid_return_type:
            message = `Invalid function return type`;
            break;
        case ZodIssueCode.invalid_date:
            message = `Invalid date`;
            break;
        case ZodIssueCode.invalid_string:
            if (typeof issue.validation === "object") {
                if ("includes" in issue.validation) {
                    message = `Invalid input: must include "${issue.validation.includes}"`;
                    if (typeof issue.validation.position === "number") {
                        message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
                    }
                }
                else if ("startsWith" in issue.validation) {
                    message = `Invalid input: must start with "${issue.validation.startsWith}"`;
                }
                else if ("endsWith" in issue.validation) {
                    message = `Invalid input: must end with "${issue.validation.endsWith}"`;
                }
                else {
                    util.assertNever(issue.validation);
                }
            }
            else if (issue.validation !== "regex") {
                message = `Invalid ${issue.validation}`;
            }
            else {
                message = "Invalid";
            }
            break;
        case ZodIssueCode.too_small:
            if (issue.type === "array")
                message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
            else if (issue.type === "string")
                message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
            else if (issue.type === "number")
                message = `Number must be ${issue.exact
                    ? `exactly equal to `
                    : issue.inclusive
                        ? `greater than or equal to `
                        : `greater than `}${issue.minimum}`;
            else if (issue.type === "date")
                message = `Date must be ${issue.exact
                    ? `exactly equal to `
                    : issue.inclusive
                        ? `greater than or equal to `
                        : `greater than `}${new Date(Number(issue.minimum))}`;
            else
                message = "Invalid input";
            break;
        case ZodIssueCode.too_big:
            if (issue.type === "array")
                message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
            else if (issue.type === "string")
                message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
            else if (issue.type === "number")
                message = `Number must be ${issue.exact
                    ? `exactly`
                    : issue.inclusive
                        ? `less than or equal to`
                        : `less than`} ${issue.maximum}`;
            else if (issue.type === "bigint")
                message = `BigInt must be ${issue.exact
                    ? `exactly`
                    : issue.inclusive
                        ? `less than or equal to`
                        : `less than`} ${issue.maximum}`;
            else if (issue.type === "date")
                message = `Date must be ${issue.exact
                    ? `exactly`
                    : issue.inclusive
                        ? `smaller than or equal to`
                        : `smaller than`} ${new Date(Number(issue.maximum))}`;
            else
                message = "Invalid input";
            break;
        case ZodIssueCode.custom:
            message = `Invalid input`;
            break;
        case ZodIssueCode.invalid_intersection_types:
            message = `Intersection results could not be merged`;
            break;
        case ZodIssueCode.not_multiple_of:
            message = `Number must be a multiple of ${issue.multipleOf}`;
            break;
        case ZodIssueCode.not_finite:
            message = "Number must be finite";
            break;
        default:
            message = _ctx.defaultError;
            util.assertNever(issue);
    }
    return { message };
};

let overrideErrorMap = errorMap;
function setErrorMap(map) {
    overrideErrorMap = map;
}
function getErrorMap() {
    return overrideErrorMap;
}

const makeIssue = (params) => {
    const { data, path, errorMaps, issueData } = params;
    const fullPath = [...path, ...(issueData.path || [])];
    const fullIssue = {
        ...issueData,
        path: fullPath,
    };
    if (issueData.message !== undefined) {
        return {
            ...issueData,
            path: fullPath,
            message: issueData.message,
        };
    }
    let errorMessage = "";
    const maps = errorMaps
        .filter((m) => !!m)
        .slice()
        .reverse();
    for (const map of maps) {
        errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
    }
    return {
        ...issueData,
        path: fullPath,
        message: errorMessage,
    };
};
const EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
    const overrideMap = getErrorMap();
    const issue = makeIssue({
        issueData: issueData,
        data: ctx.data,
        path: ctx.path,
        errorMaps: [
            ctx.common.contextualErrorMap, // contextual error map is first priority
            ctx.schemaErrorMap, // then schema-bound map if available
            overrideMap, // then global override map
            overrideMap === errorMap ? undefined : errorMap, // then global default map
        ].filter((x) => !!x),
    });
    ctx.common.issues.push(issue);
}
class ParseStatus {
    constructor() {
        this.value = "valid";
    }
    dirty() {
        if (this.value === "valid")
            this.value = "dirty";
    }
    abort() {
        if (this.value !== "aborted")
            this.value = "aborted";
    }
    static mergeArray(status, results) {
        const arrayValue = [];
        for (const s of results) {
            if (s.status === "aborted")
                return INVALID;
            if (s.status === "dirty")
                status.dirty();
            arrayValue.push(s.value);
        }
        return { status: status.value, value: arrayValue };
    }
    static async mergeObjectAsync(status, pairs) {
        const syncPairs = [];
        for (const pair of pairs) {
            const key = await pair.key;
            const value = await pair.value;
            syncPairs.push({
                key,
                value,
            });
        }
        return ParseStatus.mergeObjectSync(status, syncPairs);
    }
    static mergeObjectSync(status, pairs) {
        const finalObject = {};
        for (const pair of pairs) {
            const { key, value } = pair;
            if (key.status === "aborted")
                return INVALID;
            if (value.status === "aborted")
                return INVALID;
            if (key.status === "dirty")
                status.dirty();
            if (value.status === "dirty")
                status.dirty();
            if (key.value !== "__proto__" &&
                (typeof value.value !== "undefined" || pair.alwaysSet)) {
                finalObject[key.value] = value.value;
            }
        }
        return { status: status.value, value: finalObject };
    }
}
const INVALID = Object.freeze({
    status: "aborted",
});
const DIRTY = (value) => ({ status: "dirty", value });
const OK = (value) => ({ status: "valid", value });
const isAborted = (x) => x.status === "aborted";
const isDirty = (x) => x.status === "dirty";
const isValid = (x) => x.status === "valid";
const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;

/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */

function __classPrivateFieldGet(receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}

function __classPrivateFieldSet(receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}

typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};

var errorUtil;
(function (errorUtil) {
    errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
    errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
})(errorUtil || (errorUtil = {}));

var _ZodEnum_cache, _ZodNativeEnum_cache;
class ParseInputLazyPath {
    constructor(parent, value, path, key) {
        this._cachedPath = [];
        this.parent = parent;
        this.data = value;
        this._path = path;
        this._key = key;
    }
    get path() {
        if (!this._cachedPath.length) {
            if (this._key instanceof Array) {
                this._cachedPath.push(...this._path, ...this._key);
            }
            else {
                this._cachedPath.push(...this._path, this._key);
            }
        }
        return this._cachedPath;
    }
}
const handleResult = (ctx, result) => {
    if (isValid(result)) {
        return { success: true, data: result.value };
    }
    else {
        if (!ctx.common.issues.length) {
            throw new Error("Validation failed but no issues detected.");
        }
        return {
            success: false,
            get error() {
                if (this._error)
                    return this._error;
                const error = new ZodError(ctx.common.issues);
                this._error = error;
                return this._error;
            },
        };
    }
};
function processCreateParams(params) {
    if (!params)
        return {};
    const { errorMap, invalid_type_error, required_error, description } = params;
    if (errorMap && (invalid_type_error || required_error)) {
        throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
    }
    if (errorMap)
        return { errorMap: errorMap, description };
    const customMap = (iss, ctx) => {
        var _a, _b;
        const { message } = params;
        if (iss.code === "invalid_enum_value") {
            return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
        }
        if (typeof ctx.data === "undefined") {
            return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };
        }
        if (iss.code !== "invalid_type")
            return { message: ctx.defaultError };
        return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
    };
    return { errorMap: customMap, description };
}
class ZodType {
    get description() {
        return this._def.description;
    }
    _getType(input) {
        return getParsedType(input.data);
    }
    _getOrReturnCtx(input, ctx) {
        return (ctx || {
            common: input.parent.common,
            data: input.data,
            parsedType: getParsedType(input.data),
            schemaErrorMap: this._def.errorMap,
            path: input.path,
            parent: input.parent,
        });
    }
    _processInputParams(input) {
        return {
            status: new ParseStatus(),
            ctx: {
                common: input.parent.common,
                data: input.data,
                parsedType: getParsedType(input.data),
                schemaErrorMap: this._def.errorMap,
                path: input.path,
                parent: input.parent,
            },
        };
    }
    _parseSync(input) {
        const result = this._parse(input);
        if (isAsync(result)) {
            throw new Error("Synchronous parse encountered promise.");
        }
        return result;
    }
    _parseAsync(input) {
        const result = this._parse(input);
        return Promise.resolve(result);
    }
    parse(data, params) {
        const result = this.safeParse(data, params);
        if (result.success)
            return result.data;
        throw result.error;
    }
    safeParse(data, params) {
        var _a;
        const ctx = {
            common: {
                issues: [],
                async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
                contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
            },
            path: (params === null || params === void 0 ? void 0 : params.path) || [],
            schemaErrorMap: this._def.errorMap,
            parent: null,
            data,
            parsedType: getParsedType(data),
        };
        const result = this._parseSync({ data, path: ctx.path, parent: ctx });
        return handleResult(ctx, result);
    }
    "~validate"(data) {
        var _a, _b;
        const ctx = {
            common: {
                issues: [],
                async: !!this["~standard"].async,
            },
            path: [],
            schemaErrorMap: this._def.errorMap,
            parent: null,
            data,
            parsedType: getParsedType(data),
        };
        if (!this["~standard"].async) {
            try {
                const result = this._parseSync({ data, path: [], parent: ctx });
                return isValid(result)
                    ? {
                        value: result.value,
                    }
                    : {
                        issues: ctx.common.issues,
                    };
            }
            catch (err) {
                if ((_b = (_a = err === null || err === void 0 ? void 0 : err.message) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes("encountered")) {
                    this["~standard"].async = true;
                }
                ctx.common = {
                    issues: [],
                    async: true,
                };
            }
        }
        return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)
            ? {
                value: result.value,
            }
            : {
                issues: ctx.common.issues,
            });
    }
    async parseAsync(data, params) {
        const result = await this.safeParseAsync(data, params);
        if (result.success)
            return result.data;
        throw result.error;
    }
    async safeParseAsync(data, params) {
        const ctx = {
            common: {
                issues: [],
                contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
                async: true,
            },
            path: (params === null || params === void 0 ? void 0 : params.path) || [],
            schemaErrorMap: this._def.errorMap,
            parent: null,
            data,
            parsedType: getParsedType(data),
        };
        const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
        const result = await (isAsync(maybeAsyncResult)
            ? maybeAsyncResult
            : Promise.resolve(maybeAsyncResult));
        return handleResult(ctx, result);
    }
    refine(check, message) {
        const getIssueProperties = (val) => {
            if (typeof message === "string" || typeof message === "undefined") {
                return { message };
            }
            else if (typeof message === "function") {
                return message(val);
            }
            else {
                return message;
            }
        };
        return this._refinement((val, ctx) => {
            const result = check(val);
            const setError = () => ctx.addIssue({
                code: ZodIssueCode.custom,
                ...getIssueProperties(val),
            });
            if (typeof Promise !== "undefined" && result instanceof Promise) {
                return result.then((data) => {
                    if (!data) {
                        setError();
                        return false;
                    }
                    else {
                        return true;
                    }
                });
            }
            if (!result) {
                setError();
                return false;
            }
            else {
                return true;
            }
        });
    }
    refinement(check, refinementData) {
        return this._refinement((val, ctx) => {
            if (!check(val)) {
                ctx.addIssue(typeof refinementData === "function"
                    ? refinementData(val, ctx)
                    : refinementData);
                return false;
            }
            else {
                return true;
            }
        });
    }
    _refinement(refinement) {
        return new ZodEffects({
            schema: this,
            typeName: ZodFirstPartyTypeKind.ZodEffects,
            effect: { type: "refinement", refinement },
        });
    }
    superRefine(refinement) {
        return this._refinement(refinement);
    }
    constructor(def) {
        /** Alias of safeParseAsync */
        this.spa = this.safeParseAsync;
        this._def = def;
        this.parse = this.parse.bind(this);
        this.safeParse = this.safeParse.bind(this);
        this.parseAsync = this.parseAsync.bind(this);
        this.safeParseAsync = this.safeParseAsync.bind(this);
        this.spa = this.spa.bind(this);
        this.refine = this.refine.bind(this);
        this.refinement = this.refinement.bind(this);
        this.superRefine = this.superRefine.bind(this);
        this.optional = this.optional.bind(this);
        this.nullable = this.nullable.bind(this);
        this.nullish = this.nullish.bind(this);
        this.array = this.array.bind(this);
        this.promise = this.promise.bind(this);
        this.or = this.or.bind(this);
        this.and = this.and.bind(this);
        this.transform = this.transform.bind(this);
        this.brand = this.brand.bind(this);
        this.default = this.default.bind(this);
        this.catch = this.catch.bind(this);
        this.describe = this.describe.bind(this);
        this.pipe = this.pipe.bind(this);
        this.readonly = this.readonly.bind(this);
        this.isNullable = this.isNullable.bind(this);
        this.isOptional = this.isOptional.bind(this);
        this["~standard"] = {
            version: 1,
            vendor: "zod",
            validate: (data) => this["~validate"](data),
        };
    }
    optional() {
        return ZodOptional.create(this, this._def);
    }
    nullable() {
        return ZodNullable.create(this, this._def);
    }
    nullish() {
        return this.nullable().optional();
    }
    array() {
        return ZodArray.create(this);
    }
    promise() {
        return ZodPromise.create(this, this._def);
    }
    or(option) {
        return ZodUnion.create([this, option], this._def);
    }
    and(incoming) {
        return ZodIntersection.create(this, incoming, this._def);
    }
    transform(transform) {
        return new ZodEffects({
            ...processCreateParams(this._def),
            schema: this,
            typeName: ZodFirstPartyTypeKind.ZodEffects,
            effect: { type: "transform", transform },
        });
    }
    default(def) {
        const defaultValueFunc = typeof def === "function" ? def : () => def;
        return new ZodDefault({
            ...processCreateParams(this._def),
            innerType: this,
            defaultValue: defaultValueFunc,
            typeName: ZodFirstPartyTypeKind.ZodDefault,
        });
    }
    brand() {
        return new ZodBranded({
            typeName: ZodFirstPartyTypeKind.ZodBranded,
            type: this,
            ...processCreateParams(this._def),
        });
    }
    catch(def) {
        const catchValueFunc = typeof def === "function" ? def : () => def;
        return new ZodCatch({
            ...processCreateParams(this._def),
            innerType: this,
            catchValue: catchValueFunc,
            typeName: ZodFirstPartyTypeKind.ZodCatch,
        });
    }
    describe(description) {
        const This = this.constructor;
        return new This({
            ...this._def,
            description,
        });
    }
    pipe(target) {
        return ZodPipeline.create(this, target);
    }
    readonly() {
        return ZodReadonly.create(this);
    }
    isOptional() {
        return this.safeParse(undefined).success;
    }
    isNullable() {
        return this.safeParse(null).success;
    }
}
const cuidRegex = /^c[^\s-]{8,}$/i;
const cuid2Regex = /^[0-9a-z]+$/;
const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
// const uuidRegex =
//   /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
const nanoidRegex = /^[a-z0-9_-]{21}$/i;
const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
// from https://stackoverflow.com/a/46181/1550155
// old version: too slow, didn't support unicode
// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
//old email regex
// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
// eslint-disable-next-line
// const emailRegex =
//   /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
// const emailRegex =
//   /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
// const emailRegex =
//   /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
// const emailRegex =
//   /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
let emojiRegex;
// faster, simpler, safer
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
// const ipv6Regex =
// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
// https://base64.guru/standards/base64url
const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
// simple
// const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`;
// no leap year validation
// const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`;
// with leap year validation
const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
const dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
    let secondsRegexSource = `[0-5]\\d`;
    if (args.precision) {
        secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
    }
    else if (args.precision == null) {
        secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
    }
    const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero
    return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
    return new RegExp(`^${timeRegexSource(args)}$`);
}
// Adapted from https://stackoverflow.com/a/3143231
function datetimeRegex(args) {
    let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
    const opts = [];
    opts.push(args.local ? `Z?` : `Z`);
    if (args.offset)
        opts.push(`([+-]\\d{2}:?\\d{2})`);
    regex = `${regex}(${opts.join("|")})`;
    return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version) {
    if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
        return true;
    }
    if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
        return true;
    }
    return false;
}
function isValidJWT(jwt, alg) {
    if (!jwtRegex.test(jwt))
        return false;
    try {
        const [header] = jwt.split(".");
        // Convert base64url to base64
        const base64 = header
            .replace(/-/g, "+")
            .replace(/_/g, "/")
            .padEnd(header.length + ((4 - (header.length % 4)) % 4), "=");
        const decoded = JSON.parse(atob(base64));
        if (typeof decoded !== "object" || decoded === null)
            return false;
        if (!decoded.typ || !decoded.alg)
            return false;
        if (alg && decoded.alg !== alg)
            return false;
        return true;
    }
    catch (_a) {
        return false;
    }
}
function isValidCidr(ip, version) {
    if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
        return true;
    }
    if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
        return true;
    }
    return false;
}
class ZodString extends ZodType {
    _parse(input) {
        if (this._def.coerce) {
            input.data = String(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.string) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.string,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        const status = new ParseStatus();
        let ctx = undefined;
        for (const check of this._def.checks) {
            if (check.kind === "min") {
                if (input.data.length < check.value) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_small,
                        minimum: check.value,
                        type: "string",
                        inclusive: true,
                        exact: false,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "max") {
                if (input.data.length > check.value) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_big,
                        maximum: check.value,
                        type: "string",
                        inclusive: true,
                        exact: false,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "length") {
                const tooBig = input.data.length > check.value;
                const tooSmall = input.data.length < check.value;
                if (tooBig || tooSmall) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    if (tooBig) {
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.too_big,
                            maximum: check.value,
                            type: "string",
                            inclusive: true,
                            exact: true,
                            message: check.message,
                        });
                    }
                    else if (tooSmall) {
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.too_small,
                            minimum: check.value,
                            type: "string",
                            inclusive: true,
                            exact: true,
                            message: check.message,
                        });
                    }
                    status.dirty();
                }
            }
            else if (check.kind === "email") {
                if (!emailRegex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "email",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "emoji") {
                if (!emojiRegex) {
                    emojiRegex = new RegExp(_emojiRegex, "u");
                }
                if (!emojiRegex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "emoji",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "uuid") {
                if (!uuidRegex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "uuid",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "nanoid") {
                if (!nanoidRegex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "nanoid",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "cuid") {
                if (!cuidRegex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "cuid",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "cuid2") {
                if (!cuid2Regex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "cuid2",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "ulid") {
                if (!ulidRegex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "ulid",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "url") {
                try {
                    new URL(input.data);
                }
                catch (_a) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "url",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "regex") {
                check.regex.lastIndex = 0;
                const testResult = check.regex.test(input.data);
                if (!testResult) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "regex",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "trim") {
                input.data = input.data.trim();
            }
            else if (check.kind === "includes") {
                if (!input.data.includes(check.value, check.position)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.invalid_string,
                        validation: { includes: check.value, position: check.position },
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "toLowerCase") {
                input.data = input.data.toLowerCase();
            }
            else if (check.kind === "toUpperCase") {
                input.data = input.data.toUpperCase();
            }
            else if (check.kind === "startsWith") {
                if (!input.data.startsWith(check.value)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.invalid_string,
                        validation: { startsWith: check.value },
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "endsWith") {
                if (!input.data.endsWith(check.value)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.invalid_string,
                        validation: { endsWith: check.value },
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "datetime") {
                const regex = datetimeRegex(check);
                if (!regex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.invalid_string,
                        validation: "datetime",
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "date") {
                const regex = dateRegex;
                if (!regex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.invalid_string,
                        validation: "date",
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "time") {
                const regex = timeRegex(check);
                if (!regex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.invalid_string,
                        validation: "time",
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "duration") {
                if (!durationRegex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "duration",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "ip") {
                if (!isValidIP(input.data, check.version)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "ip",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "jwt") {
                if (!isValidJWT(input.data, check.alg)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "jwt",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "cidr") {
                if (!isValidCidr(input.data, check.version)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "cidr",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "base64") {
                if (!base64Regex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "base64",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "base64url") {
                if (!base64urlRegex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "base64url",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else {
                util.assertNever(check);
            }
        }
        return { status: status.value, value: input.data };
    }
    _regex(regex, validation, message) {
        return this.refinement((data) => regex.test(data), {
            validation,
            code: ZodIssueCode.invalid_string,
            ...errorUtil.errToObj(message),
        });
    }
    _addCheck(check) {
        return new ZodString({
            ...this._def,
            checks: [...this._def.checks, check],
        });
    }
    email(message) {
        return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
    }
    url(message) {
        return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
    }
    emoji(message) {
        return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
    }
    uuid(message) {
        return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
    }
    nanoid(message) {
        return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
    }
    cuid(message) {
        return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
    }
    cuid2(message) {
        return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
    }
    ulid(message) {
        return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
    }
    base64(message) {
        return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
    }
    base64url(message) {
        // base64url encoding is a modification of base64 that can safely be used in URLs and filenames
        return this._addCheck({
            kind: "base64url",
            ...errorUtil.errToObj(message),
        });
    }
    jwt(options) {
        return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
    }
    ip(options) {
        return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
    }
    cidr(options) {
        return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
    }
    datetime(options) {
        var _a, _b;
        if (typeof options === "string") {
            return this._addCheck({
                kind: "datetime",
                precision: null,
                offset: false,
                local: false,
                message: options,
            });
        }
        return this._addCheck({
            kind: "datetime",
            precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
            offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
            local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,
            ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
        });
    }
    date(message) {
        return this._addCheck({ kind: "date", message });
    }
    time(options) {
        if (typeof options === "string") {
            return this._addCheck({
                kind: "time",
                precision: null,
                message: options,
            });
        }
        return this._addCheck({
            kind: "time",
            precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
            ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
        });
    }
    duration(message) {
        return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
    }
    regex(regex, message) {
        return this._addCheck({
            kind: "regex",
            regex: regex,
            ...errorUtil.errToObj(message),
        });
    }
    includes(value, options) {
        return this._addCheck({
            kind: "includes",
            value: value,
            position: options === null || options === void 0 ? void 0 : options.position,
            ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
        });
    }
    startsWith(value, message) {
        return this._addCheck({
            kind: "startsWith",
            value: value,
            ...errorUtil.errToObj(message),
        });
    }
    endsWith(value, message) {
        return this._addCheck({
            kind: "endsWith",
            value: value,
            ...errorUtil.errToObj(message),
        });
    }
    min(minLength, message) {
        return this._addCheck({
            kind: "min",
            value: minLength,
            ...errorUtil.errToObj(message),
        });
    }
    max(maxLength, message) {
        return this._addCheck({
            kind: "max",
            value: maxLength,
            ...errorUtil.errToObj(message),
        });
    }
    length(len, message) {
        return this._addCheck({
            kind: "length",
            value: len,
            ...errorUtil.errToObj(message),
        });
    }
    /**
     * Equivalent to `.min(1)`
     */
    nonempty(message) {
        return this.min(1, errorUtil.errToObj(message));
    }
    trim() {
        return new ZodString({
            ...this._def,
            checks: [...this._def.checks, { kind: "trim" }],
        });
    }
    toLowerCase() {
        return new ZodString({
            ...this._def,
            checks: [...this._def.checks, { kind: "toLowerCase" }],
        });
    }
    toUpperCase() {
        return new ZodString({
            ...this._def,
            checks: [...this._def.checks, { kind: "toUpperCase" }],
        });
    }
    get isDatetime() {
        return !!this._def.checks.find((ch) => ch.kind === "datetime");
    }
    get isDate() {
        return !!this._def.checks.find((ch) => ch.kind === "date");
    }
    get isTime() {
        return !!this._def.checks.find((ch) => ch.kind === "time");
    }
    get isDuration() {
        return !!this._def.checks.find((ch) => ch.kind === "duration");
    }
    get isEmail() {
        return !!this._def.checks.find((ch) => ch.kind === "email");
    }
    get isURL() {
        return !!this._def.checks.find((ch) => ch.kind === "url");
    }
    get isEmoji() {
        return !!this._def.checks.find((ch) => ch.kind === "emoji");
    }
    get isUUID() {
        return !!this._def.checks.find((ch) => ch.kind === "uuid");
    }
    get isNANOID() {
        return !!this._def.checks.find((ch) => ch.kind === "nanoid");
    }
    get isCUID() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid");
    }
    get isCUID2() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid2");
    }
    get isULID() {
        return !!this._def.checks.find((ch) => ch.kind === "ulid");
    }
    get isIP() {
        return !!this._def.checks.find((ch) => ch.kind === "ip");
    }
    get isCIDR() {
        return !!this._def.checks.find((ch) => ch.kind === "cidr");
    }
    get isBase64() {
        return !!this._def.checks.find((ch) => ch.kind === "base64");
    }
    get isBase64url() {
        // base64url encoding is a modification of base64 that can safely be used in URLs and filenames
        return !!this._def.checks.find((ch) => ch.kind === "base64url");
    }
    get minLength() {
        let min = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "min") {
                if (min === null || ch.value > min)
                    min = ch.value;
            }
        }
        return min;
    }
    get maxLength() {
        let max = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "max") {
                if (max === null || ch.value < max)
                    max = ch.value;
            }
        }
        return max;
    }
}
ZodString.create = (params) => {
    var _a;
    return new ZodString({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodString,
        coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
        ...processCreateParams(params),
    });
};
// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
function floatSafeRemainder(val, step) {
    const valDecCount = (val.toString().split(".")[1] || "").length;
    const stepDecCount = (step.toString().split(".")[1] || "").length;
    const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
    const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
    const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
    return (valInt % stepInt) / Math.pow(10, decCount);
}
class ZodNumber extends ZodType {
    constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
        this.step = this.multipleOf;
    }
    _parse(input) {
        if (this._def.coerce) {
            input.data = Number(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.number) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.number,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        let ctx = undefined;
        const status = new ParseStatus();
        for (const check of this._def.checks) {
            if (check.kind === "int") {
                if (!util.isInteger(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.invalid_type,
                        expected: "integer",
                        received: "float",
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "min") {
                const tooSmall = check.inclusive
                    ? input.data < check.value
                    : input.data <= check.value;
                if (tooSmall) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_small,
                        minimum: check.value,
                        type: "number",
                        inclusive: check.inclusive,
                        exact: false,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "max") {
                const tooBig = check.inclusive
                    ? input.data > check.value
                    : input.data >= check.value;
                if (tooBig) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_big,
                        maximum: check.value,
                        type: "number",
                        inclusive: check.inclusive,
                        exact: false,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "multipleOf") {
                if (floatSafeRemainder(input.data, check.value) !== 0) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.not_multiple_of,
                        multipleOf: check.value,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "finite") {
                if (!Number.isFinite(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.not_finite,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else {
                util.assertNever(check);
            }
        }
        return { status: status.value, value: input.data };
    }
    gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
    }
    gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
    }
    lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
    }
    lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
    }
    setLimit(kind, value, inclusive, message) {
        return new ZodNumber({
            ...this._def,
            checks: [
                ...this._def.checks,
                {
                    kind,
                    value,
                    inclusive,
                    message: errorUtil.toString(message),
                },
            ],
        });
    }
    _addCheck(check) {
        return new ZodNumber({
            ...this._def,
            checks: [...this._def.checks, check],
        });
    }
    int(message) {
        return this._addCheck({
            kind: "int",
            message: errorUtil.toString(message),
        });
    }
    positive(message) {
        return this._addCheck({
            kind: "min",
            value: 0,
            inclusive: false,
            message: errorUtil.toString(message),
        });
    }
    negative(message) {
        return this._addCheck({
            kind: "max",
            value: 0,
            inclusive: false,
            message: errorUtil.toString(message),
        });
    }
    nonpositive(message) {
        return this._addCheck({
            kind: "max",
            value: 0,
            inclusive: true,
            message: errorUtil.toString(message),
        });
    }
    nonnegative(message) {
        return this._addCheck({
            kind: "min",
            value: 0,
            inclusive: true,
            message: errorUtil.toString(message),
        });
    }
    multipleOf(value, message) {
        return this._addCheck({
            kind: "multipleOf",
            value: value,
            message: errorUtil.toString(message),
        });
    }
    finite(message) {
        return this._addCheck({
            kind: "finite",
            message: errorUtil.toString(message),
        });
    }
    safe(message) {
        return this._addCheck({
            kind: "min",
            inclusive: true,
            value: Number.MIN_SAFE_INTEGER,
            message: errorUtil.toString(message),
        })._addCheck({
            kind: "max",
            inclusive: true,
            value: Number.MAX_SAFE_INTEGER,
            message: errorUtil.toString(message),
        });
    }
    get minValue() {
        let min = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "min") {
                if (min === null || ch.value > min)
                    min = ch.value;
            }
        }
        return min;
    }
    get maxValue() {
        let max = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "max") {
                if (max === null || ch.value < max)
                    max = ch.value;
            }
        }
        return max;
    }
    get isInt() {
        return !!this._def.checks.find((ch) => ch.kind === "int" ||
            (ch.kind === "multipleOf" && util.isInteger(ch.value)));
    }
    get isFinite() {
        let max = null, min = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "finite" ||
                ch.kind === "int" ||
                ch.kind === "multipleOf") {
                return true;
            }
            else if (ch.kind === "min") {
                if (min === null || ch.value > min)
                    min = ch.value;
            }
            else if (ch.kind === "max") {
                if (max === null || ch.value < max)
                    max = ch.value;
            }
        }
        return Number.isFinite(min) && Number.isFinite(max);
    }
}
ZodNumber.create = (params) => {
    return new ZodNumber({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodNumber,
        coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
        ...processCreateParams(params),
    });
};
class ZodBigInt extends ZodType {
    constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
    }
    _parse(input) {
        if (this._def.coerce) {
            try {
                input.data = BigInt(input.data);
            }
            catch (_a) {
                return this._getInvalidInput(input);
            }
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.bigint) {
            return this._getInvalidInput(input);
        }
        let ctx = undefined;
        const status = new ParseStatus();
        for (const check of this._def.checks) {
            if (check.kind === "min") {
                const tooSmall = check.inclusive
                    ? input.data < check.value
                    : input.data <= check.value;
                if (tooSmall) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_small,
                        type: "bigint",
                        minimum: check.value,
                        inclusive: check.inclusive,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "max") {
                const tooBig = check.inclusive
                    ? input.data > check.value
                    : input.data >= check.value;
                if (tooBig) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_big,
                        type: "bigint",
                        maximum: check.value,
                        inclusive: check.inclusive,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "multipleOf") {
                if (input.data % check.value !== BigInt(0)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.not_multiple_of,
                        multipleOf: check.value,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else {
                util.assertNever(check);
            }
        }
        return { status: status.value, value: input.data };
    }
    _getInvalidInput(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.bigint,
            received: ctx.parsedType,
        });
        return INVALID;
    }
    gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
    }
    gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
    }
    lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
    }
    lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
    }
    setLimit(kind, value, inclusive, message) {
        return new ZodBigInt({
            ...this._def,
            checks: [
                ...this._def.checks,
                {
                    kind,
                    value,
                    inclusive,
                    message: errorUtil.toString(message),
                },
            ],
        });
    }
    _addCheck(check) {
        return new ZodBigInt({
            ...this._def,
            checks: [...this._def.checks, check],
        });
    }
    positive(message) {
        return this._addCheck({
            kind: "min",
            value: BigInt(0),
            inclusive: false,
            message: errorUtil.toString(message),
        });
    }
    negative(message) {
        return this._addCheck({
            kind: "max",
            value: BigInt(0),
            inclusive: false,
            message: errorUtil.toString(message),
        });
    }
    nonpositive(message) {
        return this._addCheck({
            kind: "max",
            value: BigInt(0),
            inclusive: true,
            message: errorUtil.toString(message),
        });
    }
    nonnegative(message) {
        return this._addCheck({
            kind: "min",
            value: BigInt(0),
            inclusive: true,
            message: errorUtil.toString(message),
        });
    }
    multipleOf(value, message) {
        return this._addCheck({
            kind: "multipleOf",
            value,
            message: errorUtil.toString(message),
        });
    }
    get minValue() {
        let min = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "min") {
                if (min === null || ch.value > min)
                    min = ch.value;
            }
        }
        return min;
    }
    get maxValue() {
        let max = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "max") {
                if (max === null || ch.value < max)
                    max = ch.value;
            }
        }
        return max;
    }
}
ZodBigInt.create = (params) => {
    var _a;
    return new ZodBigInt({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodBigInt,
        coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
        ...processCreateParams(params),
    });
};
class ZodBoolean extends ZodType {
    _parse(input) {
        if (this._def.coerce) {
            input.data = Boolean(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.boolean) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.boolean,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        return OK(input.data);
    }
}
ZodBoolean.create = (params) => {
    return new ZodBoolean({
        typeName: ZodFirstPartyTypeKind.ZodBoolean,
        coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
        ...processCreateParams(params),
    });
};
class ZodDate extends ZodType {
    _parse(input) {
        if (this._def.coerce) {
            input.data = new Date(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.date) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.date,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        if (isNaN(input.data.getTime())) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_date,
            });
            return INVALID;
        }
        const status = new ParseStatus();
        let ctx = undefined;
        for (const check of this._def.checks) {
            if (check.kind === "min") {
                if (input.data.getTime() < check.value) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_small,
                        message: check.message,
                        inclusive: true,
                        exact: false,
                        minimum: check.value,
                        type: "date",
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "max") {
                if (input.data.getTime() > check.value) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_big,
                        message: check.message,
                        inclusive: true,
                        exact: false,
                        maximum: check.value,
                        type: "date",
                    });
                    status.dirty();
                }
            }
            else {
                util.assertNever(check);
            }
        }
        return {
            status: status.value,
            value: new Date(input.data.getTime()),
        };
    }
    _addCheck(check) {
        return new ZodDate({
            ...this._def,
            checks: [...this._def.checks, check],
        });
    }
    min(minDate, message) {
        return this._addCheck({
            kind: "min",
            value: minDate.getTime(),
            message: errorUtil.toString(message),
        });
    }
    max(maxDate, message) {
        return this._addCheck({
            kind: "max",
            value: maxDate.getTime(),
            message: errorUtil.toString(message),
        });
    }
    get minDate() {
        let min = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "min") {
                if (min === null || ch.value > min)
                    min = ch.value;
            }
        }
        return min != null ? new Date(min) : null;
    }
    get maxDate() {
        let max = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "max") {
                if (max === null || ch.value < max)
                    max = ch.value;
            }
        }
        return max != null ? new Date(max) : null;
    }
}
ZodDate.create = (params) => {
    return new ZodDate({
        checks: [],
        coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
        typeName: ZodFirstPartyTypeKind.ZodDate,
        ...processCreateParams(params),
    });
};
class ZodSymbol extends ZodType {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.symbol) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.symbol,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        return OK(input.data);
    }
}
ZodSymbol.create = (params) => {
    return new ZodSymbol({
        typeName: ZodFirstPartyTypeKind.ZodSymbol,
        ...processCreateParams(params),
    });
};
class ZodUndefined extends ZodType {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.undefined) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.undefined,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        return OK(input.data);
    }
}
ZodUndefined.create = (params) => {
    return new ZodUndefined({
        typeName: ZodFirstPartyTypeKind.ZodUndefined,
        ...processCreateParams(params),
    });
};
class ZodNull extends ZodType {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.null) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.null,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        return OK(input.data);
    }
}
ZodNull.create = (params) => {
    return new ZodNull({
        typeName: ZodFirstPartyTypeKind.ZodNull,
        ...processCreateParams(params),
    });
};
class ZodAny extends ZodType {
    constructor() {
        super(...arguments);
        // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
        this._any = true;
    }
    _parse(input) {
        return OK(input.data);
    }
}
ZodAny.create = (params) => {
    return new ZodAny({
        typeName: ZodFirstPartyTypeKind.ZodAny,
        ...processCreateParams(params),
    });
};
class ZodUnknown extends ZodType {
    constructor() {
        super(...arguments);
        // required
        this._unknown = true;
    }
    _parse(input) {
        return OK(input.data);
    }
}
ZodUnknown.create = (params) => {
    return new ZodUnknown({
        typeName: ZodFirstPartyTypeKind.ZodUnknown,
        ...processCreateParams(params),
    });
};
class ZodNever extends ZodType {
    _parse(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.never,
            received: ctx.parsedType,
        });
        return INVALID;
    }
}
ZodNever.create = (params) => {
    return new ZodNever({
        typeName: ZodFirstPartyTypeKind.ZodNever,
        ...processCreateParams(params),
    });
};
class ZodVoid extends ZodType {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.undefined) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.void,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        return OK(input.data);
    }
}
ZodVoid.create = (params) => {
    return new ZodVoid({
        typeName: ZodFirstPartyTypeKind.ZodVoid,
        ...processCreateParams(params),
    });
};
class ZodArray extends ZodType {
    _parse(input) {
        const { ctx, status } = this._processInputParams(input);
        const def = this._def;
        if (ctx.parsedType !== ZodParsedType.array) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.array,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        if (def.exactLength !== null) {
            const tooBig = ctx.data.length > def.exactLength.value;
            const tooSmall = ctx.data.length < def.exactLength.value;
            if (tooBig || tooSmall) {
                addIssueToContext(ctx, {
                    code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
                    minimum: (tooSmall ? def.exactLength.value : undefined),
                    maximum: (tooBig ? def.exactLength.value : undefined),
                    type: "array",
                    inclusive: true,
                    exact: true,
                    message: def.exactLength.message,
                });
                status.dirty();
            }
        }
        if (def.minLength !== null) {
            if (ctx.data.length < def.minLength.value) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.too_small,
                    minimum: def.minLength.value,
                    type: "array",
                    inclusive: true,
                    exact: false,
                    message: def.minLength.message,
                });
                status.dirty();
            }
        }
        if (def.maxLength !== null) {
            if (ctx.data.length > def.maxLength.value) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.too_big,
                    maximum: def.maxLength.value,
                    type: "array",
                    inclusive: true,
                    exact: false,
                    message: def.maxLength.message,
                });
                status.dirty();
            }
        }
        if (ctx.common.async) {
            return Promise.all([...ctx.data].map((item, i) => {
                return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
            })).then((result) => {
                return ParseStatus.mergeArray(status, result);
            });
        }
        const result = [...ctx.data].map((item, i) => {
            return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
        });
        return ParseStatus.mergeArray(status, result);
    }
    get element() {
        return this._def.type;
    }
    min(minLength, message) {
        return new ZodArray({
            ...this._def,
            minLength: { value: minLength, message: errorUtil.toString(message) },
        });
    }
    max(maxLength, message) {
        return new ZodArray({
            ...this._def,
            maxLength: { value: maxLength, message: errorUtil.toString(message) },
        });
    }
    length(len, message) {
        return new ZodArray({
            ...this._def,
            exactLength: { value: len, message: errorUtil.toString(message) },
        });
    }
    nonempty(message) {
        return this.min(1, message);
    }
}
ZodArray.create = (schema, params) => {
    return new ZodArray({
        type: schema,
        minLength: null,
        maxLength: null,
        exactLength: null,
        typeName: ZodFirstPartyTypeKind.ZodArray,
        ...processCreateParams(params),
    });
};
function deepPartialify(schema) {
    if (schema instanceof ZodObject) {
        const newShape = {};
        for (const key in schema.shape) {
            const fieldSchema = schema.shape[key];
            newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
        }
        return new ZodObject({
            ...schema._def,
            shape: () => newShape,
        });
    }
    else if (schema instanceof ZodArray) {
        return new ZodArray({
            ...schema._def,
            type: deepPartialify(schema.element),
        });
    }
    else if (schema instanceof ZodOptional) {
        return ZodOptional.create(deepPartialify(schema.unwrap()));
    }
    else if (schema instanceof ZodNullable) {
        return ZodNullable.create(deepPartialify(schema.unwrap()));
    }
    else if (schema instanceof ZodTuple) {
        return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
    }
    else {
        return schema;
    }
}
class ZodObject extends ZodType {
    constructor() {
        super(...arguments);
        this._cached = null;
        /**
         * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
         * If you want to pass through unknown properties, use `.passthrough()` instead.
         */
        this.nonstrict = this.passthrough;
        // extend<
        //   Augmentation extends ZodRawShape,
        //   NewOutput extends util.flatten<{
        //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
        //       ? Augmentation[k]["_output"]
        //       : k extends keyof Output
        //       ? Output[k]
        //       : never;
        //   }>,
        //   NewInput extends util.flatten<{
        //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
        //       ? Augmentation[k]["_input"]
        //       : k extends keyof Input
        //       ? Input[k]
        //       : never;
        //   }>
        // >(
        //   augmentation: Augmentation
        // ): ZodObject<
        //   extendShape<T, Augmentation>,
        //   UnknownKeys,
        //   Catchall,
        //   NewOutput,
        //   NewInput
        // > {
        //   return new ZodObject({
        //     ...this._def,
        //     shape: () => ({
        //       ...this._def.shape(),
        //       ...augmentation,
        //     }),
        //   }) as any;
        // }
        /**
         * @deprecated Use `.extend` instead
         *  */
        this.augment = this.extend;
    }
    _getCached() {
        if (this._cached !== null)
            return this._cached;
        const shape = this._def.shape();
        const keys = util.objectKeys(shape);
        return (this._cached = { shape, keys });
    }
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.object) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.object,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        const { status, ctx } = this._processInputParams(input);
        const { shape, keys: shapeKeys } = this._getCached();
        const extraKeys = [];
        if (!(this._def.catchall instanceof ZodNever &&
            this._def.unknownKeys === "strip")) {
            for (const key in ctx.data) {
                if (!shapeKeys.includes(key)) {
                    extraKeys.push(key);
                }
            }
        }
        const pairs = [];
        for (const key of shapeKeys) {
            const keyValidator = shape[key];
            const value = ctx.data[key];
            pairs.push({
                key: { status: "valid", value: key },
                value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
                alwaysSet: key in ctx.data,
            });
        }
        if (this._def.catchall instanceof ZodNever) {
            const unknownKeys = this._def.unknownKeys;
            if (unknownKeys === "passthrough") {
                for (const key of extraKeys) {
                    pairs.push({
                        key: { status: "valid", value: key },
                        value: { status: "valid", value: ctx.data[key] },
                    });
                }
            }
            else if (unknownKeys === "strict") {
                if (extraKeys.length > 0) {
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.unrecognized_keys,
                        keys: extraKeys,
                    });
                    status.dirty();
                }
            }
            else if (unknownKeys === "strip") ;
            else {
                throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
            }
        }
        else {
            // run catchall validation
            const catchall = this._def.catchall;
            for (const key of extraKeys) {
                const value = ctx.data[key];
                pairs.push({
                    key: { status: "valid", value: key },
                    value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)
                    ),
                    alwaysSet: key in ctx.data,
                });
            }
        }
        if (ctx.common.async) {
            return Promise.resolve()
                .then(async () => {
                const syncPairs = [];
                for (const pair of pairs) {
                    const key = await pair.key;
                    const value = await pair.value;
                    syncPairs.push({
                        key,
                        value,
                        alwaysSet: pair.alwaysSet,
                    });
                }
                return syncPairs;
            })
                .then((syncPairs) => {
                return ParseStatus.mergeObjectSync(status, syncPairs);
            });
        }
        else {
            return ParseStatus.mergeObjectSync(status, pairs);
        }
    }
    get shape() {
        return this._def.shape();
    }
    strict(message) {
        errorUtil.errToObj;
        return new ZodObject({
            ...this._def,
            unknownKeys: "strict",
            ...(message !== undefined
                ? {
                    errorMap: (issue, ctx) => {
                        var _a, _b, _c, _d;
                        const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
                        if (issue.code === "unrecognized_keys")
                            return {
                                message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,
                            };
                        return {
                            message: defaultError,
                        };
                    },
                }
                : {}),
        });
    }
    strip() {
        return new ZodObject({
            ...this._def,
            unknownKeys: "strip",
        });
    }
    passthrough() {
        return new ZodObject({
            ...this._def,
            unknownKeys: "passthrough",
        });
    }
    // const AugmentFactory =
    //   <Def extends ZodObjectDef>(def: Def) =>
    //   <Augmentation extends ZodRawShape>(
    //     augmentation: Augmentation
    //   ): ZodObject<
    //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
    //     Def["unknownKeys"],
    //     Def["catchall"]
    //   > => {
    //     return new ZodObject({
    //       ...def,
    //       shape: () => ({
    //         ...def.shape(),
    //         ...augmentation,
    //       }),
    //     }) as any;
    //   };
    extend(augmentation) {
        return new ZodObject({
            ...this._def,
            shape: () => ({
                ...this._def.shape(),
                ...augmentation,
            }),
        });
    }
    /**
     * Prior to zod@1.0.12 there was a bug in the
     * inferred type of merged objects. Please
     * upgrade if you are experiencing issues.
     */
    merge(merging) {
        const merged = new ZodObject({
            unknownKeys: merging._def.unknownKeys,
            catchall: merging._def.catchall,
            shape: () => ({
                ...this._def.shape(),
                ...merging._def.shape(),
            }),
            typeName: ZodFirstPartyTypeKind.ZodObject,
        });
        return merged;
    }
    // merge<
    //   Incoming extends AnyZodObject,
    //   Augmentation extends Incoming["shape"],
    //   NewOutput extends {
    //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
    //       ? Augmentation[k]["_output"]
    //       : k extends keyof Output
    //       ? Output[k]
    //       : never;
    //   },
    //   NewInput extends {
    //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
    //       ? Augmentation[k]["_input"]
    //       : k extends keyof Input
    //       ? Input[k]
    //       : never;
    //   }
    // >(
    //   merging: Incoming
    // ): ZodObject<
    //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
    //   Incoming["_def"]["unknownKeys"],
    //   Incoming["_def"]["catchall"],
    //   NewOutput,
    //   NewInput
    // > {
    //   const merged: any = new ZodObject({
    //     unknownKeys: merging._def.unknownKeys,
    //     catchall: merging._def.catchall,
    //     shape: () =>
    //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
    //     typeName: ZodFirstPartyTypeKind.ZodObject,
    //   }) as any;
    //   return merged;
    // }
    setKey(key, schema) {
        return this.augment({ [key]: schema });
    }
    // merge<Incoming extends AnyZodObject>(
    //   merging: Incoming
    // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
    // ZodObject<
    //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
    //   Incoming["_def"]["unknownKeys"],
    //   Incoming["_def"]["catchall"]
    // > {
    //   // const mergedShape = objectUtil.mergeShapes(
    //   //   this._def.shape(),
    //   //   merging._def.shape()
    //   // );
    //   const merged: any = new ZodObject({
    //     unknownKeys: merging._def.unknownKeys,
    //     catchall: merging._def.catchall,
    //     shape: () =>
    //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
    //     typeName: ZodFirstPartyTypeKind.ZodObject,
    //   }) as any;
    //   return merged;
    // }
    catchall(index) {
        return new ZodObject({
            ...this._def,
            catchall: index,
        });
    }
    pick(mask) {
        const shape = {};
        util.objectKeys(mask).forEach((key) => {
            if (mask[key] && this.shape[key]) {
                shape[key] = this.shape[key];
            }
        });
        return new ZodObject({
            ...this._def,
            shape: () => shape,
        });
    }
    omit(mask) {
        const shape = {};
        util.objectKeys(this.shape).forEach((key) => {
            if (!mask[key]) {
                shape[key] = this.shape[key];
            }
        });
        return new ZodObject({
            ...this._def,
            shape: () => shape,
        });
    }
    /**
     * @deprecated
     */
    deepPartial() {
        return deepPartialify(this);
    }
    partial(mask) {
        const newShape = {};
        util.objectKeys(this.shape).forEach((key) => {
            const fieldSchema = this.shape[key];
            if (mask && !mask[key]) {
                newShape[key] = fieldSchema;
            }
            else {
                newShape[key] = fieldSchema.optional();
            }
        });
        return new ZodObject({
            ...this._def,
            shape: () => newShape,
        });
    }
    required(mask) {
        const newShape = {};
        util.objectKeys(this.shape).forEach((key) => {
            if (mask && !mask[key]) {
                newShape[key] = this.shape[key];
            }
            else {
                const fieldSchema = this.shape[key];
                let newField = fieldSchema;
                while (newField instanceof ZodOptional) {
                    newField = newField._def.innerType;
                }
                newShape[key] = newField;
            }
        });
        return new ZodObject({
            ...this._def,
            shape: () => newShape,
        });
    }
    keyof() {
        return createZodEnum(util.objectKeys(this.shape));
    }
}
ZodObject.create = (shape, params) => {
    return new ZodObject({
        shape: () => shape,
        unknownKeys: "strip",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params),
    });
};
ZodObject.strictCreate = (shape, params) => {
    return new ZodObject({
        shape: () => shape,
        unknownKeys: "strict",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params),
    });
};
ZodObject.lazycreate = (shape, params) => {
    return new ZodObject({
        shape,
        unknownKeys: "strip",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params),
    });
};
class ZodUnion extends ZodType {
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        const options = this._def.options;
        function handleResults(results) {
            // return first issue-free validation if it exists
            for (const result of results) {
                if (result.result.status === "valid") {
                    return result.result;
                }
            }
            for (const result of results) {
                if (result.result.status === "dirty") {
                    // add issues from dirty option
                    ctx.common.issues.push(...result.ctx.common.issues);
                    return result.result;
                }
            }
            // return invalid
            const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_union,
                unionErrors,
            });
            return INVALID;
        }
        if (ctx.common.async) {
            return Promise.all(options.map(async (option) => {
                const childCtx = {
                    ...ctx,
                    common: {
                        ...ctx.common,
                        issues: [],
                    },
                    parent: null,
                };
                return {
                    result: await option._parseAsync({
                        data: ctx.data,
                        path: ctx.path,
                        parent: childCtx,
                    }),
                    ctx: childCtx,
                };
            })).then(handleResults);
        }
        else {
            let dirty = undefined;
            const issues = [];
            for (const option of options) {
                const childCtx = {
                    ...ctx,
                    common: {
                        ...ctx.common,
                        issues: [],
                    },
                    parent: null,
                };
                const result = option._parseSync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: childCtx,
                });
                if (result.status === "valid") {
                    return result;
                }
                else if (result.status === "dirty" && !dirty) {
                    dirty = { result, ctx: childCtx };
                }
                if (childCtx.common.issues.length) {
                    issues.push(childCtx.common.issues);
                }
            }
            if (dirty) {
                ctx.common.issues.push(...dirty.ctx.common.issues);
                return dirty.result;
            }
            const unionErrors = issues.map((issues) => new ZodError(issues));
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_union,
                unionErrors,
            });
            return INVALID;
        }
    }
    get options() {
        return this._def.options;
    }
}
ZodUnion.create = (types, params) => {
    return new ZodUnion({
        options: types,
        typeName: ZodFirstPartyTypeKind.ZodUnion,
        ...processCreateParams(params),
    });
};
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//////////                                 //////////
//////////      ZodDiscriminatedUnion      //////////
//////////                                 //////////
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
const getDiscriminator = (type) => {
    if (type instanceof ZodLazy) {
        return getDiscriminator(type.schema);
    }
    else if (type instanceof ZodEffects) {
        return getDiscriminator(type.innerType());
    }
    else if (type instanceof ZodLiteral) {
        return [type.value];
    }
    else if (type instanceof ZodEnum) {
        return type.options;
    }
    else if (type instanceof ZodNativeEnum) {
        // eslint-disable-next-line ban/ban
        return util.objectValues(type.enum);
    }
    else if (type instanceof ZodDefault) {
        return getDiscriminator(type._def.innerType);
    }
    else if (type instanceof ZodUndefined) {
        return [undefined];
    }
    else if (type instanceof ZodNull) {
        return [null];
    }
    else if (type instanceof ZodOptional) {
        return [undefined, ...getDiscriminator(type.unwrap())];
    }
    else if (type instanceof ZodNullable) {
        return [null, ...getDiscriminator(type.unwrap())];
    }
    else if (type instanceof ZodBranded) {
        return getDiscriminator(type.unwrap());
    }
    else if (type instanceof ZodReadonly) {
        return getDiscriminator(type.unwrap());
    }
    else if (type instanceof ZodCatch) {
        return getDiscriminator(type._def.innerType);
    }
    else {
        return [];
    }
};
class ZodDiscriminatedUnion extends ZodType {
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.object,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        const discriminator = this.discriminator;
        const discriminatorValue = ctx.data[discriminator];
        const option = this.optionsMap.get(discriminatorValue);
        if (!option) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_union_discriminator,
                options: Array.from(this.optionsMap.keys()),
                path: [discriminator],
            });
            return INVALID;
        }
        if (ctx.common.async) {
            return option._parseAsync({
                data: ctx.data,
                path: ctx.path,
                parent: ctx,
            });
        }
        else {
            return option._parseSync({
                data: ctx.data,
                path: ctx.path,
                parent: ctx,
            });
        }
    }
    get discriminator() {
        return this._def.discriminator;
    }
    get options() {
        return this._def.options;
    }
    get optionsMap() {
        return this._def.optionsMap;
    }
    /**
     * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
     * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
     * have a different value for each object in the union.
     * @param discriminator the name of the discriminator property
     * @param types an array of object schemas
     * @param params
     */
    static create(discriminator, options, params) {
        // Get all the valid discriminator values
        const optionsMap = new Map();
        // try {
        for (const type of options) {
            const discriminatorValues = getDiscriminator(type.shape[discriminator]);
            if (!discriminatorValues.length) {
                throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
            }
            for (const value of discriminatorValues) {
                if (optionsMap.has(value)) {
                    throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
                }
                optionsMap.set(value, type);
            }
        }
        return new ZodDiscriminatedUnion({
            typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
            discriminator,
            options,
            optionsMap,
            ...processCreateParams(params),
        });
    }
}
function mergeValues(a, b) {
    const aType = getParsedType(a);
    const bType = getParsedType(b);
    if (a === b) {
        return { valid: true, data: a };
    }
    else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
        const bKeys = util.objectKeys(b);
        const sharedKeys = util
            .objectKeys(a)
            .filter((key) => bKeys.indexOf(key) !== -1);
        const newObj = { ...a, ...b };
        for (const key of sharedKeys) {
            const sharedValue = mergeValues(a[key], b[key]);
            if (!sharedValue.valid) {
                return { valid: false };
            }
            newObj[key] = sharedValue.data;
        }
        return { valid: true, data: newObj };
    }
    else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
        if (a.length !== b.length) {
            return { valid: false };
        }
        const newArray = [];
        for (let index = 0; index < a.length; index++) {
            const itemA = a[index];
            const itemB = b[index];
            const sharedValue = mergeValues(itemA, itemB);
            if (!sharedValue.valid) {
                return { valid: false };
            }
            newArray.push(sharedValue.data);
        }
        return { valid: true, data: newArray };
    }
    else if (aType === ZodParsedType.date &&
        bType === ZodParsedType.date &&
        +a === +b) {
        return { valid: true, data: a };
    }
    else {
        return { valid: false };
    }
}
class ZodIntersection extends ZodType {
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const handleParsed = (parsedLeft, parsedRight) => {
            if (isAborted(parsedLeft) || isAborted(parsedRight)) {
                return INVALID;
            }
            const merged = mergeValues(parsedLeft.value, parsedRight.value);
            if (!merged.valid) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_intersection_types,
                });
                return INVALID;
            }
            if (isDirty(parsedLeft) || isDirty(parsedRight)) {
                status.dirty();
            }
            return { status: status.value, value: merged.data };
        };
        if (ctx.common.async) {
            return Promise.all([
                this._def.left._parseAsync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                }),
                this._def.right._parseAsync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                }),
            ]).then(([left, right]) => handleParsed(left, right));
        }
        else {
            return handleParsed(this._def.left._parseSync({
                data: ctx.data,
                path: ctx.path,
                parent: ctx,
            }), this._def.right._parseSync({
                data: ctx.data,
                path: ctx.path,
                parent: ctx,
            }));
        }
    }
}
ZodIntersection.create = (left, right, params) => {
    return new ZodIntersection({
        left: left,
        right: right,
        typeName: ZodFirstPartyTypeKind.ZodIntersection,
        ...processCreateParams(params),
    });
};
class ZodTuple extends ZodType {
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.array) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.array,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        if (ctx.data.length < this._def.items.length) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: this._def.items.length,
                inclusive: true,
                exact: false,
                type: "array",
            });
            return INVALID;
        }
        const rest = this._def.rest;
        if (!rest && ctx.data.length > this._def.items.length) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: this._def.items.length,
                inclusive: true,
                exact: false,
                type: "array",
            });
            status.dirty();
        }
        const items = [...ctx.data]
            .map((item, itemIndex) => {
            const schema = this._def.items[itemIndex] || this._def.rest;
            if (!schema)
                return null;
            return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
        })
            .filter((x) => !!x); // filter nulls
        if (ctx.common.async) {
            return Promise.all(items).then((results) => {
                return ParseStatus.mergeArray(status, results);
            });
        }
        else {
            return ParseStatus.mergeArray(status, items);
        }
    }
    get items() {
        return this._def.items;
    }
    rest(rest) {
        return new ZodTuple({
            ...this._def,
            rest,
        });
    }
}
ZodTuple.create = (schemas, params) => {
    if (!Array.isArray(schemas)) {
        throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
    }
    return new ZodTuple({
        items: schemas,
        typeName: ZodFirstPartyTypeKind.ZodTuple,
        rest: null,
        ...processCreateParams(params),
    });
};
class ZodRecord extends ZodType {
    get keySchema() {
        return this._def.keyType;
    }
    get valueSchema() {
        return this._def.valueType;
    }
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.object,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        const pairs = [];
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        for (const key in ctx.data) {
            pairs.push({
                key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
                value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
                alwaysSet: key in ctx.data,
            });
        }
        if (ctx.common.async) {
            return ParseStatus.mergeObjectAsync(status, pairs);
        }
        else {
            return ParseStatus.mergeObjectSync(status, pairs);
        }
    }
    get element() {
        return this._def.valueType;
    }
    static create(first, second, third) {
        if (second instanceof ZodType) {
            return new ZodRecord({
                keyType: first,
                valueType: second,
                typeName: ZodFirstPartyTypeKind.ZodRecord,
                ...processCreateParams(third),
            });
        }
        return new ZodRecord({
            keyType: ZodString.create(),
            valueType: first,
            typeName: ZodFirstPartyTypeKind.ZodRecord,
            ...processCreateParams(second),
        });
    }
}
class ZodMap extends ZodType {
    get keySchema() {
        return this._def.keyType;
    }
    get valueSchema() {
        return this._def.valueType;
    }
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.map) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.map,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        const pairs = [...ctx.data.entries()].map(([key, value], index) => {
            return {
                key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
                value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])),
            };
        });
        if (ctx.common.async) {
            const finalMap = new Map();
            return Promise.resolve().then(async () => {
                for (const pair of pairs) {
                    const key = await pair.key;
                    const value = await pair.value;
                    if (key.status === "aborted" || value.status === "aborted") {
                        return INVALID;
                    }
                    if (key.status === "dirty" || value.status === "dirty") {
                        status.dirty();
                    }
                    finalMap.set(key.value, value.value);
                }
                return { status: status.value, value: finalMap };
            });
        }
        else {
            const finalMap = new Map();
            for (const pair of pairs) {
                const key = pair.key;
                const value = pair.value;
                if (key.status === "aborted" || value.status === "aborted") {
                    return INVALID;
                }
                if (key.status === "dirty" || value.status === "dirty") {
                    status.dirty();
                }
                finalMap.set(key.value, value.value);
            }
            return { status: status.value, value: finalMap };
        }
    }
}
ZodMap.create = (keyType, valueType, params) => {
    return new ZodMap({
        valueType,
        keyType,
        typeName: ZodFirstPartyTypeKind.ZodMap,
        ...processCreateParams(params),
    });
};
class ZodSet extends ZodType {
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.set) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.set,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        const def = this._def;
        if (def.minSize !== null) {
            if (ctx.data.size < def.minSize.value) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.too_small,
                    minimum: def.minSize.value,
                    type: "set",
                    inclusive: true,
                    exact: false,
                    message: def.minSize.message,
                });
                status.dirty();
            }
        }
        if (def.maxSize !== null) {
            if (ctx.data.size > def.maxSize.value) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.too_big,
                    maximum: def.maxSize.value,
                    type: "set",
                    inclusive: true,
                    exact: false,
                    message: def.maxSize.message,
                });
                status.dirty();
            }
        }
        const valueType = this._def.valueType;
        function finalizeSet(elements) {
            const parsedSet = new Set();
            for (const element of elements) {
                if (element.status === "aborted")
                    return INVALID;
                if (element.status === "dirty")
                    status.dirty();
                parsedSet.add(element.value);
            }
            return { status: status.value, value: parsedSet };
        }
        const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
        if (ctx.common.async) {
            return Promise.all(elements).then((elements) => finalizeSet(elements));
        }
        else {
            return finalizeSet(elements);
        }
    }
    min(minSize, message) {
        return new ZodSet({
            ...this._def,
            minSize: { value: minSize, message: errorUtil.toString(message) },
        });
    }
    max(maxSize, message) {
        return new ZodSet({
            ...this._def,
            maxSize: { value: maxSize, message: errorUtil.toString(message) },
        });
    }
    size(size, message) {
        return this.min(size, message).max(size, message);
    }
    nonempty(message) {
        return this.min(1, message);
    }
}
ZodSet.create = (valueType, params) => {
    return new ZodSet({
        valueType,
        minSize: null,
        maxSize: null,
        typeName: ZodFirstPartyTypeKind.ZodSet,
        ...processCreateParams(params),
    });
};
class ZodFunction extends ZodType {
    constructor() {
        super(...arguments);
        this.validate = this.implement;
    }
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.function) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.function,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        function makeArgsIssue(args, error) {
            return makeIssue({
                data: args,
                path: ctx.path,
                errorMaps: [
                    ctx.common.contextualErrorMap,
                    ctx.schemaErrorMap,
                    getErrorMap(),
                    errorMap,
                ].filter((x) => !!x),
                issueData: {
                    code: ZodIssueCode.invalid_arguments,
                    argumentsError: error,
                },
            });
        }
        function makeReturnsIssue(returns, error) {
            return makeIssue({
                data: returns,
                path: ctx.path,
                errorMaps: [
                    ctx.common.contextualErrorMap,
                    ctx.schemaErrorMap,
                    getErrorMap(),
                    errorMap,
                ].filter((x) => !!x),
                issueData: {
                    code: ZodIssueCode.invalid_return_type,
                    returnTypeError: error,
                },
            });
        }
        const params = { errorMap: ctx.common.contextualErrorMap };
        const fn = ctx.data;
        if (this._def.returns instanceof ZodPromise) {
            // Would love a way to avoid disabling this rule, but we need
            // an alias (using an arrow function was what caused 2651).
            // eslint-disable-next-line @typescript-eslint/no-this-alias
            const me = this;
            return OK(async function (...args) {
                const error = new ZodError([]);
                const parsedArgs = await me._def.args
                    .parseAsync(args, params)
                    .catch((e) => {
                    error.addIssue(makeArgsIssue(args, e));
                    throw error;
                });
                const result = await Reflect.apply(fn, this, parsedArgs);
                const parsedReturns = await me._def.returns._def.type
                    .parseAsync(result, params)
                    .catch((e) => {
                    error.addIssue(makeReturnsIssue(result, e));
                    throw error;
                });
                return parsedReturns;
            });
        }
        else {
            // Would love a way to avoid disabling this rule, but we need
            // an alias (using an arrow function was what caused 2651).
            // eslint-disable-next-line @typescript-eslint/no-this-alias
            const me = this;
            return OK(function (...args) {
                const parsedArgs = me._def.args.safeParse(args, params);
                if (!parsedArgs.success) {
                    throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
                }
                const result = Reflect.apply(fn, this, parsedArgs.data);
                const parsedReturns = me._def.returns.safeParse(result, params);
                if (!parsedReturns.success) {
                    throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
                }
                return parsedReturns.data;
            });
        }
    }
    parameters() {
        return this._def.args;
    }
    returnType() {
        return this._def.returns;
    }
    args(...items) {
        return new ZodFunction({
            ...this._def,
            args: ZodTuple.create(items).rest(ZodUnknown.create()),
        });
    }
    returns(returnType) {
        return new ZodFunction({
            ...this._def,
            returns: returnType,
        });
    }
    implement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
    }
    strictImplement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
    }
    static create(args, returns, params) {
        return new ZodFunction({
            args: (args
                ? args
                : ZodTuple.create([]).rest(ZodUnknown.create())),
            returns: returns || ZodUnknown.create(),
            typeName: ZodFirstPartyTypeKind.ZodFunction,
            ...processCreateParams(params),
        });
    }
}
class ZodLazy extends ZodType {
    get schema() {
        return this._def.getter();
    }
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        const lazySchema = this._def.getter();
        return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
    }
}
ZodLazy.create = (getter, params) => {
    return new ZodLazy({
        getter: getter,
        typeName: ZodFirstPartyTypeKind.ZodLazy,
        ...processCreateParams(params),
    });
};
class ZodLiteral extends ZodType {
    _parse(input) {
        if (input.data !== this._def.value) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                received: ctx.data,
                code: ZodIssueCode.invalid_literal,
                expected: this._def.value,
            });
            return INVALID;
        }
        return { status: "valid", value: input.data };
    }
    get value() {
        return this._def.value;
    }
}
ZodLiteral.create = (value, params) => {
    return new ZodLiteral({
        value: value,
        typeName: ZodFirstPartyTypeKind.ZodLiteral,
        ...processCreateParams(params),
    });
};
function createZodEnum(values, params) {
    return new ZodEnum({
        values,
        typeName: ZodFirstPartyTypeKind.ZodEnum,
        ...processCreateParams(params),
    });
}
class ZodEnum extends ZodType {
    constructor() {
        super(...arguments);
        _ZodEnum_cache.set(this, void 0);
    }
    _parse(input) {
        if (typeof input.data !== "string") {
            const ctx = this._getOrReturnCtx(input);
            const expectedValues = this._def.values;
            addIssueToContext(ctx, {
                expected: util.joinValues(expectedValues),
                received: ctx.parsedType,
                code: ZodIssueCode.invalid_type,
            });
            return INVALID;
        }
        if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
            __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
        }
        if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
            const ctx = this._getOrReturnCtx(input);
            const expectedValues = this._def.values;
            addIssueToContext(ctx, {
                received: ctx.data,
                code: ZodIssueCode.invalid_enum_value,
                options: expectedValues,
            });
            return INVALID;
        }
        return OK(input.data);
    }
    get options() {
        return this._def.values;
    }
    get enum() {
        const enumValues = {};
        for (const val of this._def.values) {
            enumValues[val] = val;
        }
        return enumValues;
    }
    get Values() {
        const enumValues = {};
        for (const val of this._def.values) {
            enumValues[val] = val;
        }
        return enumValues;
    }
    get Enum() {
        const enumValues = {};
        for (const val of this._def.values) {
            enumValues[val] = val;
        }
        return enumValues;
    }
    extract(values, newDef = this._def) {
        return ZodEnum.create(values, {
            ...this._def,
            ...newDef,
        });
    }
    exclude(values, newDef = this._def) {
        return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
            ...this._def,
            ...newDef,
        });
    }
}
_ZodEnum_cache = new WeakMap();
ZodEnum.create = createZodEnum;
class ZodNativeEnum extends ZodType {
    constructor() {
        super(...arguments);
        _ZodNativeEnum_cache.set(this, void 0);
    }
    _parse(input) {
        const nativeEnumValues = util.getValidEnumValues(this._def.values);
        const ctx = this._getOrReturnCtx(input);
        if (ctx.parsedType !== ZodParsedType.string &&
            ctx.parsedType !== ZodParsedType.number) {
            const expectedValues = util.objectValues(nativeEnumValues);
            addIssueToContext(ctx, {
                expected: util.joinValues(expectedValues),
                received: ctx.parsedType,
                code: ZodIssueCode.invalid_type,
            });
            return INVALID;
        }
        if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
            __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");
        }
        if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
            const expectedValues = util.objectValues(nativeEnumValues);
            addIssueToContext(ctx, {
                received: ctx.data,
                code: ZodIssueCode.invalid_enum_value,
                options: expectedValues,
            });
            return INVALID;
        }
        return OK(input.data);
    }
    get enum() {
        return this._def.values;
    }
}
_ZodNativeEnum_cache = new WeakMap();
ZodNativeEnum.create = (values, params) => {
    return new ZodNativeEnum({
        values: values,
        typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
        ...processCreateParams(params),
    });
};
class ZodPromise extends ZodType {
    unwrap() {
        return this._def.type;
    }
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.promise &&
            ctx.common.async === false) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.promise,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        const promisified = ctx.parsedType === ZodParsedType.promise
            ? ctx.data
            : Promise.resolve(ctx.data);
        return OK(promisified.then((data) => {
            return this._def.type.parseAsync(data, {
                path: ctx.path,
                errorMap: ctx.common.contextualErrorMap,
            });
        }));
    }
}
ZodPromise.create = (schema, params) => {
    return new ZodPromise({
        type: schema,
        typeName: ZodFirstPartyTypeKind.ZodPromise,
        ...processCreateParams(params),
    });
};
class ZodEffects extends ZodType {
    innerType() {
        return this._def.schema;
    }
    sourceType() {
        return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects
            ? this._def.schema.sourceType()
            : this._def.schema;
    }
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const effect = this._def.effect || null;
        const checkCtx = {
            addIssue: (arg) => {
                addIssueToContext(ctx, arg);
                if (arg.fatal) {
                    status.abort();
                }
                else {
                    status.dirty();
                }
            },
            get path() {
                return ctx.path;
            },
        };
        checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
        if (effect.type === "preprocess") {
            const processed = effect.transform(ctx.data, checkCtx);
            if (ctx.common.async) {
                return Promise.resolve(processed).then(async (processed) => {
                    if (status.value === "aborted")
                        return INVALID;
                    const result = await this._def.schema._parseAsync({
                        data: processed,
                        path: ctx.path,
                        parent: ctx,
                    });
                    if (result.status === "aborted")
                        return INVALID;
                    if (result.status === "dirty")
                        return DIRTY(result.value);
                    if (status.value === "dirty")
                        return DIRTY(result.value);
                    return result;
                });
            }
            else {
                if (status.value === "aborted")
                    return INVALID;
                const result = this._def.schema._parseSync({
                    data: processed,
                    path: ctx.path,
                    parent: ctx,
                });
                if (result.status === "aborted")
                    return INVALID;
                if (result.status === "dirty")
                    return DIRTY(result.value);
                if (status.value === "dirty")
                    return DIRTY(result.value);
                return result;
            }
        }
        if (effect.type === "refinement") {
            const executeRefinement = (acc) => {
                const result = effect.refinement(acc, checkCtx);
                if (ctx.common.async) {
                    return Promise.resolve(result);
                }
                if (result instanceof Promise) {
                    throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
                }
                return acc;
            };
            if (ctx.common.async === false) {
                const inner = this._def.schema._parseSync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                });
                if (inner.status === "aborted")
                    return INVALID;
                if (inner.status === "dirty")
                    status.dirty();
                // return value is ignored
                executeRefinement(inner.value);
                return { status: status.value, value: inner.value };
            }
            else {
                return this._def.schema
                    ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
                    .then((inner) => {
                    if (inner.status === "aborted")
                        return INVALID;
                    if (inner.status === "dirty")
                        status.dirty();
                    return executeRefinement(inner.value).then(() => {
                        return { status: status.value, value: inner.value };
                    });
                });
            }
        }
        if (effect.type === "transform") {
            if (ctx.common.async === false) {
                const base = this._def.schema._parseSync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                });
                if (!isValid(base))
                    return base;
                const result = effect.transform(base.value, checkCtx);
                if (result instanceof Promise) {
                    throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
                }
                return { status: status.value, value: result };
            }
            else {
                return this._def.schema
                    ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
                    .then((base) => {
                    if (!isValid(base))
                        return base;
                    return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
                });
            }
        }
        util.assertNever(effect);
    }
}
ZodEffects.create = (schema, effect, params) => {
    return new ZodEffects({
        schema,
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        effect,
        ...processCreateParams(params),
    });
};
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
    return new ZodEffects({
        schema,
        effect: { type: "preprocess", transform: preprocess },
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        ...processCreateParams(params),
    });
};
class ZodOptional extends ZodType {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === ZodParsedType.undefined) {
            return OK(undefined);
        }
        return this._def.innerType._parse(input);
    }
    unwrap() {
        return this._def.innerType;
    }
}
ZodOptional.create = (type, params) => {
    return new ZodOptional({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodOptional,
        ...processCreateParams(params),
    });
};
class ZodNullable extends ZodType {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === ZodParsedType.null) {
            return OK(null);
        }
        return this._def.innerType._parse(input);
    }
    unwrap() {
        return this._def.innerType;
    }
}
ZodNullable.create = (type, params) => {
    return new ZodNullable({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodNullable,
        ...processCreateParams(params),
    });
};
class ZodDefault extends ZodType {
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        let data = ctx.data;
        if (ctx.parsedType === ZodParsedType.undefined) {
            data = this._def.defaultValue();
        }
        return this._def.innerType._parse({
            data,
            path: ctx.path,
            parent: ctx,
        });
    }
    removeDefault() {
        return this._def.innerType;
    }
}
ZodDefault.create = (type, params) => {
    return new ZodDefault({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodDefault,
        defaultValue: typeof params.default === "function"
            ? params.default
            : () => params.default,
        ...processCreateParams(params),
    });
};
class ZodCatch extends ZodType {
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        // newCtx is used to not collect issues from inner types in ctx
        const newCtx = {
            ...ctx,
            common: {
                ...ctx.common,
                issues: [],
            },
        };
        const result = this._def.innerType._parse({
            data: newCtx.data,
            path: newCtx.path,
            parent: {
                ...newCtx,
            },
        });
        if (isAsync(result)) {
            return result.then((result) => {
                return {
                    status: "valid",
                    value: result.status === "valid"
                        ? result.value
                        : this._def.catchValue({
                            get error() {
                                return new ZodError(newCtx.common.issues);
                            },
                            input: newCtx.data,
                        }),
                };
            });
        }
        else {
            return {
                status: "valid",
                value: result.status === "valid"
                    ? result.value
                    : this._def.catchValue({
                        get error() {
                            return new ZodError(newCtx.common.issues);
                        },
                        input: newCtx.data,
                    }),
            };
        }
    }
    removeCatch() {
        return this._def.innerType;
    }
}
ZodCatch.create = (type, params) => {
    return new ZodCatch({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodCatch,
        catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
        ...processCreateParams(params),
    });
};
class ZodNaN extends ZodType {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.nan) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.nan,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        return { status: "valid", value: input.data };
    }
}
ZodNaN.create = (params) => {
    return new ZodNaN({
        typeName: ZodFirstPartyTypeKind.ZodNaN,
        ...processCreateParams(params),
    });
};
const BRAND = Symbol("zod_brand");
class ZodBranded extends ZodType {
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        const data = ctx.data;
        return this._def.type._parse({
            data,
            path: ctx.path,
            parent: ctx,
        });
    }
    unwrap() {
        return this._def.type;
    }
}
class ZodPipeline extends ZodType {
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.common.async) {
            const handleAsync = async () => {
                const inResult = await this._def.in._parseAsync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                });
                if (inResult.status === "aborted")
                    return INVALID;
                if (inResult.status === "dirty") {
                    status.dirty();
                    return DIRTY(inResult.value);
                }
                else {
                    return this._def.out._parseAsync({
                        data: inResult.value,
                        path: ctx.path,
                        parent: ctx,
                    });
                }
            };
            return handleAsync();
        }
        else {
            const inResult = this._def.in._parseSync({
                data: ctx.data,
                path: ctx.path,
                parent: ctx,
            });
            if (inResult.status === "aborted")
                return INVALID;
            if (inResult.status === "dirty") {
                status.dirty();
                return {
                    status: "dirty",
                    value: inResult.value,
                };
            }
            else {
                return this._def.out._parseSync({
                    data: inResult.value,
                    path: ctx.path,
                    parent: ctx,
                });
            }
        }
    }
    static create(a, b) {
        return new ZodPipeline({
            in: a,
            out: b,
            typeName: ZodFirstPartyTypeKind.ZodPipeline,
        });
    }
}
class ZodReadonly extends ZodType {
    _parse(input) {
        const result = this._def.innerType._parse(input);
        const freeze = (data) => {
            if (isValid(data)) {
                data.value = Object.freeze(data.value);
            }
            return data;
        };
        return isAsync(result)
            ? result.then((data) => freeze(data))
            : freeze(result);
    }
    unwrap() {
        return this._def.innerType;
    }
}
ZodReadonly.create = (type, params) => {
    return new ZodReadonly({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodReadonly,
        ...processCreateParams(params),
    });
};
////////////////////////////////////////
////////////////////////////////////////
//////////                    //////////
//////////      z.custom      //////////
//////////                    //////////
////////////////////////////////////////
////////////////////////////////////////
function cleanParams(params, data) {
    const p = typeof params === "function"
        ? params(data)
        : typeof params === "string"
            ? { message: params }
            : params;
    const p2 = typeof p === "string" ? { message: p } : p;
    return p2;
}
function custom(check, _params = {}, 
/**
 * @deprecated
 *
 * Pass `fatal` into the params object instead:
 *
 * ```ts
 * z.string().custom((val) => val.length > 5, { fatal: false })
 * ```
 *
 */
fatal) {
    if (check)
        return ZodAny.create().superRefine((data, ctx) => {
            var _a, _b;
            const r = check(data);
            if (r instanceof Promise) {
                return r.then((r) => {
                    var _a, _b;
                    if (!r) {
                        const params = cleanParams(_params, data);
                        const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
                        ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
                    }
                });
            }
            if (!r) {
                const params = cleanParams(_params, data);
                const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
                ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
            }
            return;
        });
    return ZodAny.create();
}
const late = {
    object: ZodObject.lazycreate,
};
var ZodFirstPartyTypeKind;
(function (ZodFirstPartyTypeKind) {
    ZodFirstPartyTypeKind["ZodString"] = "ZodString";
    ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
    ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
    ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
    ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
    ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
    ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
    ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
    ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
    ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
    ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
    ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
    ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
    ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
    ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
    ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
    ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
    ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
    ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
    ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
    ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
    ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
    ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
    ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
    ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
    ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
    ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
    ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
    ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
    ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
    ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
    ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
    ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
    ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
    ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
    ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
const instanceOfType = (
// const instanceOfType = <T extends new (...args: any[]) => any>(
cls, params = {
    message: `Input not instance of ${cls.name}`,
}) => custom((data) => data instanceof cls, params);
const stringType = ZodString.create;
const numberType = ZodNumber.create;
const nanType = ZodNaN.create;
const bigIntType = ZodBigInt.create;
const booleanType = ZodBoolean.create;
const dateType = ZodDate.create;
const symbolType = ZodSymbol.create;
const undefinedType = ZodUndefined.create;
const nullType = ZodNull.create;
const anyType = ZodAny.create;
const unknownType = ZodUnknown.create;
const neverType = ZodNever.create;
const voidType = ZodVoid.create;
const arrayType = ZodArray.create;
const objectType = ZodObject.create;
const strictObjectType = ZodObject.strictCreate;
const unionType = ZodUnion.create;
const discriminatedUnionType = ZodDiscriminatedUnion.create;
const intersectionType = ZodIntersection.create;
const tupleType = ZodTuple.create;
const recordType = ZodRecord.create;
const mapType = ZodMap.create;
const setType = ZodSet.create;
const functionType = ZodFunction.create;
const lazyType = ZodLazy.create;
const literalType = ZodLiteral.create;
const enumType = ZodEnum.create;
const nativeEnumType = ZodNativeEnum.create;
const promiseType = ZodPromise.create;
const effectsType = ZodEffects.create;
const optionalType = ZodOptional.create;
const nullableType = ZodNullable.create;
const preprocessType = ZodEffects.createWithPreprocess;
const pipelineType = ZodPipeline.create;
const ostring = () => stringType().optional();
const onumber = () => numberType().optional();
const oboolean = () => booleanType().optional();
const coerce = {
    string: ((arg) => ZodString.create({ ...arg, coerce: true })),
    number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
    boolean: ((arg) => ZodBoolean.create({
        ...arg,
        coerce: true,
    })),
    bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
    date: ((arg) => ZodDate.create({ ...arg, coerce: true })),
};
const NEVER = INVALID;

var z = /*#__PURE__*/Object.freeze({
    __proto__: null,
    defaultErrorMap: errorMap,
    setErrorMap: setErrorMap,
    getErrorMap: getErrorMap,
    makeIssue: makeIssue,
    EMPTY_PATH: EMPTY_PATH,
    addIssueToContext: addIssueToContext,
    ParseStatus: ParseStatus,
    INVALID: INVALID,
    DIRTY: DIRTY,
    OK: OK,
    isAborted: isAborted,
    isDirty: isDirty,
    isValid: isValid,
    isAsync: isAsync,
    get util () { return util; },
    get objectUtil () { return objectUtil; },
    ZodParsedType: ZodParsedType,
    getParsedType: getParsedType,
    ZodType: ZodType,
    datetimeRegex: datetimeRegex,
    ZodString: ZodString,
    ZodNumber: ZodNumber,
    ZodBigInt: ZodBigInt,
    ZodBoolean: ZodBoolean,
    ZodDate: ZodDate,
    ZodSymbol: ZodSymbol,
    ZodUndefined: ZodUndefined,
    ZodNull: ZodNull,
    ZodAny: ZodAny,
    ZodUnknown: ZodUnknown,
    ZodNever: ZodNever,
    ZodVoid: ZodVoid,
    ZodArray: ZodArray,
    ZodObject: ZodObject,
    ZodUnion: ZodUnion,
    ZodDiscriminatedUnion: ZodDiscriminatedUnion,
    ZodIntersection: ZodIntersection,
    ZodTuple: ZodTuple,
    ZodRecord: ZodRecord,
    ZodMap: ZodMap,
    ZodSet: ZodSet,
    ZodFunction: ZodFunction,
    ZodLazy: ZodLazy,
    ZodLiteral: ZodLiteral,
    ZodEnum: ZodEnum,
    ZodNativeEnum: ZodNativeEnum,
    ZodPromise: ZodPromise,
    ZodEffects: ZodEffects,
    ZodTransformer: ZodEffects,
    ZodOptional: ZodOptional,
    ZodNullable: ZodNullable,
    ZodDefault: ZodDefault,
    ZodCatch: ZodCatch,
    ZodNaN: ZodNaN,
    BRAND: BRAND,
    ZodBranded: ZodBranded,
    ZodPipeline: ZodPipeline,
    ZodReadonly: ZodReadonly,
    custom: custom,
    Schema: ZodType,
    ZodSchema: ZodType,
    late: late,
    get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },
    coerce: coerce,
    any: anyType,
    array: arrayType,
    bigint: bigIntType,
    boolean: booleanType,
    date: dateType,
    discriminatedUnion: discriminatedUnionType,
    effect: effectsType,
    'enum': enumType,
    'function': functionType,
    'instanceof': instanceOfType,
    intersection: intersectionType,
    lazy: lazyType,
    literal: literalType,
    map: mapType,
    nan: nanType,
    nativeEnum: nativeEnumType,
    never: neverType,
    'null': nullType,
    nullable: nullableType,
    number: numberType,
    object: objectType,
    oboolean: oboolean,
    onumber: onumber,
    optional: optionalType,
    ostring: ostring,
    pipeline: pipelineType,
    preprocess: preprocessType,
    promise: promiseType,
    record: recordType,
    set: setType,
    strictObject: strictObjectType,
    string: stringType,
    symbol: symbolType,
    transformer: effectsType,
    tuple: tupleType,
    'undefined': undefinedType,
    union: unionType,
    unknown: unknownType,
    'void': voidType,
    NEVER: NEVER,
    ZodIssueCode: ZodIssueCode,
    quotelessJson: quotelessJson,
    ZodError: ZodError
});




/***/ }),

/***/ 21987:
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"options_popup_title_placeholder":{"message":"Enter a filter name"},"options_filters_list_search_display_option_all_filters":{"message":"All filters"},"options_filters_list_search_display_option_enabled":{"message":"Enabled"},"options_filters_list_search_display_option_disabled":{"message":"Disabled"},"options_filters_empty_title":{"message":"Nothing found"},"options_antibanner_custom_filter_already_exists":{"message":"This custom filter has already been added"},"options_filters_annoyances_consent_title":{"message":"Please read carefully before enabling annoyance filters"},"options_filters_annoyances_consent_description":{"message":"You are about to enable one or more annoyance filters. They block elements that are either unrelated to website content or related but annoying to your user experience. Website owners may consider these elements mandatory: if you block them, you may be violating their terms; some functionality of websites may not be available or may not work properly. You understand and agree that you are solely responsible to comply with the terms of use of websites you visit and that AdGuard is not responsible for your compliance with the terms of use of websites you visit."},"options_filters_annoyances_consent_question":{"message":"Enable these filters?"},"options_filters_annoyances_consent_filter_policy":{"message":"For details on what AdGuard\'s annoyance filters block, see <a>Filter policy</a>"},"options_filters_annoyances_consent_enable_button":{"message":"Enable"},"popup_header_cta_link":{"message":"How to enhance protection"},"popup_header_update_filters":{"message":"Check for filter updates"},"options_popup_import_settings_wrong_file_ext":{"message":"The file extension must be %extension%"},"popup_resume_protection_button":{"message":"Resume"},"popup_adguard_for_ios":{"message":"AdGuard for iOS"},"popup_adguard_for_android":{"message":"AdGuard for Android"},"options_filters_filter_version":{"message":"version:"},"options_filters_filter_link":{"message":"Go to homepage"},"options_filters_filter_updated":{"message":"updated:"},"options_popup_version_update_disable_notification":{"message":"Disable notifications"},"popup_adguard_footer_title":{"message":"Protect your mobile device"},"options_popup_call_to_action":{"message":"Enter the valid URL or file path of the filter into the field above."},"options_popup_description":{"message":"You will be subscribed to that filter."},"options_popup_url_title":{"message":"New filter subscription"},"options_popup_url_placeholder":{"message":"Enter URL or file path"},"options_popup_next_button":{"message":"Next"},"options_popup_checking_filter":{"message":"Checking your filter"},"options_popup_check_false_title":{"message":"Error"},"options_popup_check_false_description":{"message":"Error while adding your custom filter."},"options_add_custom_filter_modal_title":{"message":"Add custom filter"},"options_add_custom_filter_modal_checking_filter":{"message":"Checking your filter..."},"options_add_custom_filter_modal_error_title":{"message":"Failed to add custom filter"},"options_add_custom_filter_modal_error_subtitle":{"message":"Please try again or contact support"},"options_add_custom_filter_modal_add_button":{"message":"Add"},"options_add_custom_filter_modal_filter_name":{"message":"Filter name:"},"options_add_custom_filter_modal_filter_trusted":{"message":"Trusted"},"options_add_custom_filter_modal_filter_trusted_description":{"message":"Some filter rules can significantly alter your browsing experience and compromise your privacy. Make sure to only use filters from developers you trust"},"options_popup_try_again_button":{"message":"Try again"},"options_popup_filter_title":{"message":"Title:"},"options_popup_filter_description":{"message":"Description:"},"options_popup_filter_version":{"message":"Version:"},"options_popup_filter_rules_count":{"message":"Rules count:"},"options_popup_filter_homepage":{"message":"Homepage:"},"options_popup_filter_url":{"message":"URL:"},"options_popup_subscribe_button":{"message":"Subscribe"},"name":{"message":"AdGuard AdBlocker"},"description":{"message":"Unmatched adblock extension against advertising and pop-ups. Blocks ads on Facebook, YouTube and all other websites.","description":"TEXT MAX LENGTH: 132"},"background_tab_title":{"message":"Background tab"},"options_allowlist":{"message":"Allowlist"},"options_allowlist_desc":{"message":"AdGuard does not filter websites from the allowlist"},"options_allowlist_invert":{"message":"Invert allowlist"},"options_allowlist_invert_desc":{"message":"Unblock ads everywhere except for the allowlist"},"options_allowlist_alert_invert":{"message":"Allowlist is inverted. Ads are blocked only on websites added to it. <a>Disable</a>"},"options_allowlist_leave_subtitle":{"message":"Your changes to Allowlist will be lost"},"options_userfilter":{"message":"User rules"},"filtering_log_modified_rules":{"message":"Modified rules: %rules_count%"},"filtering_log_stealth_rules":{"message":"Tracking protection rules: %rules_count%"},"filtering_log_privacy_applied_rules":{"message":"Tracking protection applied"},"filtering_log_in_allowlist":{"message":"The site is allowed"},"filtering_log_hide_referrer":{"message":"Referer hidden from third-parties"},"filtering_log_hide_search_queries":{"message":"Your search queries hidden"},"filtering_log_remove_client_data":{"message":"X-Client-Data header removed"},"filtering_log_send_not_track":{"message":"Do-Not-Track header sent"},"options_select_update_period_default":{"message":"Default"},"options_select_update_period_48h":{"message":"48 hours"},"options_select_update_period_24h":{"message":"24 hours"},"options_select_update_period_12h":{"message":"12 hours"},"options_select_update_period_6h":{"message":"6 hours"},"options_select_update_period_1h":{"message":"1 hour"},"options_select_update_period_disabled":{"message":"Disabled"},"options_filters":{"message":"Filters"},"options_antibanner_rules_count":{"message":"Filter rules count: %rules_count%"},"options_antibanner_custom_group":{"message":"Custom"},"options_filters_enabled":{"message":"Enabled:"},"options_filters_enabled_and_more":{"message":"%enabled% and %more% more"},"options_filters_enabled_and_last":{"message":"%enabled% and %last%"},"options_filters_no_enabled":{"message":"No filters enabled"},"options_filters_filter_trusted_tag_desc":{"message":"You chose to trust this filter."},"options_filters_info_mv3_total_rules":{"message":"Total rules: %num%"},"options_add_custom_filter":{"message":"Add custom filter"},"options_filters_custom_disabled_cws":{"message":"Custom filters will be coming back soon. Learn more in our blog"},"options_empty_custom_filter":{"message":"You don\'t have any custom filters yet"},"options_loader_applying_changes":{"message":"Applying changes..."},"options_editor_indicator_saving":{"message":"Saving..."},"options_editor_indicator_saved":{"message":"Saved"},"options_popup_import_error_required_privacy_permission":{"message":"To import this settings file, allow AdGuard to change your privacy-related settings."},"options_popup_import_success_title":{"message":"Settings imported"},"options_popup_import_error_title":{"message":"Failed to import settings"},"options_popup_import_error_file_description":{"message":"Something went wrong."},"options_popup_trusted_filter_title":{"message":"Trusted"},"options_popup_trusted_filter_description":{"message":"Trusted filters can use powerful filtering rules modifiers which can be dangerous in the wrong hands. Do not check this box unless you fully trust it."},"popup_site_filtering_state_secure_page":{"message":"Secure page"},"popup_site_filtering_state_loading":{"message":"Loading..."},"popup_site_filtering_state_enabling":{"message":"Enabling protection..."},"popup_site_filtering_state_enabled":{"message":"Protection is enabled"},"popup_site_filtering_state_disabling":{"message":"Disabling protection..."},"popup_site_filtering_state_disabled":{"message":"Protection is disabled"},"popup_site_filtering_state_pausing":{"message":"Pausing protection..."},"popup_site_filtering_state_paused":{"message":"Protection is paused"},"popup_site_filtering_state_resuming":{"message":"Resuming protection..."},"popup_site_filtering_state_subtitle_all_websites":{"message":"for all websites"},"popup_site_exception_information":{"message":"Filtering is disabled because it can interfere with this website\'s operation."},"popup_tab_blocked_count":{"message":"Blocked: %num%"},"popup_tab_blocked_all_count":{"message":"Total blocked: %num%"},"popup_statistics_total":{"message":"Total"},"popup_statistics_all_categories":{"message":"All"},"popup_statistics_category_advertising":{"message":"Advertising"},"popup_statistics_category_trackers":{"message":"Trackers"},"popup_statistics_category_social_media":{"message":"Social media"},"popup_statistics_category_cdn":{"message":"CDN"},"popup_statistics_category_other":{"message":"Other"},"popup_statistics_week_days_mon":{"message":"Mon"},"popup_statistics_week_days_tue":{"message":"Tue"},"popup_statistics_week_days_wed":{"message":"Wed"},"popup_statistics_week_days_thu":{"message":"Thu"},"popup_statistics_week_days_fri":{"message":"Fri"},"popup_statistics_week_days_sat":{"message":"Sat"},"popup_statistics_week_days_sun":{"message":"Sun"},"popup_statistics_months_jan":{"message":"Jan"},"popup_statistics_months_feb":{"message":"Feb"},"popup_statistics_months_mar":{"message":"Mar"},"popup_statistics_months_apr":{"message":"Apr"},"popup_statistics_months_may":{"message":"May"},"popup_statistics_months_jun":{"message":"Jun"},"popup_statistics_months_jul":{"message":"Jul"},"popup_statistics_months_aug":{"message":"Aug"},"popup_statistics_months_sep":{"message":"Sep"},"popup_statistics_months_oct":{"message":"Oct"},"popup_statistics_months_nov":{"message":"Nov"},"popup_statistics_months_dec":{"message":"Dec"},"options_popup_update_title_error":{"message":"Error updating filters"},"options_popup_update_not_found":{"message":"No updates found"},"options_popup_update_error":{"message":"Failed to get updates. Please try again later."},"options_popup_update_filter":{"message":"was updated."},"options_popup_update_filters":{"message":"were updated."},"options_popup_version_update_title_text":{"message":"AdGuard extension has been updated to version %current_version%"},"options_popup_version_update_description_minor":{"message":"This version contains mostly bugfixes and minor improvements."},"options_popup_version_update_description_major":{"message":"This is a major extension upgrade that brings a lot of new features and improvements."},"options_popup_version_update_changelog_text":{"message":"What\'s new in this version?"},"options_popup_version_update_offer":{"message":"Did you know that AdGuard capabilities are not limited to this browser?"},"options_popup_version_update_offer_button_text":{"message":"LEARN MORE"},"popup_block_site_ads_option":{"message":"Block ads manually"},"popup_security_report":{"message":"Check website security"},"popup_reset_page_user_rules":{"message":"Delete user rules for this website"},"context_block_site_ads":{"message":"Block ads manually"},"context_security_report":{"message":"Check website security"},"context_complaint_website":{"message":"Report an issue"},"context_site_filtering_disabled":{"message":"AdGuard can\'t filter this page"},"context_disable_protection":{"message":"Pause AdGuard protection"},"context_enable_protection":{"message":"Resume AdGuard protection"},"context_site_protection_disabled":{"message":"AdGuard protection is paused"},"context_open_settings":{"message":"AdGuard settings"},"context_open_log":{"message":"Filtering log"},"context_site_exception":{"message":"This website is in the exceptions"},"context_site_filtering_on":{"message":"Enable filtering on this website"},"context_site_filtering_off":{"message":"Disable filtering on this website"},"context_update_antibanner_filters":{"message":"Check for filter updates"},"alert_popup_filter_enabled_title":{"message":"Auto-activation of the filters"},"alert_popup_filter_enabled_desc":{"message":"%filter_name% has been activated automatically."},"filters_download_title":{"message":"Filters database is loading..."},"filters_download_loading":{"message":"Please wait while filters database is loading..."},"post_install_loading":{"message":"Loading extension..."},"filtering_modal_element":{"message":"Element:"},"filtering_modal_cookie":{"message":"Cookie:"},"filtering_modal_important":{"message":"Give a higher priority to the rule"},"filtering_log_title":{"message":"Filtering log"},"filtering_log_search_string":{"message":"Filter log records"},"filtering_log_search_tabs_placeholder":{"message":"Search in tabs"},"filtering_log_preserve_log_off":{"message":"Do not record log"},"filtering_log_preserve_log_on":{"message":"Record log"},"filtering_refresh_tab_short":{"message":"Refresh"},"filtering_clear_log_events":{"message":"Clear log"},"filtering_type_all":{"message":"All"},"filtering_type_other":{"message":"Other"},"filtering_table_status":{"message":"Status"},"filtering_table_type":{"message":"Type"},"filtering_table_rule":{"message":"Filtering rule"},"filtering_table_source":{"message":"Source"},"filtering_table_filter":{"message":"Filter"},"filtering_table_empty_reload_page_desc":{"message":"Nothing found. <reset>Disable filters</reset> or <refresh>reload the page</refresh> to view log records."},"filtering_modal_info_title":{"message":"Request details"},"filtering_modal_preview_title":{"message":"Preview"},"filtering_modal_type":{"message":"Type:"},"filtering_modal_source":{"message":"Source:"},"filtering_modal_rule":{"message":"Rule:"},"filtering_modal_rules":{"message":"Rules:"},"filtering_modal_privacy":{"message":"Tracking protection:"},"filtering_modal_filter":{"message":"Filter:"},"filtering_modal_block":{"message":"Block"},"filtering_modal_block_again":{"message":"Block again"},"filtering_modal_unblock":{"message":"Unblock"},"filtering_modal_remove_user":{"message":"Delete rule"},"filtering_modal_preview_request_button":{"message":"Preview"},"filtering_modal_remove_allowlist":{"message":"Remove from the Allowlist"},"filtering_modal_add_title":{"message":"Adding a rule"},"filtering_modal_status_text_desc":{"message":"Status:"},"filtering_modal_status_text_error":{"message":"Failed to load preview. Please try again"},"filtering_modal_status_text_loading":{"message":"Loading..."},"filtering_modal_filtering_status_text_desc":{"message":"Filtering status:"},"filtering_modal_rule_text_desc":{"message":"Rule text:"},"filtering_modal_patterns_desc":{"message":"Patterns:"},"filtering_modal_options_desc":{"message":"Options:"},"filtering_modal_apply_domains":{"message":"Apply the rule to all websites"},"filtering_modal_third_party":{"message":"Apply to third-party requests only"},"filtering_modal_remove_param":{"message":"Remove query parameters"},"filtering_modal_add_rule":{"message":"Add a rule"},"filtering_modal_exception_title":{"message":"Add an exception"},"filtering_modal_open_in_new_tab":{"message":"Open in a new tab"},"filtering_modal_show_full_url":{"message":"Show full URL"},"filtering_modal_hide_full_url":{"message":"Hide full URL"},"filtering_modal_show_full_rule":{"message":"Show full rule"},"filtering_modal_hide_full_rule":{"message":"Hide full rule"},"filtering_modal_show_full_element":{"message":"Show full element"},"filtering_modal_hide_full_element":{"message":"Hide full element"},"filtering_modal_copy_to_clipboard":{"message":"Copy to clipboard"},"filtering_modal_copied":{"message":"Copied"},"filtering_modal_converted_to":{"message":"Converted to:"},"filtering_log_filter_regular":{"message":"Regular"},"filtering_log_filter_allowed":{"message":"Allowed"},"filtering_log_filter_blocked":{"message":"Blocked"},"filtering_log_filter_modified":{"message":"Modified"},"filtering_log_filter_user_rules":{"message":"User rules"},"filtering_log_status_processed":{"message":"Processed"},"filtering_log_status_allowed":{"message":"Allowed"},"filtering_log_status_blocked":{"message":"Blocked"},"filtering_log_status_modified":{"message":"Modified"},"options_settings":{"message":"AdGuard Settings"},"options_general_settings":{"message":"General"},"options_block_acceptable_ads":{"message":"Block search ads and websites\' self-promotion"},"options_block_acceptable_ads_desc":{"message":"Remove self-promotional ads from websites and contextual ads from search results. <a>Learn more</a>"},"options_show_blocked_ads_count_title":{"message":"Indicate the number of blocked ads on the AdGuard extension icon"},"options_enable_autodetect_filter":{"message":"Activate the most appropriate filters automatically"},"options_enable_autodetect_filter_desc":{"message":"Language-specific filters will turn on depending on the site language"},"options_select_theme":{"message":"Theme"},"options_theme_selector_system":{"message":"System default"},"options_theme_selector_light":{"message":"Light"},"options_theme_selector_dark":{"message":"Dark"},"options_export_settings":{"message":"Export settings"},"options_import_settings":{"message":"Import settings"},"options_report_bug":{"message":"Report a bug"},"options_leave_feedback":{"message":"Leave feedback"},"options_privacy":{"message":"Tracking protection"},"options_update_antibanner_filters":{"message":"Check for filter updates"},"options_check_update":{"message":"Check for updates"},"options_check_update_progress":{"message":"Checking..."},"options_set_update_interval":{"message":"Auto-update filters"},"options_set_update_interval_desc":{"message":"For more effective blocking, the filters need to be updated regularly"},"options_userfilter_export":{"message":"Export"},"options_editor_save":{"message":"Save"},"options_editor_leave_title":{"message":"Leave without saving?"},"options_editor_leave_confirm":{"message":"Yes, leave"},"options_editor_leave_cancel":{"message":"Back to editing"},"options_userfilter_import":{"message":"Import"},"options_userfilter_description_key":{"message":"You can add your own rules here. This option is recommended for advanced users familiar with HTML/CSS. Read the <a>filter rules tutorial</a> to learn how to write your own filter rules."},"options_userfilter_subtitle_key":{"message":"Fine-tune ad blocking with your own filtering rules"},"options_userfilter_line_break_off":{"message":"Line break: Disabled"},"options_userfilter_line_break_on":{"message":"Line break: Enabled"},"options_userfilter_leave_subtitle":{"message":"Your changes to the rules will be lost"},"options_open_changelog":{"message":"Changelog"},"options_safebrowsing_enabled":{"message":"Phishing and malware protection"},"options_safebrowsing_enabled_desc":{"message":"Enable AdGuard Browsing Security module that detects potentially malicious and phishing sites by checking them against an online database. <a>Read more</a>"},"options_site":{"message":"Official Website"},"options_discuss":{"message":"Discuss AdGuard"},"options_do_you_like_question":{"message":"Do you like AdGuard?"},"options_footer_like_us_cta":{"message":"Rate it!"},"options_miscellaneous_settings":{"message":"Additional settings"},"options_rule_syntax":{"message":"Rule syntax"},"options_rule_limits":{"message":"Rule limits"},"options_rule_limits_description":{"message":"Chrome limits the number of rules that can be applied"},"options_rule_limits_dynamic":{"message":"Dynamic rules"},"options_rule_limits_dynamic_user_rules":{"message":"User-added rules, such as <user_rules>user rules</user_rules>, <allowlist>allowlisted websites</allowlist>, <custom_filters>custom filters</custom_filters>, and <quick_fixes>Quick Fixes filter</quick_fixes>"},"options_rule_limits_dynamic_unsafe":{"description":"Note: First dollar sign is used to escape the second one, so eventually only one dollar sign will be displayed","message":"Unsafe dynamic rules (used for some advanced modifiers, such as $$redirect or $$cookie) — included in user-added rules"},"options_rule_limits_dynamic_regex":{"message":"Regex rules — included in user-added rules"},"options_rule_limits_static_rulesets":{"message":"Static rulesets"},"options_rule_limits_static_rulesets_builtin":{"message":"<a>Built-in filters</a>, such as Block annoyances or Language-specific filters"},"options_rule_limits_static_rules":{"message":"Static rules"},"options_rule_limits_static_rules_all":{"message":"Rules from <a>built-in filters</a>"},"options_rule_limits_static_rules_regex":{"message":"Regex rules — included in the above"},"options_rule_limits_numbers":{"message":"%current% of %maximum%"},"options_rule_limits_warning_title":{"message":"The browser has modified the list of active filters"},"options_rule_limits_warning_explanation_title":{"message":"What happened?"},"options_rule_limits_warning_explanation_description":{"message":"The limit of active built-in rules was exceeded after an update or adding a new extension. As per Manifest V3, your Chrome browser reacted by disabling all the extension\'s built-in filters except the default ones."},"options_rule_limits_warning_list_enabled_before_title":{"message":"Filters enabled before the update"},"options_rule_limits_warning_list_enabled_now_title":{"message":"Filters enabled now"},"options_rule_limits_warning_actions_title":{"message":"Your possible actions"},"options_rule_limits_warning_actions_delete_filters":{"message":"Option 1. Delete unnecessary ad-blocking extensions from your browser. To reactivate the filters mentioned in the \\"Filters enabled before the update\\" section, click <a>reactivate filters.</a>"},"options_rule_limits_warning_actions_install_app":{"message":"Option 2. Install the AdGuard Ad Blocker app: it has no restrictions on filtering rules. <a>Get the AdGuard app</a>"},"options_rule_limits_warning_actions_close_warning_one_filter":{"message":"Option 3. If you\'re satisfied with the currently enabled default filter, <a>close this warning.</a>"},"options_rule_limits_warning_actions_close_warning_multiple_filters":{"message":"Option 3. If you\'re satisfied with the currently enabled default filters, <a>close this warning.</a>"},"options_all_limits_exceeded_warning":{"message":"You\'ve reached the limit of active built-in rules. Your browser has modified the list of active built-in filters. The number of filters enabled has changed from %expected% to %current%."},"options_limits_warning_static_filters":{"message":"You\'ve reached the limit of active built-in filters. %maximum% of %current% filters are enabled. To activate new rules, disable some built-in filters."},"options_limits_warning_static_rules":{"message":"You\'ve reached the limit of active built-in rules. %maximum% of %current% rules are enabled. To activate new rules, disable some built-in filters."},"options_limits_warning_static_regex_rules":{"message":"You\'ve reached the limit of active built-in regex rules. %maximum% of %current% regex rules are enabled. To activate new rules, disable some built-in filters."},"options_limits_warning_dynamic_rules":{"message":"You\'ve reached the limit of user-added rules. %maximum% of %current% rules are enabled."},"options_limits_warning_dynamic_unsafe_rules":{"message":"You\'ve reached the limit of user-added unsafe rules. %maximum% of %current% unsafe rules are enabled."},"options_limits_warning_dynamic_regex_rules":{"message":"You\'ve reached the limit of user-added regex rules. %maximum% of %current% regex rules are enabled."},"options_show_adguard_full_version_title":{"message":"Show information on the AdGuard full version"},"options_show_app_updated_notification":{"message":"Notify about extension updates"},"options_open_log":{"message":"Open filtering log"},"options_reset_stats":{"message":"Clear statistics"},"options_reset_stats_done":{"message":"Statistics have been reset"},"options_reset_settings":{"message":"Reset settings"},"options_reset_settings_done":{"message":"Settings have been reset"},"options_reset_settings_error":{"message":"Error while resetting settings"},"options_collect_hit_stats_title":{"message":"Help with the development of AdGuard filters"},"options_collect_hit_stats_desc":{"message":"Send <a>anonymous stats on ad filter usage</a> to help AdGuard improve its filters"},"options_show_context_menu_title":{"message":"Add AdGuard item to the browser\'s context menu"},"options_use_optimized_filters":{"message":"Use optimized filters"},"options_use_optimized_filters_desc":{"message":"Uses shorter versions of filters with only the most popular rules to save traffic. Better suited to mobile browsers"},"options_privacy_title":{"message":"Tracking protection"},"options_privacy_desc":{"message":"Protect your identity and sensitive personal information from thousands of online trackers by blocking the most popular tracking methods"},"options_hide_referrer_title":{"message":"Hide Referer from third parties"},"options_hide_referrer_desc":{"message":"Prevent third parties from knowing what website you are visiting"},"options_hide_search_queries_title":{"message":"Hide your search queries"},"options_hide_search_queries_desc":{"message":"Hide the queries for websites visited from a search engine"},"options_send_not_track_title":{"message":"Ask websites not to track you"},"options_send_not_track_desc":{"message":"Send the <gpc>Global Privacy Control</gpc> and <dnt>Do Not Track</dnt> signals to the websites you visit"},"options_stripped_tracking_parameters":{"message":"Tracking parameters removed"},"options_modified_first_party_cookie":{"message":"First-party cookie modified"},"options_modified_third_party_cookie":{"message":"Third-party cookie modified"},"options_remove_client_data_title":{"message":"Remove X-Client-Data header"},"options_remove_client_data_desc":{"message":"Block Google Chrome from sending its version and modifications information to Google domains"},"options_disable_webrtc_title":{"message":"Disable WebRTC"},"options_disable_webrtc_desc":{"message":"WebRTC can leak your IP address even if you use a proxy or a VPN. Disabling WebRTC can break some websites"},"options_strip_tracking_params_title":{"message":"Remove tracking parameters"},"options_strip_tracking_params_description":{"message":"Remove parameters from web requests with AdGuard URL Tracking filter"},"options_block_known_trackers_title":{"message":"Block trackers"},"options_block_known_trackers_description":{"message":"Block trackers and web analytics tools with AdGuard Tracking Protection filter"},"options_third_party_title":{"message":"Self-destruction of third-party cookies"},"options_third_party_desc":{"message":"Limit the lifetime of third-party cookies (minutes)"},"options_first_party_title":{"message":"Self-destruction of first-party cookies (not recommended)"},"options_first_party_desc":{"message":"Limit the lifetime of first-party cookies (minutes)"},"popup_abuse_site":{"message":"Report an issue"},"popup_open_filtering_log":{"message":"Open filtering log"},"popup_tab_actions":{"message":"Actions"},"popup_tab_statistics":{"message":"Statistics"},"popup_statistics_time_day":{"message":"Last day"},"popup_statistics_time_week":{"message":"Last week"},"popup_statistics_time_month":{"message":"Last month"},"popup_statistics_time_year":{"message":"Last year"},"popup_switch_button":{"message":"Protection switch"},"popup_limits_exceeded_warning":{"message":"Your browser has modified the list of active built-in filters"},"snack_on_websites_limits_exceeded_warning":{"message":"Rule limit exceeded in AdGuard Browser Extension. Please check your filters and disable the ones you don\'t need"},"short_name":{"message":"AdGuard"},"options_about":{"message":"About"},"options_privacy_policy":{"message":"Privacy Policy"},"options_acknowledgment":{"message":"Acknowledgments"},"options_github":{"message":"GitHub"},"options_about_version":{"message":"Version"},"options_copyright":{"message":"All rights reserved."},"options_remove_filter_confirm_modal_title":{"message":"Remove this filter?"},"options_remove_filter_confirm_modal_ok_button":{"message":"Remove"},"options_nav_better_than_extension":{"message":"Why is the AdGuard app better than the extension?"},"options_nav_compare":{"message":"Compare"},"options_filters_search":{"message":"Search"},"options_about_title":{"message":"AdGuard Browser extension"},"group_description_adblocking":{"message":"Configure ad blocking here to deal with annoying banners, pop-ups, video ads and such, once and for all"},"group_description_stealth":{"message":"Protect your identity and sensitive personal info from thousands of online trackers by blocking all known popular tracking methods"},"group_description_social":{"message":"Hide unwanted \\"Like\\"/\\"Share\\" buttons and other social media widgets"},"group_description_annoyances":{"message":"Remove pop-up windows and other annoying notifications like cookie notices"},"group_description_security":{"message":"Protect yourself from malware, phishing and other online threats"},"group_description_miscellaneous":{"message":"More settings to configure your web surfing with AdGuard even further"},"group_description_custom":{"message":"Create your own filters to fine-tune web filtering to your preference."},"group_description_lang":{"message":"Don\'t limit yourself — block ads on websites in any languages"},"fullscreen_user_rules_title":{"message":"User rules"},"options_user_rules_editor_stub_title":{"message":"Editor opened in another window"},"options_user_rules_editor_stub_subtitle":{"message":"Your rules will appear here after you close it"},"options_user_rules_editor_stub_go_to_editor_button":{"message":"Go to editor"},"options_editor_open_fullscreen_button_tooltip":{"message":"Open Editor in a new window"},"options_editor_close_fullscreen_button_tooltip":{"message":"Exit the window mode"},"options_clear_stats_confirm_modal_title":{"message":"Clear statistics?"},"options_clear_stats_confirm_modal_clear_button":{"message":"Clear"},"options_reset_settings_confirm_modal_title":{"message":"Reset settings?"},"options_reset_settings_confirm_modal_clear_button":{"message":"Reset"},"options_confirm_modal_cancel_button":{"message":"Cancel"},"filtering_log_details_modal_beautify_button":{"message":"Beautify"},"filtering_log_details_modal_back_button":{"message":"Back to request"},"filtering_log_details_modal_try_again":{"message":"Try again"},"filtering_log_tag_tooltip_first_party":{"message":"First-party requests"},"filtering_log_tag_tooltip_third_party":{"message":"Third-party requests"},"filtering_log_tag_tooltip_regular":{"message":"Requests processed without filtering"},"filtering_log_tag_tooltip_allowed":{"message":"Allowed and unblocked requests"},"filtering_log_tag_tooltip_blocked":{"message":"Blocked requests"},"filtering_log_tag_tooltip_modified":{"message":"Modified requests"},"filtering_log_tag_tooltip_user_rules":{"message":"Requests affected by user rules"},"filtering_log_tag_tooltip_html":{"message":"Documents and subdocuments"},"filtering_log_tag_tooltip_css":{"message":"Stylesheets"},"filtering_log_tag_tooltip_js":{"message":"Scripts"},"filtering_log_tag_tooltip_xhr":{"message":"XMLHttpRequests and fetch requests"},"filtering_log_tag_tooltip_img":{"message":"Images"},"filtering_log_tag_tooltip_media":{"message":"Media"},"filtering_log_tag_tooltip_other":{"message":"Fonts, pings, WebRTC, WebSocket..."},"filtering_log_badge_tooltip_third_party":{"message":"Third-party request"},"filtering_log_badge_tooltip_http_req_method":{"message":"HTTP request method"},"filtering_log_badge_tooltip_http_status_code":{"message":"HTTP status code"},"filtering_log_assumed_rule_description":{"message":"This is an assumed rule. For details, see our <a>Knowledge base</a>"},"options_stealth_general_title":{"message":"General"},"options_stealth_cookies_title":{"message":"Cookies"},"options_stealth_miscellaneous_title":{"message":"Miscellaneous"},"options_coming_soon":{"message":"Coming soon"},"blocking_pages_malware":{"message":"This web page at <strong>%host%</strong> has been reported as a malware page and has been blocked based on your security preferences."},"blocking_pages_phishing":{"message":"This web page at <strong>%host%</strong> has been reported as a phishing page and has been blocked based on your security preferences."},"blocking_pages_advanced_button":{"message":"Advanced"},"blocking_pages_more_info_button":{"message":"More information"},"blocking_pages_page_title":{"message":"Access denied"},"blocking_pages_safe_header_title":{"message":"AdGuard has blocked access to this page"},"blocking_pages_rule_header_title":{"message":"Blocked by AdGuard"},"blocking_pages_rule_content_title":{"message":"AdGuard has prevented this page from loading due to the following filter rule"},"blocking_pages_btn_go_back":{"message":"Go back"},"blocking_pages_btn_proceed":{"message":"Proceed anyway"},"text_collapser_show_default":{"message":"Show full text"},"text_collapser_hide_default":{"message":"Hide full text"},"close_button_title":{"message":"Close"},"filtering_modal_applied_rules":{"message":"| Applied rule: | Applied rules:","description":"WARNING: correct number of plural forms is required"},"filtering_modal_assumed_rules":{"message":"| Assumed rule: | Assumed rules:","description":"WARNING: correct number of plural forms is required"},"filtering_modal_original_rules":{"message":"| Original rule: | Original rules:","description":"WARNING: correct number of plural forms is required"},"filtering_modal_declarative_rule":{"message":"DNR rule:"}}');

/***/ }),

/***/ 39072:
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"aes-128-ecb":{"cipher":"AES","key":128,"iv":0,"mode":"ECB","type":"block"},"aes-192-ecb":{"cipher":"AES","key":192,"iv":0,"mode":"ECB","type":"block"},"aes-256-ecb":{"cipher":"AES","key":256,"iv":0,"mode":"ECB","type":"block"},"aes-128-cbc":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes-192-cbc":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes-256-cbc":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes128":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes192":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes256":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes-128-cfb":{"cipher":"AES","key":128,"iv":16,"mode":"CFB","type":"stream"},"aes-192-cfb":{"cipher":"AES","key":192,"iv":16,"mode":"CFB","type":"stream"},"aes-256-cfb":{"cipher":"AES","key":256,"iv":16,"mode":"CFB","type":"stream"},"aes-128-cfb8":{"cipher":"AES","key":128,"iv":16,"mode":"CFB8","type":"stream"},"aes-192-cfb8":{"cipher":"AES","key":192,"iv":16,"mode":"CFB8","type":"stream"},"aes-256-cfb8":{"cipher":"AES","key":256,"iv":16,"mode":"CFB8","type":"stream"},"aes-128-cfb1":{"cipher":"AES","key":128,"iv":16,"mode":"CFB1","type":"stream"},"aes-192-cfb1":{"cipher":"AES","key":192,"iv":16,"mode":"CFB1","type":"stream"},"aes-256-cfb1":{"cipher":"AES","key":256,"iv":16,"mode":"CFB1","type":"stream"},"aes-128-ofb":{"cipher":"AES","key":128,"iv":16,"mode":"OFB","type":"stream"},"aes-192-ofb":{"cipher":"AES","key":192,"iv":16,"mode":"OFB","type":"stream"},"aes-256-ofb":{"cipher":"AES","key":256,"iv":16,"mode":"OFB","type":"stream"},"aes-128-ctr":{"cipher":"AES","key":128,"iv":16,"mode":"CTR","type":"stream"},"aes-192-ctr":{"cipher":"AES","key":192,"iv":16,"mode":"CTR","type":"stream"},"aes-256-ctr":{"cipher":"AES","key":256,"iv":16,"mode":"CTR","type":"stream"},"aes-128-gcm":{"cipher":"AES","key":128,"iv":12,"mode":"GCM","type":"auth"},"aes-192-gcm":{"cipher":"AES","key":192,"iv":12,"mode":"GCM","type":"auth"},"aes-256-gcm":{"cipher":"AES","key":256,"iv":12,"mode":"GCM","type":"auth"}}');

/***/ }),

/***/ 76178:
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"sha224WithRSAEncryption":{"sign":"rsa","hash":"sha224","id":"302d300d06096086480165030402040500041c"},"RSA-SHA224":{"sign":"ecdsa/rsa","hash":"sha224","id":"302d300d06096086480165030402040500041c"},"sha256WithRSAEncryption":{"sign":"rsa","hash":"sha256","id":"3031300d060960864801650304020105000420"},"RSA-SHA256":{"sign":"ecdsa/rsa","hash":"sha256","id":"3031300d060960864801650304020105000420"},"sha384WithRSAEncryption":{"sign":"rsa","hash":"sha384","id":"3041300d060960864801650304020205000430"},"RSA-SHA384":{"sign":"ecdsa/rsa","hash":"sha384","id":"3041300d060960864801650304020205000430"},"sha512WithRSAEncryption":{"sign":"rsa","hash":"sha512","id":"3051300d060960864801650304020305000440"},"RSA-SHA512":{"sign":"ecdsa/rsa","hash":"sha512","id":"3051300d060960864801650304020305000440"},"RSA-SHA1":{"sign":"rsa","hash":"sha1","id":"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{"sign":"ecdsa","hash":"sha1","id":""},"sha256":{"sign":"ecdsa","hash":"sha256","id":""},"sha224":{"sign":"ecdsa","hash":"sha224","id":""},"sha384":{"sign":"ecdsa","hash":"sha384","id":""},"sha512":{"sign":"ecdsa","hash":"sha512","id":""},"DSA-SHA":{"sign":"dsa","hash":"sha1","id":""},"DSA-SHA1":{"sign":"dsa","hash":"sha1","id":""},"DSA":{"sign":"dsa","hash":"sha1","id":""},"DSA-WITH-SHA224":{"sign":"dsa","hash":"sha224","id":""},"DSA-SHA224":{"sign":"dsa","hash":"sha224","id":""},"DSA-WITH-SHA256":{"sign":"dsa","hash":"sha256","id":""},"DSA-SHA256":{"sign":"dsa","hash":"sha256","id":""},"DSA-WITH-SHA384":{"sign":"dsa","hash":"sha384","id":""},"DSA-SHA384":{"sign":"dsa","hash":"sha384","id":""},"DSA-WITH-SHA512":{"sign":"dsa","hash":"sha512","id":""},"DSA-SHA512":{"sign":"dsa","hash":"sha512","id":""},"DSA-RIPEMD160":{"sign":"dsa","hash":"rmd160","id":""},"ripemd160WithRSA":{"sign":"rsa","hash":"rmd160","id":"3021300906052b2403020105000414"},"RSA-RIPEMD160":{"sign":"rsa","hash":"rmd160","id":"3021300906052b2403020105000414"},"md5WithRSAEncryption":{"sign":"rsa","hash":"md5","id":"3020300c06082a864886f70d020505000410"},"RSA-MD5":{"sign":"rsa","hash":"md5","id":"3020300c06082a864886f70d020505000410"}}');

/***/ }),

/***/ 69644:
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}');

/***/ }),

/***/ 54828:
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"modp1":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},"modp2":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},"modp5":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},"modp14":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},"modp15":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},"modp16":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},"modp17":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},"modp18":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}');

/***/ }),

/***/ 13453:
/***/ ((module) => {

"use strict";
module.exports = {"rE":"6.6.1"};

/***/ }),

/***/ 77029:
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"2.16.840.1.101.3.4.1.1":"aes-128-ecb","2.16.840.1.101.3.4.1.2":"aes-128-cbc","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"}');

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			id: moduleId,
/******/ 			loaded: false,
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ 	
/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/amd options */
/******/ 	(() => {
/******/ 		__webpack_require__.amdO = {};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/compat get default export */
/******/ 	(() => {
/******/ 		// getDefaultExport function for compatibility with non-harmony modules
/******/ 		__webpack_require__.n = (module) => {
/******/ 			var getter = module && module.__esModule ?
/******/ 				() => (module['default']) :
/******/ 				() => (module);
/******/ 			__webpack_require__.d(getter, { a: getter });
/******/ 			return getter;
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/global */
/******/ 	(() => {
/******/ 		__webpack_require__.g = (function() {
/******/ 			if (typeof globalThis === 'object') return globalThis;
/******/ 			try {
/******/ 				return this || new Function('return this')();
/******/ 			} catch (e) {
/******/ 				if (typeof window === 'object') return window;
/******/ 			}
/******/ 		})();
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/node module decorator */
/******/ 	(() => {
/******/ 		__webpack_require__.nmd = (module) => {
/******/ 			module.paths = [];
/******/ 			if (!module.children) module.children = [];
/******/ 			return module;
/******/ 		};
/******/ 	})();
/******/ 	
/************************************************************************/
var __webpack_exports__ = {};
// This entry needs to be wrapped in an IIFE because it needs to be in strict mode.
(() => {
"use strict";

// EXTERNAL MODULE: ./node_modules/.pnpm/webextension-polyfill@0.12.0/node_modules/webextension-polyfill/dist/browser-polyfill.js
var background_browser_polyfill = __webpack_require__(7967);
var background_browser_polyfill_default = /*#__PURE__*/__webpack_require__.n(background_browser_polyfill);
// EXTERNAL MODULE: ./node_modules/.pnpm/zod@3.21.4/node_modules/zod/lib/index.mjs
var background_lib = __webpack_require__(69509);
// EXTERNAL MODULE: ./node_modules/.pnpm/core-js@3.40.0/node_modules/core-js/modules/es.error.cause.js
var background_es_error_cause = __webpack_require__(59952);
// EXTERNAL MODULE: ./node_modules/.pnpm/core-js@3.40.0/node_modules/core-js/modules/es.array.reduce.js
var background_es_array_reduce = __webpack_require__(51472);
// EXTERNAL MODULE: ./node_modules/.pnpm/core-js@3.40.0/node_modules/core-js/modules/es.array.includes.js
var background_es_array_includes = __webpack_require__(90767);
// EXTERNAL MODULE: ./node_modules/.pnpm/zod@3.24.4/node_modules/zod/lib/index.mjs
var background_zod_lib = __webpack_require__(3290);
// EXTERNAL MODULE: ./node_modules/.pnpm/zod-validation-error@3.4.0_zod@3.24.4/node_modules/zod-validation-error/dist/index.mjs
var background_dist = __webpack_require__(93300);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/misc/domain-list-parser.js + 1 modules
var background_domain_list_parser = __webpack_require__(26571);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/options.js
var background_options = __webpack_require__(56928);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/parser/rule-parser.js + 21 modules
var background_rule_parser = __webpack_require__(58660);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/converter/rule.js + 33 modules
var background_rule = __webpack_require__(87363);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/rule-generator.js + 18 modules
var background_rule_generator = __webpack_require__(48094);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/generator/cosmetic/cosmetic-rule-body-generator.js + 4 modules
var background_cosmetic_rule_body_generator = __webpack_require__(98442);
// EXTERNAL MODULE: ./node_modules/.pnpm/tldts@5.7.112/node_modules/tldts/dist/es6/index.js + 12 modules
var background_es6 = __webpack_require__(13548);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+scriptlets@2.1.6/node_modules/@adguard/scriptlets/dist/validators/index.js + 12 modules
var background_validators = __webpack_require__(66448);
// EXTERNAL MODULE: ./node_modules/.pnpm/is-cidr@4.0.2/node_modules/is-cidr/index.js
var background_is_cidr = __webpack_require__(32537);
// EXTERNAL MODULE: ./node_modules/.pnpm/is-ip@3.1.0/node_modules/is-ip/index.js
var background_is_ip = __webpack_require__(85183);
// EXTERNAL MODULE: ./node_modules/.pnpm/cidr-tools@6.4.2/node_modules/cidr-tools/index.js + 3 modules
var background_cidr_tools = __webpack_require__(47562);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/constants.js
var background_constants = __webpack_require__(65523);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/quotes.js
var background_quotes = __webpack_require__(8725);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/domain.js
var background_utils_domain = __webpack_require__(35508);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/nodes/index.js
var background_nodes = __webpack_require__(64638);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/cosmetic-rule-separator.js
var background_cosmetic_rule_separator = __webpack_require__(90692);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/input-byte-buffer.js + 2 modules
var background_input_byte_buffer = __webpack_require__(35629);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+scriptlets@2.1.6/node_modules/@adguard/scriptlets/dist/scriptlets/index.js
var background_scriptlets = __webpack_require__(3030);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+css-tokenizer@1.2.0/node_modules/@adguard/css-tokenizer/dist/csstokenizer.mjs
var background_csstokenizer = __webpack_require__(25651);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/utils/adblockers.js
var background_adblockers = __webpack_require__(88226);
// EXTERNAL MODULE: ./node_modules/.pnpm/punycode@2.3.1/node_modules/punycode/punycode.js
var background_punycode = __webpack_require__(13066);
// EXTERNAL MODULE: ./node_modules/.pnpm/js-yaml@3.14.1/node_modules/js-yaml/index.js
var background_js_yaml = __webpack_require__(97420);
;// ./node_modules/.pnpm/@adguard+scriptlets@2.1.6/node_modules/@adguard/scriptlets/dist/redirects/index.js


function background_typeof(o) {
    "@babel/helpers - typeof";
    return background_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
        return typeof o;
    } : function(o) {
        return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
    }, background_typeof(o);
}

function background_toPrimitive(t, r) {
    if ("object" != background_typeof(t) || !t) return t;
    var e = t[Symbol.toPrimitive];
    if (void 0 !== e) {
        var i = e.call(t, r || "default");
        if ("object" != background_typeof(i)) return i;
        throw new TypeError("@@toPrimitive must return a primitive value.");
    }
    return ("string" === r ? String : Number)(t);
}

function background_toPropertyKey(t) {
    var i = background_toPrimitive(t, "string");
    return "symbol" == background_typeof(i) ? i : i + "";
}

function background_defineProperty(e, r, t) {
    return (r = background_toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
        value: t,
        enumerable: !0,
        configurable: !0,
        writable: !0
    }) : e[r] = t, e;
}

var background_getErrorMessage = function getErrorMessage(error) {
    var isErrorWithMessage = function isErrorWithMessage(e) {
        return typeof e === "object" && e !== null && "message" in e && typeof e.message === "string";
    };
    if (isErrorWithMessage(error)) {
        return error.message;
    }
    try {
        return new Error(JSON.stringify(error)).message;
    } catch (_unused) {
        return new Error(String(error)).message;
    }
};

function background_ownKeys(e, r) {
    var t = Object.keys(e);
    if (Object.getOwnPropertySymbols) {
        var o = Object.getOwnPropertySymbols(e);
        r && (o = o.filter((function(r) {
            return Object.getOwnPropertyDescriptor(e, r).enumerable;
        }))), t.push.apply(t, o);
    }
    return t;
}

function background_objectSpread(e) {
    for (var r = 1; r < arguments.length; r++) {
        var t = null != arguments[r] ? arguments[r] : {};
        r % 2 ? background_ownKeys(Object(t), !0).forEach((function(r) {
            background_defineProperty(e, r, t[r]);
        })) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : background_ownKeys(Object(t)).forEach((function(r) {
            Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
        }));
    }
    return e;
}

class background_Redirects {
    constructor(rawYaml) {
        try {
            var arrOfRedirects = jsYaml.safeLoad(rawYaml);
            this.redirects = arrOfRedirects.reduce((function(acc, redirect) {
                return background_objectSpread(background_objectSpread({}, acc), {}, {
                    [redirect.title]: redirect
                });
            }), {});
        } catch (e) {
            console.log(`Unable to load YAML into JavaScript: ${background_getErrorMessage(e)}`);
            throw e;
        }
    }
    getRedirect(title) {
        var _this = this;
        if (Object.prototype.hasOwnProperty.call(this.redirects, title)) {
            return this.redirects[title];
        }
        var values = Object.keys(this.redirects).map((function(key) {
            return _this.redirects[key];
        }));
        return values.find((function(redirect) {
            var {aliases: aliases} = redirect;
            if (!aliases) {
                return false;
            }
            return aliases.includes(title);
        }));
    }
    isBlocking(title) {
        var redirect = this.redirects[title];
        if (redirect) {
            return !!redirect.isBlocking;
        }
        return false;
    }
}

var background_redirectsMap = {
    "1x1-transparent.gif": "1x1-transparent.gif",
    "1x1.gif": "1x1-transparent.gif",
    "1x1-transparent-gif": "1x1-transparent.gif",
    "2x2-transparent.png": "2x2-transparent.png",
    "2x2.png": "2x2-transparent.png",
    "2x2-transparent-png": "2x2-transparent.png",
    "3x2-transparent.png": "3x2-transparent.png",
    "3x2.png": "3x2-transparent.png",
    "3x2-transparent-png": "3x2-transparent.png",
    "32x32-transparent.png": "32x32-transparent.png",
    "32x32.png": "32x32-transparent.png",
    "32x32-transparent-png": "32x32-transparent.png",
    noopframe: "noopframe.html",
    "noop.html": "noopframe.html",
    "blank-html": "noopframe.html",
    noopcss: "noopcss.css",
    "noop.css": "noopcss.css",
    "blank-css": "noopcss.css",
    noopjs: "noopjs.js",
    "noop.js": "noopjs.js",
    "blank-js": "noopjs.js",
    noopjson: "noopjson.json",
    "noop.json": "noopjson.json",
    nooptext: "nooptext.js",
    "noop.txt": "nooptext.js",
    "blank-text": "nooptext.js",
    empty: "nooptext.js",
    "noopvmap-1.0": "noopvmap01.xml",
    "noop-vmap1.xml": "noopvmap01.xml",
    "noop-vmap1.0.xml": "noopvmap01.xml",
    "noopvast-2.0": "noopvast02.xml",
    "noop-vast2.xml": "noopvast02.xml",
    "noopvast-3.0": "noopvast03.xml",
    "noop-vast3.xml": "noopvast03.xml",
    "noopvast-4.0": "noopvast04.xml",
    "noop-vast4.xml": "noopvast04.xml",
    "noopmp3-0.1s": "noopmp3.mp3",
    "blank-mp3": "noopmp3.mp3",
    "noopmp4-1s": "noopmp4.mp4",
    "noop-1s.mp4": "noopmp4.mp4",
    "blank-mp4": "noopmp4.mp4",
    "click2load.html": "click2load.html",
    "ubo-click2load.html": "click2load.html",
    "amazon-apstag": "amazon-apstag.js",
    "ubo-amazon_apstag.js": "amazon-apstag.js",
    "amazon_apstag.js": "amazon-apstag.js",
    "ati-smarttag": "ati-smarttag.js",
    "didomi-loader": "didomi-loader.js",
    fingerprintjs2: "fingerprintjs2.js",
    "ubo-fingerprint2.js": "fingerprintjs2.js",
    "fingerprint2.js": "fingerprintjs2.js",
    fingerprintjs3: "fingerprintjs3.js",
    "ubo-fingerprint3.js": "fingerprintjs3.js",
    "fingerprint3.js": "fingerprintjs3.js",
    gemius: "gemius.js",
    "google-analytics-ga": "google-analytics-ga.js",
    "ubo-google-analytics_ga.js": "google-analytics-ga.js",
    "google-analytics_ga.js": "google-analytics-ga.js",
    "google-analytics": "google-analytics.js",
    "ubo-google-analytics_analytics.js": "google-analytics.js",
    "google-analytics_analytics.js": "google-analytics.js",
    "googletagmanager-gtm": "google-analytics.js",
    "ubo-googletagmanager_gtm.js": "google-analytics.js",
    "googletagmanager_gtm.js": "google-analytics.js",
    "google-ima3": "google-ima3.js",
    "ubo-google-ima.js": "google-ima3.js",
    "google-ima.js": "google-ima3.js",
    "googlesyndication-adsbygoogle": "googlesyndication-adsbygoogle.js",
    "ubo-googlesyndication_adsbygoogle.js": "googlesyndication-adsbygoogle.js",
    "googlesyndication_adsbygoogle.js": "googlesyndication-adsbygoogle.js",
    "googletagservices-gpt": "googletagservices-gpt.js",
    "ubo-googletagservices_gpt.js": "googletagservices-gpt.js",
    "googletagservices_gpt.js": "googletagservices-gpt.js",
    matomo: "matomo.js",
    "metrika-yandex-tag": "metrika-yandex-tag.js",
    "metrika-yandex-watch": "metrika-yandex-watch.js",
    "naver-wcslog": "naver-wcslog.js",
    noeval: "noeval.js",
    "noeval.js": "noeval.js",
    "silent-noeval.js": "noeval.js",
    "ubo-noeval.js": "noeval.js",
    "ubo-silent-noeval.js": "noeval.js",
    "ubo-noeval": "noeval.js",
    "ubo-silent-noeval": "noeval.js",
    "pardot-1.0": "pardot-1.0.js",
    "prebid-ads": "prebid-ads.js",
    "ubo-prebid-ads.js": "prebid-ads.js",
    "prebid-ads.js": "prebid-ads.js",
    prebid: "prebid.js",
    "prevent-bab": "prevent-bab.js",
    "nobab.js": "prevent-bab.js",
    "ubo-nobab.js": "prevent-bab.js",
    "bab-defuser.js": "prevent-bab.js",
    "ubo-bab-defuser.js": "prevent-bab.js",
    "ubo-nobab": "prevent-bab.js",
    "ubo-bab-defuser": "prevent-bab.js",
    "prevent-bab2": "prevent-bab2.js",
    "nobab2.js": "prevent-bab2.js",
    "prevent-fab-3.2.0": "prevent-fab-3.2.0.js",
    "nofab.js": "prevent-fab-3.2.0.js",
    "ubo-nofab.js": "prevent-fab-3.2.0.js",
    "fuckadblock.js-3.2.0": "prevent-fab-3.2.0.js",
    "ubo-fuckadblock.js-3.2.0": "prevent-fab-3.2.0.js",
    "ubo-nofab": "prevent-fab-3.2.0.js",
    "prevent-popads-net": "prevent-popads-net.js",
    "popads.net.js": "prevent-popads-net.js",
    "ubo-popads.net.js": "prevent-popads-net.js",
    "ubo-popads.net": "prevent-popads-net.js",
    "scorecardresearch-beacon": "scorecardresearch-beacon.js",
    "ubo-scorecardresearch_beacon.js": "scorecardresearch-beacon.js",
    "scorecardresearch_beacon.js": "scorecardresearch-beacon.js",
    "set-popads-dummy": "set-popads-dummy.js",
    "popads-dummy.js": "set-popads-dummy.js",
    "ubo-popads-dummy.js": "set-popads-dummy.js",
    "ubo-popads-dummy": "set-popads-dummy.js"
};

var background_getRedirectFilename = function getRedirectFilename(name) {
    return background_redirectsMap[name];
};



// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+agtree@3.2.0/node_modules/@adguard/agtree/dist/deserializer/rule-deserializer.js + 32 modules
var background_rule_deserializer = __webpack_require__(97907);
;// ./node_modules/.pnpm/@adguard+tsurlfilter@3.3.3_@adguard+re2-wasm@1.2.0/node_modules/@adguard/tsurlfilter/dist/es/declarative-converter.js



















/**
 * Checks if error has message.
 *
 * @param error Error object.
 *
 * @returns If param is error.
 */
function background_isErrorWithMessage(error) {
    return (typeof error === 'object'
        && error !== null
        && 'message' in error
        && typeof error.message === 'string');
}
/**
 * Converts error to the error with message.
 *
 * @param maybeError Possible error.
 *
 * @returns Error with message.
 */
function background_toErrorWithMessage(maybeError) {
    if (background_isErrorWithMessage(maybeError)) {
        return maybeError;
    }
    try {
        return new Error(JSON.stringify(maybeError));
    }
    catch {
        // fallback in case there's an error stringifying the maybeError
        // like with circular references for example.
        return new Error(String(maybeError));
    }
}
/**
 * Converts error object to error with message. This method might be helpful to handle thrown errors.
 *
 * @param error Error object.
 *
 * @returns Message of the error.
 */
function background_declarative_converter_getErrorMessage(error) {
    // Special case: pretty print Zod errors
    if (error instanceof background_zod_lib/* ZodError */.G) {
        return (0,background_dist/* fromZodError */.yu)(error).toString();
    }
    return background_toErrorWithMessage(error).message;
}

var background_ErrorStatusCodes;
(function (ErrorStatusCodes) {
    ErrorStatusCodes[ErrorStatusCodes["ComplexRegex"] = 1001] = "ComplexRegex";
    ErrorStatusCodes[ErrorStatusCodes["RuleLimit"] = 1002] = "RuleLimit";
    ErrorStatusCodes[ErrorStatusCodes["RegexpRuleLimit"] = 1003] = "RegexpRuleLimit";
    ErrorStatusCodes[ErrorStatusCodes["RemoveparamRegexpIsNotSupported"] = 1004] = "RemoveparamRegexpIsNotSupported";
    ErrorStatusCodes[ErrorStatusCodes["RemoveparamInversionIsNotSupported"] = 1005] = "RemoveparamInversionIsNotSupported";
})(background_ErrorStatusCodes || (background_ErrorStatusCodes = {}));
const background_EMPTY_STRING = '';
const background_SEPARATOR = '|';
const background_SPACE = ' ';
const background_WILDCARD = '*';
const background_LF = '\n';
const background_CR = '\r';
const background_FF = '\f';
const background_TAB = '\t';
/**
 * Prefix for ruleset name.
 */
const background_RULESET_NAME_PREFIX = 'ruleset_';

/**
 * @file Smaller utility functions that cannot be classified in other files here,
 * but it is not worth creating a separate file for them.
 */
/**
 * Helper function to serialize data to JSON and optionally prettify it.
 * Its just helps to keep the code clean and readable.
 *
 * @param data Data to serialize.
 * @param pretty If `true`, the JSON will be prettified with tabs.
 *
 * @returns Serialized JSON.
 */
function background_serializeJson(data, pretty = false) {
    return JSON.stringify(data, null, pretty ? background_TAB : undefined);
}

/**
 * Splits the string by the delimiter, ignoring escaped delimiters
 * and without tokenizing.
 * Works for plain strings that don't include string representation of
 * complex entities, e.g $replace modifier values.
 *
 * @param string String to split.
 * @param delimiter Delimiter.
 * @param escapeCharacter Escape character.
 * @param preserveEmptyTokens If true, preserve empty parts.
 * @param shouldUnescape If true, unescape characters.
 *
 * @returns Array of string parts.
 */
function background_splitByDelimiterWithEscapeCharacter(string, delimiter, escapeCharacter, preserveEmptyTokens, shouldUnescape = true) {
    if (!string) {
        return [];
    }
    if (string.startsWith(delimiter)) {
        // eslint-disable-next-line no-param-reassign
        string = string.substring(1);
    }
    let words = [];
    if (!string.includes(escapeCharacter)) {
        words = string.split(delimiter);
        return words;
    }
    let chars = [];
    const makeWord = () => {
        const word = chars.join('');
        words.push(word);
        chars = [];
    };
    for (let i = 0; i < string.length; i += 1) {
        const char = string.charAt(i);
        const isLastChar = i === (string.length - 1);
        if (char === delimiter) {
            const isEscapedChar = i > 0 && string[i - 1] === escapeCharacter;
            if (isEscapedChar) {
                if (shouldUnescape) {
                    chars.splice(chars.length - 1, 1);
                }
                chars.push(char);
            }
            else {
                makeWord();
            }
            if (isLastChar) {
                makeWord();
            }
        }
        else if (isLastChar) {
            chars.push(char);
            makeWord();
        }
        else {
            chars.push(char);
        }
    }
    return words;
}
/**
 * `djb2` hash algorithm.
 *
 * NOTE: This version uses some bit operands to exclude overflow MAX_SAFE_INTEGER
 * (and moreover, exclude overflow 2^32).
 *
 * @see {@link https://gist.github.com/eplawless/52813b1d8ad9af510d85?permalink_comment_id=3367765#gistcomment-3367765}
 *
 * @param str String to get hash.
 *
 * @returns Hash.
 */
function background_fastHash(str) {
    if (str.length === 0) {
        return 0;
    }
    // A magic constant that gives good distribution.
    let hash = 5381;
    for (let i = 0; i < str.length; i += 1) {
        hash = hash * 33 ^ str.charCodeAt(i);
    }
    return hash >>> 0;
}
/**
 * `djb2` hash algorithm with sign bit masked off to fit 31 bits.
 *
 * @param str String to get hash.
 *
 * @returns Hash from 0 to 2^31-1.
 */
function background_fastHash31(str) {
    // Mask off sign bit to keep value in range [0, ..., 2^31‑1].
    return background_fastHash(str) & 0x7fffffff;
}
/**
 * Replaces all occurrences of find with replace in str.
 *
 * @param str The string in which to replace all occurrences of the find string.
 * @param find The substring to find in the string.
 * @param replace The substring to replace the find string with.
 *
 * @returns The string with all occurrences of find replaced by replace.
 */
function background_replaceAll(str, find, replace) {
    if (!str) {
        return str;
    }
    return str.split(find).join(replace);
}
/**
 * Checks if arrays are equal.
 *
 * @param left Array.
 * @param right Array.
 *
 * @returns {boolean} True on equality.
 */
function background_stringArraysEquals(left, right) {
    if (!left || !right) {
        return !left && !right;
    }
    if (left.length !== right.length) {
        return false;
    }
    for (let i = 0; i < left.length; i += 1) {
        if (left[i] !== right[i]) {
            return false;
        }
    }
    return true;
}
/**
 * Checks if arrays have an intersection.
 *
 * @param left Array.
 * @param right Array.
 *
 * @returns {boolean} True on equality.
 */
function background_stringArraysHaveIntersection(left, right) {
    if (!left || !right) {
        return true;
    }
    for (let i = 0; i < left.length; i += 1) {
        if (right.includes(left[i])) {
            return true;
        }
    }
    return false;
}
/**
 * Checks if string contains spaces.
 *
 * @param str String to check.
 *
 * @returns `true` if string contains spaces, `false` otherwise.
 */
function background_hasSpaces(str) {
    return str.includes(background_SPACE);
}
/**
 * Check if the given value is a string.
 *
 * @param value Value to check.
 *
 * @returns `true` if value is a string, `false` otherwise.
 */
function background_isString(value) {
    return typeof value === 'string';
}
/**
 * Unescapes the specified character in the string.
 *
 * @param str String to escape.
 * @param char Character to escape.
 *
 * @returns The string with the specified character unescaped.
 */
function background_unescapeChar(str, char) {
    return str.replace(`\\${char}`, char);
}
/**
 * Finds the next line break index in the string starting from the specified index.
 * Supports LF, CR, FF and CRLF line breaks.
 *
 * @param str String to search in.
 * @param startIndex  Start index. Default is 0.
 *
 * @returns A tuple with the line break index and the line break length.
 * If the line break is not found, returns the string length and 0.
 */
function background_findNextLineBreakIndex(str, startIndex = 0) {
    const { length } = str;
    let offset = startIndex;
    while (offset < length) {
        const char = str[offset];
        if (char === background_LF || char === background_FF) {
            return [offset, 1];
        }
        if (char === background_CR) {
            return str[offset + 1] === background_LF ? [offset, 2] : [offset, 1];
        }
        offset += 1;
    }
    return [length, 0];
}
/**
 * Finds the next occurrence of a specified character in a string that is not preceded by an escape (`\`).
 *
 * @param str The input string to search within.
 * @param char The character to find in the string.
 * @param [startIndex] The index to start searching from.
 *
 * @returns The index of the next unescaped occurrence of the character, or the length of the string if not found.
 */
const background_findNextUnescapedIndex = (str, char, startIndex = 0) => {
    let i = str.indexOf(char, startIndex);
    while (i !== -1 && str[i - 1] === '\\') {
        i = str.indexOf(char, i + 1);
    }
    return i === -1 ? str.length : i;
};
/**
 * Determines whether a given Unicode code point corresponds to a numeric digit (0-9).
 *
 * @param codePoint The Unicode code point to check.
 *
 * @returns `true` if the code point represents a numeric character (0-9), otherwise `false`.
 */
const background_isNumber = (codePoint) => {
    return codePoint >= 48 && codePoint <= 57;
};
/**
 * Determines whether a given Unicode code point corresponds to an alphabetical letter (a-z, A-Z).
 *
 * @param codePoint The Unicode code point to check.
 *
 * @returns `true` if the code point represents an alphabetic character, otherwise `false`.
 */
const background_isAlpha = (codePoint) => {
    const codePointLower = codePoint | 0x20;
    return codePointLower >= 97 && codePointLower <= 122;
};
/**
 * Determines whether a given Unicode code point corresponds to an alphanumeric character (a-z, A-Z, 0-9).
 *
 * @param codePoint The Unicode code point to check.
 *
 * @returns `true` if the code point represents an alphanumeric character, otherwise `false`.
 */
const background_isAlphaNumeric = (codePoint) => {
    return background_isAlpha(codePoint) || background_isNumber(codePoint);
};

/* eslint-disable max-classes-per-file */
/**
 * Default rule index for source mapping.
 *
 * It is -1, similar to `Array.indexOf()` return value when element is not found.
 */
const background_RULE_INDEX_NONE = -1;
/**
 * Rule with index.
 */
// TODO: Consider remove this because rule already has an index field
class background_IndexedRule {
    /**
     * Rule.
     */
    rule;
    /**
     * Index.
     */
    index;
    /**
     * Constructor.
     *
     * @param rule Rule.
     * @param index Index of the rule.
     */
    constructor(rule, index) {
        this.rule = rule;
        this.index = index;
    }
}

/* eslint-disable prefer-regex-literals */
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
// should be escaped . * + ? ^ $ { } ( ) | [ ] / \
// except of * | ^
const background_specialCharacters = ['.', '+', '?', '$', '{', '}', '(', ')', '[', ']', '/', '\\'];
const background_reSpecialCharacters = new RegExp(`[${background_specialCharacters.join('\\')}]`, 'g');
const background_reSpecialCharactersFull = /[.*+?^${}()|[\]\\]/g;
const background_reEscapedSpecialCharactersFull = /\\[.*+?^${}()|[\]\\]/g;
const background_protocolMarker = String.raw `:\/\/`;
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#using_special_characters_in_strings
const background_escapeSequence = {
    n: '\n',
    r: '\r',
    t: '\t',
    b: '\b',
    f: '\f',
    v: '\v',
};
/**
 * Class with static helper methods for working with basic filtering rules patterns.
 *
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#basic-rules}
 *
 * @returns The escaped string.
 */
class background_SimpleRegex {
    /**
     * Matching the beginning of an address. With this character you don't
     * have to specify a particular protocol and subdomain in address mask.
     * It means, `||` stands for `http://*.`, `https://*.`, `ws://*.`, `wss://*.` at once.
     */
    static MASK_START_URL = '||';
    /**
     * REGEX_START_URL corresponds to MASK_START_URL.
     */
    static REGEX_START_URL = '^(http|https|ws|wss)://([a-z0-9-_.]+\\.)?';
    /**
     * A pointer to the beginning or the end of address. The value depends on the
     * character placement in the mask. For example, a rule `swf|` corresponds
     * to `http://example.com/annoyingflash.swf`, but not to `http://example.com/swf/index.html`.
     * `|http://example.org` corresponds to `http://example.org`,
     * but not to `http://domain.com?url=http://example.org`.
     */
    static MASK_PIPE = '|';
    /**
     * REGEX_END_STRING corresponds to MASK_PIPE if it is in the end of a pattern.
     */
    static REGEX_END_STRING = '$';
    /**
     * REGEX_START_STRING corresponds to MASK_PIPE if it is in the beginning of a pattern.
     */
    static REGEX_START_STRING = '^';
    /**
     * Separator character mark. Separator character is any character,
     * but a letter, a digit, or one of the following: _ - .
     */
    static MASK_SEPARATOR = '^';
    /**
     * REGEX_SEPARATOR corresponds to MASK_SEPARATOR.
     */
    static REGEX_SEPARATOR = '([^ a-zA-Z0-9.%_-]|$)';
    /**
     * This is a wildcard character. It is used to represent "any set of characters".
     * This can also be an empty string or a string of any length.
     */
    static MASK_ANY_CHARACTER = '*';
    /**
     * Path separator.
     */
    static MASK_BACKSLASH = '/';
    /**
     * REGEX_ANY_CHARACTER corresponds to MASK_ANY_CHARACTER.
     */
    static REGEX_ANY_CHARACTER = '.*';
    /**
     * Enclose regex in two backslashes to mark a regex rule.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#regular-expressions-support}
     */
    static MASK_REGEX_RULE = '/';
    /**
     *  Regex for matching special characters in modifier regex pattern.
     */
    static reModifierPatternSpecialCharacters = /[[\],\\]/g;
    /**
     * Regex for matching escaped special characters in modifier regex pattern.
     */
    static reModifierPatternEscapedSpecialCharacters = /\\[[\],\\]/g;
    /**
     * If string starts with exclamation mark "!" we consider it as comment.
     */
    static MASK_COMMENT = '!';
    /**
     * Min length of rule shortcut
     * This value has been picked as a result of performance experiments.
     */
    static MIN_SHORTCUT_LENGTH = 3;
    /**
     * Min length of generic rule shortcut.
     */
    static MIN_GENERIC_RULE_LENGTH = 4;
    /**
     * Regex with basic matching pattern special characters.
     */
    static rePatternSpecialCharacters = new RegExp('[*^|]');
    /**
     * Extracts the shortcut from the rule's pattern.
     * Shortcut is the longest substring of the pattern that does not contain
     * any special characters.
     *
     * Please note, that the shortcut is always lower-case!
     *
     * @param pattern Network rule's pattern.
     *
     * @returns The shortcut or the empty string if we could not extract any.
     */
    static extractShortcut(pattern) {
        if (pattern.startsWith(this.MASK_REGEX_RULE) && pattern.endsWith(this.MASK_REGEX_RULE)) {
            return this.extractRegexpShortcut(pattern);
        }
        return this.extractBasicShortcut(pattern);
    }
    /**
     * Searches for the longest substring of the pattern that
     * does not contain any special characters: `*`, `^`, `|`.
     *
     * @param pattern Network rule's pattern.
     *
     * @returns The shortcut or the empty string.
     */
    static extractBasicShortcut(pattern) {
        let longest = '';
        const parts = pattern.split(this.rePatternSpecialCharacters);
        for (const part of parts) {
            if (part.length > longest.length) {
                longest = part;
            }
        }
        return (longest || '').toLowerCase();
    }
    /**
     * Extracts the longest substring from the provided regex pattern that does not
     * contain any special regex symbols or constructs that invalidate it for use
     * as a quick match shortcut.
     * The pattern is expected to be enclosed in forward slashes (e.g., `/example/`),
     * and may optionally contain a protocol marker (`://`),
     * which is ignored to prevent trivial matches like "http".
     *
     * This method discards many complex regex features (e.g., groups, character
     * classes, certain escaped sequences) when forming the shortcut, and always
     * returns the result in lower-case. If no valid substring is found, it returns
     * an empty string.
     *
     * @param pattern The input regex pattern, including the enclosing slashes.
     * For example: `/https?:\\/\\/example\\.com/`.
     *
     * @returns The longest valid substring usable as a shortcut, or an empty string if none is found.
     */
    static extractRegexpShortcut(pattern) {
        const { length } = pattern;
        if (!pattern
            // length should be at least 3: "/x/", "//" does not make sense
            || length < 3
            // regex pattern should start and end with '/'
            || pattern[0] !== '/'
            || pattern[length - 1] !== '/') {
            return '';
        }
        const protocolIndex = pattern.indexOf(background_protocolMarker);
        /**
         * `i` is our primary index into the pattern;
         * we skip the initial `/` or jump after the protocol marker `://`.
         */
        let i = protocolIndex !== -1
            ? protocolIndex + background_protocolMarker.length
            : 1;
        let longestToken = '';
        let longestTokenInGroup = '';
        let currentToken = '';
        /**
         * Resets `currentToken` and updates `longestTokenInGroup` if `currentToken` is longer.
         */
        const resetCurrentToken = () => {
            if (currentToken.length > longestTokenInGroup.length) {
                longestTokenInGroup = currentToken;
            }
            currentToken = '';
        };
        /**
         * Resets `longestTokenInGroup` and updates `longestToken` if `longestTokenInGroup` is longer.
         */
        const resetGroupToken = () => {
            if (longestTokenInGroup.length > longestToken.length) {
                longestToken = longestTokenInGroup;
            }
            longestTokenInGroup = '';
        };
        /**
         * Track parenthesis group nesting.
         */
        let groupBalance = 0;
        /**
         * Skip everything up to the closing parenthesis for the current group
         * (including nested groups).
         * This method moves `i` to the position of the closing parenthesis.
         */
        const ignoreCurrentGroup = () => {
            // Ignoring group means we should drop the current token
            currentToken = '';
            longestTokenInGroup = '';
            const startBalance = groupBalance;
            while (i < length) {
                // If `(` is not escaped, increment group count
                if (pattern[i] === '(' && pattern[i - 1] !== '\\') {
                    groupBalance += 1;
                }
                // If `)` is not escaped, decrement group count
                if (pattern[i] === ')' && pattern[i - 1] !== '\\') {
                    groupBalance -= 1;
                    // Once we return to the level before this group started, stop
                    if (groupBalance < startBalance) {
                        break;
                    }
                }
                i += 1;
            }
        };
        while (i < length) {
            const char = pattern[i];
            // 1) Handle escaped sequences
            if (char === '\\') {
                // Skip the backslash
                i += 1;
                const escaped = pattern[i];
                switch (escaped) {
                    // Ignore predefined character classes: \d, \D, \s, \S, \w, \W
                    case 'd':
                    case 'D':
                    case 's':
                    case 'S':
                    case 'w':
                    case 'W':
                    // Ignore special characters: \t, \r, \n, \v, \f, \b, \0
                    // eslint-disable-next-line no-fallthrough
                    case 't':
                    case 'r':
                    case 'n':
                    case 'v':
                    case 'f':
                    case 'b':
                    case '0':
                        resetCurrentToken();
                        i += 1;
                        continue;
                    // Ignore control characters: \cX — control character X
                    case 'c':
                        resetCurrentToken();
                        // skip 'c' and the following character
                        i += 2;
                        continue;
                    // Ignore \xhh
                    case 'x':
                        resetCurrentToken();
                        // skip 'x' and the following 2 characters
                        i += 3;
                        continue;
                    // Ignore \uhhhh
                    case 'u':
                        resetCurrentToken();
                        // skip 'u' and the following 4 characters
                        i += 5;
                        continue;
                    // Ignore named backreference: \k<...>
                    case 'k':
                        resetCurrentToken();
                        // skip 'k'
                        i += 1;
                        if (pattern[i] === '<') {
                            // Skip until the closing '>'
                            i = background_findNextUnescapedIndex(pattern, '>', i) + 1;
                        }
                        continue;
                    // Special case: add escaped '.' or '/' to the current token
                    case '.':
                    case '/':
                        currentToken += escaped;
                        i += 1;
                        continue;
                    default:
                        resetCurrentToken();
                        i += 1;
                        continue;
                }
            }
            // 2) Handle "regular" characters (i.e., not after a backslash)
            switch (char) {
                // Ignore custom character classes, like [xyz], [^xyz], [\b], [a-z], etc.
                case '[':
                    resetCurrentToken();
                    i = background_findNextUnescapedIndex(pattern, ']', i) + 1;
                    continue;
                // Ignore disjunctions (alternations), like a|b|c
                // Note: shortcut should be present in all possible tested strings,
                // this is why we ignore disjunctions
                case '|':
                    ignoreCurrentGroup();
                    continue;
                // Ignore specific quantifiers, like x{n}, x{n,}, x{n,m}
                case '{':
                    resetCurrentToken();
                    i = background_findNextUnescapedIndex(pattern, '}', i) + 1;
                    continue;
                // Handle group open
                case '(':
                    resetCurrentToken();
                    resetGroupToken();
                    groupBalance += 1;
                    // Skip `(`
                    i += 1;
                    // Ignore negative lookahead: (?!...) and negative lookbehind: (?<!...)
                    // Negative lookbehind and lookahead contain data that should not be present in the tested strings,
                    // this is why we ignore them
                    if (pattern.indexOf('?!', i) === i || pattern.indexOf('?<!', i) === i) {
                        ignoreCurrentGroup();
                    }
                    // Ignore name section from named groups: (?<...>
                    if (pattern.indexOf('?<', i) === i) {
                        // Skip until the closing '>'
                        i = background_findNextUnescapedIndex(pattern, '>', i + 2) + 1;
                    }
                    continue;
                // Handle group close
                case ')':
                    resetCurrentToken();
                    resetGroupToken();
                    groupBalance -= 1;
                    // Skip `)`
                    i += 1;
                    continue;
                // Handle special regex symbols: . * + ? ^ $ /
                case '.':
                case '*':
                case '+':
                case '?':
                case '^':
                case '$':
                case '/':
                    resetCurrentToken();
                    i += 1;
                    continue;
                default:
                    // For performance, let's check if it's a valid token char
                    // Note: isValidRegexpShortcutChar checks for alphanumeric or
                    // escaped '.' or '/'
                    if (background_isAlphaNumeric(char.charCodeAt(0))) {
                        currentToken += char;
                    }
                    else {
                        // If it's not a valid char for a shortcut, reset
                        resetCurrentToken();
                    }
                    i += 1;
                    break;
            }
        }
        // Finalize the last token
        resetCurrentToken();
        resetGroupToken();
        return longestToken.toLowerCase();
    }
    /**
     * PatternToRegexp is a helper method for creating regular expressions from the simple
     * wildcard-based syntax which is used in basic filters.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#basic-rules}
     *
     * @param pattern Basic rule pattern.
     *
     * @returns Regular expression.
     */
    static patternToRegexp(pattern) {
        if (pattern === this.MASK_START_URL
            || pattern === this.MASK_PIPE
            || pattern === this.MASK_ANY_CHARACTER
            || pattern === '') {
            return this.REGEX_ANY_CHARACTER;
        }
        if (pattern.startsWith(this.MASK_REGEX_RULE) && pattern.endsWith(this.MASK_REGEX_RULE)) {
            // This is a regex rule, just remove the regex markers
            return pattern.substring(this.MASK_REGEX_RULE.length, pattern.length - this.MASK_REGEX_RULE.length);
        }
        // Escape special characters except of * | ^
        let regex = pattern.replace(background_reSpecialCharacters, '\\$&');
        // Now escape "|" characters but avoid escaping them in the special places
        if (regex.startsWith(this.MASK_START_URL)) {
            regex = regex.substring(0, this.MASK_START_URL.length)
                + background_replaceAll(regex.substring(this.MASK_START_URL.length, regex.length - this.MASK_PIPE.length), this.MASK_PIPE, `\\${this.MASK_PIPE}`)
                + regex.substring(regex.length - this.MASK_PIPE.length);
        }
        else {
            regex = regex.substring(0, this.MASK_PIPE.length)
                + background_replaceAll(regex.substring(this.MASK_PIPE.length, regex.length - this.MASK_PIPE.length), this.MASK_PIPE, `\\${this.MASK_PIPE}`)
                + regex.substring(regex.length - this.MASK_PIPE.length);
        }
        // Replace special URL masks
        regex = background_replaceAll(regex, this.MASK_ANY_CHARACTER, this.REGEX_ANY_CHARACTER);
        regex = background_replaceAll(regex, this.MASK_SEPARATOR, this.REGEX_SEPARATOR);
        // Replace start URL and pipes
        if (regex.startsWith(this.MASK_START_URL)) {
            regex = this.REGEX_START_URL + regex.substring(this.MASK_START_URL.length);
        }
        else if (regex.startsWith(this.MASK_PIPE)) {
            regex = this.REGEX_START_STRING + regex.substring(this.MASK_PIPE.length);
        }
        if (regex.endsWith(this.MASK_PIPE)) {
            regex = regex.substring(0, regex.length - this.MASK_PIPE.length) + this.REGEX_END_STRING;
        }
        return regex;
    }
    /**
     * Creates RegExp object from string in '/reg_exp/gi' format.
     *
     * @param str The string to escape.
     *
     * @returns The created RegExp object.
     */
    static patternFromString(str) {
        const parts = background_splitByDelimiterWithEscapeCharacter(str, '/', '\\');
        let modifiers = (parts[1] || '');
        if (modifiers.indexOf('g') < 0) {
            modifiers += 'g';
        }
        return new RegExp(parts[0], modifiers);
    }
    /**
     * Escapes characters with special meaning inside a regular expression.
     *
     * @param str The string to escape.
     * @param searchPattern Pattern for detecting special characters. Optional.
     *
     * @returns The escaped string.
     */
    static escapeRegexSpecials(str, searchPattern = background_reSpecialCharactersFull) {
        return str.replace(searchPattern, '\\$&');
    }
    /**
     * Unescapes characters with special meaning inside a regular expression.
     *
     * @param str The string to unescape.
     * @param searchPattern Pattern for detecting special characters. Optional.
     *
     * @returns The unescaped string.
     */
    static unescapeRegexSpecials(str, searchPattern = background_reEscapedSpecialCharactersFull) {
        return str.replace(searchPattern, (match) => match.substring(1));
    }
    /**
     * Check if pattern is Regex.
     *
     * @param str The string to check.
     *
     * @returns True if the string is a regex pattern, false otherwise.
     */
    static isRegexPattern(str) {
        return str.startsWith('/') && str.endsWith('/');
    }
    /**
     * Unescapes special characters in a string.
     *
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#using_special_characters_in_strings}
     *
     * @param str The string to unescape.
     *
     * @returns The unescaped string.
     */
    static unescapeSpecials(str) {
        const keys = Object.keys(background_escapeSequence).join('|');
        const regex = new RegExp(`\\\\(${keys})`, 'g');
        return str.replace(regex, (match, group) => {
            return background_escapeSequence[group];
        });
    }
}

/**
 * Export logger implementation.
 */
let background_logger = console;

/**
 * Pipe separator.
 */
const background_PIPE_SEPARATOR$1 = '|';
/**
 * This is a helper class that is used specifically to work
 * with domains restrictions.
 *
 * There are two options how you can add a domain restriction:
 * - `$domain` modifier;
 * - domains list for the cosmetic rules.
 *
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#domain-modifier}
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#cosmetic-rules}
 *
 * The only difference between them is that in one case we use `|` as a separator,
 * and in the other case - `,`.
 *
 * @example
 * `||example.org^$domain=example.com|~sub.example.com` -- network rule
 * `example.com,~sub.example.com##banner` -- cosmetic rule
 */
class background_DomainModifier {
    /**
     * List of permitted domains or null.
     */
    permittedDomains;
    /**
     * List of restricted domains or null.
     */
    restrictedDomains;
    /**
     * Processes domain list node, which means extracting permitted and restricted
     * domains from it.
     *
     * @param domainListNode Domain list node to process.
     *
     * @returns Processed domain list (permitted and restricted domains) ({@link ProcessedDomainList}).
     */
    static processDomainList(domainListNode) {
        const result = {
            permittedDomains: [],
            restrictedDomains: [],
        };
        const { children: domains } = domainListNode;
        for (const { exception, value: domain } of domains) {
            const domainLowerCased = domain.toLowerCase();
            if (!background_SimpleRegex.isRegexPattern(domain) && domain.includes(background_WILDCARD) && !domain.endsWith(background_WILDCARD)) {
                throw new SyntaxError(`Wildcards are only supported for top-level domains: "${domain}"`);
            }
            if (exception) {
                result.restrictedDomains.push(domainLowerCased);
            }
            else {
                result.permittedDomains.push(domainLowerCased);
            }
        }
        return result;
    }
    /**
     * Parses the `domains` string and initializes the object.
     *
     * @param domains Domain list string or AGTree DomainList node.
     * @param separator Separator — `,` or `|`.
     *
     * @throws An error if the domains string is empty or invalid.
     */
    constructor(domains, separator) {
        let processed;
        if (background_isString(domains)) {
            const node = background_domain_list_parser/* DomainListParser */.y.parse(domains.trim(), { ...background_options/* defaultParserOptions */.n, isLocIncluded: false }, 0, separator);
            if (node.children.length === 0) {
                throw new SyntaxError('At least one domain must be specified');
            }
            processed = background_DomainModifier.processDomainList(node);
        }
        else {
            // domain list node stores the separator
            if (separator !== domains.separator) {
                throw new SyntaxError('Separator mismatch');
            }
            processed = background_DomainModifier.processDomainList(domains);
        }
        // Unescape separator character in domains
        processed.permittedDomains = processed.permittedDomains.map((domain) => background_unescapeChar(domain, separator));
        processed.restrictedDomains = processed.restrictedDomains.map((domain) => background_unescapeChar(domain, separator));
        this.restrictedDomains = processed.restrictedDomains.length > 0 ? processed.restrictedDomains : null;
        this.permittedDomains = processed.permittedDomains.length > 0 ? processed.permittedDomains : null;
    }
    /**
     * Checks if the filtering rule is allowed on this domain.
     *
     * @param domain Domain to check.
     *
     * @returns True if the filtering rule is allowed on this domain.
     */
    matchDomain(domain) {
        if (this.hasRestrictedDomains()) {
            if (background_DomainModifier.isDomainOrSubdomainOfAny(domain, this.restrictedDomains)) {
                // Domain or host is restricted
                // i.e. $domain=~example.org
                return false;
            }
        }
        if (this.hasPermittedDomains()) {
            if (!background_DomainModifier.isDomainOrSubdomainOfAny(domain, this.permittedDomains)) {
                // Domain is not among permitted
                // i.e. $domain=example.org and we're checking example.com
                return false;
            }
        }
        return true;
    }
    /**
     * Checks if rule has permitted domains.
     *
     * @returns True if the rule has permitted domains.
     */
    hasPermittedDomains() {
        return !!this.permittedDomains && this.permittedDomains.length > 0;
    }
    /**
     * Checks if rule has restricted domains.
     *
     * @returns True if the rule has restricted domains.
     */
    hasRestrictedDomains() {
        return !!this.restrictedDomains && this.restrictedDomains.length > 0;
    }
    /**
     * Gets list of permitted domains.
     *
     * @returns List of permitted domains or null if none.
     */
    getPermittedDomains() {
        return this.permittedDomains;
    }
    /**
     * Gets list of restricted domains.
     *
     * @returns List of restricted domains or null if none.
     */
    getRestrictedDomains() {
        return this.restrictedDomains;
    }
    /**
     * Checks if `domain` is the same or a subdomain
     * of any of `domains`.
     *
     * @param domain Domain to check.
     * @param domains Domains list to check against.
     *
     * @returns True if `domain` is the same or a subdomain of any of `domains`.
     */
    static isDomainOrSubdomainOfAny(domain, domains) {
        for (let i = 0; i < domains.length; i += 1) {
            const d = domains[i];
            if (background_DomainModifier.isWildcardDomain(d)) {
                if (background_DomainModifier.matchAsWildcard(d, domain)) {
                    return true;
                }
            }
            if (domain === d || (domain.endsWith(d) && domain.endsWith(`.${d}`))) {
                return true;
            }
            if (background_SimpleRegex.isRegexPattern(d)) {
                try {
                    /**
                     * Regular expressions are cached internally by the browser
                     * (for instance, they're stored in the CompilationCache in V8/Chromium),
                     * so calling the constructor here should not be a problem.
                     *
                     * TODO: use SimpleRegex.patternFromString(d) after it is refactored to not add 'g' flag.
                     */
                    const domainPattern = new RegExp(d.slice(1, -1));
                    if (domainPattern.test(domain)) {
                        return true;
                    }
                }
                catch {
                    background_logger.error(`Invalid regular expression as domain pattern: "${d}"`);
                }
                continue;
            }
        }
        return false;
    }
    /**
     * Checks if domain ends with wildcard.
     *
     * @param domain Domain string to check.
     *
     * @returns True if domain ends with wildcard.
     */
    static isWildcardDomain(domain) {
        return domain.endsWith('.*');
    }
    /**
     * Checks if domain string does not ends with wildcard and is not regex pattern.
     *
     * @param domain Domain string to check.
     *
     * @returns True if given domain is a wildcard or regexp pattern.
     */
    static isWildcardOrRegexDomain(domain) {
        return background_DomainModifier.isWildcardDomain(domain) || background_SimpleRegex.isRegexPattern(domain);
    }
    /**
     * Checks if wildcard matches domain.
     *
     * @param wildcard The wildcard pattern to match against the domain.
     * @param domainNameToCheck The domain name to check against the wildcard pattern.
     *
     * @returns True if wildcard matches domain.
     */
    static matchAsWildcard(wildcard, domainNameToCheck) {
        const wildcardedDomainToCheck = background_DomainModifier.genTldWildcard(domainNameToCheck);
        if (wildcardedDomainToCheck) {
            return wildcardedDomainToCheck === wildcard
                || (wildcardedDomainToCheck.endsWith(wildcard) && wildcardedDomainToCheck.endsWith(`.${wildcard}`));
        }
        return false;
    }
    /**
     * Generates from domain tld wildcard.
     *
     * @param domainName The domain name to generate the TLD wildcard for.
     *
     * @returns String is empty if tld for provided domain name doesn't exists.
     *
     * @example
     * `google.com` -> `google.*`
     * `youtube.co.uk` -> `youtube.*`
     */
    static genTldWildcard(domainName) {
        // To match eTld like "com.ru" we use allowPrivateDomains wildcard
        // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2650
        const tld = (0,background_es6/* getPublicSuffix */.pj)(domainName, { allowPrivateDomains: true });
        if (tld) {
            // lastIndexOf() is needed not to match the domain, e.g. 'www.chrono24.ch'.
            // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2312.
            return `${domainName.slice(0, domainName.lastIndexOf(`.${tld}`))}.*`;
        }
        return '';
    }
}

/**
 * Replace modifier class.
 */
class background_ReplaceModifier {
    /**
     * Replace option value.
     */
    replaceOption;
    /**
     * Replace option apply function.
     */
    replaceApply;
    /**
     * Constructor.
     *
     * @param value Replace modifier value.
     */
    constructor(value) {
        const parsed = background_ReplaceModifier.parseReplaceOption(value);
        this.replaceOption = parsed.optionText;
        this.replaceApply = parsed.apply;
    }
    /**
     * Parses replace option.
     *
     * @param option Replace option.
     *
     * @returns Parsed replace option.
     */
    static parseReplaceOption(option) {
        if (!option) {
            return {
                apply: (x) => x,
                optionText: '',
            };
        }
        const parts = background_splitByDelimiterWithEscapeCharacter(option, '/', '\\');
        let modifiers = (parts[2] || '');
        if (modifiers.indexOf('g') < 0) {
            modifiers += 'g';
        }
        const pattern = new RegExp(parts[0], modifiers);
        // unescape replacement alias
        let replacement = parts[1].replace(/\\\$/g, '$');
        replacement = background_SimpleRegex.unescapeSpecials(replacement);
        const apply = (input) => input.replace(pattern, replacement);
        return {
            apply,
            optionText: option,
        };
    }
    /**
     * Replace content.
     *
     * @returns The replace option value.
     */
    getValue() {
        return this.replaceOption;
    }
    /**
     * Replace apply function.
     *
     * @returns The function to apply the replacement.
     */
    getApplyFunc() {
        return this.replaceApply;
    }
}

const background_CSP_HEADER_NAME = 'Content-Security-Policy';
/**
 * Csp modifier class.
 */
class background_CspModifier {
    /**
     * Csp directive.
     *
     * @returns The CSP directive.
     */
    cspDirective;
    /**
     * Is allowlist rule.
     */
    isAllowlist;
    /**
     * Constructor.
     *
     * @param value Value of the modifier.
     * @param isAllowlist Whether the rule is an allowlist rule or not.
     */
    constructor(value, isAllowlist) {
        this.cspDirective = value;
        this.isAllowlist = isAllowlist;
        this.validateCspDirective();
    }
    /**
     * Csp directive.
     *
     * @returns The CSP directive.
     */
    getValue() {
        return this.cspDirective;
    }
    /**
     * Validates CSP rule.
     */
    validateCspDirective() {
        /**
         * CSP directive may be empty in case of allowlist rule,
         * it means to disable all $csp rules matching the allowlist rule.
         *
         * @see {@link https://github.com/AdguardTeam/AdguardBrowserExtension/issues/685}
         */
        if (!this.isAllowlist && !this.cspDirective) {
            throw new Error('Invalid $CSP rule: CSP directive must not be empty');
        }
        if (this.cspDirective) {
            /**
             * Forbids report-to and report-uri directives.
             *
             * @see {@link https://github.com/AdguardTeam/AdguardBrowserExtension/issues/685#issue-228287090}
             */
            const cspDirective = this.cspDirective.toLowerCase();
            if (cspDirective.indexOf('report-') >= 0) {
                throw new Error(`Forbidden CSP directive: ${cspDirective}`);
            }
        }
    }
}

/**
 * Cookie modifier class.
 *
 * Learn more about it here:
 * https://github.com/AdguardTeam/AdguardBrowserExtension/issues/961.
 */
class background_CookieModifier {
    /**
     * Cookie `maxAge` name.
     */
    static MAX_AGE = 'maxAge';
    /**
     * Cookie `sameSite` name.
     */
    static SAME_SITE = 'sameSite';
    /**
     * Option value.
     */
    optionValue;
    /**
     * Regexp value.
     */
    regex;
    /**
     * Cookie name.
     */
    cookieName;
    /**
     * Cookie `sameSite` value.
     */
    sameSite;
    /**
     * Cookie `maxAge` value.
     */
    maxAge;
    /**
     * Constructor.
     *
     * @param value Value of the modifier.
     */
    constructor(value) {
        // Save the source text of the option modifier
        this.optionValue = value || '';
        this.regex = null;
        this.cookieName = null;
        this.sameSite = null;
        this.maxAge = null;
        // Parse cookie name/regex
        const parts = this.optionValue.split(/;/);
        if (parts.length < 1) {
            throw new Error(`Cannot parse ${this.optionValue}`);
        }
        const cookieName = parts[0];
        if (cookieName.startsWith('/') && cookieName.endsWith('/')) {
            const pattern = cookieName.substring(1, cookieName.length - 1);
            // Save regex to be used further for matching cookies
            this.regex = new RegExp(pattern);
        }
        else {
            // Match by cookie name
            this.cookieName = cookieName;
        }
        // Parse other cookie options
        if (parts.length > 1) {
            for (let i = 1; i < parts.length; i += 1) {
                const nameValue = parts[i].split('=');
                const optionName = nameValue[0];
                const optionValue = nameValue[1];
                if (optionName === background_CookieModifier.MAX_AGE) {
                    this.maxAge = parseInt(optionValue, 10);
                }
                else if (optionName === background_CookieModifier.SAME_SITE) {
                    this.sameSite = optionValue;
                }
                else {
                    throw new Error(`Unknown $cookie option: ${optionName}`);
                }
            }
        }
    }
    /**
     * Gets modifier value.
     *
     * @returns Modifier value.
     */
    getValue() {
        return this.optionValue;
    }
    /**
     * First cookie name.
     *
     * @returns The first cookie name.
     */
    getCookieName() {
        return this.cookieName;
    }
    /**
     * Max age cookie value.
     *
     * @returns The max age cookie value.
     */
    getMaxAge() {
        return this.maxAge;
    }
    /**
     * Same site cookie value.
     *
     * @returns The same site cookie value.
     */
    getSameSite() {
        return this.sameSite;
    }
    /**
     * Checks if cookie with the specified name matches this option.
     *
     * @param name Cookie name.
     *
     * @returns True if matches, false otherwise.
     */
    matches(name) {
        if (!name) {
            return false;
        }
        if (this.regex) {
            return this.regex.test(name);
        }
        if (this.cookieName) {
            return this.cookieName === name;
        }
        // Empty regex and cookieName means that we must match all cookies
        return true;
    }
    /**
     * Checks if cookie rule has an empty $cookie option.
     *
     * @returns True if $cookie option is empty.
     */
    isEmpty() {
        return !this.regex && !this.cookieName;
    }
    /**
     * Checks if the given modifier is an instance of CookieModifier.
     *
     * @param m The modifier to check.
     *
     * @returns True if the modifier is an instance of CookieModifier, false otherwise.
     */
    static isCookieModifier = (m) => {
        return m instanceof background_CookieModifier;
    };
}

/**
 * Array of all stealth options available, even those which are not supported by browser extension.
 */
var background_UniversalStealthOption;
(function (UniversalStealthOption) {
    UniversalStealthOption["HideSearchQueries"] = "searchqueries";
    UniversalStealthOption["DoNotTrack"] = "donottrack";
    UniversalStealthOption["ThirdPartyCookies"] = "3p-cookie";
    UniversalStealthOption["FirstPartyCookies"] = "1p-cookie";
    UniversalStealthOption["ThirdPartyCache"] = "3p-cache";
    UniversalStealthOption["ThirdPartyAuth"] = "3p-auth";
    UniversalStealthOption["WebRTC"] = "webrtc";
    UniversalStealthOption["Push"] = "push";
    UniversalStealthOption["Location"] = "location";
    UniversalStealthOption["Flash"] = "flash";
    UniversalStealthOption["Java"] = "java";
    UniversalStealthOption["HideReferrer"] = "referrer";
    UniversalStealthOption["UserAgent"] = "useragent";
    UniversalStealthOption["IP"] = "ip";
    UniversalStealthOption["XClientData"] = "xclientdata";
    UniversalStealthOption["DPI"] = "dpi";
})(background_UniversalStealthOption || (background_UniversalStealthOption = {}));
/**
 * List of stealth options, supported by browser extension, which can be disabled by $stealth modifier.
 *
 * Following stealth options are initialized on the engine start
 * and can't be disabled via $stealth modifier:
 * - `Block trackers` and `Remove tracking parameters`, as they are applied by a specific
 *   rule lists, initialized on app start;
 * - `Disabling WebRTC`, as it is not being applied on per-request basis.
 */
var background_StealthOptionName;
(function (StealthOptionName) {
    StealthOptionName["HideSearchQueries"] = "searchqueries";
    StealthOptionName["DoNotTrack"] = "donottrack";
    StealthOptionName["HideReferrer"] = "referrer";
    StealthOptionName["XClientData"] = "xclientdata";
    StealthOptionName["FirstPartyCookies"] = "1p-cookie";
    StealthOptionName["ThirdPartyCookies"] = "3p-cookie";
})(background_StealthOptionName || (background_StealthOptionName = {}));
const background_StealthModifierOptions = new Set(Object.values(background_StealthOptionName));
const background_UniversalStealthOptions = new Set(Object.values(background_UniversalStealthOption));
const background_StealthOption = {
    NotSet: 0,
    [background_StealthOptionName.HideSearchQueries]: 1,
    [background_StealthOptionName.DoNotTrack]: 1 << 1,
    [background_StealthOptionName.HideReferrer]: 1 << 2,
    [background_StealthOptionName.XClientData]: 1 << 3,
    [background_StealthOptionName.FirstPartyCookies]: 1 << 4,
    [background_StealthOptionName.ThirdPartyCookies]: 1 << 5,
};
/**
 * Stealth modifier class.
 * Rules with $stealth modifier will disable specified stealth options for matched requests.
 *
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#stealth-modifier}
 */
class background_StealthModifier {
    PIPE_SEPARATOR = '|';
    options = background_StealthOption.NotSet;
    /**
     * Parses the options string and creates a new stealth modifier instance.
     *
     * @param optionsStr Options string.
     *
     * @throws SyntaxError on inverted stealth options, which are not supported.
     */
    constructor(optionsStr) {
        if (optionsStr.trim().length === 0) {
            return;
        }
        // This prevents parsing invalid syntax as rule without supported options
        if (optionsStr.includes(',')) {
            throw new SyntaxError(`Invalid separator of stealth options used: "${optionsStr}"`);
        }
        const tokens = optionsStr.split(this.PIPE_SEPARATOR);
        for (let i = 0; i < tokens.length; i += 1) {
            const optionName = tokens[i].trim();
            if (optionName === '') {
                continue;
            }
            if (optionName.startsWith('~')) {
                throw new SyntaxError(`Inverted $stealth modifier values are not allowed: "${optionsStr}"`);
            }
            if (!background_StealthModifier.isValidStealthOption(optionName)) {
                throw new SyntaxError(`Invalid $stealth option in modifier value: "${optionsStr}"`);
            }
            // Skip options which are not supported by browser extension
            if (!background_StealthModifier.isSupportedStealthOption(optionName)) {
                continue;
            }
            const option = background_StealthOption[optionName];
            if (this.options & option) {
                background_logger.debug(`Duplicate $stealth modifier value "${optionName}" in "${optionsStr}"`);
            }
            this.options |= option;
        }
        if (this.options === background_StealthOption.NotSet) {
            // eslint-disable-next-line max-len
            const msg = `$stealth modifier does not contain any options supported by browser extension: "${optionsStr}"`;
            background_logger.debug(msg);
        }
    }
    /**
     * Checks if the given string is a valid $stealth option, supported by browser extension.
     *
     * @param option Option name.
     *
     * @returns True if the given string is a valid $stealth option.
     */
    static isSupportedStealthOption = (option) => background_StealthModifierOptions.has(option);
    /**
     * Checks if the given string is a valid $stealth option.
     *
     * @param option Option name.
     *
     * @returns True if the given string is a valid $stealth option.
     */
    static isValidStealthOption = (option) => background_UniversalStealthOptions.has(option);
    /**
     * Checks if this stealth modifier has values.
     *
     * @returns True if this stealth modifier has at least one value.
     */
    hasValues() {
        return this.options !== background_StealthOption.NotSet;
    }
    /**
     * Checks if this stealth modifier is disabling the given stealth option.
     *
     * @param optionName Stealth option name.
     *
     * @returns True if this stealth modifier is disabling the given stealth option.
     */
    hasStealthOption(optionName) {
        const option = background_StealthOption[optionName];
        return !!(option && this.options & option);
    }
}

/**
 * Redirect modifier class.
 */
class background_RedirectModifier {
    /**
     * Redirect title.
     */
    redirectTitle;
    /**
     * Is redirecting only blocked requests
     * See $redirect-rule options.
     */
    isRedirectingOnlyBlocked = false;
    /**
     * Constructor.
     *
     * @param value Redirect modifier value.
     * @param isAllowlist Is allowlist rule.
     * @param isRedirectingOnlyBlocked Is redirect-rule modifier.
     */
    constructor(value, isAllowlist, isRedirectingOnlyBlocked = false) {
        background_RedirectModifier.validate(value, isAllowlist);
        this.redirectTitle = value;
        this.isRedirectingOnlyBlocked = isRedirectingOnlyBlocked;
    }
    /**
     * Redirect title.
     *
     * @returns The redirect title.
     */
    getValue() {
        return this.redirectTitle;
    }
    /**
     * Validates redirect rule.
     *
     * @param redirectTitle The title of the redirect.
     * @param isAllowlist Indicates if the rule is an allowlist rule.
     */
    static validate(redirectTitle, isAllowlist) {
        if (isAllowlist && !redirectTitle) {
            return;
        }
        if (!redirectTitle) {
            throw new SyntaxError('Invalid $redirect rule, redirect value must not be empty');
        }
        if (!(0,background_validators/* isRedirectResourceCompatibleWithAdg */.td)(redirectTitle)) {
            throw new SyntaxError('$redirect modifier is invalid');
        }
    }
}

/**
 * Splits url into parts.
 *
 * @param url The URL to be checked.
 *
 * @returns An object containing the path, query, and hash of the URL.
 */
function background_splitUrl(url) {
    let strippedUrl = url;
    let hash = '';
    const hashIndex = url.indexOf('#');
    if (hashIndex >= 0) {
        hash = url.slice(hashIndex);
        strippedUrl = url.slice(0, hashIndex);
    }
    let query = '';
    const queryIndex = url.indexOf('?');
    if (queryIndex >= 0) {
        query = strippedUrl.slice(queryIndex + 1);
        strippedUrl = strippedUrl.slice(0, queryIndex);
    }
    return {
        path: strippedUrl,
        query,
        hash,
    };
}
/**
 * Normalizes url query parameters.
 *
 * @param query The query string to be normalized.
 *
 * @returns The normalized query string.
 */
function background_normalizeQuery(query) {
    // Cleanup empty params (p0=0&=2&=3)
    let result = query
        .split('&')
        .filter((x) => x && !x.startsWith('='))
        .join('&');
    // If we've collapsed the URL to the point where there's an '&' against the '?'
    // then we need to get rid of that.
    while (result.charAt(0) === '&') {
        result = result.slice(1);
    }
    return result;
}
/**
 * Removes query params from url by regexp.
 *
 * @param url The URL from which query parameters will be removed.
 * @param regExp The regular expression to match query parameters.
 * @param invert Remove every parameter in url except the ones matched regexp.
 *
 * @returns The URL with the specified query parameters removed.
 */
function background_cleanUrlParamByRegExp(url, regExp, invert = false) {
    const searchIndex = url.indexOf('?');
    // If no params, nothing to modify
    if (searchIndex === -1) {
        return url;
    }
    const split = background_splitUrl(url);
    /**
     * We are checking both regular param and decoded param, in case if regexp
     * contains decoded params and url contains encoded params.
     *
     * @see {@link https://github.com/AdguardTeam/AdguardBrowserExtension/issues/3015}
     */
    let modifiedQuery;
    if (invert) {
        modifiedQuery = split.query
            .split('&')
            .filter((x) => x && (x.match(regExp) || decodeURIComponent(x).match(regExp)))
            .join('&');
    }
    else {
        modifiedQuery = split.query
            .split('&')
            .filter((x) => {
            const test = x.includes('=') ? x : `${x}=`;
            return !test.match(regExp) && !decodeURIComponent(test).match(regExp);
        })
            .join('&');
    }
    // Do not normalize if regexp is not applied
    if (modifiedQuery === split.query) {
        return url;
    }
    modifiedQuery = background_normalizeQuery(modifiedQuery);
    let result = split.path;
    if (modifiedQuery) {
        result += `?${modifiedQuery}`;
    }
    return result + split.hash;
}
/**
 * Extract relative part from hierarchical structured URL.
 *
 * @param url The URL from which the relative part will be extracted.
 *
 * @returns The relative part of the URL or null if not found.
 */
const background_getRelativeUrl = (url) => {
    const i = url.indexOf('/', url.indexOf('://') + 3);
    return i !== -1 ? url.slice(i) : null;
};

/**
 * Query parameters filtering modifier class.
 * Works with `$removeparam` modifier.
 */
class background_RemoveParamModifier {
    /**
     * Value of the modifier.
     */
    value;
    /**
     * Is modifier valid for MV3 or not.
     *
     * @returns True if the modifier is valid for MV3, false otherwise.
     */
    mv3Valid = true;
    /**
     * RegExp to apply.
     */
    valueRegExp;
    /**
     * Constructor.
     *
     * @param value The value used to initialize the modifier.
     */
    constructor(value) {
        this.value = value;
        let rawValue = value;
        // TODO: Seems like negation not using in valueRegExp
        if (value.startsWith('~')) {
            rawValue = value.substring(1);
            this.mv3Valid = false;
        }
        if (rawValue.startsWith('/')) {
            this.valueRegExp = background_SimpleRegex.patternFromString(rawValue);
            this.mv3Valid = false;
        }
        else {
            if (rawValue.includes('|')) {
                throw new Error('Unsupported option in $removeparam: multiple values are not allowed');
            }
            // no need to match "&" in the beginning, because we are splitting by "&"
            // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/3076
            this.valueRegExp = new RegExp(`^${background_SimpleRegex.escapeRegexSpecials(rawValue)}=[^&#]*$`, 'g');
        }
    }
    /**
     * Modifier value.
     *
     * @returns The value of the modifier.
     */
    getValue() {
        return this.value;
    }
    /**
     * Is modifier valid for MV3 or not.
     *
     * @returns True if the modifier is valid for MV3, false otherwise.
     */
    getMV3Validity() {
        return this.mv3Valid;
    }
    /**
     * Checks if the given modifier is an instance of RemoveParamModifier.
     *
     * @param m The modifier to check.
     *
     * @returns True if the modifier is an instance of RemoveParamModifier, false otherwise.
     */
    static isRemoveParamModifier = (m) => {
        return m instanceof background_RemoveParamModifier;
    };
    /**
     * Removes query parameters from url.
     *
     * @param url The URL from which query parameters should be removed.
     *
     * @returns The URL with the query parameters removed.
     */
    removeParameters(url) {
        const sepIndex = url.indexOf('?');
        if (sepIndex < 0) {
            return url;
        }
        if (!this.value) {
            return url.substring(0, sepIndex);
        }
        if (sepIndex === url.length - 1) {
            return url;
        }
        if (this.value.startsWith('~')) {
            return background_cleanUrlParamByRegExp(url, this.valueRegExp, true);
        }
        return background_cleanUrlParamByRegExp(url, this.valueRegExp);
    }
}

/**
 * Headers filtering modifier class.
 * Rules with $removeheader modifier are intended to remove headers from HTTP requests and responses.
 */
class background_RemoveHeaderModifier {
    /**
     * List of forbidden headers.
     */
    static FORBIDDEN_HEADERS = [
        'access-control-allow-origin',
        'access-control-allow-credentials',
        'access-control-allow-headers',
        'access-control-allow-methods',
        'access-control-expose-headers',
        'access-control-max-age',
        'access-control-request-headers',
        'access-control-request-method',
        'origin',
        'timing-allow-origin',
        'allow',
        'cross-origin-embedder-policy',
        'cross-origin-opener-policy',
        'cross-origin-resource-policy',
        'content-security-policy',
        'content-security-policy-report-only',
        'expect-ct',
        'feature-policy',
        'origin-isolation',
        'strict-transport-security',
        'upgrade-insecure-requests',
        'x-content-type-options',
        'x-download-options',
        'x-frame-options',
        'x-permitted-cross-domain-policies',
        'x-powered-by',
        'x-xss-protection',
        'public-key-pins',
        'public-key-pins-report-only',
        'sec-websocket-key',
        'sec-websocket-extensions',
        'sec-websocket-accept',
        'sec-websocket-protocol',
        'sec-websocket-version',
        'p3p',
        'sec-fetch-mode',
        'sec-fetch-dest',
        'sec-fetch-site',
        'sec-fetch-user',
        'referrer-policy',
        'content-type',
        'content-length',
        'accept',
        'accept-encoding',
        'host',
        'connection',
        'transfer-encoding',
        'upgrade',
    ];
    /**
     * Request prefix.
     */
    static REQUEST_PREFIX = 'request:';
    /**
     * Prefixed headers are applied to request headers.
     */
    isRequestModifier;
    /**
     * Effective header name to be removed.
     */
    applicableHeaderName;
    /**
     * Value.
     */
    value;
    /**
     * Is rule valid or not.
     */
    valid;
    /**
     * Constructor.
     *
     * @param value Value of the modifier.
     * @param isAllowlist Whether the rule is an allowlist rule or not.
     */
    constructor(value, isAllowlist) {
        this.value = value.toLowerCase();
        if (!isAllowlist && !this.value) {
            throw new SyntaxError('Invalid $removeheader rule, removeheader value must not be empty');
        }
        this.isRequestModifier = this.value.startsWith(background_RemoveHeaderModifier.REQUEST_PREFIX);
        const headerName = this.isRequestModifier
            ? this.value.substring(background_RemoveHeaderModifier.REQUEST_PREFIX.length)
            : this.value;
        // Values with ":" are not supported in MV3 declarative rules, e.g. "$removeheader=dnt:1"
        this.valid = background_RemoveHeaderModifier.isAllowedHeader(headerName) && !headerName.includes(':');
        this.applicableHeaderName = this.valid ? headerName : null;
    }
    /**
     * Modifier value.
     *
     * @returns The value of the modifier.
     */
    getValue() {
        return this.value;
    }
    /**
     * Modifier validity.
     *
     * @returns True if the rule is valid, false otherwise.
     */
    get isValid() {
        return this.valid;
    }
    /**
     * Checks if the given modifier is an instance of RemoveHeaderModifier.
     *
     * @param m The modifier to check.
     *
     * @returns True if the modifier is an instance of RemoveHeaderModifier, false otherwise.
     */
    static isRemoveHeaderModifier = (m) => {
        return m instanceof background_RemoveHeaderModifier;
    };
    /**
     * Returns effective header name to be removed.
     *
     * @param isRequestHeaders Flag to determine that the header is a *request* header,
     * otherwise *response* header.
     *
     * @returns The applicable header name if valid, otherwise null.
     */
    getApplicableHeaderName(isRequestHeaders) {
        if (!this.applicableHeaderName) {
            return null;
        }
        if (isRequestHeaders !== this.isRequestModifier) {
            return null;
        }
        return this.applicableHeaderName;
    }
    /**
     * Some headers are forbidden to remove.
     *
     * @param headerName Header name to check.
     *
     * @returns True if the header is allowed to be removed, false otherwise.
     */
    static isAllowedHeader(headerName) {
        return !this.FORBIDDEN_HEADERS.includes(headerName);
    }
}

/**
 * This is a helper class that is used specifically to work with app restrictions.
 *
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#app}
 *
 * @example
 * ```adblock
 * ||baddomain.com^$app=org.example.app
 * ||baddomain.com^$app=org.example.app1|org.example.app2
 * ```
 */
class background_AppModifier {
    /**
     * List of permitted apps or null.
     */
    permittedApps;
    /**
     * List of restricted apps or null.
     */
    restrictedApps;
    /**
     * Parses the `apps` string.
     *
     * @param apps Apps string.
     *
     * @throws An error if the app string is empty or invalid.
     */
    constructor(apps) {
        if (!apps) {
            throw new SyntaxError('$app modifier cannot be empty');
        }
        const permittedApps = [];
        const restrictedApps = [];
        const parts = apps.split(background_SEPARATOR);
        for (let i = 0; i < parts.length; i += 1) {
            let app = parts[i];
            let restricted = false;
            if (app.startsWith('~')) {
                restricted = true;
                app = app.substring(1).trim();
            }
            if (app === '') {
                throw new SyntaxError(`Empty app specified in "${apps}"`);
            }
            if (restricted) {
                restrictedApps.push(app);
            }
            else {
                permittedApps.push(app);
            }
        }
        this.restrictedApps = restrictedApps.length > 0 ? restrictedApps : null;
        this.permittedApps = permittedApps.length > 0 ? permittedApps : null;
    }
}

var background_HTTPMethod;
(function (HTTPMethod) {
    HTTPMethod["GET"] = "GET";
    HTTPMethod["POST"] = "POST";
    HTTPMethod["PUT"] = "PUT";
    HTTPMethod["DELETE"] = "DELETE";
    HTTPMethod["PATCH"] = "PATCH";
    HTTPMethod["HEAD"] = "HEAD";
    HTTPMethod["OPTIONS"] = "OPTIONS";
    HTTPMethod["CONNECT"] = "CONNECT";
    HTTPMethod["TRACE"] = "TRACE";
})(background_HTTPMethod || (background_HTTPMethod = {}));
/**
 * Method modifier class.
 * Rules with $method modifier will be applied only to requests with specified methods.
 *
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#method-modifier}
 */
class background_MethodModifier {
    /**
     * Request methods separator.
     */
    static PIPE_SEPARATOR = '|';
    /**
     * List of permitted methods or null.
     */
    permittedValues;
    /**
     * List of restricted methods or null.
     */
    restrictedValues;
    /**
     * Constructor.
     *
     * @param methodsStr Value of the modifier.
     */
    constructor(methodsStr) {
        if (methodsStr === '') {
            throw new SyntaxError('$method modifier value cannot be empty');
        }
        const permittedMethods = [];
        const restrictedMethods = [];
        const parts = methodsStr.toUpperCase().split(background_MethodModifier.PIPE_SEPARATOR);
        for (let i = 0; i < parts.length; i += 1) {
            let method = parts[i].trim();
            let restricted = false;
            if (method.startsWith('~')) {
                restricted = true;
                method = method.substring(1);
            }
            if (!background_MethodModifier.isHTTPMethod(method)) {
                throw new SyntaxError(`Invalid $method modifier value: ${method}`);
            }
            if (restricted) {
                restrictedMethods.push(method);
            }
            else {
                permittedMethods.push(method);
            }
        }
        if (restrictedMethods.length > 0 && permittedMethods.length > 0) {
            throw new SyntaxError(`Negated values cannot be mixed with non-negated values: ${methodsStr}`);
        }
        this.restrictedValues = restrictedMethods.length > 0 ? restrictedMethods : null;
        this.permittedValues = permittedMethods.length > 0 ? permittedMethods : null;
    }
    static isHTTPMethod = (value) => value in background_HTTPMethod;
}

/**
 * Header modifier class.
 * The $header modifier allows matching the HTTP response
 * by a specific header with (optionally) a specific value.
 *
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#header-modifier}
 */
class background_HeaderModifier {
    /**
     * Colon separator.
     */
    COLON_SEPARATOR = ':';
    /**
     * Forward slash regexp marker.
     */
    FORWARD_SLASH = '/';
    /**
     * Header name to match on request.
     */
    header;
    /**
     * Header value to match on request.
     * Empty string if value is not specified, and, in that case,
     * only header name will be matched.
     */
    value;
    /**
     * Constructor.
     *
     * @param headerStr Header modifier value.
     */
    constructor(headerStr) {
        if (headerStr === '') {
            throw new SyntaxError('$header modifier value cannot be empty');
        }
        const separatorIndex = headerStr.indexOf(this.COLON_SEPARATOR);
        if (separatorIndex === -1) {
            this.header = headerStr;
            this.value = null;
            return;
        }
        this.header = headerStr.slice(0, separatorIndex);
        const rawValue = headerStr.slice(separatorIndex + 1);
        if (rawValue === '') {
            throw new SyntaxError(`Invalid $header modifier value: "${headerStr}"`);
        }
        if (rawValue.startsWith(this.FORWARD_SLASH) && rawValue.endsWith(this.FORWARD_SLASH)) {
            this.value = new RegExp(rawValue.slice(1, -1));
        }
        else {
            this.value = rawValue;
        }
    }
    /**
     * Returns header modifier value.
     *
     * @returns Header modifier value.
     */
    getHeaderModifierValue() {
        return {
            header: this.header,
            value: this.value,
        };
    }
}

/**
 * `$to` modifier class.
 * Rules with $to modifier are limited to requests made to the specified domains and their subdomains.
 *
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#to-modifier}
 */
class background_ToModifier {
    /**
     * Domains separator.
     */
    static PIPE_SEPARATOR = '|';
    /**
     * List of permitted domains or null.
     */
    permittedValues;
    /**
     * List of restricted domains or null.
     */
    restrictedValues;
    /**
     * Constructor.
     *
     * @param domainsStr String with domains separated by `|`.
     */
    constructor(domainsStr) {
        if (!domainsStr) {
            throw new SyntaxError('$to modifier value cannot be empty');
        }
        const permittedDomains = [];
        const restrictedDomains = [];
        const parts = domainsStr.toLowerCase().split(background_ToModifier.PIPE_SEPARATOR);
        for (let i = 0; i < parts.length; i += 1) {
            let domain = parts[i].trim();
            let restricted = false;
            if (domain.startsWith('~')) {
                restricted = true;
                domain = domain.substring(1);
            }
            if (domain === '') {
                throw new SyntaxError(`Empty domain specified in "${domainsStr}"`);
            }
            if (restricted) {
                restrictedDomains.push(domain);
            }
            else {
                permittedDomains.push(domain);
            }
        }
        this.restrictedValues = restrictedDomains.length > 0 ? restrictedDomains : null;
        this.permittedValues = permittedDomains.length > 0 ? permittedDomains : null;
    }
}

const background_PERMISSIONS_POLICY_HEADER_NAME = 'Permissions-Policy';
const background_COMMA_SEPARATOR = ',';
const background_PIPE_SEPARATOR = '|';
/**
 * Permissions modifier class.
 * Allows setting permission policies, effectively blocking specific page functionality.
 *
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#permissions-modifier}
 */
class background_PermissionsModifier {
    /**
     * Permission Policy directive.
     */
    permissionPolicyDirective;
    /**
     * Regular expression to apply correct separators.
     * It replaces escaped commas and pipe separators with commas.
     */
    static RE_SEPARATOR_REPLACE = new RegExp(`(\\\\${background_COMMA_SEPARATOR}|\\${background_PIPE_SEPARATOR})`, 'g');
    /**
     * Constructor.
     *
     * @param permissionPolicyStr The permission policy string to be set.
     * @param isAllowlist Indicates if the permission policy is for an allowlist.
     */
    constructor(permissionPolicyStr, isAllowlist) {
        this.permissionPolicyDirective = permissionPolicyStr
            .replace(background_PermissionsModifier.RE_SEPARATOR_REPLACE, background_COMMA_SEPARATOR);
        background_PermissionsModifier.validatePermissionPolicyDirective(this.permissionPolicyDirective, isAllowlist);
    }
    /**
     * Returns permission policy allowlist string.
     *
     * @returns Permission policy allowlist string.
     */
    getValue() {
        return this.permissionPolicyDirective;
    }
    /**
     * Validates permission policy directive.
     *
     * @param directive The permission policy directive to validate.
     * @param isAllowlist Indicates if the directive is for an allowlist.
     *
     * @throws SyntaxError on invalid permission policy directive.
     */
    static validatePermissionPolicyDirective(directive, isAllowlist) {
        /**
         * $permissions modifier value may be empty only in case of allowlist rule,
         * it means to disable all $permissions rules matching the rule pattern.
         */
        if (!isAllowlist && !directive) {
            throw new SyntaxError('Invalid $permissions rule: permissions directive must not be empty');
        }
    }
}

/**
 * Compatibility types are used to configure engine for better support of different libraries
 * For example:
 *  extension doesn't support $app modifier. So if we set in configuration CompatibilityTypes.Extension,
 *  engine would ignore rules with $app modifier.
 */
var background_CompatibilityTypes;
(function (CompatibilityTypes) {
    CompatibilityTypes[CompatibilityTypes["Extension"] = 1] = "Extension";
    CompatibilityTypes[CompatibilityTypes["CoreLibs"] = 2] = "CoreLibs";
    CompatibilityTypes[CompatibilityTypes["Dns"] = 4] = "Dns";
})(background_CompatibilityTypes || (background_CompatibilityTypes = {}));
/**
 * Application configuration class.
 */
class background_Configuration {
    defaultConfig = {
        engine: null,
        version: null,
        verbose: false,
        compatibility: null,
    };
    /**
     * {'extension'|'corelibs'} engine application type.
     */
    engine = null;
    /**
     * {string} version.
     */
    version = null;
    /**
     * {boolean} verbose flag.
     */
    verbose = false;
    /**
     * Compatibility flag.
     */
    compatibility = background_CompatibilityTypes.Extension;
    constructor(inputConfig) {
        const config = { ...this.defaultConfig, ...inputConfig };
        this.engine = config.engine;
        this.version = config.version;
        this.verbose = config.verbose;
        this.compatibility = config.compatibility;
    }
}
// eslint-disable-next-line import/no-mutable-exports
let background_config = new background_Configuration();
/**
 * Checks config is compatible with input level.
 *
 * @param compatibilityLevel Compatibility level to check against.
 *
 * @returns True if compatible, otherwise false.
 */
function background_isCompatibleWith(compatibilityLevel) {
    if (background_config.compatibility === null) {
        return false;
    }
    return (background_config.compatibility & compatibilityLevel) === compatibilityLevel;
}

const background_NETWORK_RULE_OPTIONS = {
    THIRD_PARTY: 'third-party',
    FIRST_PARTY: 'first-party',
    MATCH_CASE: 'match-case',
    IMPORTANT: 'important',
    DOMAIN: 'domain',
    DENYALLOW: 'denyallow',
    ELEMHIDE: 'elemhide',
    GENERICHIDE: 'generichide',
    SPECIFICHIDE: 'specifichide',
    GENERICBLOCK: 'genericblock',
    JSINJECT: 'jsinject',
    URLBLOCK: 'urlblock',
    CONTENT: 'content',
    DOCUMENT: 'document',
    DOC: 'doc',
    STEALTH: 'stealth',
    POPUP: 'popup',
    EMPTY: 'empty',
    MP4: 'mp4',
    SCRIPT: 'script',
    STYLESHEET: 'stylesheet',
    SUBDOCUMENT: 'subdocument',
    OBJECT: 'object',
    IMAGE: 'image',
    XMLHTTPREQUEST: 'xmlhttprequest',
    MEDIA: 'media',
    FONT: 'font',
    WEBSOCKET: 'websocket',
    OTHER: 'other',
    PING: 'ping',
    BADFILTER: 'badfilter',
    CSP: 'csp',
    REPLACE: 'replace',
    COOKIE: 'cookie',
    REDIRECT: 'redirect',
    REDIRECTRULE: 'redirect-rule',
    REMOVEPARAM: 'removeparam',
    REMOVEHEADER: 'removeheader',
    JSONPRUNE: 'jsonprune',
    HLS: 'hls',
    REFERRERPOLICY: 'referrerpolicy',
    APP: 'app',
    NETWORK: 'network',
    EXTENSION: 'extension',
    NOOP: '_',
    CLIENT: 'client',
    DNSREWRITE: 'dnsrewrite',
    DNSTYPE: 'dnstype',
    CTAG: 'ctag',
    HEADER: 'header',
    METHOD: 'method',
    TO: 'to',
    PERMISSIONS: 'permissions',
    ALL: 'all',
};
const background_OPTIONS_DELIMITER = '$';
const background_MASK_ALLOWLIST = '@@';
const background_NOT_MARK = '~';

/**
 * RequestType is the request types enumeration.
 * Important: the enumeration is marked as const to avoid side effects when
 * importing it into an extension.
 */
const background_RequestType = {
    /**
     * No value is set. Syntax sugar to simplify code.
     */
    NotSet: 0,
    /**
     * Main frame.
     */
    Document: 1,
    /**
     * (iframe) $subdocument.
     */
    SubDocument: 2, // 1 << 1
    /**
     * (javascript, etc) $script.
     */
    Script: 4, // 1 << 2
    /**
     * (css) $stylesheet.
     */
    Stylesheet: 8, // 1 << 3
    /**
     * (flash, etc) $object.
     */
    Object: 16, // 1 << 4
    /**
     * (any image) $image.
     */
    Image: 32, // 1 << 5
    /**
     * (ajax/fetch) $xmlhttprequest.
     */
    XmlHttpRequest: 64, // 1 << 6
    /**
     * (video/music) $media.
     */
    Media: 128, // 1 << 7
    /**
     * (any custom font) $font.
     */
    Font: 256, // 1 << 8
    /**
     * (a websocket connection) $websocket.
     */
    WebSocket: 512, // 1 << 9
    /**
     * (navigator.sendBeacon()) $ping.
     */
    Ping: 1024, // 1 << 10
    /**
     * Csp_report.
     */
    CspReport: 2048, // 1 << 11
    /**
     * Any other request type.
     */
    Other: 4096, // 1 << 12
};

/**
 * This is the base class representing double values modifiers.
 */
class background_BaseValuesModifier {
    /**
     * List of permitted values or null.
     */
    permitted;
    /**
     * List of restricted values or null.
     */
    restricted;
    /**
     * Value.
     */
    value;
    /**
     * Parses the values string.
     *
     * @param values Values string.
     *
     * @throws An error if the string is empty or invalid.
     */
    constructor(values) {
        if (!values) {
            throw new SyntaxError('Modifier cannot be empty');
        }
        this.value = values;
        const permittedValues = [];
        const restrictedValues = [];
        const parts = values.split(background_SEPARATOR);
        for (let i = 0; i < parts.length; i += 1) {
            let app = parts[i];
            let restricted = false;
            if (app.startsWith('~')) {
                restricted = true;
                app = app.substring(1).trim();
            }
            if (app === '') {
                throw new SyntaxError(`Empty values specified in "${values}"`);
            }
            if (restricted) {
                restrictedValues.push(app);
            }
            else {
                permittedValues.push(app);
            }
        }
        this.restricted = restrictedValues.length > 0 ? restrictedValues : null;
        this.permitted = permittedValues.length > 0 ? permittedValues : null;
    }
    getPermitted() {
        return this.permitted;
    }
    getRestricted() {
        return this.restricted;
    }
    getValue() {
        return this.value;
    }
    match(value) {
        if (!this.restricted && !this.permitted) {
            return true;
        }
        if (this.restricted && this.restricted.includes(value)) {
            return false;
        }
        if (this.permitted) {
            return this.permitted.includes(value);
        }
        return true;
    }
}

// eslint-disable-next-line max-classes-per-file
/**
 * Netmasks class.
 */
class background_NetmasksCollection {
    ipv4Masks = [];
    ipv6Masks = [];
    /**
     * Returns true if any of the containing masks contains provided value.
     *
     * @param value Value to check.
     *
     * @returns True if any of the containing masks contains provided value.
     */
    contains(value) {
        if (background_is_ip.v4(value)) {
            return this.ipv4Masks.some((x) => (0,background_cidr_tools/* contains */.gR)(x, value));
        }
        return this.ipv6Masks.some((x) => (0,background_cidr_tools/* contains */.gR)(x, value));
    }
}
/**
 * The client modifier allows specifying clients this rule will be working for.
 * It accepts client names (not ClientIDs), IP addresses, or CIDR ranges.
 */
class background_ClientModifier extends background_BaseValuesModifier {
    permittedNetmasks;
    restrictedNetmasks;
    /**
     * Constructor.
     *
     * @param value Value of the modifier.
     */
    constructor(value) {
        super(value);
        const permitted = this.getPermitted();
        if (permitted) {
            this.permitted = background_ClientModifier.stripValues(permitted);
            this.permittedNetmasks = background_ClientModifier.parseNetmasks(this.permitted);
        }
        const restricted = this.getRestricted();
        if (restricted) {
            this.restricted = background_ClientModifier.stripValues(restricted);
            this.restrictedNetmasks = background_ClientModifier.parseNetmasks(this.restricted);
        }
    }
    /**
     * Unquotes and unescapes string.
     *
     * @param values Values to process.
     *
     * @returns Unquoted and unescaped values.
     */
    static stripValues(values) {
        return values.map((v) => {
            if ((v.startsWith('"') && v.endsWith('"'))
                || (v.startsWith('\'') && v.endsWith('\''))) {
                // eslint-disable-next-line no-param-reassign
                v = v.substr(1, v.length - 2);
            }
            return v.replace(/\\/ig, '');
        });
    }
    /**
     * Checks if this modifier matches provided params.
     *
     * @param clientName Client name.
     * @param clientIP Client IP.
     *
     * @returns True if this modifier matches provided params.
     */
    matchAny(clientName, clientIP) {
        if (this.restricted) {
            if (clientName && this.restricted.includes(clientName)) {
                return false;
            }
            if (clientIP && this.restricted.includes(clientIP)) {
                return false;
            }
            return true;
        }
        if (this.restrictedNetmasks) {
            if (clientIP && this.restrictedNetmasks.contains(clientIP)) {
                return false;
            }
            return true;
        }
        if (this.permitted) {
            if (clientName && this.permitted.includes(clientName)) {
                return true;
            }
            if (clientIP && this.permitted.includes(clientIP)) {
                return true;
            }
        }
        if (this.permittedNetmasks) {
            if (clientIP && this.permittedNetmasks.contains(clientIP)) {
                return true;
            }
        }
        return false;
    }
    /**
     * Parses netmasks from client's strings.
     *
     * @param values Values to parse.
     *
     * @returns Parsed netmasks.
     */
    static parseNetmasks(values) {
        const result = new background_NetmasksCollection();
        values.forEach((x) => {
            const cidrVersion = background_is_cidr(x);
            if (cidrVersion === 4) {
                result.ipv4Masks.push(x);
            }
            else if (cidrVersion === 6) {
                result.ipv6Masks.push(x);
            }
        });
        return result;
    }
}

/**
 * The dnsrewrite response modifier allows replacing the content of the response
 * to the DNS request for the matching hosts.
 *
 * TODO: This modifier is not yet implemented.
 *
 * @see {@link https://github.com/AdguardTeam/AdGuardHome/wiki/Hosts-Blocklists#dnsrewrite}
 */
class background_DnsRewriteModifier {
    /**
     * Value.
     */
    value;
    /**
     * Constructor.
     *
     * @param value Modifier value.
     */
    constructor(value) {
        this.value = value;
    }
    /**
     * Modifier value.
     *
     * @returns The value of the modifier.
     */
    getValue() {
        return this.value;
    }
}

/**
 * The `$dnstype` modifier allows specifying DNS request type on which this rule will be triggered.
 */
class background_DnsTypeModifier extends background_BaseValuesModifier {
    /**
     * Constructor.
     *
     * @param value The value used to initialize the modifier.
     */
    constructor(value) {
        super(value);
        if (this.permitted) {
            this.restricted = null;
        }
    }
}

/**
 * The ctag modifier allows to block domains only for specific types of DNS client tags.
 */
class background_CtagModifier extends background_BaseValuesModifier {
    /**
     * The list of allowed tags.
     */
    static ALLOWED_TAGS = [
        // By device type:
        'device_audio',
        'device_camera',
        'device_gameconsole',
        'device_laptop',
        'device_nas',
        'device_pc',
        'device_phone',
        'device_printer',
        'device_securityalarm',
        'device_tablet',
        'device_tv',
        'device_other',
        // By operating system:
        'os_android',
        'os_ios',
        'os_linux',
        'os_macos',
        'os_windows',
        'os_other',
        // By user group:
        'user_admin',
        'user_regular',
        'user_child',
    ];
    /**
     * Constructor.
     *
     * @param value Value of the modifier.
     */
    constructor(value) {
        super(value);
        this.validate();
    }
    /**
     * Validates tag values.
     */
    validate() {
        if (!this.getValue()) {
            throw new Error('Invalid rule: Ctag modifier must not be empty');
        }
        const tags = this.permitted ? this.permitted : this.restricted;
        if (tags && tags.some((x) => !background_CtagModifier.ALLOWED_TAGS.includes(x))) {
            throw new Error('Invalid rule: Invalid ctag modifier');
        }
    }
}

/**
 * Rule pattern class.
 *
 * This class parses rule pattern text to simple fields.
 */
class background_Pattern {
    /**
     * Original pattern text.
     */
    pattern;
    /**
     * Shortcut string.
     */
    shortcut;
    /**
     * If this pattern already prepared indicator.
     */
    prepared;
    /**
     * Parsed hostname.
     */
    hostname;
    /**
     * Parsed regular expression.
     */
    regex;
    /**
     * Invalid regex flag.
     */
    regexInvalid;
    /**
     * Domain specific pattern flag.
     */
    patternDomainSpecific;
    /**
     * If true, pattern and shortcut are the same.
     * In this case, we don't actually need to use `matchPattern`
     * if shortcut was already matched.
     */
    patternShortcut;
    /**
     * If pattern is match-case regex.
     */
    matchcase;
    /**
     * Constructor.
     *
     * @param pattern Pattern.
     * @param matchcase Flag for case-sensitive matching, default is false.
     */
    constructor(pattern, matchcase = false) {
        this.pattern = pattern;
        this.shortcut = background_SimpleRegex.extractShortcut(this.pattern);
        this.matchcase = matchcase;
    }
    /**
     * Checks if this rule pattern matches the specified request.
     *
     * @param request Request to check.
     * @param shortcutMatched If true, it means that the request already matches
     * this pattern's shortcut and we don't need to match it again.
     *
     * @returns True if pattern matches.
     */
    matchPattern(request, shortcutMatched) {
        this.prepare();
        if (this.patternShortcut) {
            return shortcutMatched || this.matchShortcut(request.urlLowercase);
        }
        if (this.hostname) {
            // If we have a `||example.org^` rule, it's easier to match
            // against the request's hostname only without matching
            // a regular expression.
            return request.hostname === this.hostname
                || ( // First light check without new string memory allocation
                request.hostname.endsWith(this.hostname)
                    // Strict check
                    && request.hostname.endsWith(`.${this.hostname}`));
        }
        // If the regular expression is invalid, just return false right away.
        if (this.regexInvalid || !this.regex) {
            return false;
        }
        // This is needed for DNS filtering only, not used in browser blocking.
        if (this.shouldMatchHostname(request)) {
            return this.regex.test(request.hostname);
        }
        return this.regex.test(request.url);
    }
    /**
     * Checks if this rule pattern matches the specified relative path string.
     * This method is used in cosmetic rules to implement the $path modifier matching logic.
     *
     * @param path Path to check.
     *
     * @returns True if pattern matches.
     */
    matchPathPattern(path) {
        this.prepare();
        if (this.hostname) {
            return false;
        }
        const pathIsEmptyString = this.pattern === '';
        // No-value $path should match root URL
        if (pathIsEmptyString && path === '/') {
            return true;
        }
        if (!pathIsEmptyString && this.patternShortcut) {
            return this.matchShortcut(path);
        }
        // If the regular expression is invalid, just return false right away.
        if (this.regexInvalid || !this.regex) {
            return false;
        }
        return this.regex.test(path);
    }
    /**
     * Simply checks if shortcut is a substring of the URL.
     *
     * @param str Shortcut to check.
     *
     * @returns True if the shortcut is a substring of the URL.
     */
    matchShortcut(str) {
        return str.indexOf(this.shortcut) >= 0;
    }
    /**
     * Prepares this pattern.
     */
    prepare() {
        if (this.prepared) {
            return;
        }
        this.prepared = true;
        // If shortcut and pattern are the same, we don't need to actually compile
        // a regex and can simply use matchShortcut instead,
        // except for the $match-case modifier
        if (this.pattern === this.shortcut && !this.matchcase) {
            this.patternShortcut = true;
            return;
        }
        // Rules like `/example/*` are rather often in the real-life filters,
        // we might want to process them.
        if (this.pattern.startsWith(this.shortcut)
            && this.pattern.length === this.shortcut.length + 1
            && this.pattern.endsWith('*')) {
            this.patternShortcut = true;
            return;
        }
        if (this.pattern.startsWith(background_SimpleRegex.MASK_START_URL)
            && this.pattern.endsWith(background_SimpleRegex.MASK_SEPARATOR)
            && this.pattern.indexOf('*') < 0
            && this.pattern.indexOf('/') < 0) {
            this.hostname = this.pattern.slice(2, this.pattern.length - 1);
            return;
        }
        this.compileRegex();
    }
    /**
     * Compiles this pattern regex.
     */
    compileRegex() {
        const regexText = background_SimpleRegex.patternToRegexp(this.pattern);
        try {
            let flags = 'i';
            if (this.matchcase) {
                flags = '';
            }
            this.regex = new RegExp(regexText, flags);
        }
        catch (e) {
            this.regexInvalid = true;
        }
    }
    /**
     * Checks if we should match hostnames and not the URL
     * this is important for the cases when we use urlfilter for DNS-level blocking
     * Note, that even though we may work on a DNS-level, we should still sometimes match full URL instead.
     *
     * @param request Request to check.
     *
     * @returns True if the hostname should be matched.
     */
    shouldMatchHostname(request) {
        if (!request.isHostnameRequest) {
            return false;
        }
        return !this.isPatternDomainSpecific();
    }
    /**
     * In case pattern starts with the following it targets some specific domain.
     *
     * @returns True if the pattern targets a specific domain.
     */
    isPatternDomainSpecific() {
        if (this.patternDomainSpecific === undefined) {
            this.patternDomainSpecific = this.pattern.startsWith(background_SimpleRegex.MASK_START_URL)
                || this.pattern.startsWith('http://')
                || this.pattern.startsWith('https:/')
                || this.pattern.startsWith('://');
        }
        return this.patternDomainSpecific;
    }
}

/* eslint-disable no-param-reassign */
/**
 * Counts the number of set bits (1s) in a 32-bit number using Hamming Weight (SWAR) method.
 *
 * @param a Number to count bits in.
 *
 * @returns The number of bits set to 1.
 */
function background_getBitCount(a) {
    a -= ((a >>> 1) & 0x55555555);
    a = (a & 0x33333333) + ((a >>> 2) & 0x33333333);
    a = (a + (a >>> 4)) & 0x0F0F0F0F;
    a += (a >>> 8);
    a += (a >>> 16);
    return a & 0x3F;
}
/**
 * Count the number of bits enabled in a number based on a bit mask.
 *
 * @param base Base number to check.
 * @param mask Mask to apply.
 *
 * @returns Number of bits set in `base & mask`.
 */
function background_countEnabledBits(base, mask) {
    return background_getBitCount(base & mask);
}

/**
 * NetworkRuleOption is the enumeration of various rule options.
 * In order to save memory, we store some options as a flag.
 *
 * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#basic-rule-modifiers}
 */
var background_NetworkRuleOption;
(function (NetworkRuleOption) {
    /**
     * No value is set. Syntax sugar to simplify code.
     */
    NetworkRuleOption[NetworkRuleOption["NotSet"] = 0] = "NotSet";
    /**
     * $third-party modifier.
     */
    NetworkRuleOption[NetworkRuleOption["ThirdParty"] = 1] = "ThirdParty";
    /**
     * $match-case modifier.
     */
    NetworkRuleOption[NetworkRuleOption["MatchCase"] = 2] = "MatchCase";
    /**
     * $important modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Important"] = 4] = "Important";
    // Allowlist rules modifiers
    // Each of them can disable part of the functionality
    /**
     * $elemhide modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Elemhide"] = 8] = "Elemhide";
    /**
     * $generichide modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Generichide"] = 16] = "Generichide";
    /**
     * $specifichide modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Specifichide"] = 32] = "Specifichide";
    /**
     * $genericblock modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Genericblock"] = 64] = "Genericblock";
    /**
     * $jsinject modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Jsinject"] = 128] = "Jsinject";
    /**
     * $urlblock modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Urlblock"] = 256] = "Urlblock";
    /**
     * $content modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Content"] = 512] = "Content";
    /**
     * $extension modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Extension"] = 1024] = "Extension";
    /**
     * $stealth modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Stealth"] = 2048] = "Stealth";
    // Other modifiers
    /**
     * $popup modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Popup"] = 4096] = "Popup";
    /**
     * $csp modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Csp"] = 8192] = "Csp";
    /**
     * $replace modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Replace"] = 16384] = "Replace";
    /**
     * $cookie modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Cookie"] = 32768] = "Cookie";
    /**
     * $redirect modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Redirect"] = 65536] = "Redirect";
    /**
     * $badfilter modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Badfilter"] = 131072] = "Badfilter";
    /**
     * $removeparam modifier.
     */
    NetworkRuleOption[NetworkRuleOption["RemoveParam"] = 262144] = "RemoveParam";
    /**
     * $removeheader modifier.
     */
    NetworkRuleOption[NetworkRuleOption["RemoveHeader"] = 524288] = "RemoveHeader";
    /**
     * $jsonprune modifier.
     */
    NetworkRuleOption[NetworkRuleOption["JsonPrune"] = 1048576] = "JsonPrune";
    /**
     * $hls modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Hls"] = 2097152] = "Hls";
    // Compatibility dependent
    /**
     * $network modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Network"] = 4194304] = "Network";
    /**
     * Dns modifiers.
     */
    NetworkRuleOption[NetworkRuleOption["Client"] = 8388608] = "Client";
    NetworkRuleOption[NetworkRuleOption["DnsRewrite"] = 16777216] = "DnsRewrite";
    NetworkRuleOption[NetworkRuleOption["DnsType"] = 33554432] = "DnsType";
    NetworkRuleOption[NetworkRuleOption["Ctag"] = 67108864] = "Ctag";
    /**
     * $method modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Method"] = 134217728] = "Method";
    /**
     * $to modifier.
     */
    NetworkRuleOption[NetworkRuleOption["To"] = 268435456] = "To";
    /**
     * $permissions modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Permissions"] = 536870912] = "Permissions";
    /**
     * $header modifier.
     */
    NetworkRuleOption[NetworkRuleOption["Header"] = 1073741824] = "Header";
})(background_NetworkRuleOption || (background_NetworkRuleOption = {}));
/**
 * NetworkRuleOptions is the enumeration of various rule options groups
 * needed for validation.
 */
var background_NetworkRuleGroupOptions;
(function (NetworkRuleGroupOptions) {
    /**
     * Allowlist-only modifiers.
     */
    NetworkRuleGroupOptions[NetworkRuleGroupOptions["AllowlistOnly"] = 4088] = "AllowlistOnly";
    /**
     * Options supported by host-level network rules.
     */
    NetworkRuleGroupOptions[NetworkRuleGroupOptions["OptionHostLevelRules"] = 125960196] = "OptionHostLevelRules";
    /**
     * Cosmetic option modifiers.
     */
    NetworkRuleGroupOptions[NetworkRuleGroupOptions["CosmeticOption"] = 696] = "CosmeticOption";
    /**
     * Removeparam compatible modifiers.
     *
     * $removeparam rules are compatible only with content type modifiers ($subdocument, $script, $stylesheet, etc)
     * except $document (using by default) and this list of modifiers.
     */
    NetworkRuleGroupOptions[NetworkRuleGroupOptions["RemoveParamCompatibleOptions"] = 393223] = "RemoveParamCompatibleOptions";
    /**
     * Removeheader compatible modifiers.
     *
     * $removeheader rules are compatible only with content type modifiers ($subdocument, $script, $stylesheet, etc)
     * except $document (using by default) and this list of modifiers.
     */
    NetworkRuleGroupOptions[NetworkRuleGroupOptions["RemoveHeaderCompatibleOptions"] = 1074397191] = "RemoveHeaderCompatibleOptions";
    /**
     * Permissions compatible modifiers.
     *
     * $permissions is compatible with the limited list of modifiers: $domain, $important, and $subdocument.
     */
    NetworkRuleGroupOptions[NetworkRuleGroupOptions["PermissionsCompatibleOptions"] = 537001988] = "PermissionsCompatibleOptions";
    /**
     * Header compatible modifiers.
     *
     * $header is compatible with the limited list of modifiers: $csp and $removeheader (on response headers).
     */
    NetworkRuleGroupOptions[NetworkRuleGroupOptions["HeaderCompatibleOptions"] = 1074405380] = "HeaderCompatibleOptions";
})(background_NetworkRuleGroupOptions || (background_NetworkRuleGroupOptions = {}));
/**
 * Basic network filtering rule.
 *
 * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#basic-rules}
 */
class background_NetworkRule {
    ruleIndex;
    filterListId;
    allowlist;
    pattern;
    /**
     * Domains in denyallow modifier providing exceptions for permitted domains.
     *
     * @see {@link https://github.com/AdguardTeam/CoreLibs/issues/1304}
     */
    denyAllowDomains = null;
    /**
     * Flag with all enabled rule options.
     */
    enabledOptions = background_NetworkRuleOption.NotSet;
    /**
     * Flag with all disabled rule options.
     */
    disabledOptions = background_NetworkRuleOption.NotSet;
    /**
     * Flag with all permitted request types.
     */
    permittedRequestTypes = background_RequestType.NotSet;
    /**
     * Flag with all restricted request types.
     */
    restrictedRequestTypes = background_RequestType.NotSet;
    /**
     * Rule Advanced modifier.
     */
    advancedModifier = null;
    /**
     * Rule Domain modifier.
     */
    domainModifier = null;
    /**
     * Rule App modifier.
     */
    appModifier = null;
    /**
     * Rule Method modifier.
     */
    methodModifier = null;
    /**
     * Rule header modifier.
     */
    headerModifier = null;
    /**
     * Rule To modifier.
     */
    toModifier = null;
    /**
     * Rule Stealth modifier.
     */
    stealthModifier = null;
    /**
     * Options used by the rule, regardless of whether they are enabled or disabled.
     */
    usedOptionNames = new Set();
    /**
     * Rule priority, which is needed when the engine has to choose between
     * several rules matching the query. This value is calculated based on
     * the rule modifiers enabled or disabled and rounded up
     * to the smallest integer greater than or equal to the calculated weight
     * in the {@link calculatePriorityWeight}.
     *
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-1
     */
    priorityWeight = 1;
    /**
     * Rules with base modifiers, from category 1, each of them adds 1
     * to the weight of the rule.
     *
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-1
     */
    static CATEGORY_1_OPTIONS_MASK = background_NetworkRuleOption.ThirdParty
        | background_NetworkRuleOption.MatchCase
        | background_NetworkRuleOption.DnsRewrite;
    /**
     * The priority weight used in {@link calculatePriorityWeight} for rules
     * with permitted request types and methods.
     * The value 50 is chosen in order to cover (with a margin) all possible
     * combinations and variations of rules from categories with a lower
     * priority (each of them adds 1 to the rule priority).
     *
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-2
     */
    static CategoryTwoWeight = 50;
    /**
     * The priority weight used in {@link calculatePriorityWeight} for rules
     * with allowed domains.
     * The value 100 is chosen to cover all possible combinations and variations
     * of rules from categories with a lower priority, for example a rule with
     * one allowed query type will get priority 100 (50 + 50/1), but for allowed
     * domains with any number of domains we will get at least 101 (for 100
     * domains: 100 + 100/100; for 200 100 + 100/200; or even for 10000:
     * 100 + 100/10000) because the resulting weight is rounded up.
     *
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-3
     */
    static CategoryThreeWeight = 100;
    /**
     * The priority weight used in {@link calculatePriorityWeight}
     * for $redirect rules.
     *
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-6
     */
    static CategoryFourWeight = 10 ** 3;
    /**
     * The priority weight used in {@link calculatePriorityWeight} for rules
     * with specific exceptions.
     *
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-4
     */
    static CategoryFiveWeight = 10 ** 4;
    /**
     * Rules with specific exclusions, from category 4, each of them adds
     * {@link SpecificExceptionsWeight} to the weight of the rule.
     *
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-4
     */
    static SPECIFIC_EXCLUSIONS_MASK = background_NetworkRuleOption.Elemhide
        | background_NetworkRuleOption.Generichide
        | background_NetworkRuleOption.Specifichide
        | background_NetworkRuleOption.Content
        | background_NetworkRuleOption.Urlblock
        | background_NetworkRuleOption.Genericblock
        | background_NetworkRuleOption.Jsinject
        | background_NetworkRuleOption.Extension;
    /**
     * The priority weight used in {@link calculatePriorityWeight} for rules
     * with allowlist mark '@@'.
     *
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-5
     */
    static CategorySixWeight = 10 ** 5;
    /**
     * The priority weight used in {@link calculatePriorityWeight}
     * for $important rules.
     *
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-7
     */
    static CategorySevenWeight = 10 ** 6;
    /**
     * Separates the rule pattern from the list of modifiers.
     *
     * ```
     * rule = ["@@"] pattern [ "$" modifiers ]
     * modifiers = [modifier0, modifier1[, ...[, modifierN]]]
     * ```
     */
    static OPTIONS_DELIMITER = background_OPTIONS_DELIMITER;
    /**
     * A marker that is used in rules of exception.
     * To turn off filtering for a request, start your rule with this marker.
     */
    static MASK_ALLOWLIST = background_MASK_ALLOWLIST;
    /**
     * Mark that negates options.
     */
    static NOT_MARK = background_NOT_MARK;
    /**
     * Rule options.
     */
    static OPTIONS = background_NETWORK_RULE_OPTIONS;
    /**
     * Rule options that can be negated.
     */
    static NEGATABLE_OPTIONS = new Set([
        // General options
        background_NetworkRule.OPTIONS.FIRST_PARTY,
        background_NetworkRule.OPTIONS.THIRD_PARTY,
        background_NetworkRule.OPTIONS.MATCH_CASE,
        background_NetworkRule.OPTIONS.DOCUMENT,
        background_NetworkRule.OPTIONS.DOC,
        // Content type options
        background_NetworkRule.OPTIONS.SCRIPT,
        background_NetworkRule.OPTIONS.STYLESHEET,
        background_NetworkRule.OPTIONS.SUBDOCUMENT,
        background_NetworkRule.OPTIONS.OBJECT,
        background_NetworkRule.OPTIONS.IMAGE,
        background_NetworkRule.OPTIONS.XMLHTTPREQUEST,
        background_NetworkRule.OPTIONS.MEDIA,
        background_NetworkRule.OPTIONS.FONT,
        background_NetworkRule.OPTIONS.WEBSOCKET,
        background_NetworkRule.OPTIONS.OTHER,
        background_NetworkRule.OPTIONS.PING,
        // Dns modifiers
        background_NetworkRule.OPTIONS.EXTENSION,
    ]);
    /**
     * Advanced option modifier names.
     */
    static ADVANCED_OPTIONS = new Set([
        background_NetworkRule.OPTIONS.CSP,
        background_NetworkRule.OPTIONS.REPLACE,
        background_NetworkRule.OPTIONS.COOKIE,
        background_NetworkRule.OPTIONS.REDIRECT,
        background_NetworkRule.OPTIONS.REDIRECTRULE,
        background_NetworkRule.OPTIONS.REMOVEPARAM,
        background_NetworkRule.OPTIONS.REMOVEHEADER,
        background_NetworkRule.OPTIONS.PERMISSIONS,
        background_NetworkRule.OPTIONS.CLIENT,
        background_NetworkRule.OPTIONS.DNSREWRITE,
        background_NetworkRule.OPTIONS.DNSTYPE,
        background_NetworkRule.OPTIONS.CTAG,
    ]);
    // TODO: Remove .getText() completely
    ruleText;
    // TODO: Remove .getText() completely
    /**
     * Returns the rule text.
     *
     * @returns The rule text.
     */
    getText() {
        return this.ruleText;
    }
    /**
     * Returns the rule index.
     *
     * @returns Rule index.
     */
    getIndex() {
        return this.ruleIndex;
    }
    /**
     * Returns the identifier of the filter from which the rule was received.
     *
     * @returns Identifier of the filter from which the rule was received.
     */
    getFilterListId() {
        return this.filterListId;
    }
    /**
     * Returns all options that are used in the rule, regardless of whether they are
     * enabled or disabled.
     *
     * @returns Set of option names.
     */
    getUsedOptionNames() {
        return this.usedOptionNames;
    }
    /**
     * Each rule has its own priority, which is necessary when several rules
     * match the request and the filtering system needs to select one of them.
     * Priority is measured as a positive integer.
     * In the case of a conflict between two rules with the same priority value,
     * it is not specified which one of them will be chosen.
     *
     * @returns Rule priority.
     */
    getPriorityWeight() {
        return this.priorityWeight;
    }
    /**
     * Returns rule pattern,
     * which currently is used only in the rule validator module.
     *
     * @returns Rule pattern.
     */
    getPattern() {
        return this.pattern.pattern;
    }
    /**
     * Returns `true` if the rule is "allowlist", e.g. if it disables other
     * rules when the pattern matches the request.
     *
     * @returns True if the rule is an allowlist rule.
     */
    isAllowlist() {
        return this.allowlist;
    }
    /**
     * Checks if the rule is a document-level allowlist rule with $urlblock or
     * $genericblock or $content.
     * This means that the rule is supposed to disable or modify blocking
     * of the page sub-requests.
     * For instance, `@@||example.org^$urlblock` unblocks all sub-requests.
     *
     * @returns True if the rule is a document-level allowlist rule with specific modifiers.
     */
    isDocumentLevelAllowlistRule() {
        if (!this.isAllowlist()) {
            return false;
        }
        return this.isOptionEnabled(background_NetworkRuleOption.Urlblock)
            || this.isOptionEnabled(background_NetworkRuleOption.Genericblock)
            || this.isOptionEnabled(background_NetworkRuleOption.Content);
    }
    /**
     * Checks if the rule completely disables filtering.
     *
     * @returns True if the rule completely disables filtering.
     */
    isFilteringDisabled() {
        if (!this.isAllowlist()) {
            return false;
        }
        return this.isOptionEnabled(background_NetworkRuleOption.Elemhide)
            && this.isOptionEnabled(background_NetworkRuleOption.Content)
            && this.isOptionEnabled(background_NetworkRuleOption.Urlblock)
            && this.isOptionEnabled(background_NetworkRuleOption.Jsinject);
    }
    /**
     * The longest part of pattern without any special characters.
     * It is used to improve the matching performance.
     *
     * @returns The longest part of the pattern without any special characters.
     */
    getShortcut() {
        return this.pattern.shortcut;
    }
    /**
     * Gets list of permitted domains.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#domain-modifier}
     *
     * @returns List of permitted domains or null if none.
     */
    getPermittedDomains() {
        if (this.domainModifier) {
            return this.domainModifier.getPermittedDomains();
        }
        return null;
    }
    /**
     * Gets list of restricted domains.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#domain-modifier}
     *
     * @returns List of restricted domains or null if none.
     */
    getRestrictedDomains() {
        if (this.domainModifier) {
            return this.domainModifier.getRestrictedDomains();
        }
        return null;
    }
    /**
     * Gets list of denyAllow domains.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#denyallow-modifier}
     *
     * @returns List of denyAllow domains or null if none.
     */
    getDenyAllowDomains() {
        return this.denyAllowDomains;
    }
    /**
     * Get list of permitted $to domains.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#to-modifier}
     *
     * @returns List of permitted $to domains or null if none.
     */
    getPermittedToDomains() {
        if (this.toModifier) {
            return this.toModifier.permittedValues;
        }
        return null;
    }
    /**
     * Get list of restricted $to domains.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#to-modifier}
     *
     * @returns List of restricted $to domains or null if none.
     */
    getRestrictedToDomains() {
        if (this.toModifier) {
            return this.toModifier.restrictedValues;
        }
        return null;
    }
    /**
     * Gets list of permitted domains.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#app}
     *
     * @returns List of permitted domains or null if none.
     */
    getPermittedApps() {
        if (this.appModifier) {
            return this.appModifier.permittedApps;
        }
        return null;
    }
    /**
     * Gets list of restricted domains.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#app}
     *
     * @returns List of restricted domains or null if none.
     */
    getRestrictedApps() {
        if (this.appModifier) {
            return this.appModifier.restrictedApps;
        }
        return null;
    }
    /**
     * Gets list of permitted methods.
     *
     * @see {@link https://kb.adguard.com/general/how-to-create-your-own-ad-filters#method-modifier}
     *
     * @returns List of permitted methods or null if none.
     */
    getRestrictedMethods() {
        if (this.methodModifier) {
            return this.methodModifier.restrictedValues;
        }
        return null;
    }
    /**
     * Gets list of restricted methods.
     *
     * @see {@link https://kb.adguard.com/general/how-to-create-your-own-ad-filters#method-modifier}
     *
     * @returns List of restricted methods or null if none.
     */
    getPermittedMethods() {
        if (this.methodModifier) {
            return this.methodModifier.permittedValues;
        }
        return null;
    }
    /**
     * Flag with all permitted request types.
     * The value {@link RequestType.NotSet} here means "all request types are allowed".
     *
     * @returns The flag with all permitted request types.
     */
    getPermittedRequestTypes() {
        return this.permittedRequestTypes;
    }
    /**
     * Flag with all restricted request types.
     * The value {@link RequestType.NotSet} here means "no type of request is restricted".
     *
     * @returns The flag with all restricted request types.
     */
    getRestrictedRequestTypes() {
        return this.restrictedRequestTypes;
    }
    /**
     * Advanced modifier.
     *
     * @returns The advanced modifier or null if none.
     */
    getAdvancedModifier() {
        return this.advancedModifier;
    }
    /**
     * Stealth modifier.
     *
     * @returns The stealth modifier or null if none.
     */
    getStealthModifier() {
        return this.stealthModifier;
    }
    /**
     * Advanced modifier value.
     *
     * @returns The advanced modifier value or null if none.
     */
    getAdvancedModifierValue() {
        return this.advancedModifier && this.advancedModifier.getValue();
    }
    /**
     * Retrieves the header modifier value.
     *
     * @returns The header modifier value or null if none.
     */
    getHeaderModifierValue() {
        if (!this.headerModifier) {
            return null;
        }
        return this.headerModifier.getHeaderModifierValue();
    }
    /**
     * Returns true if rule's pattern is a regular expression.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#regexp-support}
     *
     * @returns True if the rule pattern is a regular expression.
     */
    isRegexRule() {
        return (this.getPattern().startsWith(background_SimpleRegex.MASK_REGEX_RULE)
            && this.getPattern().endsWith(background_SimpleRegex.MASK_REGEX_RULE));
    }
    /**
     * Checks if this filtering rule matches the specified request.
     *
     * @param request Request to check.
     * @param useShortcut The flag to use this rule shortcut.
     *
     * @returns True if the rule matches the request.
     *
     * In case we use Trie in lookup table, we don't need to use shortcut cause we already check if request's url
     * includes full rule shortcut.
     */
    match(request, useShortcut = true) {
        // Regex rules should not be tested by shortcut
        if (useShortcut && !this.matchShortcut(request)) {
            return false;
        }
        if (this.isOptionEnabled(background_NetworkRuleOption.Method) && !this.matchMethod(request.method)) {
            return false;
        }
        if (this.isOptionEnabled(background_NetworkRuleOption.ThirdParty) && !request.thirdParty) {
            return false;
        }
        if (this.isOptionDisabled(background_NetworkRuleOption.ThirdParty) && request.thirdParty) {
            return false;
        }
        if (!this.matchRequestType(request.requestType)) {
            return false;
        }
        if (!this.matchDomainModifier(request)) {
            return false;
        }
        if (this.isOptionEnabled(background_NetworkRuleOption.RemoveParam)
            || this.isOptionEnabled(background_NetworkRuleOption.Permissions)) {
            if (!this.matchRequestTypeExplicit(request.requestType)) {
                return false;
            }
        }
        if (!this.matchDenyAllowDomains(request.hostname)) {
            return false;
        }
        if (this.isOptionEnabled(background_NetworkRuleOption.To) && !this.matchToModifier(request.hostname)) {
            return false;
        }
        if (!this.matchDnsType(request.dnsType)) {
            return false;
        }
        if (!this.matchClientTags(request.clientTags)) {
            return false;
        }
        if (!this.matchClient(request.clientName, request.clientIP)) {
            return false;
        }
        return this.pattern.matchPattern(request, true);
    }
    /**
     * Simply checks if shortcut is a substring of the URL.
     *
     * @param request Request to check.
     *
     * @returns True if the shortcut is a substring of the URL.
     */
    matchShortcut(request) {
        return request.urlLowercase.indexOf(this.getShortcut()) >= 0;
    }
    /**
     * Check if request matches domain modifier by request referrer (general case) or by request target.
     *
     * In some cases the $domain modifier can match not only the referrer domain, but also the target domain.
     * This happens when the following is true (1 AND ((2 AND 3) OR 4):
     *
     * 1) The request has $document request type (not subdocument)
     * 2) The rule's pattern doesn't match any particular domain(s)
     * 3) The rule's pattern doesn't contain regular expressions
     * 4) The $domain modifier contains only excluded domains (e.g., $domain=~example.org|~example.com).
     *
     * When all these conditions are met, the domain modifier will match both the referrer domain and the target domain.
     *
     * @see {@link https://github.com/AdguardTeam/tsurlfilter/issues/45}
     *
     * @param request The request to check.
     *
     * @returns True if the rule matches the domain modifier.
     */
    matchDomainModifier(request) {
        if (!this.domainModifier) {
            return true;
        }
        const { domainModifier } = this;
        const isDocumentType = request.requestType === background_RequestType.Document;
        const hasOnlyExcludedDomains = !domainModifier.hasPermittedDomains()
            && domainModifier.hasRestrictedDomains();
        const patternIsRegex = this.isRegexRule();
        const patternIsDomainSpecific = this.pattern.isPatternDomainSpecific();
        const matchesTargetByPatternCondition = !patternIsRegex && !patternIsDomainSpecific;
        if (isDocumentType && (hasOnlyExcludedDomains || matchesTargetByPatternCondition)) {
            // check if matches source hostname if exists or if matches target hostname
            return (request.sourceHostname && domainModifier.matchDomain(request.sourceHostname))
                || domainModifier.matchDomain(request.hostname);
        }
        return domainModifier.matchDomain(request.sourceHostname || '');
    }
    /**
     * Checks if the filtering rule is allowed on this domain.
     *
     * @param domain The request's domain.
     *
     * @returns True if the rule must be applied to the request.
     */
    matchDenyAllowDomains(domain) {
        if (!this.denyAllowDomains) {
            return true;
        }
        if (this.denyAllowDomains.length > 0) {
            if (background_DomainModifier.isDomainOrSubdomainOfAny(domain, this.denyAllowDomains)) {
                return false;
            }
        }
        return true;
    }
    /**
     * Checks if the request domain matches the specified conditions.
     *
     * @param domain The request's domain.
     *
     * @returns True if the request domain matches the permitted domains and does not match the restricted domains.
     */
    matchToModifier(domain) {
        if (!this.toModifier) {
            return true;
        }
        /**
         * The request's domain must be either explicitly permitted or not be included
         * in the list of restricted domains for the rule to apply.
         */
        const permittedDomains = this.getPermittedToDomains();
        const restrictedDomains = this.getRestrictedToDomains();
        let matches = false;
        if (permittedDomains) {
            matches = background_DomainModifier.isDomainOrSubdomainOfAny(domain, permittedDomains);
        }
        if (restrictedDomains) {
            matches = !background_DomainModifier.isDomainOrSubdomainOfAny(domain, restrictedDomains);
        }
        return matches;
    }
    /**
     * Return `true` if this rule matches with the tags associated with a client.
     *
     * @param clientTags Client tags.
     *
     * @returns True if the rule matches the client tags.
     */
    matchClientTags(clientTags) {
        const advancedModifier = this.getAdvancedModifier();
        if (!advancedModifier || !(advancedModifier instanceof background_CtagModifier)) {
            return true;
        }
        if (!clientTags) {
            return false;
        }
        const cTagsModifier = advancedModifier;
        return clientTags.every((x) => cTagsModifier.match(x));
    }
    /**
     * Returns TRUE if the rule matches with the specified client.
     *
     * @param clientName The name of the client.
     * @param clientIP The IP address of the client.
     *
     * @returns True if the rule matches the client.
     */
    matchClient(clientName, clientIP) {
        const advancedModifier = this.getAdvancedModifier();
        if (!advancedModifier || !(advancedModifier instanceof background_ClientModifier)) {
            return true;
        }
        if (!clientName && !clientIP) {
            return false;
        }
        const modifier = advancedModifier;
        return modifier.matchAny(clientName, clientIP);
    }
    /**
     * Return `true` if this rule matches with the request DNS type.
     *
     * @param dnstype The DNS type to check.
     *
     * @returns True if the rule matches the DNS type.
     */
    matchDnsType(dnstype) {
        const advancedModifier = this.getAdvancedModifier();
        if (!advancedModifier || !(advancedModifier instanceof background_DnsTypeModifier)) {
            return true;
        }
        if (!dnstype) {
            return false;
        }
        const modifier = advancedModifier;
        return modifier.match(dnstype);
    }
    /**
     * Checks if the request's type matches the rule properties.
     *
     * @param requestType Request type to check.
     *
     * @returns True if the rule must be applied to the request.
     */
    matchRequestType(requestType) {
        if (this.permittedRequestTypes !== background_RequestType.NotSet) {
            if ((this.permittedRequestTypes & requestType) !== requestType) {
                return false;
            }
        }
        if (this.restrictedRequestTypes !== background_RequestType.NotSet) {
            if ((this.restrictedRequestTypes & requestType) === requestType) {
                return false;
            }
        }
        return true;
    }
    /**
     * In case of $removeparam, $permissions modifier,
     * we only allow it to target other content types if the rule has an explicit content-type modifier.
     *
     * @param requestType Request type to check.
     *
     * @returns True if the rule must be applied to the request.
     */
    matchRequestTypeExplicit(requestType) {
        if (this.permittedRequestTypes === background_RequestType.NotSet
            && this.restrictedRequestTypes === background_RequestType.NotSet
            && requestType !== background_RequestType.Document
            && requestType !== background_RequestType.SubDocument) {
            return false;
        }
        return this.matchRequestType(requestType);
    }
    /**
     * Checks if request's method matches with the rule.
     *
     * @param method Request's method.
     *
     * @returns True, if rule must be applied to the request.
     */
    matchMethod(method) {
        if (!method || !background_MethodModifier.isHTTPMethod(method)) {
            return false;
        }
        /**
         * Request's method must be either explicitly
         * permitted or not be included in list of restricted methods
         * for the rule to apply.
         */
        const permittedMethods = this.getPermittedMethods();
        if (permittedMethods?.includes(method)) {
            return true;
        }
        const restrictedMethods = this.getRestrictedMethods();
        return !!restrictedMethods && !restrictedMethods.includes(method);
    }
    /**
     * Checks if request's response headers matches with
     * the rule's $header modifier value.
     *
     * @param responseHeadersItems Request's response headers.
     *
     * @returns True, if rule must be applied to the request.
     */
    matchResponseHeaders(responseHeadersItems) {
        if (!responseHeadersItems || responseHeadersItems.length === 0) {
            return false;
        }
        const ruleData = this.getHeaderModifierValue();
        if (!ruleData) {
            return false;
        }
        const { header: ruleHeaderName, value: ruleHeaderValue, } = ruleData;
        return responseHeadersItems.some((responseHeadersItem) => {
            const { name: responseHeaderName, value: responseHeaderValue, } = responseHeadersItem;
            // Header name matching is case-insensitive
            if (ruleHeaderName.toLowerCase() !== responseHeaderName.toLowerCase()) {
                return false;
            }
            if (ruleHeaderValue === null) {
                return true;
            }
            // Unlike header name, header value matching is case-sensitive
            if (typeof ruleHeaderValue === 'string') {
                return ruleHeaderValue === responseHeaderValue;
            }
            if (responseHeaderValue && ruleHeaderValue instanceof RegExp) {
                return ruleHeaderValue.test(responseHeaderValue);
            }
            return false;
        });
    }
    /**
     * Checks if a network rule is too general.
     *
     * @param node AST node of the network rule.
     *
     * @returns True if the rule is too general.
     */
    static isTooGeneral(node) {
        return !(node.modifiers?.children?.length) && node.pattern.value.length < 4;
    }
    /**
     * Creates an instance of the {@link NetworkRule}.
     * It parses this rule and extracts the rule pattern (see {@link SimpleRegex}),
     * and rule modifiers.
     *
     * @param node AST node of the network rule.
     * @param filterListId ID of the filter list this rule belongs to.
     * @param ruleIndex Line start index in the source filter list; it will be used to find the original rule text
     * in the filtering log when a rule is applied. Default value is {@link RULE_INDEX_NONE} which means that
     * the rule does not have source index.
     *
     * @throws Error if it fails to parse the rule.
     */
    constructor(node, filterListId, ruleIndex = background_RULE_INDEX_NONE) {
        this.ruleIndex = ruleIndex;
        // TODO: Remove this completely
        this.ruleText = background_rule_generator/* RuleGenerator */.u.generate(node);
        this.filterListId = filterListId;
        this.allowlist = node.exception;
        const pattern = node.pattern.value;
        if (pattern && background_hasSpaces(pattern)) {
            throw new SyntaxError('Rule has spaces, seems to be an host rule');
        }
        if (node.modifiers?.children?.length) {
            this.loadOptions(node.modifiers);
        }
        if (background_NetworkRule.isTooGeneral(node)) {
            throw new SyntaxError(`Rule is too general: ${background_rule_generator/* RuleGenerator */.u.generate(node)}`);
        }
        this.calculatePriorityWeight();
        this.pattern = new background_Pattern(pattern, this.isOptionEnabled(background_NetworkRuleOption.MatchCase));
    }
    /**
     * Parses the options string and saves them.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#basic-rules-modifiers}
     *
     * @param options Modifier list node.
     *
     * @throws An error if there is an unsupported modifier.
     */
    loadOptions(options) {
        for (const option of options.children) {
            let value = background_EMPTY_STRING;
            if (option.value && option.value.value) {
                value = option.value.value;
            }
            this.loadOption(option.name.value, value, option.exception);
            this.usedOptionNames.add(option.name.value);
        }
        this.validateOptions();
    }
    /**
     * Returns true if rule contains (enabled or disabled) specified option.
     * Please note, that options have three state: enabled, disabled, undefined.
     *
     * @param option Rule option to check.
     *
     * @returns True if rule contains (enabled or disabled) specified option.
     */
    hasOption(option) {
        return this.isOptionEnabled(option) || this.isOptionDisabled(option);
    }
    /**
     * Returns true if rule has at least one cosmetic option enabled.
     *
     * @returns True if the rule has at least one cosmetic option enabled.
     */
    hasCosmeticOption() {
        return (this.enabledOptions & background_NetworkRuleGroupOptions.CosmeticOption) !== 0;
    }
    /**
     * Returns true if the specified option is enabled.
     * Please note, that options have three state: enabled, disabled, undefined.
     *
     * @param option Rule option to check.
     *
     * @returns True if the specified option is enabled.
     */
    isOptionEnabled(option) {
        return (this.enabledOptions & option) === option;
    }
    /**
     * Returns true if one and only option is enabled.
     *
     * @param option Rule option to check.
     *
     * @returns True if the specified option is enabled.
     */
    isSingleOptionEnabled(option) {
        return this.enabledOptions === option;
    }
    /**
     * Returns true if the specified option is disabled.
     * Please note, that options have three state: enabled, disabled, undefined.
     *
     * @param option Rule option to check.
     *
     * @returns True if the specified option is disabled.
     */
    isOptionDisabled(option) {
        return (this.disabledOptions & option) === option;
    }
    /**
     * Checks if the rule has higher priority that the specified rule:
     * `allowlist + $important` > `$important` > `redirect` > `allowlist` > `basic rules`.
     *
     * @param r Rule to compare with.
     *
     * @returns True if the rule has higher priority than `r`.
     */
    isHigherPriority(r) {
        return this.priorityWeight > r.priorityWeight;
    }
    /**
     * Returns true if the rule is considered "generic"
     * "generic" means that the rule is not restricted to a limited set of domains
     * Please note that it might be forbidden on some domains, though.
     *
     * @returns True if the rule is considered "generic".
     */
    isGeneric() {
        return !this.domainModifier?.hasPermittedDomains();
    }
    /**
     * Returns true if this rule negates the specified rule.
     * Only makes sense when this rule has a `badfilter` modifier.
     *
     * @param specifiedRule Rule to check.
     *
     * @returns True if this rule negates the specified rule.
     */
    negatesBadfilter(specifiedRule) {
        if (!this.isOptionEnabled(background_NetworkRuleOption.Badfilter)) {
            return false;
        }
        if (this.allowlist !== specifiedRule.allowlist) {
            return false;
        }
        if (this.pattern.pattern !== specifiedRule.pattern.pattern) {
            return false;
        }
        if (this.permittedRequestTypes !== specifiedRule.permittedRequestTypes) {
            return false;
        }
        if (this.restrictedRequestTypes !== specifiedRule.restrictedRequestTypes) {
            return false;
        }
        if ((this.enabledOptions ^ background_NetworkRuleOption.Badfilter) !== specifiedRule.enabledOptions) {
            return false;
        }
        if (this.disabledOptions !== specifiedRule.disabledOptions) {
            return false;
        }
        if (!background_stringArraysEquals(this.getRestrictedDomains(), specifiedRule.getRestrictedDomains())) {
            return false;
        }
        if (!background_stringArraysHaveIntersection(this.getPermittedDomains(), specifiedRule.getPermittedDomains())) {
            return false;
        }
        return true;
    }
    /**
     * Checks if this rule can be used for hosts-level blocking.
     *
     * @returns True if the rule can be used for hosts-level blocking.
     */
    isHostLevelNetworkRule() {
        if (this.domainModifier?.hasPermittedDomains() || this.domainModifier?.hasRestrictedDomains()) {
            return false;
        }
        if (this.permittedRequestTypes !== 0 && this.restrictedRequestTypes !== 0) {
            return false;
        }
        if (this.disabledOptions !== background_NetworkRuleOption.NotSet) {
            return false;
        }
        if (this.enabledOptions !== background_NetworkRuleOption.NotSet) {
            return ((this.enabledOptions
                & background_NetworkRuleGroupOptions.OptionHostLevelRules)
                | (this.enabledOptions
                    ^ background_NetworkRuleGroupOptions.OptionHostLevelRules)) === background_NetworkRuleGroupOptions.OptionHostLevelRules;
        }
        return true;
    }
    /**
     * Enables or disables the specified option.
     *
     * @param option Option to enable or disable.
     * @param enabled True to enable, false to disable.
     * @param skipRestrictions Skip options allowlist/blacklist restrictions.
     *
     * @throws An error if the option we're trying to enable cannot be.
     * For instance, you cannot enable $elemhide for blacklist rules.
     */
    setOptionEnabled(option, enabled, skipRestrictions = false) {
        if (!skipRestrictions) {
            if (!this.allowlist && (option & background_NetworkRuleGroupOptions.AllowlistOnly) === option) {
                throw new SyntaxError(`Modifier ${background_NetworkRuleOption[option]} cannot be used in blacklist rule`);
            }
        }
        if (enabled) {
            this.enabledOptions |= option;
        }
        else {
            this.disabledOptions |= option;
        }
    }
    /**
     * Permits or forbids the specified request type.
     * "Permits" means that the rule will match **only** the types that are permitted.
     * "Restricts" means that the rule will match **all but restricted**.
     *
     * @param requestType Request type.
     * @param permitted True if it's permitted (whic).
     */
    setRequestType(requestType, permitted) {
        if (permitted) {
            this.permittedRequestTypes |= requestType;
        }
        else {
            this.restrictedRequestTypes |= requestType;
        }
    }
    /**
     * Sets and validates exceptionally allowed domains presented in $denyallow modifier.
     *
     * @param optionValue Denyallow modifier value.
     */
    setDenyAllowDomains(optionValue) {
        const domainModifier = new background_DomainModifier(optionValue, background_PIPE_SEPARATOR$1);
        if (domainModifier.restrictedDomains && domainModifier.restrictedDomains.length > 0) {
            throw new SyntaxError('Invalid modifier: $denyallow domains cannot be negated');
        }
        if (domainModifier.permittedDomains) {
            if (domainModifier.permittedDomains.some(background_DomainModifier.isWildcardOrRegexDomain)) {
                throw new SyntaxError('Invalid modifier: $denyallow does not support wildcards and regex domains');
            }
        }
        this.denyAllowDomains = domainModifier.permittedDomains;
    }
    /**
     * Loads the specified modifier.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#basic-rules-modifiers}
     *
     * @param optionName Modifier name.
     * @param optionValue Modifier value.
     * @param exception True if the modifier is negated.
     *
     * @throws An error if there is an unsupported modifier.
     */
    loadOption(optionName, optionValue, exception = false) {
        const { OPTIONS, NEGATABLE_OPTIONS } = background_NetworkRule;
        if (optionName.startsWith(OPTIONS.NOOP)) {
            /**
             * A noop modifier does nothing and can be used to increase some rules readability.
             * It consists of the sequence of underscore characters (_) of any length
             * and can appear in a rule as many times as it's needed.
             */
            if (!optionName.split(OPTIONS.NOOP).some((s) => !!s)) {
                return;
            }
        }
        // TODO: Speed up this by creating a map from names to bit mask positions
        if (exception && !NEGATABLE_OPTIONS.has(optionName)) {
            throw new SyntaxError(`Invalid modifier: '${optionName}' cannot be negated`);
        }
        switch (optionName) {
            // General options
            // $first-party, $~first-party
            case OPTIONS.FIRST_PARTY:
                this.setOptionEnabled(background_NetworkRuleOption.ThirdParty, exception);
                break;
            // $third-party, $~third-party
            case OPTIONS.THIRD_PARTY:
                this.setOptionEnabled(background_NetworkRuleOption.ThirdParty, !exception);
                break;
            // $match-case, $~match-case
            case OPTIONS.MATCH_CASE:
                this.setOptionEnabled(background_NetworkRuleOption.MatchCase, !exception);
                break;
            // $important
            case OPTIONS.IMPORTANT:
                this.setOptionEnabled(background_NetworkRuleOption.Important, true);
                break;
            // $domain
            case OPTIONS.DOMAIN:
                this.domainModifier = new background_DomainModifier(optionValue, background_PIPE_SEPARATOR$1);
                break;
            // $denyallow
            case OPTIONS.DENYALLOW:
                this.setDenyAllowDomains(optionValue);
                break;
            // $method modifier
            case OPTIONS.METHOD: {
                this.setOptionEnabled(background_NetworkRuleOption.Method, true);
                this.methodModifier = new background_MethodModifier(optionValue);
                break;
            }
            // $header modifier
            case OPTIONS.HEADER:
                this.setOptionEnabled(background_NetworkRuleOption.Header, true);
                this.headerModifier = new background_HeaderModifier(optionValue);
                break;
            // $to modifier
            case OPTIONS.TO: {
                this.setOptionEnabled(background_NetworkRuleOption.To, true);
                this.toModifier = new background_ToModifier(optionValue);
                break;
            }
            // Document-level allowlist rules
            // $elemhide
            case OPTIONS.ELEMHIDE:
                this.setOptionEnabled(background_NetworkRuleOption.Elemhide, true);
                this.setRequestType(background_RequestType.Document, true);
                this.setRequestType(background_RequestType.SubDocument, true);
                break;
            // $generichide
            case OPTIONS.GENERICHIDE:
                this.setOptionEnabled(background_NetworkRuleOption.Generichide, true);
                this.setRequestType(background_RequestType.Document, true);
                this.setRequestType(background_RequestType.SubDocument, true);
                break;
            // $specifichide
            case OPTIONS.SPECIFICHIDE:
                this.setOptionEnabled(background_NetworkRuleOption.Specifichide, true);
                this.setRequestType(background_RequestType.Document, true);
                this.setRequestType(background_RequestType.SubDocument, true);
                break;
            // $genericblock
            case OPTIONS.GENERICBLOCK:
                this.setOptionEnabled(background_NetworkRuleOption.Genericblock, true);
                this.setRequestType(background_RequestType.Document, true);
                this.setRequestType(background_RequestType.SubDocument, true);
                break;
            // $jsinject
            case OPTIONS.JSINJECT:
                this.setOptionEnabled(background_NetworkRuleOption.Jsinject, true);
                this.setRequestType(background_RequestType.Document, true);
                this.setRequestType(background_RequestType.SubDocument, true);
                break;
            // $urlblock
            case OPTIONS.URLBLOCK:
                this.setOptionEnabled(background_NetworkRuleOption.Urlblock, true);
                this.setRequestType(background_RequestType.Document, true);
                this.setRequestType(background_RequestType.SubDocument, true);
                break;
            // $content
            case OPTIONS.CONTENT:
                this.setOptionEnabled(background_NetworkRuleOption.Content, true);
                this.setRequestType(background_RequestType.Document, true);
                this.setRequestType(background_RequestType.SubDocument, true);
                break;
            // $document, $doc / $~document, $~doc
            case OPTIONS.DOCUMENT:
            case OPTIONS.DOC:
                if (exception) {
                    this.setRequestType(background_RequestType.Document, false);
                    break;
                }
                this.setRequestType(background_RequestType.Document, true);
                // In the case of allowlist rules $document implicitly includes
                // all these modifiers: `$content`, `$elemhide`, `$jsinject`,
                // `$urlblock`.
                if (this.isAllowlist()) {
                    this.setOptionEnabled(background_NetworkRuleOption.Elemhide, true, true);
                    this.setOptionEnabled(background_NetworkRuleOption.Jsinject, true, true);
                    this.setOptionEnabled(background_NetworkRuleOption.Urlblock, true, true);
                    this.setOptionEnabled(background_NetworkRuleOption.Content, true, true);
                }
                break;
            // $stealth
            case OPTIONS.STEALTH:
                this.setOptionEnabled(background_NetworkRuleOption.Stealth, true);
                this.stealthModifier = new background_StealthModifier(optionValue);
                break;
            // $popup
            case OPTIONS.POPUP:
                this.setOptionEnabled(background_NetworkRuleOption.Popup, true);
                break;
            // Content type options
            // $script, $~script
            case OPTIONS.SCRIPT:
                this.setRequestType(background_RequestType.Script, !exception);
                break;
            // $stylesheet, $~stylesheet
            case OPTIONS.STYLESHEET:
                this.setRequestType(background_RequestType.Stylesheet, !exception);
                break;
            // $subdocument, $~subdocument
            case OPTIONS.SUBDOCUMENT:
                this.setRequestType(background_RequestType.SubDocument, !exception);
                break;
            // $object, $~object
            case OPTIONS.OBJECT:
                this.setRequestType(background_RequestType.Object, !exception);
                break;
            // $image, $~image
            case OPTIONS.IMAGE:
                this.setRequestType(background_RequestType.Image, !exception);
                break;
            // $xmlhttprequest, $~xmlhttprequest
            case OPTIONS.XMLHTTPREQUEST:
                this.setRequestType(background_RequestType.XmlHttpRequest, !exception);
                break;
            // $media, $~media
            case OPTIONS.MEDIA:
                this.setRequestType(background_RequestType.Media, !exception);
                break;
            // $font, $~font
            case OPTIONS.FONT:
                this.setRequestType(background_RequestType.Font, !exception);
                break;
            // $websocket, $~websocket
            case OPTIONS.WEBSOCKET:
                this.setRequestType(background_RequestType.WebSocket, !exception);
                break;
            // $other, $~other
            case OPTIONS.OTHER:
                this.setRequestType(background_RequestType.Other, !exception);
                break;
            // $ping, $~ping
            case OPTIONS.PING:
                this.setRequestType(background_RequestType.Ping, !exception);
                break;
            // Special modifiers
            // $badfilter
            case OPTIONS.BADFILTER:
                this.setOptionEnabled(background_NetworkRuleOption.Badfilter, true);
                break;
            // $csp
            case OPTIONS.CSP:
                this.setOptionEnabled(background_NetworkRuleOption.Csp, true);
                this.advancedModifier = new background_CspModifier(optionValue, this.isAllowlist());
                break;
            // $replace
            case OPTIONS.REPLACE:
                this.setOptionEnabled(background_NetworkRuleOption.Replace, true);
                this.advancedModifier = new background_ReplaceModifier(optionValue);
                break;
            // $cookie
            case OPTIONS.COOKIE:
                this.setOptionEnabled(background_NetworkRuleOption.Cookie, true);
                this.advancedModifier = new background_CookieModifier(optionValue);
                break;
            // $redirect
            case OPTIONS.REDIRECT:
                this.setOptionEnabled(background_NetworkRuleOption.Redirect, true);
                this.advancedModifier = new background_RedirectModifier(optionValue, this.isAllowlist());
                break;
            // $redirect-rule
            case OPTIONS.REDIRECTRULE:
                this.setOptionEnabled(background_NetworkRuleOption.Redirect, true);
                this.advancedModifier = new background_RedirectModifier(optionValue, this.isAllowlist(), true);
                break;
            // $removeparam
            case OPTIONS.REMOVEPARAM:
                this.setOptionEnabled(background_NetworkRuleOption.RemoveParam, true);
                this.advancedModifier = new background_RemoveParamModifier(optionValue);
                break;
            // $removeheader
            case OPTIONS.REMOVEHEADER:
                this.setOptionEnabled(background_NetworkRuleOption.RemoveHeader, true);
                this.advancedModifier = new background_RemoveHeaderModifier(optionValue, this.isAllowlist());
                break;
            // $permissions
            case OPTIONS.PERMISSIONS:
                this.setOptionEnabled(background_NetworkRuleOption.Permissions, true);
                this.advancedModifier = new background_PermissionsModifier(optionValue, this.isAllowlist());
                break;
            // $jsonprune
            // simple validation of jsonprune rules for compiler
            // https://github.com/AdguardTeam/FiltersCompiler/issues/168
            case OPTIONS.JSONPRUNE:
                if (background_isCompatibleWith(background_CompatibilityTypes.Extension)) {
                    throw new SyntaxError('Extension does not support $jsonprune modifier yet');
                }
                this.setOptionEnabled(background_NetworkRuleOption.JsonPrune, true);
                // TODO: should be properly implemented later
                // https://github.com/AdguardTeam/tsurlfilter/issues/71
                break;
            // $hls
            // simple validation of hls rules for compiler
            // https://github.com/AdguardTeam/FiltersCompiler/issues/169
            case OPTIONS.HLS:
                if (background_isCompatibleWith(background_CompatibilityTypes.Extension)) {
                    throw new SyntaxError('Extension does not support $hls modifier yet');
                }
                this.setOptionEnabled(background_NetworkRuleOption.Hls, true);
                // TODO: should be properly implemented later
                // https://github.com/AdguardTeam/tsurlfilter/issues/72
                break;
            // $referrerpolicy
            // simple validation of referrerpolicy rules for compiler
            // https://github.com/AdguardTeam/FiltersCompiler/issues/191
            case OPTIONS.REFERRERPOLICY:
                if (background_isCompatibleWith(background_CompatibilityTypes.Extension)) {
                    throw new SyntaxError('Extension does not support $referrerpolicy modifier');
                }
                // do nothing as $referrerpolicy is supported by CoreLibs-based apps only.
                // it is needed for proper rule conversion performed by FiltersCompiler
                // so rules with $referrerpolicy modifier is not marked as invalid
                break;
            // Dns modifiers
            // $client
            case OPTIONS.CLIENT:
                if (background_isCompatibleWith(background_CompatibilityTypes.Extension)) {
                    throw new SyntaxError('Extension doesn\'t support $client modifier');
                }
                this.setOptionEnabled(background_NetworkRuleOption.Client, true);
                this.advancedModifier = new background_ClientModifier(optionValue);
                break;
            // $dnsrewrite
            case OPTIONS.DNSREWRITE:
                if (background_isCompatibleWith(background_CompatibilityTypes.Extension)) {
                    throw new SyntaxError('Extension doesn\'t support $dnsrewrite modifier');
                }
                this.setOptionEnabled(background_NetworkRuleOption.DnsRewrite, true);
                this.advancedModifier = new background_DnsRewriteModifier(optionValue);
                break;
            // $dnstype
            case OPTIONS.DNSTYPE:
                if (background_isCompatibleWith(background_CompatibilityTypes.Extension)) {
                    throw new SyntaxError('Extension doesn\'t support $dnstype modifier');
                }
                this.setOptionEnabled(background_NetworkRuleOption.DnsType, true);
                this.advancedModifier = new background_DnsTypeModifier(optionValue);
                break;
            // $ctag
            case OPTIONS.CTAG:
                if (background_isCompatibleWith(background_CompatibilityTypes.Extension)) {
                    throw new SyntaxError('Extension doesn\'t support $ctag modifier');
                }
                this.setOptionEnabled(background_NetworkRuleOption.Ctag, true);
                this.advancedModifier = new background_CtagModifier(optionValue);
                break;
            // $app
            case OPTIONS.APP:
                if (background_isCompatibleWith(background_CompatibilityTypes.Extension)) {
                    throw new SyntaxError('Extension doesn\'t support $app modifier');
                }
                this.appModifier = new background_AppModifier(optionValue);
                break;
            // $network
            case OPTIONS.NETWORK:
                if (background_isCompatibleWith(background_CompatibilityTypes.Extension)) {
                    throw new SyntaxError('Extension doesn\'t support $network modifier');
                }
                this.setOptionEnabled(background_NetworkRuleOption.Network, true);
                break;
            // $extension, $~extension
            case OPTIONS.EXTENSION:
                if (background_isCompatibleWith(background_CompatibilityTypes.Extension)) {
                    throw new SyntaxError('Extension doesn\'t support $extension modifier');
                }
                this.setOptionEnabled(background_NetworkRuleOption.Extension, !exception);
                break;
            // $all
            case OPTIONS.ALL:
                if (this.isAllowlist()) {
                    throw new SyntaxError('Rule with $all modifier can not be allowlist rule');
                }
                // Set all request types
                Object.values(background_RequestType).forEach((type) => {
                    this.setRequestType(type, true);
                });
                this.setOptionEnabled(background_NetworkRuleOption.Popup, true);
                break;
            // $empty and $mp4
            // Deprecated in favor of $redirect
            case OPTIONS.EMPTY:
            case OPTIONS.MP4:
                // Do nothing.
                break;
            default: {
                // clear empty values
                const modifierView = [optionName, optionValue]
                    .filter((i) => i)
                    .join('=');
                throw new SyntaxError(`Unknown modifier: ${modifierView}`);
            }
        }
    }
    /**
     * To calculate priority, we've categorized modifiers into different groups.
     * These groups are ranked based on their priority, from lowest to highest.
     * A modifier that significantly narrows the scope of a rule adds more
     * weight to its total priority. Conversely, if a rule applies to a broader
     * range of requests, its priority decreases.
     *
     * It's worth noting that there are cases where a single-parameter modifier
     * has a higher priority than multi-parameter ones. For instance, in
     * the case of `$domain=example.com|example.org`, a rule that includes two
     * domains has a slightly broader effective area than a rule with one
     * specified domain, therefore its priority is lower.
     *
     * The base priority weight of any rule is 1. If the calculated priority
     * is a floating-point number, it will be **rounded up** to the smallest
     * integer greater than or equal to the calculated weight.
     *
     * @see {@link NetworkRule.PermittedRequestTypeWeight}
     * @see {@link NetworkRule.PermittedDomainWeight}
     * @see {@link NetworkRule.SpecificExceptionsWeight}
     * @see {@link NetworkRule.AllowlistRuleWeight}
     * @see {@link NetworkRule.RedirectRuleWeight}
     * @see {@link NetworkRule.ImportantRuleWeight}
     * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-counting}
     */
    calculatePriorityWeight() {
        // Base modifiers, category 1.
        this.priorityWeight += background_countEnabledBits(this.enabledOptions, background_NetworkRule.CATEGORY_1_OPTIONS_MASK);
        this.priorityWeight += background_countEnabledBits(this.disabledOptions, background_NetworkRule.CATEGORY_1_OPTIONS_MASK);
        /**
         * When dealing with a negated domain, app, method, or content-type,
         * we add a point for the existence of the modifier itself, regardless
         * of the quantity of negated domains or content-types. This is because
         * the rule's scope is already infinitely broad. Put simply,
         * by prohibiting multiple domains, content-types, methods or apps,
         * the scope of the rule becomes only minimally smaller.
         */
        if (this.denyAllowDomains && this.denyAllowDomains.length > 0) {
            this.priorityWeight += 1;
        }
        const { domainModifier } = this;
        if (domainModifier?.hasRestrictedDomains()) {
            this.priorityWeight += 1;
        }
        if (this.methodModifier?.restrictedValues && this.methodModifier.restrictedValues.length > 0) {
            this.priorityWeight += 1;
        }
        if (this.restrictedRequestTypes !== background_RequestType.NotSet) {
            this.priorityWeight += 1;
        }
        // $to modifier is basically a replacement for a regular expression
        // See https://github.com/AdguardTeam/KnowledgeBase/pull/196#discussion_r1221401215
        if (this.toModifier) {
            this.priorityWeight += 1;
        }
        /**
         * Category 2: permitted request types, methods, headers, $popup.
         * Specified content-types add `50 + 50 / number_of_content_types`,
         * for example: `||example.com^$image,script` will add
         * `50 + 50 / 2 = 50 + 25 = 75` to the total weight of the rule.
         * The `$popup` also belongs to this category, because it implicitly
         * adds the modifier `$document`.
         * Similarly, specific exceptions add `$document,subdocument`.
         *
         * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#priority-category-2}
         */
        if (this.permittedRequestTypes !== background_RequestType.NotSet) {
            const numberOfPermittedRequestTypes = background_getBitCount(this.permittedRequestTypes);
            // More permitted request types mean less priority weight.
            const relativeWeight = background_NetworkRule.CategoryTwoWeight / numberOfPermittedRequestTypes;
            this.priorityWeight += background_NetworkRule.CategoryTwoWeight + relativeWeight;
        }
        if (this.methodModifier?.permittedValues && this.methodModifier.permittedValues.length > 0) {
            // More permitted request methods mean less priority weight.
            const relativeWeight = background_NetworkRule.CategoryTwoWeight / this.methodModifier.permittedValues.length;
            this.priorityWeight += background_NetworkRule.CategoryTwoWeight + relativeWeight;
        }
        if (this.headerModifier) {
            // $header modifier in the rule adds 50
            this.priorityWeight += background_NetworkRule.CategoryTwoWeight;
        }
        /**
         * Category 3: permitted domains.
         * Specified domains through `$domain` and specified applications
         * through `$app` add `100 + 100 / number_domains (or number_applications)`,
         * for example:
         * `||example.com^$domain=example.com|example.org|example.net`
         * will add `100 + 100 / 3 = 134.3 = 134` or
         * `||example.com^$app=org.example.app1|org.example.app2`
         * will add `100 + 100 / 2 = 151`.
         */
        if (domainModifier?.hasPermittedDomains()) {
            // More permitted domains mean less priority weight.
            const relativeWeight = background_NetworkRule.CategoryThreeWeight / domainModifier.getPermittedDomains().length;
            this.priorityWeight += background_NetworkRule.CategoryThreeWeight + relativeWeight;
        }
        // Category 4: redirect rules.
        if (this.isOptionEnabled(background_NetworkRuleOption.Redirect)) {
            this.priorityWeight += background_NetworkRule.CategoryFourWeight;
        }
        // Category 5: specific exceptions.
        this.priorityWeight += background_NetworkRule.CategoryFiveWeight * background_countEnabledBits(this.enabledOptions, background_NetworkRule.SPECIFIC_EXCLUSIONS_MASK);
        // Category 6: allowlist rules.
        if (this.isAllowlist()) {
            this.priorityWeight += background_NetworkRule.CategorySixWeight;
        }
        // Category 7: important rules.
        if (this.isOptionEnabled(background_NetworkRuleOption.Important)) {
            this.priorityWeight += background_NetworkRule.CategorySevenWeight;
        }
        // Round up to avoid overlap between different categories of rules.
        this.priorityWeight = Math.ceil(this.priorityWeight);
    }
    /**
     * Validates rule options.
     */
    validateOptions() {
        if (this.advancedModifier instanceof background_RemoveParamModifier) {
            this.validateRemoveParamRule();
        }
        else if (this.advancedModifier instanceof background_RemoveHeaderModifier) {
            this.validateRemoveHeaderRule();
        }
        else if (this.advancedModifier instanceof background_PermissionsModifier) {
            this.validatePermissionsRule();
        }
        else if (this.headerModifier instanceof background_HeaderModifier) {
            this.validateHeaderRule();
        }
        else if (this.toModifier !== null) {
            this.validateToRule();
        }
        else if (this.denyAllowDomains !== null) {
            this.validateDenyallowRule();
        }
    }
    /**
     * $header rules are not compatible with any other
     * modifiers except for $important, $csp, $removeheader, $badfilter.
     * The rules with any other modifiers are considered invalid and will be discarded.
     */
    validateHeaderRule() {
        if ((this.enabledOptions | background_NetworkRuleGroupOptions.HeaderCompatibleOptions)
            !== background_NetworkRuleGroupOptions.HeaderCompatibleOptions) {
            throw new SyntaxError('$header rules are not compatible with some other modifiers');
        }
        if (this.advancedModifier && this.isOptionEnabled(background_NetworkRuleOption.RemoveHeader)) {
            const removeHeaderValue = this.getAdvancedModifierValue();
            if (!removeHeaderValue || removeHeaderValue.includes('request:')) {
                const message = '$header rules are only compatible with response headers removal of $removeheader.';
                throw new SyntaxError(message);
            }
        }
    }
    /**
     * $permissions rules are not compatible with any other
     * modifiers except $domain, $important, and $subdocument.
     * The rules with any other modifiers are considered invalid and will be discarded.
     */
    validatePermissionsRule() {
        if ((this.enabledOptions | background_NetworkRuleGroupOptions.PermissionsCompatibleOptions)
            !== background_NetworkRuleGroupOptions.PermissionsCompatibleOptions) {
            throw new SyntaxError('$permissions rules are not compatible with some other modifiers');
        }
    }
    /**
     * $removeparam rules are not compatible with any other modifiers except $domain,
     * $third-party, $app, $important, $match-case and permitted content type modifiers ($script, $stylesheet, etc).
     * The rules with any other modifiers are considered invalid and will be discarded.
     */
    validateRemoveParamRule() {
        if ((this.enabledOptions | background_NetworkRuleGroupOptions.RemoveParamCompatibleOptions)
            !== background_NetworkRuleGroupOptions.RemoveParamCompatibleOptions) {
            throw new SyntaxError('$removeparam rules are not compatible with some other modifiers');
        }
    }
    /**
     * $removeheader rules are not compatible with any other modifiers except $domain,
     * $third-party, $app, $important, $match-case and permitted content type modifiers ($script, $stylesheet, etc).
     * The rules with any other modifiers are considered invalid and will be discarded.
     */
    validateRemoveHeaderRule() {
        if ((this.enabledOptions | background_NetworkRuleGroupOptions.RemoveHeaderCompatibleOptions)
            !== background_NetworkRuleGroupOptions.RemoveHeaderCompatibleOptions) {
            throw new SyntaxError('$removeheader rules are not compatible with some other modifiers');
        }
        if (this.headerModifier && this.isOptionEnabled(background_NetworkRuleOption.Header)) {
            const removeHeaderValue = this.getAdvancedModifierValue();
            if (!removeHeaderValue || removeHeaderValue.includes('request:')) {
                const message = 'Request headers removal of $removeheaders is not compatible with $header rules.';
                throw new SyntaxError(message);
            }
        }
    }
    /**
     * $to rules are not compatible $denyallow - these rules considered invalid
     * and will be discarded.
     */
    validateToRule() {
        if (this.denyAllowDomains) {
            throw new SyntaxError('modifier $to is not compatible with $denyallow modifier');
        }
    }
    /**
     * $denyallow rules are not compatible $to - these rules considered invalid
     * and will be discarded.
     */
    validateDenyallowRule() {
        if (this.toModifier) {
            throw new SyntaxError('modifier $to is not compatible with $denyallow modifier');
        }
    }
}

/**
 * @file Known CSS / Extended CSS elements.
 */
/**
 * Supported Extended CSS pseudo-classes.
 *
 * These pseudo-classes are not supported by browsers natively, so we need Extended CSS library to support them.
 *
 * Please keep this list sorted alphabetically.
 */
const background_SUPPORTED_EXT_CSS_PSEUDO_CLASSES = new Set([
    /**
     * Pseudo-classes :is(), and :not() may use native implementation.
     *
     * @see {@link https://github.com/AdguardTeam/ExtendedCss#extended-css-is}
     * @see {@link https://github.com/AdguardTeam/ExtendedCss#extended-css-not}
     */
    /**
     * :has() should also be conditionally considered as extended and should not be in this list,
     * for details check: https://github.com/AdguardTeam/ExtendedCss#extended-css-has,
     * but there is a bug with content blocker in safari:
     * for details check: https://bugs.webkit.org/show_bug.cgi?id=248868.
     *
     * TODO: remove 'has' later.
     */
    '-abp-contains', // alias for 'contains'
    '-abp-has', // alias for 'has'
    'contains',
    'has', // some browsers support 'has' natively
    'has-text', // alias for 'contains'
    'if',
    'if-not',
    'matches-attr',
    'matches-css',
    'matches-css-after', // deprecated, replaced by 'matches-css'
    'matches-css-before', // deprecated, replaced by 'matches-css'
    'matches-property',
    'nth-ancestor',
    'remove',
    'upward',
    'xpath',
]);
/**
 * Supported native CSS pseudo-classes.
 *
 * These pseudo-classes are supported by browsers natively, so we don't need Extended CSS library to support them.
 *
 * The problem with pseudo-classes is that any unknown pseudo-class makes browser ignore the whole CSS rule,
 * which contains a lot more selectors. So, if CSS selector contains a pseudo-class, we should try to validate it.
 * One more problem with pseudo-classes is that they are actively used in uBlock, hence it may mess AG styles.
 *
 * Please keep this list sorted alphabetically.
 */
const background_SUPPORTED_CSS_PSEUDO_CLASSES = new Set([
    'active', // https://developer.mozilla.org/en-US/docs/Web/CSS/:active
    'checked', // https://developer.mozilla.org/en-US/docs/Web/CSS/:checked
    'disabled', // https://developer.mozilla.org/en-US/docs/Web/CSS/:disabled
    'empty', // https://developer.mozilla.org/en-US/docs/Web/CSS/:empty
    'enabled', // https://developer.mozilla.org/en-US/docs/Web/CSS/:enabled
    'first-child', // https://developer.mozilla.org/en-US/docs/Web/CSS/:first-child
    'first-of-type', // https://developer.mozilla.org/en-US/docs/Web/CSS/:first-of-type
    'focus', // https://developer.mozilla.org/en-US/docs/Web/CSS/:focus
    'has', // https://developer.mozilla.org/en-US/docs/Web/CSS/:has
    'hover', // https://developer.mozilla.org/en-US/docs/Web/CSS/:hover
    'in-range', // https://developer.mozilla.org/en-US/docs/Web/CSS/:in-range
    'invalid', // https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid
    'is', // https://developer.mozilla.org/en-US/docs/Web/CSS/:is
    'lang', // https://developer.mozilla.org/en-US/docs/Web/CSS/:lang
    'last-child', // https://developer.mozilla.org/en-US/docs/Web/CSS/:last-child
    'last-of-type', // https://developer.mozilla.org/en-US/docs/Web/CSS/:last-of-type
    'link', // https://developer.mozilla.org/en-US/docs/Web/CSS/:link
    'not', // https://developer.mozilla.org/en-US/docs/Web/CSS/:not
    'nth-child', // https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child
    'nth-last-child', // https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child
    'nth-last-of-type', // https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-of-type
    'nth-of-type', // https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-of-type
    'only-child', // https://developer.mozilla.org/en-US/docs/Web/CSS/:only-child
    'only-of-type', // https://developer.mozilla.org/en-US/docs/Web/CSS/:only-of-type
    'optional', // https://developer.mozilla.org/en-US/docs/Web/CSS/:optional
    'out-of-range', // https://developer.mozilla.org/en-US/docs/Web/CSS/:out-of-range
    'read-only', // https://developer.mozilla.org/en-US/docs/Web/CSS/:read-only
    'read-write', // https://developer.mozilla.org/en-US/docs/Web/CSS/:read-write
    'required', // https://developer.mozilla.org/en-US/docs/Web/CSS/:required
    'root', // https://developer.mozilla.org/en-US/docs/Web/CSS/:root
    'target', // https://developer.mozilla.org/en-US/docs/Web/CSS/:target
    'valid', // https://developer.mozilla.org/en-US/docs/Web/CSS/:valid
    'visited', // https://developer.mozilla.org/en-US/docs/Web/CSS/:visited
    'where', // https://developer.mozilla.org/en-US/docs/Web/CSS/:where
]);
/**
 * Every Extended CSS pseudo-class should start with this prefix.
 *
 * @see {@link https://github.com/AdguardTeam/ExtendedCss#-backward-compatible-syntax}
 */
const background_EXT_CSS_ATTRIBUTE_SELECTOR_PREFIX = '-ext-';
/**
 * Supported legacy Extended CSS attribute selectors.
 *
 * Attribute selector way is deprecated and will be removed completely in the future,
 * we replaced it with Extended CSS pseudo-classes. For example, instead of
 * `[-ext-has="a[href]"]` you should use `:has(a[href])`.
 *
 * Please keep this list sorted alphabetically.
 */
const background_SUPPORTED_EXT_CSS_ATTRIBUTE_SELECTORS = new Set([
    `${background_EXT_CSS_ATTRIBUTE_SELECTOR_PREFIX}has`,
    `${background_EXT_CSS_ATTRIBUTE_SELECTOR_PREFIX}contains`,
    `${background_EXT_CSS_ATTRIBUTE_SELECTOR_PREFIX}has-text`,
    `${background_EXT_CSS_ATTRIBUTE_SELECTOR_PREFIX}matches-css`,
    `${background_EXT_CSS_ATTRIBUTE_SELECTOR_PREFIX}matches-css-before`,
    `${background_EXT_CSS_ATTRIBUTE_SELECTOR_PREFIX}matches-css-after`,
]);
/**
 * Known CSS functions that aren't allowed in CSS injection rules, because they
 * able to load external resources. Please, keep this list sorted.
 */
const background_FORBIDDEN_CSS_FUNCTIONS = new Set([
    // https://developer.mozilla.org/en-US/docs/Web/CSS/cross-fade
    '-webkit-cross-fade',
    'cross-fade',
    // https://developer.mozilla.org/en-US/docs/Web/CSS/image
    'image',
    // https://developer.mozilla.org/en-US/docs/Web/CSS/image-set
    '-webkit-image-set',
    'image-set',
    // https://developer.mozilla.org/en-US/docs/Web/CSS/url
    'url',
]);

/**
 * @file Selector list validator.
 */
/**
 * Does a basic validation of a selector list.
 * Checks for unsupported pseudo-classes and attribute selectors,
 * and determines if the selector is an Extended CSS selector.
 *
 * @param selectorList Selector list to validate.
 *
 * @returns Validation result, see {@link CssValidationResult}.
 *
 * @note This is a basic validation for the most necessary things, it does not guarantee that the CSS is completely
 * valid.
 */
const background_validateSelectorList = (selectorList) => {
    const result = {
        isValid: true,
        isExtendedCss: false,
    };
    try {
        let prevIsDoubleColon = false;
        let prevToken;
        let prevNonWhitespaceToken;
        (0,background_csstokenizer/* tokenizeExtended */.jz)(selectorList, (token, start, end) => {
            if ((token === background_csstokenizer/* TokenType */.ks.Function || token === background_csstokenizer/* TokenType */.ks.Ident)
                && prevToken === background_csstokenizer/* TokenType */.ks.Colon
                && !prevIsDoubleColon) {
                // whitespace is NOT allowed between the ':' and the pseudo-class name, like ': active('
                const name = selectorList.slice(start, 
                // function tokens look like 'func(', so we need to remove the last character
                token === background_csstokenizer/* TokenType */.ks.Function ? end - 1 : end);
                // function name may contain escaped characters, like '\75' instead of 'u', so we need to decode it
                const decodedName = (0,background_csstokenizer/* decodeIdent */.f0)(name);
                if (background_SUPPORTED_EXT_CSS_PSEUDO_CLASSES.has(decodedName)) {
                    result.isExtendedCss = true;
                }
                else if (!background_SUPPORTED_CSS_PSEUDO_CLASSES.has(decodedName)) {
                    throw new Error(`Unsupported pseudo-class: ':${decodedName}'`);
                }
            }
            else if (token === background_csstokenizer/* TokenType */.ks.Ident && prevNonWhitespaceToken === background_csstokenizer/* TokenType */.ks.OpenSquareBracket) {
                // whitespace is allowed between the '[' and the attribute name, like '[ attr]'
                const attributeName = selectorList.slice(start, end);
                if (attributeName.startsWith(background_EXT_CSS_ATTRIBUTE_SELECTOR_PREFIX)) {
                    result.isExtendedCss = true;
                    if (!background_SUPPORTED_EXT_CSS_ATTRIBUTE_SELECTORS.has(attributeName)) {
                        throw new Error(`Unsupported Extended CSS attribute selector: '${attributeName}'`);
                    }
                }
            }
            else if (token === background_csstokenizer/* TokenType */.ks.OpenCurlyBracket || token === background_csstokenizer/* TokenType */.ks.CloseCurlyBracket) {
                throw new Error('Curly brackets are not allowed in selector lists');
            }
            else if (token === background_csstokenizer/* TokenType */.ks.Comment) {
                throw new Error('Comments are not allowed in selector lists');
            }
            // memorize tokens, we need them later
            if (token === background_csstokenizer/* TokenType */.ks.Colon) {
                prevIsDoubleColon = prevToken === background_csstokenizer/* TokenType */.ks.Colon;
            }
            prevToken = token;
            if (token !== background_csstokenizer/* TokenType */.ks.Whitespace) {
                prevNonWhitespaceToken = token;
            }
        });
    }
    catch (error) {
        result.isValid = false;
        result.errorMessage = background_declarative_converter_getErrorMessage(error);
    }
    return result;
};

/**
 * @file Declaration list validator.
 */
const background_REMOVE_PROPERTY = 'remove';
const background_REMOVE_LENGTH = background_REMOVE_PROPERTY.length;
/**
 * Check if function name is forbidden. If so, throws an error.
 *
 * @param functionName Function name to check.
 *
 * @throws Error if function name is forbidden.
 */
const background_checkFunctionName = (functionName) => {
    // function name may contain escaped characters, like '\75' instead of 'u', so we need to decode it
    const decodedFunctionName = (0,background_csstokenizer/* decodeIdent */.f0)(functionName);
    if (background_FORBIDDEN_CSS_FUNCTIONS.has(decodedFunctionName)) {
        throw new Error(`Using '${decodedFunctionName}()' is not allowed`);
    }
};
/**
 * Does a basic validation of a declaration list.
 * Checks for unsafe resource loading and determines if the declaration list is an Extended CSS declaration list.
 *
 * @param declarationList Declaration list to validate.
 *
 * @returns Validation result, see {@link CssValidationResult}.
 *
 * @note This is a basic validation for the most necessary things, it does not guarantee that the CSS is completely
 * valid.
 */
const background_validateDeclarationList = (declarationList) => {
    const result = {
        isValid: true,
        isExtendedCss: false,
    };
    try {
        (0,background_csstokenizer/* tokenizeExtended */.jz)(declarationList, (token, start, end) => {
            switch (token) {
                // Special case: according to CSS specs, sometimes url() is handled as a separate token type
                case background_csstokenizer/* TokenType */.ks.Url:
                case background_csstokenizer/* TokenType */.ks.BadUrl:
                    throw new Error("Using 'url()' is not allowed");
                case background_csstokenizer/* TokenType */.ks.Function:
                    // we need -1 to exclude closing bracket, because function tokens look like 'func('
                    background_checkFunctionName(declarationList.slice(start, end - 1));
                    break;
                case background_csstokenizer/* TokenType */.ks.Ident:
                    // do a fast check before getting the substring
                    if (end - start === background_REMOVE_LENGTH) {
                        // TODO: Improve this check, and check the whole `remove: true` sequence.
                        // Please note that the `remove : true` case also valid.
                        if ((0,background_csstokenizer/* decodeIdent */.f0)(declarationList.slice(start, end)) === background_REMOVE_PROPERTY) {
                            result.isExtendedCss = true;
                        }
                    }
                    break;
                case background_csstokenizer/* TokenType */.ks.Comment:
                    throw new Error('Comments are not allowed in declaration lists');
                default:
                    break;
            }
        });
    }
    catch (error) {
        result.isValid = false;
        result.errorMessage = background_declarative_converter_getErrorMessage(error);
    }
    return result;
};

/* eslint-disable max-classes-per-file */
class background_ScriptletParams {
    props = null;
    constructor(name, args) {
        if (typeof name !== 'undefined') {
            this.props = {
                name,
                args: args || [],
            };
        }
    }
    get name() {
        return this.props?.name;
    }
    get args() {
        return this.props?.args ?? [];
    }
    toString() {
        const result = [];
        result.push(background_constants/* ADG_SCRIPTLET_MASK */.x$);
        result.push('(');
        if (this.name) {
            result.push(background_quotes/* QuoteUtils */.Qj.setStringQuoteType(this.name, background_quotes/* QuoteType */.XA.Single));
        }
        if (this.args.length) {
            result.push(', ');
            result.push(this.args.map((arg) => background_quotes/* QuoteUtils */.Qj.setStringQuoteType(arg, background_quotes/* QuoteType */.XA.Single)).join(', '));
        }
        result.push(')');
        return result.join(background_EMPTY_STRING);
    }
}
/**
 * @typedef {import('./cosmetic-result').CosmeticResult} CosmeticResult
 */
/**
 * Implements a basic cosmetic rule.
 *
 * Cosmetic rules syntax are almost similar and looks like this.
 * ```
 * rule = [domains] "marker" content
 * domains = [domain0, domain1[, ...[, domainN]]]
 * ```
 *
 * The rule type is defined by the `type` property, you can find the list of them
 * in the {@link CosmeticRuleType} enumeration.
 *
 * What matters, though, is what's in the `content` part of it.
 *
 * @example
 * `example.org##.banner` -- element hiding rule
 * `example.org#$#.banner { display: block; }` -- CSS rule
 * `example.org#%#window.x=1;` -- JS rule
 * `example.org#%#//scriptlet('scriptlet-name')` -- Scriptlet rule
 * `example.org$$div[id="test"]` -- HTML filtering rule
 */
class background_CosmeticRule {
    ruleIndex;
    filterListId;
    content;
    type;
    allowlist = false;
    extendedCss = false;
    /**
     * $domain modifier pattern. It is only set if $domain modifier is specified for this rule.
     */
    domainModifier = null;
    /**
     * $path modifier pattern. It is only set if $path modifier is specified for this rule.
     */
    pathModifier;
    /**
     * $url modifier pattern. It is only set if $url modifier is specified for this rule,
     * but $path and $domain modifiers are not.
     *
     * TODO: add this to test cases.
     */
    urlModifier;
    /**
     * Js script to execute.
     */
    script = undefined;
    /**
     * Object with script code ready to execute and debug, domain values.
     *
     * @private
     */
    scriptData = null;
    /**
     * Object with scriptlet function and params.
     *
     * @private
     */
    scriptletData = null;
    /**
     * Scriptlet parameters.
     */
    scriptletParams;
    /**
     * If the rule contains scriptlet content.
     */
    isScriptlet = false;
    getIndex() {
        return this.ruleIndex;
    }
    getFilterListId() {
        return this.filterListId;
    }
    /**
     * Returns the rule content.
     *
     * @returns The content of the rule.
     */
    getContent() {
        return this.content;
    }
    /**
     * Cosmetic rule type (always present).
     *
     * @returns The type of the cosmetic rule.
     */
    getType() {
        return this.type;
    }
    /**
     * Allowlist means that this rule is meant to disable other rules,
     * i.e. an exception rule.
     *
     * @see {@link https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#elemhide-exceptions}
     *
     * @returns True if the rule is an allowlist rule, false otherwise.
     */
    isAllowlist() {
        return this.allowlist;
    }
    /**
     * Returns script ready to execute or null
     * Rebuilds scriptlet script if debug or domain params change.
     *
     * @param options Script options.
     *
     * @returns Script code or null.
     */
    getScript(options = {}) {
        const { debug = false, frameUrl } = options;
        const { scriptData } = this;
        if (scriptData && !this.isScriptlet) {
            return scriptData.code;
        }
        if (scriptData && scriptData.debug === debug) {
            if (frameUrl) {
                if (frameUrl === scriptData.frameUrl) {
                    return scriptData.code;
                }
            }
            else {
                return scriptData.code;
            }
        }
        this.initScript(options);
        return this.scriptData?.code ?? null;
    }
    /**
     * Gets list of permitted domains.
     *
     * @returns List of permitted domains or null if no domain modifier is set.
     */
    getPermittedDomains() {
        if (this.domainModifier) {
            return this.domainModifier.getPermittedDomains();
        }
        return null;
    }
    /**
     * Gets list of restricted domains.
     *
     * @returns List of restricted domains or null if no domain modifier is set.
     */
    getRestrictedDomains() {
        if (this.domainModifier) {
            return this.domainModifier.getRestrictedDomains();
        }
        return null;
    }
    /**
     * Returns true if the rule is considered "generic"
     * "generic" means that the rule is not restricted to a limited set of domains
     * Please note that it might be forbidden on some domains, though.
     *
     * @returns True if the rule is generic, false otherwise.
     */
    isGeneric() {
        return !this.domainModifier?.hasPermittedDomains();
    }
    /**
     * Checks if the rule is ExtendedCss.
     *
     * @returns True if the rule is ExtendedCss, false otherwise.
     */
    isExtendedCss() {
        return this.extendedCss;
    }
    /**
     * Processes cosmetic rule modifiers, e.g. `$path`.
     *
     * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#modifiers-for-non-basic-type-of-rules}
     *
     * @param ruleNode Cosmetic rule node to process.
     *
     * @returns Processed modifiers ({@link ProcessedModifiers}) or `null` if there are no modifiers.
     */
    static processModifiers(ruleNode) {
        // Do nothing if there are no modifiers in the rule node
        if (!ruleNode.modifiers) {
            return null;
        }
        const result = {};
        // We don't allow duplicate modifiers, so we collect them in a set
        const usedModifiers = new Set();
        // Destructure the modifiers array just for convenience
        const { children: modifierNodes } = ruleNode.modifiers;
        // AGTree parser tolerates this case: [$]example.com##.foo
        // However, we should throw an error here if the modifier list is empty
        // (if the modifier list isn't specified at all, then ruleNode.modifiers
        // will be undefined, so we won't get here)
        if (modifierNodes.length < 1) {
            throw new SyntaxError('Modifiers list cannot be be empty');
        }
        for (const modifierNode of modifierNodes) {
            const modifierName = modifierNode.name.value;
            // Check if the modifier is already used
            if (usedModifiers.has(modifierName)) {
                throw new Error(`Duplicated modifier: '${modifierName}'`);
            }
            // Mark the modifier as used by adding it to the set
            usedModifiers.add(modifierName);
            const modifierValue = modifierNode.value?.value || background_EMPTY_STRING;
            // Every modifier should have a value at the moment, so for simplicity we throw an error here if the
            // modifier value is not present.
            // TODO: Improve this when we decide to add modifiers without values
            if (modifierValue.length < 1 && modifierName !== "path" /* CosmeticRuleModifier.Path */) {
                throw new SyntaxError(`'$${modifierName}' modifier should have a value`);
            }
            // Process the modifier based on its name
            switch (modifierName) {
                case "domain" /* CosmeticRuleModifier.Domain */:
                    if (ruleNode.domains.children.length > 0) {
                        throw new SyntaxError(`'$${modifierName}' modifier is not allowed in a domain-specific rule`);
                    }
                    result.domainModifier = new background_DomainModifier(modifierValue, background_constants/* PIPE_MODIFIER_SEPARATOR */.fW);
                    break;
                case "path" /* CosmeticRuleModifier.Path */:
                    result.pathModifier = new background_Pattern(background_SimpleRegex.isRegexPattern(modifierValue)
                        // eslint-disable-next-line max-len
                        ? background_SimpleRegex.unescapeRegexSpecials(modifierValue, background_SimpleRegex.reModifierPatternEscapedSpecialCharacters)
                        : modifierValue);
                    break;
                case "url" /* CosmeticRuleModifier.Url */:
                    if (ruleNode.domains.children.length > 0) {
                        throw new SyntaxError(`'$${modifierName}' modifier is not allowed in a domain-specific rule`);
                    }
                    result.urlModifier = new background_Pattern(background_SimpleRegex.isRegexPattern(modifierValue)
                        // eslint-disable-next-line max-len
                        ? background_SimpleRegex.unescapeRegexSpecials(modifierValue, background_SimpleRegex.reModifierPatternEscapedSpecialCharacters)
                        : modifierValue);
                    break;
                // Don't allow unknown modifiers
                default:
                    throw new SyntaxError(`'$${modifierName}' modifier is not supported`);
            }
        }
        // $url modifier can't be used with other modifiers
        // TODO: Extend / change this check if we decide to add more such modifiers
        if (result.urlModifier && usedModifiers.size > 1) {
            throw new SyntaxError(`'$${"url" /* CosmeticRuleModifier.Url */}' modifier cannot be used with other modifiers`);
        }
        return result;
    }
    /**
     * Validates cosmetic rule node.
     *
     * @param ruleNode Cosmetic rule node to validate.
     *
     * @returns Validation result {@link ValidationResult}.
     */
    static validate(ruleNode) {
        const result = {
            isValid: true,
            isExtendedCss: false,
        };
        let scriptletName;
        let selectorListValidationResult;
        const { type: ruleType } = ruleNode;
        try {
            // Common validation: every cosmetic rule has a domain list
            if (ruleNode.domains?.children.length) {
                // Iterate over the domain list and check every domain
                for (const { value: domain } of ruleNode.domains.children) {
                    if (!background_utils_domain/* DomainUtils */.Aw.isValidDomainOrHostname(domain)) {
                        throw new Error(`'${domain}' is not a valid domain name`);
                    }
                }
            }
            // Type-specific validation
            switch (ruleType) {
                case background_nodes/* CosmeticRuleType */.k9.ElementHidingRule:
                    selectorListValidationResult = background_validateSelectorList(ruleNode.body.selectorList.value);
                    if (!selectorListValidationResult.isValid) {
                        throw new Error(selectorListValidationResult.errorMessage);
                    }
                    // Detect ExtendedCss and unsupported pseudo-classes
                    result.isExtendedCss = selectorListValidationResult.isExtendedCss;
                    break;
                case background_nodes/* CosmeticRuleType */.k9.CssInjectionRule:
                    selectorListValidationResult = background_validateSelectorList(ruleNode.body.selectorList.value);
                    if (!selectorListValidationResult.isValid) {
                        throw new Error(selectorListValidationResult.errorMessage);
                    }
                    // Detect ExtendedCss and unsupported pseudo-classes
                    result.isExtendedCss = selectorListValidationResult.isExtendedCss;
                    // AGTree won't allow the following rule:
                    // `#$#selector { remove: true; padding: 0; }`
                    // because it mixes removal and non-removal declarations.
                    if (ruleNode.body.declarationList) {
                        // eslint-disable-next-line max-len
                        const declarationListValidationResult = background_validateDeclarationList(ruleNode.body.declarationList.value);
                        if (!declarationListValidationResult.isValid) {
                            throw new Error(declarationListValidationResult.errorMessage);
                        }
                        // If the selector list is not ExtendedCss, then we should set this flag based on the
                        // declaration list validation result
                        if (!result.isExtendedCss) {
                            result.isExtendedCss = declarationListValidationResult.isExtendedCss;
                        }
                    }
                    break;
                case background_nodes/* CosmeticRuleType */.k9.ScriptletInjectionRule:
                    // Scriptlet name is the first child of the parameter list
                    // eslint-disable-next-line max-len
                    scriptletName = background_quotes/* QuoteUtils */.Qj.removeQuotes(ruleNode.body.children[0]?.children[0]?.value ?? background_EMPTY_STRING);
                    // Special case: scriptlet name is empty, e.g. '#%#//scriptlet()'
                    if (scriptletName.length === 0) {
                        break;
                    }
                    // Check if the scriptlet name is valid
                    if (!(0,background_validators/* isValidScriptletName */.GY)(scriptletName)) {
                        throw new Error(`'${scriptletName}' is not a known scriptlet name`);
                    }
                    break;
                case background_nodes/* CosmeticRuleType */.k9.HtmlFilteringRule:
                    // TODO: Validate HTML filtering rules
                    break;
                case background_nodes/* CosmeticRuleType */.k9.JsInjectionRule:
                    // TODO: Validate JS injection rules
                    break;
                default:
                    break;
            }
        }
        catch (error) {
            result.isValid = false;
            result.errorMessage = background_declarative_converter_getErrorMessage(error);
        }
        return result;
    }
    /**
     * Checks if the domain list contains any domains, but returns `false` if only
     * the wildcard domain is specified.
     *
     * @param domainListNode Domain list node to check.
     *
     * @returns `true` if the domain list contains any domains, `false` otherwise.
     */
    static isAnyDomainSpecified(domainListNode) {
        if (domainListNode.children.length > 0) {
            // Skip wildcard domain list (*)
            return !(domainListNode.children.length === 1 && domainListNode.children[0].value === background_WILDCARD);
        }
        return false;
    }
    /**
     * Creates an instance of the {@link CosmeticRule}.
     * It parses the rule and extracts the permitted/restricted domains,
     * and also the cosmetic rule's content.
     *
     * Depending on the rule type, the content might be transformed in
     * one of the helper classes, or kept as string when it's appropriate.
     *
     * @param node AST node of the cosmetic rule.
     * @param filterListId ID of the filter list this rule belongs to.
     * @param ruleIndex Line start index in the source filter list; it will be used to find the original rule text
     * in the filtering log when a rule is applied. Default value is {@link RULE_INDEX_NONE} which means that
     * the rule does not have source index.
     *
     * @throws Error if it fails to parse the rule.
     */
    constructor(node, filterListId, ruleIndex = background_RULE_INDEX_NONE) {
        this.ruleIndex = ruleIndex;
        this.filterListId = filterListId;
        this.allowlist = background_cosmetic_rule_separator/* CosmeticRuleSeparatorUtils */.m.isException(node.separator.value);
        this.type = node.type;
        this.isScriptlet = node.type === background_nodes/* CosmeticRuleType */.k9.ScriptletInjectionRule;
        this.content = background_cosmetic_rule_body_generator/* CosmeticRuleBodyGenerator */.H.generate(node);
        // Store the scriptlet parameters. They will be used later, when we initialize the scriptlet,
        // but at this point we need to store them in order to avoid double parsing
        if (node.type === background_nodes/* CosmeticRuleType */.k9.ScriptletInjectionRule) {
            // Transform complex node into a simple array of strings
            const params = node.body.children[0]?.children.map((param) => (param === null ? background_EMPTY_STRING : background_quotes/* QuoteUtils */.Qj.removeQuotesAndUnescape(param.value))) ?? [];
            this.scriptletParams = new background_ScriptletParams(params[0] ?? '', params.slice(1));
        }
        else {
            this.scriptletParams = new background_ScriptletParams();
        }
        const validationResult = background_CosmeticRule.validate(node);
        // We should throw an error if the validation failed for any reason
        if (!validationResult.isValid) {
            throw new SyntaxError(validationResult.errorMessage);
        }
        // Check if the rule is ExtendedCss
        const isExtendedCssSeparator = background_cosmetic_rule_separator/* CosmeticRuleSeparatorUtils */.m.isExtendedCssMarker(node.separator.value);
        this.extendedCss = isExtendedCssSeparator || validationResult.isExtendedCss;
        // Process cosmetic rule modifiers
        const processedModifiers = background_CosmeticRule.processModifiers(node);
        if (processedModifiers) {
            if (processedModifiers.domainModifier) {
                this.domainModifier = processedModifiers.domainModifier;
            }
            if (processedModifiers.pathModifier) {
                this.pathModifier = processedModifiers.pathModifier;
            }
            if (processedModifiers.urlModifier) {
                this.urlModifier = processedModifiers.urlModifier;
            }
        }
        // Process domain list, if at least one domain is specified
        const { domains: domainListNode } = node;
        if (background_CosmeticRule.isAnyDomainSpecified(domainListNode)) {
            this.domainModifier = new background_DomainModifier(domainListNode, background_constants/* COMMA_DOMAIN_LIST_SEPARATOR */.oo);
        }
    }
    /**
     * Match returns true if this rule can be used on the specified request.
     *
     * @param request Request to check.
     *
     * @returns True if the rule matches the request, false otherwise.
     */
    match(request) {
        if (!this.domainModifier
            && !this.pathModifier
            && !this.urlModifier) {
            return true;
        }
        if (this.urlModifier) {
            return this.urlModifier.matchPattern(request, false);
        }
        if (this.domainModifier) {
            if (!this.domainModifier.matchDomain(request.hostname)) {
                return false;
            }
        }
        if (this.pathModifier) {
            const path = background_getRelativeUrl(request.urlLowercase);
            if (path) {
                return this.pathModifier.matchPathPattern(path);
            }
            return false;
        }
        return true;
    }
    /**
     * Returns the scriptlet's data consisting of the scriptlet function and its arguments.
     * This method is supposed to be used in the manifest V3 extension.
     *
     * @returns The scriptlet data or null if not available.
     */
    getScriptletData() {
        if (this.scriptletData) {
            return this.scriptletData;
        }
        this.initScript();
        return this.scriptletData;
    }
    /**
     * Updates this.scriptData and this.scriptletData when it is necessary in a lazy way.
     *
     * @param options Initialization options for the script.
     */
    initScript(options = {}) {
        const { debug = false, frameUrl } = options;
        const ruleContent = this.getContent();
        if (!this.isScriptlet) {
            this.scriptData = {
                code: ruleContent,
            };
            return;
        }
        // A scriptlet without a name can only be an allowlist scriptlet
        // https://github.com/AdguardTeam/Scriptlets/issues/377
        // or it is considered invalid if the scriptlet was invalid.
        // This does not require finding scriptData and scriptletData.
        if (!this.scriptletParams?.name) {
            return;
        }
        const params = {
            args: this.scriptletParams.args,
            engine: background_config.engine || background_EMPTY_STRING,
            name: this.scriptletParams.name,
            verbose: debug,
            domainName: frameUrl,
            version: background_config.version || background_EMPTY_STRING,
        };
        this.scriptData = {
            code: background_scriptlets/* scriptlets */.e.invoke(params) ?? null,
            debug,
            frameUrl,
        };
        this.scriptletData = {
            func: background_scriptlets/* scriptlets */.e.getScriptletFunction(params.name),
            params,
        };
    }
}

/**
 * Implements a host rule.
 *
 * HostRule is a structure for simple host-level rules (i.e. /etc/hosts syntax).
 * More details: http://man7.org/linux/man-pages/man5/hosts.5.html.
 * It also supports "just domain" syntax. In this case, the IP will be set to `0.0.0.0`.
 *
 * Rules syntax looks like this.
 * ```
 * IP_address canonical_hostname [aliases...]
 * ```
 *
 * Examples:
 * `192.168.1.13 bar.mydomain.org bar` -- ipv4
 * `ff02::1 ip6-allnodes` -- ipv6
 * `::1 localhost ip6-localhost ip6-loopback` -- ipv6 aliases
 * `example.org` -- "just domain" syntax.
 *
 * @returns True if this rule can be used on the specified hostname.
 */
class background_HostRule {
    ruleIndex;
    filterListId;
    hostnames = [];
    ip = '';
    invalid = false;
    /**
     * Constructor.
     *
     * Parses the rule and creates a new HostRule instance.
     *
     * @param node Original rule text.
     * @param filterListId ID of the filter list this rule belongs to.
     * @param ruleIndex Index of the rule.
     *
     * @throws Error if it fails to parse the rule.
     */
    constructor(node, filterListId, ruleIndex = background_RULE_INDEX_NONE) {
        this.ruleIndex = ruleIndex;
        this.filterListId = filterListId;
        this.ip = node.ip.value;
        if (node.hostnames.children.length === 0) {
            this.invalid = true;
            return;
        }
        this.hostnames = node.hostnames.children.map((hostname) => hostname.value);
    }
    /**
     * Match returns true if this rule can be used on the specified hostname.
     *
     * @param hostname Hostname to check.
     *
     * @returns True if the hostname matches one of the hostnames in the rule.
     */
    match(hostname) {
        return this.hostnames.includes(hostname);
    }
    /**
     * Returns list id.
     *
     * @returns The filter list ID.
     */
    getFilterListId() {
        return this.filterListId;
    }
    /**
     * Returns rule index.
     *
     * @returns The rule index.
     */
    getIndex() {
        return this.ruleIndex;
    }
    /**
     * Returns ip address.
     *
     * @returns IP address.
     */
    getIp() {
        return this.ip;
    }
    /**
     * Returns hostnames.
     *
     * @returns Array of hostnames.
     */
    getHostnames() {
        return this.hostnames;
    }
    /**
     * Checks if the rule is invalid.
     *
     * @returns True if the rule is invalid.
     */
    isInvalid() {
        return this.invalid;
    }
}

/**
 * Helper function to create an allowlist rule node for a given domain.
 *
 * @param domain Domain to create an allowlist rule for.
 *
 * @returns Allowlist rule node or null.
 */
const background_createAllowlistRuleNode = (domain) => {
    const domainToUse = domain.startsWith('www.') ? domain.substring(4) : domain;
    if (!domainToUse) {
        return null;
    }
    let pattern;
    // Special case: Wildcard TLD + N domain
    if (domainToUse.startsWith('*.')) {
        pattern = `${background_SimpleRegex.MASK_START_URL}${domainToUse.slice(2)}`;
    }
    else {
        // In other cases we use regexp to match domain and it`s 'www' subdomain strictly.
        let regexp = '';
        // transform allowlist domain special characters
        for (let i = 0; i < domainToUse.length; i += 1) {
            const char = domainToUse[i];
            // transform wildcard to regexp equivalent
            if (char === '*') {
                regexp += '.*';
                // escape domain separator
            }
            else if (char === '.') {
                regexp += String.raw `\.`;
            }
            else {
                regexp += char;
            }
        }
        pattern = String.raw `///(www\.)?${regexp}/`;
    }
    const node = {
        category: background_nodes/* RuleCategory */.$O.Network,
        type: background_nodes/* NetworkRuleType */.vY.NetworkRule,
        syntax: background_adblockers/* AdblockSyntax */.Y.Common,
        exception: true,
        pattern: {
            type: 'Value',
            value: pattern,
        },
        modifiers: {
            type: 'ModifierList',
            children: [
                {
                    type: 'Modifier',
                    name: {
                        type: 'Value',
                        value: 'document',
                    },
                },
                {
                    type: 'Modifier',
                    name: {
                        type: 'Value',
                        value: 'important',
                    },
                },
            ],
        },
    };
    return node;
};

/**
 * Rule builder class.
 */
class background_RuleFactory {
    /**
     * Creates rule of suitable class from text string
     * It returns null if the line is empty or if it is a comment.
     *
     * TODO: Pack `ignore*` parameters and `silent` into one object with flags.
     *
     * @param node Rule node.
     * @param filterListId List id.
     * @param ruleIndex Line start index in the source filter list; it will be used to find the original rule text
     * in the filtering log when a rule is applied. Default value is {@link RULE_INDEX_NONE} which means that
     * the rule does not have source index.
     * @param ignoreNetwork Do not create network rules.
     * @param ignoreCosmetic Do not create cosmetic rules.
     * @param ignoreHost Do not create host rules.
     * @param silent Log the error for `true`, otherwise throw an exception on
     * a rule creation.
     *
     * @returns IRule object or null.
     *
     * @throws Error when `silent` flag is passed as false on rule creation error.
     */
    static createRule(node, filterListId, ruleIndex = background_RULE_INDEX_NONE, ignoreNetwork = false, ignoreCosmetic = false, ignoreHost = true, silent = true) {
        try {
            switch (node.category) {
                case background_nodes/* RuleCategory */.$O.Invalid:
                case background_nodes/* RuleCategory */.$O.Empty:
                case background_nodes/* RuleCategory */.$O.Comment:
                    return null;
                case background_nodes/* RuleCategory */.$O.Cosmetic:
                    if (ignoreCosmetic) {
                        return null;
                    }
                    return new background_CosmeticRule(node, filterListId, ruleIndex);
                case background_nodes/* RuleCategory */.$O.Network:
                    if (node.type === background_nodes/* NetworkRuleType */.vY.HostRule) {
                        if (ignoreHost) {
                            return null;
                        }
                        return new background_HostRule(node, filterListId, ruleIndex);
                    }
                    if (ignoreNetwork) {
                        return null;
                    }
                    return new background_NetworkRule(node, filterListId, ruleIndex);
                default:
                    // should not happen in normal operation
                    return null;
            }
        }
        catch (e) {
            let msg = `"${background_declarative_converter_getErrorMessage(e)}" in the rule: `;
            try {
                msg += `"${background_rule_generator/* RuleGenerator */.u.generate(node)}"`;
            }
            catch (generateError) {
                msg += `"${JSON.stringify(node)}" (generate error: ${background_declarative_converter_getErrorMessage(generateError)})`;
            }
            if (silent) {
                background_logger.info(`Error: ${msg}`);
            }
            else {
                throw new Error(msg);
            }
        }
        return null;
    }
    /**
     * Creates allowlist rule for domain.
     *
     * @param domain Domain name.
     * @param filterListId List id.
     * @param ruleIndex Line start index in the source filter list.
     *
     * @returns Allowlist rule or null.
     */
    static createAllowlistRule(domain, filterListId, ruleIndex = background_RULE_INDEX_NONE) {
        const node = background_createAllowlistRuleNode(domain);
        if (!node) {
            return null;
        }
        return new background_NetworkRule(node, filterListId, ruleIndex);
    }
}

/**
 * Network rule with index and hashes for pattern and rule's text.
 *
 * This class is "wrapper" around simple IndexedRule for the needs of DNR converter:
 * pattern hashes are needed to quickly compare two different network rules with the same,
 * while rule's text hash is needed to keep ID of the rule in the filter the same
 * between several runs. Thus is needed to be able to use "skip review" option in CWS.
 */
class background_IndexedNetworkRuleWithHash extends background_IndexedRule {
    /**
     * Rule's hash created with {@link fastHash}. Needed to quickly compare
     * two different network rules with the same pattern part for future
     * checking of $badfilter application from one of them to another.
     *
     * Hash is create only from "pattern" part of the rule.
     */
    hash;
    /**
     * Constructor.
     *
     * @param rule Item of {@link NetworkRule}.
     * @param index Rule's index.
     * @param hash Hash of the rule.
     */
    constructor(rule, index, hash) {
        super(rule, index);
        this.hash = hash;
        this.rule = rule;
    }
    /**
     * Creates hash for pattern part of the network rule and return it. Needed
     * to quickly compare two different rules with the same pattern part for
     * future checking of $badfilter application from one of them to another.
     *
     * @param networkRule Item of {@link NetworkRule}.
     *
     * @returns Hash for pattern part of the network rule.
     */
    static createRulePatternHash(networkRule) {
        // TODO: Improve this part: maybe use trie-lookup-table and .getShortcut()?
        // or use agtree to collect pattern + all enabled network options without values
        const significantPart = networkRule.getPattern();
        return background_fastHash(significantPart);
    }
    /**
     * Gets hash for whole text of the network rule and return it. Needed
     * to keep ID of the rule in the filter the same between several runs. Thus
     * is needed to be able to use "skip review" option in CWS.
     *
     * @param salt Salt for hash, needed to make hash unique event if the rule
     * is the same (e.g. for different filters). To keep check simple, we just
     * use numbers.
     *
     * @returns Hash for pattern part of the network rule.
     */
    getRuleTextHash(salt) {
        const textOfNetworkRule = this.rule.getText();
        // Append a null-char to not collide with legitimate rule text.
        const trialText = salt === undefined ? textOfNetworkRule : `${textOfNetworkRule}\0${salt}`;
        return background_fastHash31(trialText);
    }
    /**
     * Create {@link IndexedNetworkRuleWithHash} from rule. If an error
     * was detected during the conversion - return it.
     *
     * @param filterId Filter id.
     * @param index Rule's buffer index in that filter.
     * @param ruleConvertedToAGSyntax Rule which was converted to AG syntax.
     *
     * @throws Error when conversion failed.
     *
     * @returns Item of {@link IndexedNetworkRuleWithHash} or Error.
     */
    static createIndexedNetworkRuleWithHash(filterId, index, ruleConvertedToAGSyntax) {
        // Create indexed network rule from AG rule. These rules will be used in
        // declarative rules, that's why we ignore cosmetic and host rules.
        let networkRule;
        try {
            // Note: for correct throwing error it is important to use setConfiguration(),
            // because it will set compatibility type and future parsing options
            // for network rules will take it into account.
            networkRule = background_RuleFactory.createRule(ruleConvertedToAGSyntax, filterId, index, false, // convert only network rules
            true, // ignore cosmetic rules
            true, // ignore host rules
            false);
        }
        catch (e) {
            // eslint-disable-next-line max-len
            throw new Error(`Cannot create IRule from filter "${filterId}" and byte offset "${index}": ${background_declarative_converter_getErrorMessage(e)}`);
        }
        /**
         * The converted rule will be null when there was a comment or
         * an ignored cosmetic/host rule.
         */
        if (networkRule === null) {
            return null;
        }
        if (!(networkRule instanceof background_NetworkRule)) {
            // eslint-disable-next-line max-len
            throw new Error(`Rule from filter "${filterId}" and byte offset "${index}" is not network rule: ${networkRule}`);
        }
        const patternHash = background_IndexedNetworkRuleWithHash.createRulePatternHash(networkRule);
        // If rule is not empty - pack to IndexedNetworkRuleWithHash and add it
        // to the result array.
        const indexedNetworkRuleWithHash = new background_IndexedNetworkRuleWithHash(networkRule, index, patternHash);
        if (!indexedNetworkRuleWithHash) {
            // eslint-disable-next-line max-len
            throw new Error(`Cannot create indexed network rule with hash from filter "${filterId}" and byte offset "${index}"`);
        }
        return indexedNetworkRuleWithHash;
    }
    /**
     * Creates {@link IndexedNetworkRuleWithHash} from rule node.
     *
     * @param filterId Filter's id from which rule was extracted.
     * @param ruleIndex Buffer index of rule in that filter.
     * @param node Rule node.
     *
     * @throws Error when rule cannot be converted to AG syntax or when indexed
     * rule cannot be created from the rule which is already converted to AG
     * syntax.
     *
     * @returns Item of {@link IndexedNetworkRuleWithHash}.
     */
    static createFromNode(filterId, ruleIndex, node) {
        // Converts a raw string rule to AG syntax (apply aliases, etc.)
        let rulesConvertedToAGSyntax;
        try {
            const conversionResult = background_rule/* RuleConverter */.b.convertToAdg(node);
            if (conversionResult.isConverted) {
                rulesConvertedToAGSyntax = conversionResult.result;
            }
            else {
                rulesConvertedToAGSyntax = [node];
            }
        }
        catch (e) {
            // eslint-disable-next-line max-len
            throw new Error(`Unknown error during conversion rule to AG syntax: ${background_declarative_converter_getErrorMessage(e)}`);
        }
        const rules = [];
        const convertedAGRules = rulesConvertedToAGSyntax;
        // Now convert to IRule and then IndexedRule.
        for (let rulesIndex = 0; rulesIndex < convertedAGRules.length; rulesIndex += 1) {
            const ruleConvertedToAGSyntax = convertedAGRules[rulesIndex];
            try {
                const networkIndexedRuleWithHash = background_IndexedNetworkRuleWithHash.createIndexedNetworkRuleWithHash(filterId, ruleIndex, ruleConvertedToAGSyntax);
                if (networkIndexedRuleWithHash) {
                    rules.push(networkIndexedRuleWithHash);
                }
            }
            catch (e) {
                // eslint-disable-next-line max-len
                throw new Error(`Error during creating indexed rule with hash: ${background_declarative_converter_getErrorMessage(e)}`);
            }
        }
        return rules;
    }
}

/* eslint-disable jsdoc/require-description-complete-sentence */
/**
 * @file Describes types from declarativeNetRequest,
 * since @types/chrome does not contain actual information.
 *
 * Updated 07/09/2022.
 */
/**
 * https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#type-DomainType
 */
var background_DomainType;
(function (DomainType) {
    DomainType["FirstParty"] = "firstParty";
    DomainType["ThirdParty"] = "thirdParty";
})(background_DomainType || (background_DomainType = {}));
/**
 * https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#type-ResourceType
 */
var background_ResourceType;
(function (ResourceType) {
    ResourceType["MainFrame"] = "main_frame";
    ResourceType["SubFrame"] = "sub_frame";
    ResourceType["Stylesheet"] = "stylesheet";
    ResourceType["Script"] = "script";
    ResourceType["Image"] = "image";
    ResourceType["Font"] = "font";
    ResourceType["Object"] = "object";
    ResourceType["XmlHttpRequest"] = "xmlhttprequest";
    ResourceType["Ping"] = "ping";
    ResourceType["Media"] = "media";
    ResourceType["WebSocket"] = "websocket";
    ResourceType["Other"] = "other";
    // Temporary not using
    // TODO: Add csp_report handler similar to AG-24613 but in declarative way.
    // CspReport = 'csp_report',
    // WebTransport = 'webtransport',
    // WebBundle = 'webbundle',
})(background_ResourceType || (background_ResourceType = {}));
/**
 * https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#type-QueryKeyValue
 */
const background_QueryKeyValueValidator = background_zod_lib.z.strictObject({
    key: background_zod_lib.z.string(),
    replaceOnly: background_zod_lib.z.boolean().optional(),
    value: background_zod_lib.z.string(),
});
/**
 * https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#type-QueryTransform
 */
const background_QueryTransformValidator = background_zod_lib.z.strictObject({
    addOrReplaceParams: background_QueryKeyValueValidator.array().optional(),
    removeParams: background_zod_lib.z.string().array().optional(),
});
/**
 * https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#type-URLTransform
 */
const background_URLTransformValidator = background_zod_lib.z.strictObject({
    fragment: background_zod_lib.z.string().optional(),
    host: background_zod_lib.z.string().optional(),
    password: background_zod_lib.z.string().optional(),
    path: background_zod_lib.z.string().optional(),
    port: background_zod_lib.z.string().optional(),
    query: background_zod_lib.z.string().optional(),
    queryTransform: background_QueryTransformValidator.optional(),
    scheme: background_zod_lib.z.string().optional(),
    username: background_zod_lib.z.string().optional(),
});
/**
 * https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#type-Redirect
 */
const background_RedirectValidator = background_zod_lib.z.strictObject({
    extensionPath: background_zod_lib.z.string().optional(),
    regexSubstitution: background_zod_lib.z.string().optional(),
    transform: background_URLTransformValidator.optional(),
    url: background_zod_lib.z.string().optional(),
});
/**
 * https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#type-HeaderOperation
 */
var background_HeaderOperation;
(function (HeaderOperation) {
    HeaderOperation["Append"] = "append";
    HeaderOperation["Set"] = "set";
    HeaderOperation["Remove"] = "remove";
})(background_HeaderOperation || (background_HeaderOperation = {}));
/**
 * https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#type-ModifyHeaderInfo
 */
const background_ModifyHeaderInfoValidator = background_zod_lib.z.strictObject({
    header: background_zod_lib.z.string(),
    operation: background_zod_lib.z.nativeEnum(background_HeaderOperation),
    value: background_zod_lib.z.string().optional(),
});
/**
 * https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#type-RuleActionType
 */
var background_RuleActionType;
(function (RuleActionType) {
    RuleActionType["BLOCK"] = "block";
    RuleActionType["REDIRECT"] = "redirect";
    RuleActionType["ALLOW"] = "allow";
    RuleActionType["UPGRADE_SCHEME"] = "upgradeScheme";
    RuleActionType["MODIFY_HEADERS"] = "modifyHeaders";
    /**
     * For allowAllRequests rules {@link RuleCondition.resourceTypes} may only
     * include the 'sub_frame' and 'main_frame' resource types.
     */
    RuleActionType["ALLOW_ALL_REQUESTS"] = "allowAllRequests";
})(background_RuleActionType || (background_RuleActionType = {}));
/**
 * https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#type-RuleAction
 */
const background_RuleActionValidator = background_zod_lib.z.strictObject({
    redirect: background_RedirectValidator.optional(),
    requestHeaders: background_ModifyHeaderInfoValidator.array().optional(),
    responseHeaders: background_ModifyHeaderInfoValidator.array().optional(),
    type: background_zod_lib.z.nativeEnum(background_RuleActionType),
});
/**
 * https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#type-RequestMethod
 */
var background_RequestMethod;
(function (RequestMethod) {
    RequestMethod["Connect"] = "connect";
    RequestMethod["Delete"] = "delete";
    RequestMethod["Get"] = "get";
    RequestMethod["Head"] = "head";
    RequestMethod["Options"] = "options";
    RequestMethod["Patch"] = "patch";
    RequestMethod["Post"] = "post";
    RequestMethod["Put"] = "put";
})(background_RequestMethod || (background_RequestMethod = {}));
/**
 * Map {@link HTTPMethod} to declarative {@link RequestMethod}.
 */
const background_DECLARATIVE_REQUEST_METHOD_MAP = {
    [background_HTTPMethod.GET]: background_RequestMethod.Get,
    [background_HTTPMethod.POST]: background_RequestMethod.Post,
    [background_HTTPMethod.PUT]: background_RequestMethod.Put,
    [background_HTTPMethod.DELETE]: background_RequestMethod.Delete,
    [background_HTTPMethod.PATCH]: background_RequestMethod.Patch,
    [background_HTTPMethod.HEAD]: background_RequestMethod.Head,
    [background_HTTPMethod.OPTIONS]: background_RequestMethod.Options,
    [background_HTTPMethod.CONNECT]: background_RequestMethod.Connect,
};
/**
 * https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#type-RuleCondition
 */
const background_RuleConditionValidator = background_zod_lib.z.strictObject({
    domainType: background_zod_lib.z.nativeEnum(background_DomainType).optional(),
    excludedInitiatorDomains: background_zod_lib.z.string().array().optional(),
    excludedRequestDomains: background_zod_lib.z.string().array().optional(),
    excludedRequestMethods: background_zod_lib.z.nativeEnum(background_RequestMethod).array().optional(),
    excludedResourceTypes: background_zod_lib.z.nativeEnum(background_ResourceType).array().optional(),
    excludedTabIds: background_zod_lib.z.number().array().optional(),
    initiatorDomains: background_zod_lib.z.string().array().optional(),
    isUrlFilterCaseSensitive: background_zod_lib.z.boolean().optional(),
    regexFilter: background_zod_lib.z.string().optional(),
    requestDomains: background_zod_lib.z.string().array().optional(),
    requestMethods: background_zod_lib.z.nativeEnum(background_RequestMethod).array().optional(),
    /**
     * If none of the `excludedResourceTypes` and `resourceTypes` are specified,
     * all resource types except "main_frame" will be matched.
     */
    resourceTypes: background_zod_lib.z.nativeEnum(background_ResourceType).array().optional(),
    tabIds: background_zod_lib.z.number().array().optional(),
    urlFilter: background_zod_lib.z.string().optional(),
});
/**
 * https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#type-Rule
 */
const background_DeclarativeRuleValidator = background_zod_lib.z.strictObject({
    action: background_RuleActionValidator,
    condition: background_RuleConditionValidator,
    id: background_zod_lib.z.number(),
    priority: background_zod_lib.z.number().optional(),
});
/**
 * Map request types to declarative types.
 */
const background_DECLARATIVE_RESOURCE_TYPES_MAP = {
    [background_ResourceType.MainFrame]: background_RequestType.Document,
    [background_ResourceType.SubFrame]: background_RequestType.SubDocument,
    [background_ResourceType.Stylesheet]: background_RequestType.Stylesheet,
    [background_ResourceType.Script]: background_RequestType.Script,
    [background_ResourceType.Image]: background_RequestType.Image,
    [background_ResourceType.Font]: background_RequestType.Font,
    [background_ResourceType.Object]: background_RequestType.Object,
    [background_ResourceType.XmlHttpRequest]: background_RequestType.XmlHttpRequest,
    [background_ResourceType.Ping]: background_RequestType.Ping,
    // TODO: what should match this resource type?
    // [ResourceType.CSP_REPORT]: RequestType.Document,
    [background_ResourceType.Media]: background_RequestType.Media,
    [background_ResourceType.WebSocket]: background_RequestType.WebSocket,
    [background_ResourceType.Other]: background_RequestType.Other,
};

/**
 * Describes an error when rule set source is not available.
 */
class background_UnavailableRuleSetSourceError extends Error {
    ruleSetId;
    /**
     * Describes an error when rule set source is not available.
     *
     * @param message Message of error.
     * @param ruleSetId Rule set id, the source of which is not available.
     * @param cause Basic error, describes why the source is unavailable.
     */
    constructor(message, ruleSetId, cause) {
        super(message, { cause });
        this.name = this.constructor.name;
        this.ruleSetId = ruleSetId;
        // For proper work of the "instanceof" operator
        Object.setPrototypeOf(this, background_UnavailableRuleSetSourceError.prototype);
    }
}

/**
 * Contains a list of records with source rule ID, converted rule ID
 * and filter ID.
 * Can return the source filter and rule for the provided conversion rule ID.
 */
class background_SourceMap {
    sources = [];
    /**
     * Needs for fast search for source rule.
     */
    ruleIdMap = new Map();
    /**
     * Needs for fast search for source rule.
     */
    declarativeIdMap = new Map();
    /**
     * Creates new SourceMap from provided list of sources.
     *
     * @param sources List of sources.
     */
    constructor(sources) {
        this.sources = sources;
        // For fast search
        this.sources.forEach((item) => {
            const { sourceRuleIndex, filterId, declarativeRuleId } = item;
            // Fill source rules map.
            const existingSourcePairs = this.ruleIdMap.get(declarativeRuleId);
            const value = {
                sourceRuleIndex,
                filterId,
            };
            const newSourceValue = existingSourcePairs
                ? existingSourcePairs.concat(value)
                : [value];
            this.ruleIdMap.set(declarativeRuleId, newSourceValue);
            // Fill
            const key = background_SourceMap.getKeyFromSource(value);
            const existingDeclarativeIdsPairs = this.declarativeIdMap.get(key);
            const newDeclarativeIdsValue = existingDeclarativeIdsPairs
                ? existingDeclarativeIdsPairs.concat(declarativeRuleId)
                : [declarativeRuleId];
            this.declarativeIdMap.set(key, newDeclarativeIdsValue);
        });
    }
    /**
     * Creates unique key for provided pair of source rule and filter id.
     *
     * @param source Pair of source rule and filter id.
     *
     * @returns Unique key for dictionary.
     */
    static getKeyFromSource(source) {
        return `${source.filterId}_${source.sourceRuleIndex}`;
    }
    /**
     * Returns source filter id and source text rule id
     * for provided declarative rule id.
     *
     * @param ruleId Converted rule id.
     *
     * @returns List of pairs: source filter id and source rule id.
     */
    getByDeclarativeRuleId(ruleId) {
        return this.ruleIdMap.get(ruleId) || [];
    }
    /**
     * Returns ids of converted declarative rules for provided pairs of source
     * filter id and source text rule.
     *
     * @param source Pair of source rule and filter id.
     *
     * @returns List of ids of converted declarative rules.
     */
    getBySourceRuleIndex(source) {
        const key = background_SourceMap.getKeyFromSource(source);
        return this.declarativeIdMap.get(key) || [];
    }
    /**
     * Deserializes array of sources from string.
     *
     * @param sourceString The original map that was serialized into a string.
     *
     * @returns List of sources.
     */
    static deserializeSources(sourceString) {
        // TODO: Add validation
        const arr = JSON.parse(sourceString);
        return arr.map((item) => ({
            declarativeRuleId: item[0],
            sourceRuleIndex: item[1],
            filterId: item[2],
        }));
    }
    /**
     * Serializes source map to JSON string.
     *
     * @todo (TODO:) Can use protocol VLQ.
     *
     * @returns JSON string.
     */
    serialize() {
        // Remove fields names to reduce size of serialized string
        const plainArray = this.sources.map(({ declarativeRuleId, sourceRuleIndex, filterId, }) => ([declarativeRuleId, sourceRuleIndex, filterId]));
        return JSON.stringify(plainArray);
    }
}

/**
 * @file Utility functions for working with metadata rules.
 *
 * Metadata rules are declarative rules that do not block anything themselves,
 * but contain additional information. This information is used by the extension to process other rules,
 * conversion maps, and source maps.
 */
/**
 * Metadata rule ID. Always the first rule in the rule set.
 */
const background_METADATA_RULE_ID = 1;
/**
 * Metadata key in the rule object.
 */
const background_METADATA_KEY = 'metadata';
/**
 * Dummy rule URL that should not match any request.
 */
const background_DUMMY_RULE_URL = 'dummy.rule.adguard.com';
/**
 * Creates a declarative rule with metadata.
 *
 * @param content - Metadata rule configuration.
 *
 * @returns Declarative rule object with metadata.
 */
const background_createMetadataRule = (content) => {
    return {
        id: background_METADATA_RULE_ID,
        action: {
            type: background_RuleActionType.BLOCK,
        },
        condition: {
            urlFilter: background_DUMMY_RULE_URL,
            resourceTypes: [background_ResourceType.XmlHttpRequest],
        },
        [background_METADATA_KEY]: content,
    };
};

const background_serializedRuleSetLazyDataValidator = background_zod_lib.z.strictObject({
    sourceMapRaw: background_zod_lib.z.string(),
    filterIds: background_zod_lib.z.number().array(),
});
const background_serializedRuleSetDataValidator = background_zod_lib.z.strictObject({
    regexpRulesCount: background_zod_lib.z.number(),
    unsafeRulesCount: background_zod_lib.z.number().optional(),
    rulesCount: background_zod_lib.z.number(),
    ruleSetHashMapRaw: background_zod_lib.z.string(),
    badFilterRulesRaw: background_zod_lib.z.string().array(),
});
/**
 * Keeps converted declarative rules, counters of rules and source map for them.
 */
class background_RuleSet {
    /**
     * Id of rule set.
     */
    id;
    /**
     * Array of converted declarative rules.
     */
    declarativeRules = [];
    /**
     * Number of converted declarative rules.
     *
     * This is needed for the lazy version of the rule set,
     * when content not loaded.
     */
    rulesCount = 0;
    /**
     * Converted declarative unsafe rules.
     */
    unsafeRulesCount = 0;
    /**
     * Converted declarative regexp rules.
     */
    regexpRulesCount = 0;
    /**
     * Source map for declarative rules.
     */
    sourceMap;
    /**
     * Dictionary which helps to fast find rule by its hash.
     */
    rulesHashMap;
    /**
     * List of network rules with $badfilter option.
     */
    badFilterRules;
    /**
     * Keeps array of source filter lists
     * TODO: ? May it leads to memory leaks,
     * because one FilterList with its content
     * can be in the several RuleSet's at the same time ?
     */
    filterList = new Map();
    /**
     * The content provider of a rule set, is needed for lazy initialization.
     * If request the source rules from rule set, the content provider will be
     * called to load the source map, filter list and declarative rules list.
     */
    ruleSetContentProvider;
    /**
     * Whether the content is loaded or not.
     */
    initialized = false;
    /**
     * Waiter for initialization, will be resolved when the content is loaded.
     */
    initializerPromise;
    /**
     * Constructor of RuleSet.
     *
     * @param id Id of rule set.
     * @param rulesCount Number of rules.
     * @param unsafeRulesCount Number of unsafe rules.
     * @param regexpRulesCount Number of regexp rules.
     * @param ruleSetContentProvider Rule set content provider.
     * @param badFilterRules List of rules with $badfilter modifier.
     * @param rulesHashMap Dictionary with hashes for all source rules.
     */
    constructor(id, rulesCount, unsafeRulesCount, regexpRulesCount, ruleSetContentProvider, badFilterRules, rulesHashMap) {
        this.id = id;
        this.rulesCount = rulesCount;
        this.unsafeRulesCount = unsafeRulesCount;
        this.regexpRulesCount = regexpRulesCount;
        this.ruleSetContentProvider = ruleSetContentProvider;
        this.badFilterRules = badFilterRules;
        this.rulesHashMap = rulesHashMap;
    }
    /** @inheritdoc */
    getRulesCount() {
        return this.rulesCount || this.declarativeRules.length;
    }
    /** @inheritdoc */
    getUnsafeRulesCount() {
        return this.unsafeRulesCount;
    }
    /** @inheritdoc */
    getRegexpRulesCount() {
        return this.regexpRulesCount;
    }
    /** @inheritdoc */
    getId() {
        return this.id;
    }
    /**
     * Returns a list of pairs of source text rules and their filter identifiers
     * for a given declarative rule identifier.
     *
     * @param declarativeRuleId {@link DeclarativeRule|declarative rule} Id.
     *
     * @throws An error when filter is not found or filter content is unavailable.
     *
     * @returns Promise with list of source rules.
     */
    async findSourceRules(declarativeRuleId) {
        if (!this.sourceMap) {
            return [];
        }
        const sourcePairs = this.sourceMap.getByDeclarativeRuleId(declarativeRuleId);
        const sourceRules = sourcePairs.map(async ({ filterId, sourceRuleIndex, }) => {
            const filter = this.filterList.get(filterId);
            if (!filter) {
                throw new Error(`Not found filter list with id: ${filterId}`);
            }
            const sourceRule = await filter.getRuleByIndex(sourceRuleIndex);
            return {
                sourceRule,
                filterId,
            };
        });
        return Promise.all(sourceRules);
    }
    /**
     * Run inner lazy deserialization from rule set content provider to load
     * data which is not needed on the creation of rule set:
     * the source map, filter list and declarative rules list.
     */
    async loadContent() {
        if (this.initialized) {
            return;
        }
        if (this.initializerPromise) {
            await this.initializerPromise;
            return;
        }
        const initialize = async () => {
            const { loadSourceMap, loadFilterList, loadDeclarativeRules, } = this.ruleSetContentProvider;
            this.sourceMap = await loadSourceMap();
            this.declarativeRules = await loadDeclarativeRules();
            // TODO: Find a better method to load filters (AG-42364)
            const filtersList = await loadFilterList();
            filtersList.forEach((filter) => {
                this.filterList.set(filter.getId(), filter);
            });
            this.initialized = true;
        };
        this.initializerPromise = initialize().then(() => {
            this.initializerPromise = undefined;
        });
        await this.initializerPromise;
    }
    /** @inheritdoc */
    unloadContent() {
        // If content is not initialized, there is nothing to unload
        if (!this.initialized && !this.initializerPromise) {
            return;
        }
        // If initialization is in progress
        if (this.initializerPromise) {
            this.initializerPromise.finally(() => {
                this.unloadContent();
            });
            return;
        }
        // Safely unload all filters in the filter list
        this.filterList.forEach((filter) => filter.unloadContent());
        // Clear loaded resources
        this.sourceMap = undefined;
        this.declarativeRules = [];
        this.filterList.clear();
        // Mark the content as unloaded
        this.initialized = false;
        this.initializerPromise = undefined;
    }
    /** @inheritdoc */
    async getRulesById(declarativeRuleId) {
        try {
            await this.loadContent();
            const originalRules = await this.findSourceRules(declarativeRuleId);
            return originalRules;
        }
        catch (e) {
            const id = this.getId();
            // eslint-disable-next-line max-len
            const msg = `Cannot extract source rule for given declarativeRuleId ${declarativeRuleId} in rule set '${id}', got error: ${background_declarative_converter_getErrorMessage(e)}`;
            throw new background_UnavailableRuleSetSourceError(msg, id, e);
        }
    }
    /** @inheritdoc */
    getBadFilterRules() {
        return this.badFilterRules;
    }
    /** @inheritdoc */
    getRulesHashMap() {
        return this.rulesHashMap;
    }
    /** @inheritdoc */
    async getDeclarativeRulesIdsBySourceRuleIndex(source) {
        await this.loadContent();
        if (!this.sourceMap) {
            const { filterId, sourceRuleIndex } = source;
            // eslint-disable-next-line max-len
            throw new Error(`Cannot find declarative rules for filter id - ${filterId}, rule index - ${sourceRuleIndex} because source map is undefined in ruleset: ${this.getId()}`);
        }
        return this.sourceMap.getBySourceRuleIndex(source);
    }
    /** @inheritdoc */
    async getDeclarativeRules() {
        await this.loadContent();
        return this.declarativeRules;
    }
    /**
     * For provided source rule and filter id return network rule.
     * This method is needed for checking the applicability of $badfilter after
     * a fast-check of rules by comparing only hashes. Afterward, we should
     * build the 'full' Network rule from provided source, not just the hash,
     * to determine the applicability of $badfilter.
     *
     * @param source Source rule and filter id.
     *
     * @returns List of {@link NetworkRule | network rules}.
     */
    static getNetworkRuleBySourceRule(source) {
        const { sourceRule, filterId } = source;
        let networkIndexedRulesWithHash = [];
        try {
            networkIndexedRulesWithHash = background_IndexedNetworkRuleWithHash.createFromNode(filterId, 
            // We don't need line index because this indexedNetworkRulesWithHash
            // will be used only for matching $badfilter rules.
            0, background_rule_parser/* RuleParser */.G.parse(sourceRule));
        }
        catch (e) {
            return [];
        }
        const networkRules = networkIndexedRulesWithHash.map(({ rule }) => rule);
        return networkRules;
    }
    /**
     * Deserializes rule set to primitives values with lazy load.
     *
     * @param id Id of rule set.
     * @param rawData An item of {@link SerializedRuleSetData} for instant
     * creating ruleset. It contains counters for regular declarative and regexp
     * declarative rules, a map of hashes for all rules, and a list of rules
     * with the `$badfilter` modifier.
     * @param loadLazyData An item of {@link SerializedRuleSetLazyData} for lazy
     * loading ruleset data to find and display source rules when declarative
     * filtering log is enabled. It includes a map of sources for all rules,
     * a list of declarative rules, and a list of source filter IDs.
     * @param loadDeclarativeRules Loader for ruleset's declarative rules from
     * raw file as a string.
     * @param filterList List of {@link IFilter}.
     *
     * @returns Deserialized rule set.
     *
     * @throws Error {@link UnavailableRuleSetSourceError} if rule set source
     * is not available.
     */
    static async deserialize(id, rawData, loadLazyData, loadDeclarativeRules, filterList) {
        let data;
        try {
            const objectFromString = JSON.parse(rawData);
            data = background_serializedRuleSetDataValidator.parse(objectFromString);
        }
        catch (e) {
            // eslint-disable-next-line max-len
            const msg = `Cannot parse serialized ruleset's data with id "${id}", got error: ${background_declarative_converter_getErrorMessage(e)}`;
            throw new background_UnavailableRuleSetSourceError(msg, id, e);
        }
        /**
         * This variable is used as a singleton for all three functions
         * (`loadSourceMap`, `loadFilterList`, `loadDeclarativeRules`) to load
         * data only once.
         */
        let deserializedLazyData;
        const getLazyData = async () => {
            if (deserializedLazyData !== undefined) {
                return deserializedLazyData;
            }
            try {
                const lazyData = await loadLazyData();
                const objectFromString = JSON.parse(lazyData);
                deserializedLazyData = background_serializedRuleSetLazyDataValidator.parse(objectFromString);
                return deserializedLazyData;
            }
            catch (e) {
                // eslint-disable-next-line max-len
                const msg = `Cannot parse or load data for lazy metadata for rule set with id "${id}": ${background_declarative_converter_getErrorMessage(e)}`;
                throw new background_UnavailableRuleSetSourceError(msg, id, e);
            }
        };
        const deserialized = {
            id,
            data,
            ruleSetContentProvider: {
                loadSourceMap: async () => {
                    const { sourceMapRaw } = await getLazyData();
                    const sources = background_SourceMap.deserializeSources(sourceMapRaw);
                    return new background_SourceMap(sources);
                },
                loadFilterList: async () => {
                    const { filterIds } = await getLazyData();
                    return filterList.filter((filter) => filterIds.includes(filter.getId()));
                },
                loadDeclarativeRules: async () => {
                    const rawFileContent = await loadDeclarativeRules();
                    const objectFromString = JSON.parse(rawFileContent);
                    const declarativeRules = background_DeclarativeRuleValidator
                        .array()
                        .parse(objectFromString);
                    return declarativeRules;
                },
            },
        };
        return deserialized;
    }
    /**
     * Helper method to get serialized rule set data.
     *
     * @returns Serialized rule set data.
     */
    getSerializedRuleSetData() {
        return {
            regexpRulesCount: this.regexpRulesCount,
            unsafeRulesCount: this.unsafeRulesCount,
            rulesCount: this.rulesCount,
            ruleSetHashMapRaw: this.rulesHashMap.serialize(),
            // TODO: Remove .getText() completely
            badFilterRulesRaw: this.badFilterRules.map((r) => r.rule.getText()) || [],
        };
    }
    /**
     * Helper method to get serialized rule set lazy data.
     *
     * @returns Serialized rule set lazy data.
     */
    getSerializedRuleSetLazyData() {
        return {
            sourceMapRaw: this.sourceMap?.serialize() || background_EMPTY_STRING,
            filterIds: Array.from(this.filterList.keys()),
        };
    }
    /** @inheritdoc */
    async serialize() {
        try {
            await this.loadContent();
        }
        catch (e) {
            const id = this.getId();
            // eslint-disable-next-line max-len
            const msg = `Cannot serialize rule set '${id}' because of not available source, got error: ${background_declarative_converter_getErrorMessage(e)}`;
            throw new background_UnavailableRuleSetSourceError(msg, id, e);
        }
        const serialized = {
            id: this.id,
            data: JSON.stringify(this.getSerializedRuleSetData()),
            lazyData: JSON.stringify(this.getSerializedRuleSetLazyData()),
        };
        return serialized;
    }
    /** @inheritdoc */
    async serializeCompact(prettyPrint = true) {
        try {
            await this.loadContent();
        }
        catch (e) {
            const id = this.getId();
            // eslint-disable-next-line max-len
            const msg = `Cannot serialize ruleset '${id}' because of not available source, got error: ${background_declarative_converter_getErrorMessage(e)}`;
            throw new background_UnavailableRuleSetSourceError(msg, id, e);
        }
        // TODO: Improve this code once we introduce multiple filters within a single rule set
        // Also, do not forget to change metadata rule's structure to store preprocessed filter lists in an array
        const filter = this.filterList.values().next().value;
        const content = await filter.getContent();
        const metadataRule = background_createMetadataRule({
            metadata: this.getSerializedRuleSetData(),
            lazyMetadata: this.getSerializedRuleSetLazyData(),
            conversionMap: content.conversionMap,
            rawFilterList: content.rawFilterList,
        });
        const declarativeRules = await this.getDeclarativeRules();
        declarativeRules.unshift(metadataRule);
        const result = background_serializeJson(declarativeRules, prettyPrint);
        return result;
    }
}

/**
 * Describes abstract error when declarative rule is invalid.
 */
class background_InvalidDeclarativeRuleError extends Error {
    networkRule;
    declarativeRule;
    /**
     * Describes a reason of the error.
     */
    reason;
    /**
     * Describes abstract error when declarative rule is invalid.
     *
     * @param message Message of error.
     * @param networkRule {@link NetworkRule}.
     * @param declarativeRule {@link DeclarativeRule}.
     */
    constructor(message, networkRule, declarativeRule) {
        super(message);
        this.name = this.constructor.name;
        this.networkRule = networkRule;
        this.declarativeRule = declarativeRule;
        // For proper work of the "instanceof" operator
        Object.setPrototypeOf(this, background_InvalidDeclarativeRuleError.prototype);
    }
}

/**
 * Describes error when converted rule contains empty list of resources types.
 */
class background_EmptyResourcesError extends background_InvalidDeclarativeRuleError {
    /**
     * Describes error when converted rule contains empty list of resources types.
     *
     * @param message Message of error.
     * @param networkRule {@link NetworkRule}.
     * @param declarativeRule {@link DeclarativeRule}.
     */
    constructor(message, networkRule, declarativeRule) {
        super(message, networkRule, declarativeRule);
        this.name = this.constructor.name;
        // For proper work of the "instanceof" operator
        Object.setPrototypeOf(this, background_EmptyResourcesError.prototype);
    }
}

/**
 * @typedef {import(
 *   '../../grouped-rules-converters/abstract-rule-converter'
 * ).DeclarativeRuleConverter} DeclarativeRuleConverter
 */
/**
 * Describes an error when a source network rule contains some of
 * the unsupported modifiers.
 *
 * @see {@link DeclarativeRuleConverter.checkNetworkRuleConvertible} for more details.
 */
class background_UnsupportedModifierError extends Error {
    networkRule;
    /**
     * Describes an error when a source network rule contains some of
     * the unsupported modifiers.
     *
     * @param message Message of error.
     * @param networkRule {@link NetworkRule}.
     */
    constructor(message, networkRule) {
        super(message);
        this.name = this.constructor.name;
        this.networkRule = networkRule;
        // For proper work of the "instanceof" operator
        Object.setPrototypeOf(this, background_UnsupportedModifierError.prototype);
    }
}

/**
 * Describes an error when the converted rule contains an unsupported RE2
 * regexp syntax error.
 *
 * @see https://github.com/google/re2/wiki/Syntax
 */
class background_UnsupportedRegexpError extends background_InvalidDeclarativeRuleError {
    /**
     * Describes an error when the converted rule contains an unsupported RE2
     * regexp syntax error.
     *
     * @param message Message of error.
     * @param networkRule {@link NetworkRule}.
     * @param declarativeRule {@link DeclarativeRule}.
     * @param reason Describes a reason of the error.
     */
    constructor(message, networkRule, declarativeRule, reason) {
        super(message, networkRule, declarativeRule);
        this.name = this.constructor.name;
        this.reason = reason;
        // For proper work of the "instanceof" operator
        Object.setPrototypeOf(this, background_UnsupportedRegexpError.prototype);
    }
}

/**
 * Describes error when maximum number of rules is equal or less than 0.
 */
class background_EmptyOrNegativeNumberOfRulesError extends Error {
    /**
     * Describes error when maximum number of rules is equal or less than 0.
     *
     * @param message Message of error.
     */
    constructor(message) {
        super(message);
        this.name = this.constructor.name;
        // For proper work of the "instanceof" operator
        Object.setPrototypeOf(this, background_EmptyOrNegativeNumberOfRulesError.prototype);
    }
}

/**
 * Describes error when maximum number of rules is less than 0.
 */
class background_NegativeNumberOfRulesError extends Error {
    /**
     * Describes error when maximum number of rules is less than 0.
     *
     * @param message Message of error.
     */
    constructor(message) {
        super(message);
        this.name = this.constructor.name;
        // For proper work of the "instanceof" operator
        Object.setPrototypeOf(this, background_NegativeNumberOfRulesError.prototype);
    }
}

/**
 * Describes error when the resources path does not start with a slash
 * or it ends with a slash.
 */
class background_ResourcesPathError extends Error {
    /**
     * Describes error when the resources path does not start with a slash
     * or it ends with a slash.
     *
     * @param message Message of error.
     */
    constructor(message) {
        super(message);
        this.name = this.constructor.name;
        // For proper work of the "instanceof" operator
        Object.setPrototypeOf(this, background_ResourcesPathError.prototype);
    }
}

/**
 * Class for validating network rules.
 */
class background_NetworkRuleDeclarativeValidator {
    /**
     * Checks if the $redirect values in the provided network rule
     * are supported for conversion to MV3.
     *
     * @param r Network rule.
     * @param name Modifier's name.
     *
     * @returns Error {@link UnsupportedModifierError} or null if rule is supported.
     */
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    static checkRemoveParamModifierFn(r, name) {
        const removeParam = r.getAdvancedModifier();
        if (!removeParam) {
            return null;
        }
        if (!background_RemoveParamModifier.isRemoveParamModifier(removeParam)) {
            return null;
        }
        if (!removeParam.getMV3Validity()) {
            return new background_UnsupportedModifierError('Network rule with $removeparam modifier with negation or regexp is not supported', r);
        }
        return null;
    }
    /**
     * Checks if the provided rule is an allowlist rule.
     *
     * @param r Network rule.
     * @param name Modifier's name.
     *
     * @returns Error {@link UnsupportedModifierError} or null if rule is supported.
     */
    static checkAllowRulesFn(r, name) {
        if (r.isAllowlist()) {
            return new background_UnsupportedModifierError(`Network allowlist rule with ${name} modifier is not supported`, r);
        }
        return null;
    }
    /**
     * Checks if the specified modifier is included in rule explicitly.
     *
     * @param r Network rule.
     * @param name Modifier's name.
     *
     * @returns Error {@link UnsupportedModifierError} or null if rule is supported.
     */
    static checkHasModifierExplicitlyFn(r, name) {
        let nameToCheck = name;
        // Remove leading dollar sign, if any
        if (nameToCheck.startsWith(background_OPTIONS_DELIMITER)) {
            nameToCheck = nameToCheck.slice(background_OPTIONS_DELIMITER.length);
        }
        // Get all used modifier names from the network rule
        const optionNames = r.getUsedOptionNames();
        if (optionNames.has(nameToCheck)) {
            return new background_UnsupportedModifierError(`Network rule with explicitly enabled ${name} modifier is not supported`, r);
        }
        return null;
    }
    /**
     * Checks if the $removeparam values in the provided network rule
     * are supported for conversion to MV3.
     *
     * @param r Network rule.
     * @param name Modifier's name.
     *
     * @returns Error {@link UnsupportedModifierError} or null if rule is supported.
     */
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    static checkRemoveHeaderModifierFn(r, name) {
        const removeHeader = r.getAdvancedModifier();
        if (!removeHeader) {
            return null;
        }
        if (!background_RemoveHeaderModifier.isRemoveHeaderModifier(removeHeader)) {
            return null;
        }
        if (!removeHeader.isValid) {
            return new background_UnsupportedModifierError(
            // eslint-disable-next-line max-len
            'Network rule with $removeheader modifier contains some of the unsupported headers', r);
        }
        return null;
    }
    /**
     * Checks if the $method values in the provided network rule
     * are supported for conversion to MV3.
     *
     * @param r Network rule.
     * @param name Modifier's name.
     *
     * @returns Error {@link UnsupportedModifierError} or null if rule is supported.
     */
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    static checkMethodModifierFn(r, name) {
        const permittedMethods = r.getPermittedMethods();
        const restrictedMethods = r.getRestrictedMethods();
        if (permittedMethods?.some((method) => method === background_HTTPMethod.TRACE)
            || restrictedMethods?.some((method) => method === background_HTTPMethod.TRACE)) {
            return new background_UnsupportedModifierError('Network rule with $method modifier containing \'trace\' method is not supported', r);
        }
        return null;
    }
    /**
     * Checks if the $cookie values in the provided network rule
     * are supported for conversion to MV3.
     *
     * @param r Network rule.
     * @param name Modifier's name.
     *
     * @returns Error {@link UnsupportedModifierError} or null if rule is supported.
     */
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    static checkCookieModifierFn = (r, name) => {
        const cookieModifier = r.getAdvancedModifier();
        if (!cookieModifier) {
            return null;
        }
        if (!background_CookieModifier.isCookieModifier(cookieModifier)) {
            return null;
        }
        if (!cookieModifier.isEmpty()) {
            // eslint-disable-next-line max-len
            const msg = 'The use of additional parameters in $cookie (apart from $cookie itself) is not supported';
            return new background_UnsupportedModifierError(msg, r);
        }
        return null;
    };
    /**
     * Checks if rule is a "document"-allowlist and contains all these
     * `$elemhide,content,urlblock,jsinject` modifiers at the same time.
     * If it is - we allow partially convert this rule, because `$content`
     * is not supported in the MV3 at all and `$jsinject` and `$urlblock`
     * are not implemented yet, but we can support at least allowlist-rule
     * with `$elemhide` modifier (not in the DNR, but with tsurlfilter engine).
     *
     * TODO: Change the description when `$jsinject` and `$urlblock`
     * are implemented.
     *
     * @param r Network rule.
     * @param name Modifier's name.
     *
     * @returns Error {@link UnsupportedModifierError} or null if rule is supported.
     */
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    static checkDocumentAllowlistFn = (r, name) => {
        if (r.isFilteringDisabled()) {
            return null;
        }
        return new background_UnsupportedModifierError(`Network rule with "${name}" modifier is not supported`, r);
    };
    /**
     * The $redirect-rule support will be possible to implement after browsers add this feature:
     * https://github.com/w3c/webextensions/issues/493.
     *
     * @param r Network rule.
     * @param name Modifier's name.
     *
     * @returns Error {@link UnsupportedModifierError} or null if rule is supported.
     */
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    static checkRedirectModifierFn = (r, name) => {
        const isRedirectRule = r.isOptionEnabled(background_NetworkRuleOption.Redirect)
            && r.getAdvancedModifier().isRedirectingOnlyBlocked;
        if (!isRedirectRule) {
            return null;
        }
        return new background_UnsupportedModifierError('Network rule with $redirect-rule modifier is not supported', r);
    };
    static optionsValidators = {
        // Supported
        ThirdParty: { name: '$third-party' },
        MatchCase: { name: '$match-case' },
        Important: { name: '$important' },
        To: { name: '$to' },
        Badfilter: { name: '$badfilter' },
        Permissions: { name: '$permissions' },
        // Supported without conversion.
        Elemhide: { name: '$elemhide', skipConversion: true },
        Generichide: { name: '$generichide', skipConversion: true },
        Specifichide: { name: '$specifichide', skipConversion: true },
        // Partially supported.
        Jsinject: { name: '$jsinject', customChecks: [background_NetworkRuleDeclarativeValidator.checkDocumentAllowlistFn] },
        Urlblock: { name: '$urlblock', customChecks: [background_NetworkRuleDeclarativeValidator.checkDocumentAllowlistFn] },
        Content: { name: '$content', customChecks: [background_NetworkRuleDeclarativeValidator.checkDocumentAllowlistFn] },
        // $popup is not supported in MV3, but rule with $all modifier includes $popup, so we should skip it.
        Popup: { name: '$popup', customChecks: [background_NetworkRuleDeclarativeValidator.checkHasModifierExplicitlyFn] },
        Csp: { name: '$csp', customChecks: [background_NetworkRuleDeclarativeValidator.checkAllowRulesFn] },
        Redirect: {
            // $redirect and $redirect-rule modifiers are falling under this option
            name: '$redirect',
            customChecks: [
                background_NetworkRuleDeclarativeValidator.checkAllowRulesFn,
                background_NetworkRuleDeclarativeValidator.checkRedirectModifierFn,
            ],
        },
        RemoveParam: {
            name: '$removeparam',
            customChecks: [
                background_NetworkRuleDeclarativeValidator.checkAllowRulesFn,
                background_NetworkRuleDeclarativeValidator.checkRemoveParamModifierFn,
            ],
        },
        RemoveHeader: {
            name: '$removeheader',
            customChecks: [
                background_NetworkRuleDeclarativeValidator.checkAllowRulesFn,
                background_NetworkRuleDeclarativeValidator.checkRemoveHeaderModifierFn,
            ],
        },
        Cookie: {
            name: '$cookie',
            customChecks: [
                background_NetworkRuleDeclarativeValidator.checkAllowRulesFn,
                background_NetworkRuleDeclarativeValidator.checkCookieModifierFn,
            ],
        },
        Method: { name: '$method', customChecks: [background_NetworkRuleDeclarativeValidator.checkMethodModifierFn] },
        // Not supported.
        Header: { name: '$header', notSupported: true },
        // Not supported yet.
        Genericblock: { name: '$genericblock', notSupported: true },
        Stealth: { name: '$stealth', notSupported: true },
        // Will not be supported.
        Replace: { name: '$replace', notSupported: true },
        JsonPrune: { name: '$jsonprune', notSupported: true },
        Hls: { name: '$hls', notSupported: true },
        // DNS modifiers.
        Client: { name: '$client', notSupported: true },
        DnsRewrite: { name: '$dnsrewrite', notSupported: true },
        DnsType: { name: '$dnstype', notSupported: true },
        Ctag: { name: '$ctag', notSupported: true },
        // Desktop modifiers only.
        Network: { name: '$network', notSupported: true },
        Extension: { name: '$extension', notSupported: true },
    };
    /**
     * Checks if a network rule can be converted to a declarative format or not.
     * We skip the following modifiers:
     *
     * All specific exceptions:
     * $genericblock;
     * $jsinject;
     * $urlblock;
     * $content;
     * $extension;
     * $stealth;
     *
     * Following specific exceptions are not require conversion, but they
     * are used in the {@link MatchingResult.getCosmeticOption}:
     * $elemhide
     * $generichide;
     * $specifichide;
     *
     * Other:
     * $header;
     * $popup;
     * $csp;
     * $replace;
     * $cookie - if modifier is not empty and contains any parameters;
     * $redirect - if the rule is a allowlist;
     * $removeparam - if it contains a negation, or regexp,
     * or the rule is a allowlist;
     * $removeheader - if it contains a title from a prohibited list
     * (see {@link RemoveHeaderModifier.FORBIDDEN_HEADERS});
     * $jsonprune;
     * $method - if the modifier contains 'trace' method,
     * $hls;
     * $permissions.
     *
     * @param rule - Network rule.
     *
     * @throws Error with type {@link UnsupportedModifierError} if the rule is not
     * convertible.
     *
     * @returns Boolean flag - `false` if the rule does not require conversion
     * and `true` if the rule is convertible.
     */
    static shouldConvertNetworkRule(rule) {
        // Filter NetworkRuleOption.NotSet because this is syntax sugar and
        // not a real valuable option.
        const options = Object.keys(background_NetworkRuleOption).filter((key) => key !== 'NotSet');
        // Because we don't have public getter of rule's options, we need
        // to iterate over all existing network options and check each of them.
        for (const option of options) {
            const networkOption = background_NetworkRuleOption[option];
            if (!rule.isOptionEnabled(networkOption)) {
                continue;
            }
            const validator = this.optionsValidators[option];
            if (!validator) {
                throw new Error(`Validator for option "${option}" is not found`);
            }
            const { name, customChecks, skipConversion, notSupported, } = validator;
            if (notSupported) {
                throw new background_UnsupportedModifierError(`Unsupported option "${name}"`, rule);
            }
            if (skipConversion) {
                if (rule.isSingleOptionEnabled(networkOption)) {
                    return false;
                }
                continue;
            }
            if (customChecks) {
                for (let j = 0; j < customChecks.length; j += 1) {
                    const err = customChecks[j](rule, name);
                    if (err !== null) {
                        throw err;
                    }
                }
            }
        }
        return true;
    }
}

/**
 * Describes error when converted rule contains an empty list of domains, but original contains.
 */
class background_EmptyDomainsError extends background_InvalidDeclarativeRuleError {
    /**
     * Describes error when converted rule contains an empty list of domains, but original contains.
     *
     * @param message Message of error.
     * @param networkRule {@link NetworkRule}.
     * @param declarativeRule {@link DeclarativeRule}.
     */
    constructor(message, networkRule, declarativeRule) {
        super(message, networkRule, declarativeRule);
        this.name = this.constructor.name;
        // For proper work of the "instanceof" operator
        Object.setPrototypeOf(this, background_EmptyDomainsError.prototype);
    }
}

/**
 * Check if the regex is supported in a browser extension using the built-in chrome.declarativeNetRequest API.
 *
 * @param regexFilter Regex to check.
 * @returns Promise that resolves to true if the regex is supported, and rejects with an error otherwise.
 */
const background_regexValidatorExtension = async (regexFilter) => {
    return new Promise((resolve, reject) => {
        if (typeof chrome !== 'undefined' && chrome.declarativeNetRequest) {
            const regexOptions = { regex: regexFilter };
            chrome.declarativeNetRequest.isRegexSupported(regexOptions, (result) => {
                if (chrome.runtime.lastError) {
                    reject(chrome.runtime.lastError);
                }
                else if (result.isSupported) {
                    resolve(true);
                }
                else {
                    reject(new Error(result.reason));
                }
            });
        }
        else {
            reject(new Error('chrome.declarativeNetRequest is not available'));
        }
    });
};

/**
 * Class to manage regex validation using a customizable validator function.
 * By default, it uses the Chrome validator, but a custom validator can be set.
 */
class background_Re2Validator {
    /**
     * The default validator function.
     * By default, it uses the builtin browser validator.
     */
    validator = background_regexValidatorExtension;
    /**
     * Set a custom validator function.
     *
     * @param validator - The custom validator function to use.
     */
    setValidator(validator) {
        this.validator = validator;
    }
    /**
     * Check if the regex is supported using the current validator function.
     *
     * @param regexFilter - The regex pattern to validate.
     * @returns A promise that resolves to true if the regex is supported, false otherwise.
     */
    async isRegexSupported(regexFilter) {
        return this.validator(regexFilter);
    }
}
/**
 * Singleton instance of the Re2Validator class.
 * Provides a single point of access to manage regex validation.
 */
const background_re2Validator = new background_Re2Validator();

/* eslint-disable jsdoc/require-description-complete-sentence */
/* eslint-disable jsdoc/no-multi-asterisks */
/**
 * @file Describes how to convert one {@link NetworkRule} into one or many
 * {@link DeclarativeRule|declarative rules}.
 *
 *      Heir classes                                        DeclarativeRuleConverter
 *
 *                            │                                         │
 *    *override layer*        │              *protected layer*          │              *private layer*
 *                            │                                         │
 *                            │                                         │
 * Subclasses should define   │    Converts a set of indexed rules      │
 * the logic in this method.  │    into declarative rules while         │
 *                            │    handling errors.                     │
 *  ┌─────────────────────┐   │   ┌───────────────────────────┐         │
 *  │                     │   │   │                           │         │
 *  │  abstract convert() ├───┼──►│  protected convertRules() │         │
 *  │                     │   │   │                           │         │
 *  └─────────────────────┘   │   └─────────────┬─────────────┘         │
 *                            │                 │                       │
 *                            │                 │                       │
 *                            │   ┌─────────────▼─────────────┐         │
 *                            │   │                           │         │
 *                            │   │  protected convertRule()  ├─────────┼───────────────────────┐
 *                            │   │                           │         │                       │
 *                            │   └───────────────────────────┘         │                       │
 *                            │   Transforms a single Network Rule      │     ┌─────────────────▼────────────────────┐
 *                            │   into one or several                   │     │                                      │
 *                            │   declarative rules.                    │  ┌──┤ static shouldConvertNetworkRule()    │
 *                            │                                         │  │  │                                      │
 *                            │                                         │  │  └──────────────────────────────────────┘
 *                            │                                         │  │  Checks if network rule conversion
 *                            │                                         │  │  is supported and if it is needed at all.
 *                            │                                         │  │
 *                            │                                         │  │  ┌──────────────────────────┐
 *                            │                                         │  └──►                          │
 *                            │                                         │     │   private getAction()    │
 *                            │                                         │  ┌──┤                          │
 *                            │                                         │  │  └──────────────────────────┘
 *                            │                                         │  │  Generates the action section
 *                            │                                         │  │  of a declarative rule.
 *                            │                                         │  │
 *                            │                                         │  │  ┌────────────────────────────────────┐
 *                            │                                         │  └──►                                    │
 *                            │                                         │     │     private getRedirectAction()    │
 *                            │                                         │     │  static getModifyHeadersAction()   │
 *                            │                                         │     │ static getAddingCspHeadersAction() │
 *                            │                                         │  ┌──┤                                    │
 *                            │                                         │  │  └────────────────────────────────────┘
 *                            │                                         │  │  Modifier-specific methods. A distinct
 *                            │                                         │  │  section will be created for each modifier.
 *                            │                                         │  │
 *                            │                                         │  │  ┌─────────────────────────┐
 *                            │                                         │  └──►                         │
 *                            │                                         │     │  static getCondition()  │
 *                            │                                         │  ┌──┤                         │
 *                            │                                         │  │  └─────────────────────────┘
 *                            │                                         │  │  Generates the condition section
 *                            │                                         │  │  of a declarative rule.
 *                            │                                         │  │
 *                            │                                         │  │  ┌────────────────────────┐
 *                            │                                         │  └──►                        │
 *                            │                                         │     │  static getPriority()  │
 *                            │                                         │  ┌──┤                        │
 *                            │                                         │  │  └────────────────────────┘
 *                            │                                         │  │  Generates the priority of
 *                            │                                         │  │  a declarative rule.
 *                            │                                         │  │
 *                            │                                         │  │  ┌───────────────────────────────────────┐
 *                            │                                         │  └──►                                       │
 *                            │                                         │     │static checkDeclarativeRuleApplicable()│
 *                            │                                         │  ┌──┤                                       │
 *                            │                                         │  │  └───────────────────────────────────────┘
 *                            │                                         │  │  After conversion, checks if the generated
 *                            │                                         │  │  declarative rule contains any unsupported
 *                            │                                         │  │  values.
 *                            │                                         │  │
 *                            │                                         │  │  ┌─────────────────────────────────────┐
 *                            │                                         │  └──►                                     │
 *                            │                                         │     │ static catchErrorDuringConversion() │
 *                            │               ┌─────────────────────────┼─────┤                                     │
 *                            │               │                         │     └─────────────────────────────────────┘
 *                            │   ┌───────────▼────────────────────┐    │     Handles errors during conversion.
 *                            │   │                                │    │
 *                            │   │ protected groupConvertedRules()│    │
 *                            │   │                                │    │
 *                            │   └────────────────────────────────┘    │
 *                            │                                         │
 *                            │   Groups converted declarative rules    │
 *                            │   using the provided grouper-functions. │
 *                            │                                         │
 *                            │   This method is optional and is not    │
 *                            │   used by all derived classes.          │
 *                            │                                         │
 */
/* eslint-enable jsdoc/require-description-complete-sentence */
/* eslint-enable jsdoc/no-multi-asterisks */
/**
 * Contains the generic logic for converting a {@link NetworkRule}
 * into a {@link DeclarativeRule}.
 *
 * Descendant classes must override the {@link DeclarativeRuleConverter.convert} method,
 * where some logic must be defined for each rule type.
 *
 * Also descendant classes can use {@link DeclarativeRuleConverter.convertRules},
 * {@link DeclarativeRuleConverter.convertRule}
 * and {@link DeclarativeRuleConverter.groupConvertedRules} methods, which contains
 * the general logic of transformation and grouping of rules.
 */
class background_DeclarativeRuleConverter {
    /**
     * String path to web accessible resources,
     * relative to the extension root dir.
     * Should start with leading slash '/'.
     */
    webAccessibleResourcesPath;
    /**
     * Creates an instance of DeclarativeRuleConverter.
     *
     * @param webAccessibleResourcesPath Path to web accessible resources.
     */
    constructor(webAccessibleResourcesPath) {
        this.webAccessibleResourcesPath = webAccessibleResourcesPath;
    }
    /**
     * Gets resource type matching request type.
     *
     * @param requestTypes Request type.
     *
     * @returns List of resource types.
     */
    static getResourceTypes(requestTypes) {
        return Object.entries(background_DECLARATIVE_RESOURCE_TYPES_MAP)
            // Skips the first element
            .filter(([, requestType]) => (requestTypes & requestType) === requestType)
            .map(([resourceTypeKey]) => resourceTypeKey);
    }
    /**
     * Converts list of tsurlfilter {@link HTTPMethod|methods} to declarative
     * supported http {@link RequestMethod|methods} via excluding 'trace' method.
     *
     * @param methods List of {@link HTTPMethod|methods}.
     *
     * @returns List of {@link RequestMethod|methods}.
     */
    static mapHttpMethodToDeclarativeHttpMethod(methods) {
        return methods
            // Filters unsupported `trace` method
            .filter((m) => m !== background_HTTPMethod.TRACE)
            // Map tsurlfilter http method to supported declarative http method
            .map((m) => background_DECLARATIVE_REQUEST_METHOD_MAP[m]);
    }
    /**
     * Checks if the string contains only ASCII characters.
     *
     * @param str String to test.
     *
     * @returns True if string contains only ASCII characters.
     */
    static isASCII(str) {
        // eslint-disable-next-line no-control-regex
        return /^[\x00-\x7F]+$/.test(str);
    }
    /**
     * Converts to ASCII characters only if `str` contains non-ASCII characters.
     *
     * @param str String to convert.
     *
     * @returns A transformed string containing only ASCII characters or
     * the original string.
     *
     * @throws Error if conversion into ASCII fails.
     */
    static prepareASCII(str) {
        let res = str;
        try {
            if (!background_DeclarativeRuleConverter.isASCII(res)) {
                // for cyrillic domains we need to convert them by isASCII()
                res = background_punycode.toASCII(res);
            }
            // after toASCII() some characters can be still non-ASCII
            // e.g. `abc“@` with non-ASCII `“`
            if (!background_DeclarativeRuleConverter.isASCII(res)) {
                res = background_punycode.encode(res);
            }
        }
        catch (e) {
            throw new Error(`Error converting to ASCII: "${str}" due to ${background_declarative_converter_getErrorMessage(e)}`);
        }
        return res;
    }
    /**
     * Removes slashes from the beginning and end of the string.
     * We do that because regexFilter does not support them.
     *
     * @param str String to remove slashes.
     * @returns String without slashes.
     */
    static removeSlashes(str) {
        if (str.startsWith('/') && str.endsWith('/')) {
            return str.substring(1, str.length - 1);
        }
        return str;
    }
    /**
     * Converts a list of strings into strings containing only ASCII characters.
     *
     * @param strings List of strings.
     *
     * @returns List of string containing only ASCII characters.
     */
    static toASCII(strings) {
        return strings.map((s) => {
            return background_DeclarativeRuleConverter.prepareASCII(s);
        });
    }
    /**
     * Checks if network rule can be converted to {@link RuleActionType.ALLOW_ALL_REQUESTS}.
     *
     * @param rule Network rule.
     *
     * @returns Is rule compatible with {@link RuleActionType.ALLOW_ALL_REQUESTS}.
     */
    static isCompatibleWithAllowAllRequests(rule) {
        const types = background_DeclarativeRuleConverter.getResourceTypes(rule.getPermittedRequestTypes());
        const allowedRequestTypes = [background_ResourceType.MainFrame, background_ResourceType.SubFrame];
        // If found resource type which is incompatible with allowAllRequest field
        if (types.some((type) => !allowedRequestTypes.includes(type))) {
            return false;
        }
        return true;
    }
    /**
     * Rule priority.
     *
     * @see {@link NetworkRule.getPriorityWeight}
     * @see {@link NetworkRule.priorityWeight}
     * @see {@link NetworkRule.calculatePriorityWeight}
     * @see {@link https://adguard.com/kb/en/general/ad-filtering/create-own-filters/#rule-priorities}
     *
     * @param rule Network rule.
     *
     * @returns Priority of the rule or null.
     */
    static getPriority(rule) {
        return rule.getPriorityWeight();
    }
    /**
     * Rule redirect action.
     *
     * @param rule Network rule.
     *
     * @throws Error {@link ResourcesPathError} when a network rule has
     * a $redirect modifier and no path to web-accessible resources
     * is specified.
     *
     * @returns Redirect, which describes where and how the request
     * should be redirected.
     */
    getRedirectAction(rule) {
        if (rule.isOptionEnabled(background_NetworkRuleOption.Redirect)) {
            const resourcesPath = this.webAccessibleResourcesPath;
            if (!resourcesPath) {
                throw new background_ResourcesPathError('Empty web accessible resources path');
            }
            const advancedModifier = rule.getAdvancedModifier();
            const redirectTo = advancedModifier;
            const filename = background_getRedirectFilename(redirectTo.getValue());
            return { extensionPath: `${resourcesPath}/${filename}` };
        }
        if (rule.isOptionEnabled(background_NetworkRuleOption.RemoveParam)) {
            const advancedModifier = rule.getAdvancedModifier();
            const removeParamModifier = advancedModifier;
            const value = removeParamModifier.getValue();
            if (value === '') {
                return { transform: { query: '' } };
            }
            return {
                transform: {
                    queryTransform: {
                        /**
                         * In case if param is encoded URI we need to decode it first:
                         * https://github.com/AdguardTeam/AdguardBrowserExtension/issues/3014.
                         */
                        removeParams: [decodeURIComponent(value)],
                    },
                },
            };
        }
        return {};
    }
    /**
     * Returns rule modify headers action.
     *
     * @param rule Network rule.
     *
     * @returns Modify headers action, which describes which headers should
     * be changed: added, set or deleted.
     */
    static getModifyHeadersAction(rule) {
        if (!rule.isOptionEnabled(background_NetworkRuleOption.RemoveHeader)) {
            return null;
        }
        const removeHeaderModifier = rule.getAdvancedModifier();
        const removeRequestHeader = removeHeaderModifier.getApplicableHeaderName(true);
        if (removeRequestHeader) {
            return {
                requestHeaders: [{
                        header: removeRequestHeader,
                        operation: background_HeaderOperation.Remove,
                    }],
            };
        }
        const removeResponseHeader = removeHeaderModifier.getApplicableHeaderName(false);
        if (removeResponseHeader) {
            return {
                responseHeaders: [{
                        header: removeResponseHeader,
                        operation: background_HeaderOperation.Remove,
                    }],
            };
        }
        return null;
    }
    /**
     * Returns rule modify headers action with removing Cookie headers from response and request.
     *
     * @param rule Network rule.
     *
     * @returns Add headers action, which describes which headers should be added.
     */
    static getRemovingCookieHeadersAction(rule) {
        if (!rule.isOptionEnabled(background_NetworkRuleOption.Cookie)) {
            return null;
        }
        return {
            responseHeaders: [{
                    operation: background_HeaderOperation.Remove,
                    header: 'Set-Cookie',
                }],
            requestHeaders: [{
                    operation: background_HeaderOperation.Remove,
                    header: 'Cookie',
                }],
        };
    }
    /**
     * Returns rule modify headers action with adding CSP headers to response.
     *
     * @param rule Network rule.
     *
     * @returns Add headers action, which describes what headers should be added.
     */
    static getAddingCspHeadersAction(rule) {
        if (!rule.isOptionEnabled(background_NetworkRuleOption.Csp)) {
            return null;
        }
        const cspHeaderValue = rule.getAdvancedModifierValue();
        if (cspHeaderValue) {
            return {
                operation: background_HeaderOperation.Append,
                header: background_CSP_HEADER_NAME,
                value: cspHeaderValue,
            };
        }
        return null;
    }
    /**
     * Returns rule modify headers action with adding Permissions headers to response.
     *
     * @param rule Network rule.
     *
     * @returns Add headers action, which describes what headers should be added.
     */
    static getAddingPermissionsHeadersAction(rule) {
        if (!rule.isOptionEnabled(background_NetworkRuleOption.Permissions)) {
            return null;
        }
        const permissionsHeaderValue = rule.getAdvancedModifierValue();
        if (permissionsHeaderValue) {
            return {
                operation: background_HeaderOperation.Append,
                header: background_PERMISSIONS_POLICY_HEADER_NAME,
                value: permissionsHeaderValue,
            };
        }
        return null;
    }
    /**
     * Rule action.
     *
     * @param rule Network rule.
     *
     * @throws Error {@link ResourcesPathError} when specified an empty
     * path to the web accessible resources.
     *
     * @returns The action of a rule that describes what should be done
     * with the request.
     */
    getAction(rule) {
        if (rule.isAllowlist()) {
            if (rule.isFilteringDisabled() && background_DeclarativeRuleConverter.isCompatibleWithAllowAllRequests(rule)) {
                return { type: background_RuleActionType.ALLOW_ALL_REQUESTS };
            }
            return { type: background_RuleActionType.ALLOW };
        }
        if (rule.isOptionEnabled(background_NetworkRuleOption.Redirect)
            || rule.isOptionEnabled(background_NetworkRuleOption.RemoveParam)) {
            return {
                type: background_RuleActionType.REDIRECT,
                redirect: this.getRedirectAction(rule),
            };
        }
        if (rule.isOptionEnabled(background_NetworkRuleOption.RemoveHeader)) {
            const modifyHeadersAction = background_DeclarativeRuleConverter.getModifyHeadersAction(rule);
            if (modifyHeadersAction?.requestHeaders) {
                return {
                    type: background_RuleActionType.MODIFY_HEADERS,
                    requestHeaders: modifyHeadersAction.requestHeaders,
                };
            }
            if (modifyHeadersAction?.responseHeaders) {
                return {
                    type: background_RuleActionType.MODIFY_HEADERS,
                    responseHeaders: modifyHeadersAction.responseHeaders,
                };
            }
        }
        if (rule.isOptionEnabled(background_NetworkRuleOption.Csp)) {
            const headersAction = background_DeclarativeRuleConverter.getAddingCspHeadersAction(rule);
            if (headersAction) {
                return {
                    type: background_RuleActionType.MODIFY_HEADERS,
                    responseHeaders: [headersAction],
                };
            }
        }
        if (rule.isOptionEnabled(background_NetworkRuleOption.Permissions)) {
            const headersAction = background_DeclarativeRuleConverter.getAddingPermissionsHeadersAction(rule);
            if (headersAction) {
                return {
                    type: background_RuleActionType.MODIFY_HEADERS,
                    responseHeaders: [headersAction],
                };
            }
        }
        if (rule.isOptionEnabled(background_NetworkRuleOption.Cookie)) {
            const removeCookieHeaders = background_DeclarativeRuleConverter.getRemovingCookieHeadersAction(rule);
            if (removeCookieHeaders) {
                const { responseHeaders, requestHeaders } = removeCookieHeaders;
                return {
                    type: background_RuleActionType.MODIFY_HEADERS,
                    responseHeaders,
                    requestHeaders,
                };
            }
        }
        return { type: background_RuleActionType.BLOCK };
    }
    /**
     * Rule condition.
     *
     * @param rule Network rule.
     *
     * @returns A rule condition that describes to which request the declarative
     * rule should be applied.
     */
    static getCondition(rule) {
        const condition = {};
        const pattern = rule.getPattern();
        if (pattern) {
            // set regexFilter
            if (rule.isRegexRule()) {
                const regexFilter = background_DeclarativeRuleConverter.removeSlashes(pattern);
                condition.regexFilter = background_DeclarativeRuleConverter.prepareASCII(regexFilter);
            }
            else {
                // A pattern beginning with ||* is not allowed. Use * instead.
                const patternWithoutVerticals = pattern.startsWith('||*')
                    ? pattern.substring(2)
                    : pattern;
                condition.urlFilter = background_DeclarativeRuleConverter.prepareASCII(patternWithoutVerticals);
            }
        }
        // set domainType
        if (rule.isOptionEnabled(background_NetworkRuleOption.ThirdParty)) {
            condition.domainType = background_DomainType.ThirdParty;
        }
        else if (rule.isOptionDisabled(background_NetworkRuleOption.ThirdParty)) {
            condition.domainType = background_DomainType.FirstParty;
        }
        // set initiatorDomains
        const permittedDomains = rule.getPermittedDomains()?.filter((d) => {
            // Wildcard and regex domains are not supported by declarative converter
            return !d.includes(background_SimpleRegex.MASK_ANY_CHARACTER) && !background_SimpleRegex.isRegexPattern(d);
        });
        if (permittedDomains && permittedDomains.length > 0) {
            condition.initiatorDomains = this.toASCII(permittedDomains);
        }
        // set excludedInitiatorDomains
        const excludedDomains = rule.getRestrictedDomains();
        if (excludedDomains && excludedDomains.length > 0) {
            condition.excludedInitiatorDomains = this.toASCII(excludedDomains);
        }
        const permittedToDomains = rule.getPermittedToDomains();
        if (permittedToDomains && permittedToDomains.length > 0) {
            condition.requestDomains = this.toASCII(permittedToDomains);
        }
        // Can be specified $to or $denyallow, but not together.
        const denyAllowDomains = rule.getDenyAllowDomains();
        const restrictedToDomains = rule.getRestrictedToDomains();
        if (denyAllowDomains && denyAllowDomains.length !== 0) {
            condition.excludedRequestDomains = this.toASCII(denyAllowDomains);
        }
        else if (restrictedToDomains && restrictedToDomains.length !== 0) {
            condition.excludedRequestDomains = this.toASCII(restrictedToDomains);
        }
        // set excludedResourceTypes
        const restrictedRequestTypes = rule.getRestrictedRequestTypes();
        const hasExcludedResourceTypes = restrictedRequestTypes !== 0;
        if (hasExcludedResourceTypes) {
            condition.excludedResourceTypes = this.getResourceTypes(restrictedRequestTypes);
            /**
             * By default, we do not block the requests that
             * are loaded in the browser tab ("main_frame").
             */
            if (!condition.excludedResourceTypes.includes(background_ResourceType.MainFrame)) {
                condition.excludedResourceTypes.push(background_ResourceType.MainFrame);
            }
        }
        // set resourceTypes
        const permittedRequestTypes = rule.getPermittedRequestTypes();
        if (!hasExcludedResourceTypes && permittedRequestTypes !== 0) {
            condition.resourceTypes = this.getResourceTypes(permittedRequestTypes);
        }
        const permittedMethods = rule.getPermittedMethods();
        if (permittedMethods && permittedMethods.length !== 0) {
            condition.requestMethods = this.mapHttpMethodToDeclarativeHttpMethod(permittedMethods);
        }
        const restrictedMethods = rule.getRestrictedMethods();
        if (restrictedMethods && restrictedMethods.length !== 0) {
            condition.excludedRequestMethods = this.mapHttpMethodToDeclarativeHttpMethod(restrictedMethods);
        }
        // By default, this option is false, so there is no need to specify it everywhere.
        // We do it only if it is true.
        if (rule.isOptionEnabled(background_NetworkRuleOption.MatchCase)) {
            condition.isUrlFilterCaseSensitive = rule.isOptionEnabled(background_NetworkRuleOption.MatchCase);
        }
        /**
         * Adds the main_frame resource type to the resourceTypes if the popup modifier is enabled.
         * Popup rules apply only to document requests, so adding main_frame ensures the rules are correctly applied.
         */
        if (rule.isOptionEnabled(background_NetworkRuleOption.Popup)) {
            condition.resourceTypes = condition.resourceTypes || [];
            if (!condition.resourceTypes.includes(background_ResourceType.MainFrame)) {
                condition.resourceTypes.push(background_ResourceType.MainFrame);
            }
        }
        const emptyResourceTypes = !condition.resourceTypes && !condition.excludedResourceTypes;
        if (emptyResourceTypes) {
            /**
             * Here we need to set 'main_frame' to apply to document requests
             * as well (because by default it applies to all requests except
             * document).
             * And if we specify 'main_frame', then we also need to specify all
             * other types, so that it works not only for document requests, but
             * also for all other types of requests.
             */
            const shouldMatchAllResourcesTypes = rule.isOptionEnabled(background_NetworkRuleOption.RemoveHeader)
                || rule.isOptionEnabled(background_NetworkRuleOption.Csp)
                || rule.isOptionEnabled(background_NetworkRuleOption.Cookie)
                || rule.isOptionEnabled(background_NetworkRuleOption.To)
                || rule.isOptionEnabled(background_NetworkRuleOption.Method);
            /**
             * $permissions and $removeparam modifiers must be applied only
             * to `document` content-type ('main_frame' and 'sub_frame')
             * if they don't have resource types.
             */
            const shouldMatchOnlyDocument = rule.isOptionEnabled(background_NetworkRuleOption.RemoveParam)
                || rule.isOptionEnabled(background_NetworkRuleOption.Permissions);
            if (shouldMatchAllResourcesTypes) {
                condition.resourceTypes = [
                    background_ResourceType.MainFrame,
                    background_ResourceType.SubFrame,
                    background_ResourceType.Stylesheet,
                    background_ResourceType.Script,
                    background_ResourceType.Image,
                    background_ResourceType.Font,
                    background_ResourceType.Object,
                    background_ResourceType.XmlHttpRequest,
                    background_ResourceType.Ping,
                    background_ResourceType.Media,
                    background_ResourceType.WebSocket,
                    background_ResourceType.Other,
                ];
            }
            else if (shouldMatchOnlyDocument) {
                condition.resourceTypes = [background_ResourceType.MainFrame, background_ResourceType.SubFrame];
            }
        }
        return condition;
    }
    /**
     * Converts the network rule into an array of declarative rules.
     *
     * Method to use only in class heirs.
     *
     * @protected
     *
     * @param id Rule identifier.
     * @param rule Network rule.
     *
     * @throws An {@link UnsupportedModifierError} if the network rule
     * contains an unsupported modifier
     * OR an {@link EmptyResourcesError} if there is empty resources in the rule
     * OR an {@link UnsupportedRegexpError} if regexp is not supported in
     * the RE2 syntax.
     * OR a {@link ResourcesPathError} when specified an empty
     * path to the web accessible resources.
     *
     * @returns A list of declarative rules.
     */
    async convertRule(id, rule) {
        // If the rule is not convertible - method will throw an error.
        const shouldConvert = background_NetworkRuleDeclarativeValidator.shouldConvertNetworkRule(rule);
        // The rule does not require conversion.
        if (!shouldConvert) {
            return [];
        }
        const declarativeRule = {
            id,
            action: this.getAction(rule),
            condition: background_DeclarativeRuleConverter.getCondition(rule),
        };
        const priority = background_DeclarativeRuleConverter.getPriority(rule);
        if (priority) {
            declarativeRule.priority = priority;
        }
        const conversionErr = await background_DeclarativeRuleConverter.checkDeclarativeRuleApplicable(rule, declarativeRule);
        if (conversionErr) {
            throw conversionErr;
        }
        return [declarativeRule];
    }
    /**
     * Verifies whether the converted declarative rule passes the regular expression (regexp) validation.
     *
     * Additionally, it checks whether the rule contains resource types.
     *
     * Note: some complex regexps are not allowed,
     * e.g. back references, possessive quantifiers, negative lookaheads.
     *
     * @see {@link https://github.com/google/re2/wiki/Syntax}.
     *
     * @param networkRule The original network rule.
     * @param declarativeRule The converted declarative rule.
     *
     * @returns Different errors:
     * - {@link EmptyResourcesError} if the rule has empty resources,
     * - {@link UnsupportedRegexpError} if the regexp is not supported
     * by RE2 syntax (@see {@link https://github.com/google/re2/wiki/Syntax}),
     * - {@link EmptyDomainsError} if the declarative rule has empty domains
     * while the original rule has non-empty domains.
     */
    static async checkDeclarativeRuleApplicable(networkRule, declarativeRule) {
        const { regexFilter, resourceTypes } = declarativeRule.condition;
        if (resourceTypes?.length === 0) {
            return new background_EmptyResourcesError('Conversion resourceTypes is empty', networkRule, declarativeRule);
        }
        const permittedDomains = networkRule.getPermittedDomains();
        if (permittedDomains && permittedDomains.length > 0) {
            const { initiatorDomains } = declarativeRule.condition;
            if (!initiatorDomains || initiatorDomains.length === 0) {
                const ruleText = networkRule.getText();
                const msg = `Conversion initiatorDomains is empty, but original rule's domains not: "${ruleText}"`;
                return new background_EmptyDomainsError(msg, networkRule, declarativeRule);
            }
        }
        // More complex regex than allowed as part of the "regexFilter" key.
        if (regexFilter) {
            try {
                await background_re2Validator.isRegexSupported(regexFilter);
            }
            catch (e) {
                const ruleText = networkRule.getText();
                const msg = `Regex is unsupported: "${ruleText}"`;
                return new background_UnsupportedRegexpError(msg, networkRule, declarativeRule, background_declarative_converter_getErrorMessage(e));
            }
        }
        return null;
    }
    /**
     * Checks the captured conversion error, if it is one of the expected
     * conversion errors - returns it, otherwise adds information about
     * the original rule, packages it into a new error and returns it.
     *
     * @param rule An error was caught while converting this rule.
     * @param index Index of {@link IndexedNetworkRuleWithHash}.
     * @param id Identifier of the desired declarative rule.
     * @param e Captured error.
     *
     * @returns Initial error or new packaged error.
     */
    static catchErrorDuringConversion(rule, index, id, e) {
        if (e instanceof background_EmptyResourcesError
            || e instanceof background_UnsupportedModifierError
            || e instanceof background_UnsupportedRegexpError
            || e instanceof background_EmptyDomainsError) {
            return e;
        }
        const msg = `Non-categorized error during a conversion rule (index - ${index}, id - ${id})`;
        return e instanceof Error
            ? new Error(msg, { cause: e })
            : new Error(msg);
    }
    /**
     * Converts the provided set of indexed rules into declarative rules,
     * collecting source rule identifiers for declarative rules
     * and catching conversion errors.
     *
     * @param filterId An identifier for the filter.
     * @param rules Indexed rules.
     * @param usedIds Set with already used IDs to exclude duplications in IDs.
     * Since we use hash of the rule text to generate ID, we need to ensure that
     * the ID is unique for the whole ruleset (especially when we convert
     * several filters into one ruleset).
     *
     * @returns Transformed declarative rules with their sources
     * and caught conversion errors.
     */
    async convertRules(filterId, rules, usedIds) {
        const res = {
            declarativeRules: [],
            errors: [],
            sourceMapValues: [],
        };
        await Promise.all(rules.map(async (r) => {
            const { rule, index } = r;
            const id = background_DeclarativeRuleConverter.generateUniqueId(r, usedIds);
            let converted = [];
            try {
                converted = await this.convertRule(id, rule);
            }
            catch (e) {
                const err = background_DeclarativeRuleConverter.catchErrorDuringConversion(rule, index, id, e);
                res.errors.push(err);
                return;
            }
            // For each converted declarative rule save it's source.
            converted.forEach((dRule) => {
                res.sourceMapValues.push({
                    declarativeRuleId: dRule.id,
                    sourceRuleIndex: index,
                    filterId,
                });
                res.declarativeRules.push(dRule);
            });
        }));
        return res;
    }
    /**
     * This function groups similar rules among those already converted into
     * declarative rules. If a similar rule is found, it combines the two
     * declarative rules into one.
     *
     * @param converted An instance of {@link ConvertedRules} that includes
     * converted declarative rules, recorded errors, and a hash mapping
     * declarative rule IDs to corresponding source test rule IDs.
     * @param createRuleTemplate A function that stores the template of
     * a declarative rule. This template is used to compare different
     * declarative rules.
     * @param combineRulePair A function that attempts to find a similar
     * declarative rule by comparing rule templates. If a match is found,
     * it merges the two declarative rules into one and returns combined rule.
     *
     * @returns Object with grouped similar declarative rules.
     */
    // eslint-disable-next-line class-methods-use-this
    groupConvertedRules(converted, createRuleTemplate, combineRulePair) {
        const rulesTemplates = new Map();
        const saveRuleTemplate = (rule) => {
            const template = createRuleTemplate(rule);
            rulesTemplates.set(template, rule);
        };
        const result = {
            declarativeRules: [],
            sourceMapValues: [],
            errors: converted.errors,
        };
        const { sourceMapValues, declarativeRules } = converted;
        declarativeRules.forEach((dRule) => {
            // Trying to find a declarative rule for siblings.
            const template = createRuleTemplate(dRule);
            const siblingDeclarativeRule = rulesTemplates.get(template);
            // Finds the source rule identifier.
            const source = sourceMapValues.find((s) => s.declarativeRuleId === dRule.id);
            if (source === undefined) {
                result.errors.push(new Error(`Cannot find source for converted rule "${dRule}"`));
                return;
            }
            // If a similar rule is found, the function combines the two
            // declarative rules into one and returns the resulting combined rule.
            if (siblingDeclarativeRule) {
                const combinedRule = combineRulePair(siblingDeclarativeRule, dRule);
                // Updates template.
                saveRuleTemplate(combinedRule);
                // Updates the declarative rule identified for the merged rule.
                result.sourceMapValues.push({
                    ...source,
                    declarativeRuleId: combinedRule.id,
                });
            }
            else {
                // If not found - saves the template part of the declarative
                // rule to compare it with next values.
                saveRuleTemplate(dRule);
                // Keeps the source unchanged because the current rule
                // has not been merged.
                result.sourceMapValues.push(source);
            }
        });
        result.declarativeRules = Array.from(rulesTemplates.values());
        return result;
    }
    /**
     * Creates unique ID for rule via adding salt to the hash of the rule if
     * found duplicate ID.
     *
     * @param r Indexed network rule with hash.
     * @param usedIds Set with already used IDs to exclude duplications in IDs.
     *
     * @returns Unique ID for the rule.
     */
    static generateUniqueId(r, usedIds) {
        let id = r.getRuleTextHash();
        // While the ID is already used, we add salt to the hash of the rule.
        let salt = 0;
        while (usedIds.has(id)) {
            salt += 1;
            id = r.getRuleTextHash(salt);
        }
        usedIds.add(id);
        return id;
    }
}

/**
 * @typedef {import('../rules-grouper').RulesGroup} RulesGroup
 */
/**
 * Describes how to convert all rules that are not grouped
 * for separate conversion.
 *
 * @see {@link RulesGroup}
 */
class background_RegularRulesConverter extends background_DeclarativeRuleConverter {
    /**
     * Converts ungrouped, basic indexed rules into declarative rules.
     *
     * @param filterId Filter id.
     * @param rules List of indexed network rules with hash.
     * @param usedIds Set with already used IDs to exclude duplications in IDs.
     *
     * @returns Converted rules.
     */
    convert(filterId, rules, usedIds) {
        return this.convertRules(filterId, rules, usedIds);
    }
}

/**
 * Describes how to convert $removeparam rules.
 */
class background_RemoveParamRulesConverter extends background_DeclarativeRuleConverter {
    /**
     * Converts indexed rules grouped by $removeparam into declarative rules:
     * for each rule looks for similar rules and groups them into a new rule.
     *
     * @param filterId Filter id.
     * @param rules List of indexed network rules with hash.
     * @param usedIds Set with already used IDs to exclude duplications in IDs.
     *
     * @returns Converted rules.
     */
    async convert(filterId, rules, usedIds) {
        const createRuleTemplate = (rule) => {
            // Deep copy without relation to source rule
            // Note: Partial type is used because we need to delete some fields,
            // but we cannot mark them as optional in the parent type.
            const template = JSON.parse(JSON.stringify(rule));
            delete template.id;
            delete template.action?.redirect?.transform?.queryTransform?.removeParams;
            return JSON.stringify(template);
        };
        const combineRulePair = (sourceRule, ruleToMerge) => {
            const resultRule = JSON.parse(JSON.stringify(sourceRule));
            const params = ruleToMerge.action.redirect?.transform?.queryTransform?.removeParams || [];
            resultRule.action.redirect?.transform?.queryTransform?.removeParams?.push(...params);
            return resultRule;
        };
        const converted = await this.convertRules(filterId, rules, usedIds);
        const result = this.groupConvertedRules(converted, createRuleTemplate, combineRulePair);
        return result;
    }
}

/**
 * Describes how to convert $removeheader rules.
 *
 * TODO: Add checks for rules containing the $removeheader and
 * incompatible modifiers: '$domain', '$third-party', '$important', '$app',
 * '$match-case', '$script', '$stylesheet, etc.
 *
 */
class background_RemoveHeaderRulesConverter extends background_DeclarativeRuleConverter {
    /**
     * Converts indexed rules grouped by $removeheader into declarative rules:
     * for each rule looks for similar rules and groups them into a new rule.
     *
     * @param filterId Filter id.
     * @param rules List of indexed network rules with hash.
     * @param usedIds Set with already used IDs to exclude duplications in IDs.
     *
     * @returns Converted rules.
     */
    async convert(filterId, rules, usedIds) {
        const createRuleTemplate = (rule) => {
            // Deep copy without relation to source rule
            const template = JSON.parse(JSON.stringify(rule));
            delete template.id;
            delete template.action.requestHeaders;
            delete template.action.responseHeaders;
            return JSON.stringify(template);
        };
        const combineRulePair = (sourceRule, ruleToMerge) => {
            const resultRule = JSON.parse(JSON.stringify(sourceRule));
            const { responseHeaders, requestHeaders } = ruleToMerge.action;
            if (responseHeaders) {
                if (resultRule.action.responseHeaders) {
                    resultRule.action.responseHeaders.push(...responseHeaders);
                }
                else {
                    resultRule.action.responseHeaders = responseHeaders;
                }
            }
            if (requestHeaders) {
                if (resultRule.action.requestHeaders) {
                    resultRule.action.requestHeaders.push(...requestHeaders);
                }
                else {
                    resultRule.action.requestHeaders = requestHeaders;
                }
            }
            return resultRule;
        };
        const converted = await this.convertRules(filterId, rules, usedIds);
        const result = this.groupConvertedRules(converted, createRuleTemplate, combineRulePair);
        return result;
    }
}

/**
 * Describes how to convert $csp rules.
 */
class background_CspRulesConverter extends background_DeclarativeRuleConverter {
    /**
     * Converts indexed rules grouped by $csp into declarative rules:
     * for each rule looks for similar rules and groups them into a new rule.
     *
     * @param filterId Filter id.
     * @param rules List of indexed rules.
     * @param usedIds Set with already used IDs to exclude duplications in IDs.
     *
     * @returns Converted rules.
     */
    async convert(filterId, rules, usedIds) {
        const createRuleTemplate = (rule) => {
            // Deep copy without relation to source rule
            const template = JSON.parse(JSON.stringify(rule));
            delete template.id;
            // Converted $csp rules contain only one response headers action.
            delete template.action.responseHeaders[0].value;
            return JSON.stringify(template);
        };
        const combineRulePair = (sourceRule, ruleToMerge) => {
            const resultRule = JSON.parse(JSON.stringify(sourceRule));
            // If the headers are empty in the rule to merge, do not take any action.
            if (!ruleToMerge.action.responseHeaders || ruleToMerge.action.responseHeaders.length === 0) {
                return resultRule;
            }
            // Try to find CSP header in the rule to merge - if not found, do not take any action.
            const cspHeaderToMerge = ruleToMerge.action.responseHeaders
                .find((h) => h.header === background_CSP_HEADER_NAME);
            if (!cspHeaderToMerge) {
                return resultRule;
            }
            // Combine the CSP header from the rule to merge with a copy of the source rule.
            if (resultRule.action.responseHeaders && resultRule.action.responseHeaders.length > 0) {
                const idx = resultRule.action.responseHeaders
                    .findIndex((h) => h.header === background_CSP_HEADER_NAME);
                if (idx === -1) {
                    return resultRule;
                }
                const cspHeaderValue = resultRule.action.responseHeaders[idx].value;
                if (cspHeaderValue) {
                    resultRule.action.responseHeaders[idx].value = `${cspHeaderValue}; ${cspHeaderToMerge.value}`;
                }
                else {
                    resultRule.action.responseHeaders[idx].value = cspHeaderToMerge.value;
                }
            }
            else {
                resultRule.action.responseHeaders = [cspHeaderToMerge];
            }
            return resultRule;
        };
        const converted = await this.convertRules(filterId, rules, usedIds);
        const result = this.groupConvertedRules(converted, createRuleTemplate, combineRulePair);
        return result;
    }
}

/**
 * Describes an error when the maximum number of rules is reached and
 * some rules are skipped from scanning.
 */
class background_MaxScannedRulesError extends Error {
    /**
     * Line index of the filter from which the rules are skipped.
     */
    lineIndex;
    /**
     * Describes an error when the maximum number of rules is reached and some
     * rules are skipped from scanning.
     *
     * @param message Message of error.
     * @param lineIndex Line index of the filter from which the rules
     * are skipped.
     */
    constructor(message, lineIndex) {
        super(message);
        this.name = this.constructor.name;
        this.lineIndex = lineIndex;
        // For proper work of the "instanceof" operator
        Object.setPrototypeOf(this, background_MaxScannedRulesError.prototype);
    }
}

/**
 * @typedef {import('../../source-map').Source} Source
 */
/**
 * Describes an error when the maximum number of regexp rules is reached.
 */
class background_TooManyRegexpRulesError extends Error {
    /**
     * List of excluded source (important!) {@link Source} rules ids.
     */
    excludedRulesIds;
    /**
     * Number of maximum rules.
     */
    numberOfMaximumRules;
    /**
     * Number of excluded declarative rules.
     */
    numberOfExcludedDeclarativeRules;
    /**
     * Describes an error when the maximum number of regexp rules is reached.
     *
     * @param message Message of error.
     * @param excludedRulesIds List of excluded source (important!) {@link Source} rules ids.
     * @param numberOfMaximumRules Number of maximum rules.
     * @param numberOfExcludedDeclarativeRules Number of excluded declarative rules.
     */
    constructor(message, excludedRulesIds, numberOfMaximumRules, numberOfExcludedDeclarativeRules) {
        super(message);
        this.name = this.constructor.name;
        this.excludedRulesIds = excludedRulesIds;
        this.numberOfMaximumRules = numberOfMaximumRules;
        this.numberOfExcludedDeclarativeRules = numberOfExcludedDeclarativeRules;
        // For proper work of the "instanceof" operator
        Object.setPrototypeOf(this, background_TooManyRegexpRulesError.prototype);
    }
}

/**
 * @typedef {import('../../source-map').Source} Source
 */
/**
 * Describes an error when the maximum number of unsafe rules is reached.
 */
class background_TooManyUnsafeRulesError extends Error {
    /**
     * List of excluded source (important!) {@link Source} rules ids.
     */
    excludedRulesIds;
    /**
     * Number of maximum rules.
     */
    numberOfMaximumRules;
    /**
     * Number of excluded declarative rules.
     */
    numberOfExcludedDeclarativeRules;
    /**
     * Describes an error when the maximum number of unsafe rules is reached.
     *
     * @param message Message of error.
     * @param excludedRulesIds List of excluded source (important!) {@link Source} rules ids.
     * @param numberOfMaximumRules Number of maximum rules.
     * @param numberOfExcludedDeclarativeRules Number of excluded declarative rules.
     */
    constructor(message, excludedRulesIds, numberOfMaximumRules, numberOfExcludedDeclarativeRules) {
        super(message);
        this.name = this.constructor.name;
        this.excludedRulesIds = excludedRulesIds;
        this.numberOfMaximumRules = numberOfMaximumRules;
        this.numberOfExcludedDeclarativeRules = numberOfExcludedDeclarativeRules;
        // For proper work of the "instanceof" operator
        Object.setPrototypeOf(this, background_TooManyUnsafeRulesError.prototype);
    }
}

/**
 * @typedef {import('../../source-map').Source} Source
 */
/**
 * Describes an error when the maximum number of rules is reached.
 */
class background_TooManyRulesError extends Error {
    /**
     * List of excluded source (important!) {@link Source} rules ids.
     */
    excludedRulesIds;
    /**
     * Number of maximum rules.
     */
    numberOfMaximumRules;
    /**
     * Number of excluded declarative rules.
     */
    numberOfExcludedDeclarativeRules;
    /**
     * Describes an error when the maximum number of rules is reached.
     *
     * @param message Message of error.
     * @param excludedRulesIds List of excluded source (important!) {@link Source} rules ids.
     * @param numberOfMaximumRules Number of maximum rules.
     * @param numberOfExcludedDeclarativeRules Number of excluded declarative rules.
     */
    constructor(message, excludedRulesIds, numberOfMaximumRules, numberOfExcludedDeclarativeRules) {
        super(message);
        this.name = this.constructor.name;
        this.excludedRulesIds = excludedRulesIds;
        this.numberOfMaximumRules = numberOfMaximumRules;
        this.numberOfExcludedDeclarativeRules = numberOfExcludedDeclarativeRules;
        // For proper work of the "instanceof" operator
        Object.setPrototypeOf(this, background_TooManyRulesError.prototype);
    }
}

/**
 * Just a dummy for $badfilter-rules, because they don't need to be converted.
 */
class background_BadFilterRulesConverter extends background_DeclarativeRuleConverter {
    /**
     * Skips converting bad rules.
     *
     * @param filterId Filter id.
     * @param rules List of indexed rules.
     * @param usedIds Set with already used IDs to exclude duplications in IDs.
     *
     * @returns Empty converted rules.
     */
    // eslint-disable-next-line class-methods-use-this
    convert(
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    filterId, 
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    rules, 
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    usedIds) {
        return Promise.resolve({
            sourceMapValues: [],
            declarativeRules: [],
            errors: [],
        });
    }
}

var background_RulesGroup;
(function (RulesGroup) {
    RulesGroup[RulesGroup["Regular"] = 0] = "Regular";
    RulesGroup[RulesGroup["RemoveParam"] = 1] = "RemoveParam";
    RulesGroup[RulesGroup["RemoveHeader"] = 2] = "RemoveHeader";
    RulesGroup[RulesGroup["Csp"] = 3] = "Csp";
    RulesGroup[RulesGroup["BadFilter"] = 4] = "BadFilter";
})(background_RulesGroup || (background_RulesGroup = {}));
/**
 * Contains logic on how to divide the rules into certain groups.
 *
 * @see {@link RulesGroup}
 */
class background_DeclarativeRulesGrouper {
    /**
     * Returns group of the indexed rule.
     *
     * @param indexedNetworkRuleWithHash Indexed network rule with hash.
     *
     * @returns Group of the indexed rule.
     */
    static getRuleGroup(indexedNetworkRuleWithHash) {
        const { rule } = indexedNetworkRuleWithHash;
        if (rule.isOptionEnabled(background_NetworkRuleOption.RemoveParam)) {
            return background_RulesGroup.RemoveParam;
        }
        if (rule.isOptionEnabled(background_NetworkRuleOption.RemoveHeader)) {
            return background_RulesGroup.RemoveHeader;
        }
        if (rule.isOptionEnabled(background_NetworkRuleOption.Csp)) {
            return background_RulesGroup.Csp;
        }
        if (rule.isOptionEnabled(background_NetworkRuleOption.Badfilter)) {
            return background_RulesGroup.BadFilter;
        }
        return background_RulesGroup.Regular;
    }
    /**
     * Splits the list of indexed rules into an index with groups.
     *
     * @param rules List of indexed rules.
     *
     * @returns Index with grouped, indexed rules.
     */
    static splitRulesByGroups(rules) {
        const rulesToProcess = {
            [background_RulesGroup.RemoveParam]: [],
            [background_RulesGroup.RemoveHeader]: [],
            [background_RulesGroup.BadFilter]: [],
            [background_RulesGroup.Regular]: [],
            [background_RulesGroup.Csp]: [],
        };
        // Categorizing rule groups
        rules.forEach((indexedNetworkRuleWithHash) => {
            const group = background_DeclarativeRulesGrouper.getRuleGroup(indexedNetworkRuleWithHash);
            rulesToProcess[group].push(indexedNetworkRuleWithHash);
        });
        return rulesToProcess;
    }
}

/* eslint-disable jsdoc/require-description-complete-sentence  */
/**
 * @file Describes the conversion process from {@link IndexedNetworkRuleWithHash}
 * to declarative rules {@link DeclarativeRule} via applying $badfilter-rules
 * {@link DeclarativeRulesConverter#applyBadFilter} and checks for specified
 * limitations {@link DeclarativeRulesConverter#checkLimitations}.
 *
 *                                                                           Conversion
 *
 *
 *
 *
 *       Two entry points        │                FilterConverter             │             RulesConverter
 *                               │                                            │
 *                               │       Perform the conversion at the        │      Perform the conversion at the
 *                               │       filter level.                        │      rules level.
 *                               │                                            │
 *  Converting static rules      │       Validate passed number of rules      │
 *  during extension assembly.   │       and path to web accessible resources.│
 * ┌─────────────────────────┐   │      ┌────────────────────────────────┐    │
 * │                         ├─┬─┼─────►│                                │    │
 * │  convertStaticRuleSet() │ │ │      │      checkConverterOptions()   │    │
 * │                         │ │ │  ┌───┤                                │    │
 * └─────────────────────────┘ │ │  │   └────────────────────────────────┘    │
 *                             │ │  │                                         │
 *  On-the-fly conversion      │ │  │    Filter only network rules and create │
 *  for dynamic rules.         │ │  │    indexed rule with hash.              │
 * ┌─────────────────────────┐ │ │  │    In this method, when converting      │
 * │                         │ │ │  │    dynamic rules, the rules canceled by │
 * │ convertDynamicRuleSets()├─┘ │  │    $badfilter rules from static filters │
 * │                         │   │  │    are filtered out - such rules are    │
 * └─────────────────────────┘   │  │    discarded during filter scanning.    │
 *                               │  │   ┌────────────────────────────────┐    │
 *                               │  └──►│                                │    │
 *                               │      │ NetworkRulesScanner.scanRules()│    │
 *                               │  ┌───┤                                │    │
 *                               │  │   └────────────────────────────────┘    │  Filter rules affected by $badfilter
 *                               │  │                                         │  within one filter, then group the rules
 *                               │  │                                         │  based on modifiers, requiring specific
 *                               │  │    Convert our network rule to DNR.     │  conversion processes such as
 *                               │  │   ┌────────────────────────────────┐    │  post-processing for similar rules.
 *                               │  └──►│                                │    │   ┌────────────────────────────────┐
 *                               │      │           convert()            ├────┼───┤                                │
 *                               │      │                                │    │   │        applyBadFilter()        │
 *                               │      └────────────────────────────────┘    │ ┌─┤                                │
 *                               │                                            │ │ └────────────────────────────────┘
 *                               │                                            │ │
 *                               │                                            │ │ Each group of rules within a single
 *                               │                                            │ │ filter has its converter that performs
 *                               │                                            │ │ the conversion, then combines the
 *                               │                                            │ │ results and returns them.
 *                               │                                            │ │
 *                               │                                            │ │ For details, please go to the
 *                               │                                            │ │ abstract-rule-converter.ts schema.
 *                               │                                            │ │ ┌────────────────────────────────┐
 *                               │                                            │ └►│                                │
 *                               │                                            │   │          convertRules()        │
 *                               │                                            │ ┌─┤                                │
 *                               │                                            │ │ └────────────────────────────────┘
 *                               │                                            │ │
 *                               │                                            │ │ The declarative rules are checked to
 *                               │                                            │ │ ensure they meet the specified
 *                               │                                            │ │ constraints, and if necessary,
 *                               │                                            │ │ some rules are removed.
 *                               │                                            │ │ ┌────────────────────────────────┐
 *                               │                                            │ └►│                                │
 *                               │                                            │   │         checkLimitations()     │
 *                               │   ┌────────────────────────────────────────┼───┤                                │
 *                               │   │                                        │   └────────────────────────────────┘
 *                               │   │   Wrap conversion result into RuleSet. │
 *                               │   │  ┌────────────────────────────────┐    │
 *                               │   └─►│                                │    │
 *                               │      │    collectConvertedResult()    │    │
 *                               │  ┌───┤                                │    │
 *                               │  │   └────────────────────────────────┘    │
 *                               │  │                                         │
 *                               │  │    This method is only called during the│
 *                               │  │    conversion of dynamic rules.         │
 *                               │  │    Applies rules with $badfilter        │
 *                               │  │    modifier from dynamic rulesets to    │
 *                               │  │    all rules from static rulesets and   │
 *                               │  │    returns list of ids of declarative   │
 *                               │  │    rules to disable them.               │
 *                               │  │   ┌──────────────────────────────────┐  │
 *                               │  └──►│                                  │  │
 *                               │      │ collectDeclarativeRulesToCancel()│  │
 *                               │      │                                  │  │
 *                               │      └──────────────────────────────────┘  │
 *                               │                                            │
 */
/* eslint-enable jsdoc/require-description-complete-sentence */
/**
 * Describes how to convert {@link IndexedNetworkRuleWithHash|indexed network rules}
 * into list of {@link DeclarativeRule|declarative rules}.
 */
class background_DeclarativeRulesConverter {
    /**
     * The declarative identifier of a rule must be a natural number.
     */
    static MIN_DECLARATIVE_RULE_ID = 1;
    /**
     * The declarative identifier of a rule must be less than signed 32-bit
     * integer. The maximum value of a signed 32-bit integer is 2^31 - 1.
     * @see {@link https://groups.google.com/a/chromium.org/g/chromium-extensions/c/yVb56u5Vf0s?}
     */
    static MAX_DECLARATIVE_RULE_ID = 2 ** 31 - 1;
    /**
     * List of declarative rule actions which are considered safe.
     *
     * @see {@link https://developer.chrome.com/docs/extensions/reference/api/declarativeNetRequest#safe_rules}
     */
    static SAFE_RULE_ACTIONS = new Set([
        background_RuleActionType.BLOCK,
        background_RuleActionType.ALLOW,
        background_RuleActionType.ALLOW_ALL_REQUESTS,
        background_RuleActionType.UPGRADE_SCHEME,
    ]);
    /**
     * Describes for which group of rules which converter should be used.
     */
    static converters = {
        [background_RulesGroup.Regular]: background_RegularRulesConverter,
        [background_RulesGroup.Csp]: background_CspRulesConverter,
        [background_RulesGroup.RemoveParam]: background_RemoveParamRulesConverter,
        [background_RulesGroup.RemoveHeader]: background_RemoveHeaderRulesConverter,
        [background_RulesGroup.BadFilter]: background_BadFilterRulesConverter,
    };
    /**
     * Converts list of filters ids with indexed rules to declarative rules:
     * applies $badfilter rules, then for each group of rules (inside one
     * filter) runs specified converter.
     *
     * TODO: The $removeparam, $removeheader, $csp converters can also combine
     * rules across multiple filters.
     *
     * @see {@link DeclarativeRulesConverter.converters}.
     *
     * @param filtersWithRules List of filters ids with indexed rules.
     * @param options Options for conversion.
     *
     * @returns A list of declarative rules, a regexp rule counter,
     * and a list of sourcemap values that contain the relationship between the
     * transformed declarative rule and the source rule.
     */
    static async convert(filtersWithRules, options) {
        const filters = this.applyBadFilter(filtersWithRules);
        let converted = {
            sourceMapValues: [],
            declarativeRules: [],
            errors: [],
        };
        // Set to store unique IDs of declarative rules, it will be modified
        // during the conversion process after each converted rule.
        //
        // Note: since we apply post-converting processing via grouping similar
        // rules for some modifiers, we may have some "released" IDs, but we
        // suppose that 2^31-1 is enough for all rules even with such not used
        // IDs, so to keep the code simple we don't delete them from the set
        // after conversion.
        const uniqueIds = new Set();
        for (const [filterId, groupedRules] of filters) {
            const { sourceMapValues, declarativeRules, errors,
            // eslint-disable-next-line no-await-in-loop
             } = await this.convertRules(filterId, groupedRules, uniqueIds, options);
            converted.sourceMapValues = converted.sourceMapValues.concat(sourceMapValues);
            converted.declarativeRules = converted.declarativeRules.concat(declarativeRules);
            converted.errors = converted.errors.concat(errors);
        }
        converted = this.checkLimitations(converted, options?.maxNumberOfRules, options?.maxNumberOfUnsafeRules, options?.maxNumberOfRegexpRules);
        if (!this.checkRulesHaveUniqueIds(converted.declarativeRules)) {
            throw new Error('Declarative rules have non-unique identifiers.');
        }
        if (!this.checkRulesHaveCorrectIds(converted.declarativeRules)) {
            throw new Error('Declarative rules have incorrect identifiers.');
        }
        return converted;
    }
    /**
     * Converts filter's indexed rules into declarative rules.
     *
     * @param filterId Filed id.
     * @param groupsRules Grouped rules.
     * @param usedIds Set with already used IDs to exclude duplications in IDs.
     * @param options Options for conversion.
     *
     * @returns A list of declarative rules, a regexp rule counter,
     * and a list of sourcemap values that contain the relationship between the
     * transformed declarative rule and the source rule.
     */
    static async convertRules(filterId, groupsRules, usedIds, options) {
        const converted = {
            sourceMapValues: [],
            declarativeRules: [],
            errors: [],
        };
        // Map because RulesGroup values are numbers
        const groups = Object.keys(groupsRules).map(Number);
        await Promise.all(groups.map(async (key) => {
            const converter = new background_DeclarativeRulesConverter.converters[key](options?.resourcesPath);
            const { sourceMapValues, declarativeRules, errors, } = await converter.convert(filterId, groupsRules[key], usedIds);
            converted.sourceMapValues = converted.sourceMapValues.concat(sourceMapValues);
            converted.declarativeRules = converted.declarativeRules.concat(declarativeRules);
            converted.errors = converted.errors.concat(errors);
        }));
        return converted;
    }
    /**
     * Checks that IDs of declarative rules fit into the range of 1 to 2^31-1.
     *
     * This check is needed because we have post-converting grouping rules,
     * where some code could easily change any part of an already converted DNR
     * rule, and we would receive a critical error.
     * That's why we added post-processing checks.
     *
     * @see {@link https://groups.google.com/a/chromium.org/g/chromium-extensions/c/yVb56u5Vf0s?}
     *
     * @param rules List of declarative rules.
     *
     * @returns True if all rules identifiers which fit in allowed range,
     * otherwise false.
     */
    static checkRulesHaveCorrectIds(rules) {
        return rules.every(({ id }) => {
            return id >= this.MIN_DECLARATIVE_RULE_ID && id <= this.MAX_DECLARATIVE_RULE_ID;
        });
    }
    /**
     * Checks that declarative rules have unique identifiers.
     *
     * This check is needed because we have post-converting grouping rules,
     * where some code could easily change any part of an already converted DNR
     * rule, and we would receive a critical error.
     * That's why we added post-processing checks.
     *
     * @param rules List of declarative rules.
     *
     * @returns True if all rules have unique identifiers, otherwise false.
     */
    static checkRulesHaveUniqueIds(rules) {
        const ids = rules.map(({ id }) => id);
        const uniqueIds = new Set(ids);
        return uniqueIds.size === rules.length;
    }
    /**
     * Checks whether the declarative rule is safe.
     *
     * @see {@link https://developer.chrome.com/docs/extensions/reference/api/declarativeNetRequest#safe_rules}
     *
     * @param rule Declarative rule to check.
     *
     * @returns True if the rule is safe, otherwise false.
     */
    static isSafeRule(rule) {
        return this.SAFE_RULE_ACTIONS.has(rule.action.type);
    }
    /**
     * Checks whether the declarative rule is regex.
     *
     * @see {@link https://developer.chrome.com/docs/extensions/reference/api/declarativeNetRequest#property-RuleCondition-regexFilter}
     *
     * @param rule Declarative rule to check.
     *
     * @returns True if the rule is regex, otherwise false.
     */
    static isRegexRule(rule) {
        return rule.condition.regexFilter !== undefined;
    }
    /**
     * Removes sources and errors associated with a truncated rule.
     *
     * @param ruleId The ID of the truncated rule.
     * @param sourcesIndex The index of sources.
     * @param errorsIndex The index of errors.
     * @param excludedRulesIds The list of excluded rule IDs.
     */
    static removeTruncatedRuleSourcesAndErrors(ruleId, sourcesIndex, errorsIndex, excludedRulesIds) {
        // Removing a source for a truncated rule
        const sources = sourcesIndex.get(ruleId) || [];
        const sourcesRulesIds = sources.map(({ sourceRuleIndex }) => sourceRuleIndex);
        sourcesIndex.set(ruleId, []);
        // Removing an error for a truncated rule
        errorsIndex.set(ruleId, []);
        // Note: be sure, that sourceRulesIds are not too much to overflow stack.
        excludedRulesIds.push(...sourcesRulesIds);
    }
    /**
     * Check that declarative rules matches the specified constraints and
     * cuts rules if needed as from list also from source map.
     *
     * @param converted Converted rules, errors, sourcemap and counters.
     * @param maxNumberOfRules Maximum number of converted rules.
     * @param maxNumberOfUnsafeRules Maximum number of converted unsafe rules.
     * @param maxNumberOfRegexpRules Maximum number of converted regexp rules.
     *
     * @returns Transformed converted rules with modified (if abbreviated)
     * counters, declarative rules list, source map and errors.
     */
    static checkLimitations(converted, maxNumberOfRules, maxNumberOfUnsafeRules, maxNumberOfRegexpRules) {
        const limitations = [];
        // We apply restrictions only to transformed rules, so we need to filter
        // rule conversion errors if we remove the transformed rule associated
        // with those errors
        let { declarativeRules, sourceMapValues, errors, } = converted;
        const convertedRulesErrors = [];
        const otherErrors = [];
        for (let i = 0; i < errors.length; i += 1) {
            const e = errors[i];
            // Checks only errors of converted declarative rules
            if (e instanceof background_InvalidDeclarativeRuleError) {
                convertedRulesErrors.push(e);
            }
            else {
                otherErrors.push(e);
            }
        }
        // TODO: Lazy creation of index
        // Create index of errors for fast search and filtering
        const convertedRulesErrorsIndex = new Map();
        convertedRulesErrors.forEach((e) => {
            // Checks only errors of converted declarative rules
            const errorsList = convertedRulesErrorsIndex.get(e.declarativeRule.id);
            const newValue = errorsList
                ? errorsList.concat(e)
                : [e];
            convertedRulesErrorsIndex.set(e.declarativeRule.id, newValue);
        });
        // TODO: Lazy creation of index
        // Create index of sources for fast search and filtering
        const sourcesIndex = new Map();
        sourceMapValues.forEach((source) => {
            const sources = sourcesIndex.get(source.declarativeRuleId);
            const newValue = sources
                ? sources.concat(source)
                : [source];
            sourcesIndex.set(source.declarativeRuleId, newValue);
        });
        // Checks and, if necessary, trims the maximum number of rules
        if (maxNumberOfRules && declarativeRules.length > 0) {
            const filteredRules = [];
            const excludedRulesIds = [];
            let unsafeRulesCounter = 0;
            for (let i = 0; i < declarativeRules.length; i += 1) {
                const rule = declarativeRules[i];
                if (maxNumberOfUnsafeRules && !this.isSafeRule(rule)) {
                    unsafeRulesCounter += 1;
                    if (unsafeRulesCounter > maxNumberOfUnsafeRules) {
                        this.removeTruncatedRuleSourcesAndErrors(rule.id, sourcesIndex, convertedRulesErrorsIndex, excludedRulesIds);
                        continue;
                    }
                }
                if (i < maxNumberOfRules) {
                    filteredRules.push(rule);
                    continue;
                }
                this.removeTruncatedRuleSourcesAndErrors(rule.id, sourcesIndex, convertedRulesErrorsIndex, excludedRulesIds);
            }
            if (maxNumberOfUnsafeRules
                && unsafeRulesCounter > maxNumberOfUnsafeRules) {
                const msg = 'After conversion, too many unsafe rules remain: '
                    + `${unsafeRulesCounter} exceeds `
                    + `the limit provided - ${maxNumberOfUnsafeRules}`;
                const err = new background_TooManyUnsafeRulesError(msg, excludedRulesIds, maxNumberOfUnsafeRules, unsafeRulesCounter - maxNumberOfUnsafeRules);
                limitations.push(err);
            }
            if (declarativeRules.length > maxNumberOfRules) {
                const msg = 'After conversion, too many declarative rules remain: '
                    + `${declarativeRules.length} exceeds `
                    + `the limit provided - ${maxNumberOfRules}`;
                const err = new background_TooManyRulesError(msg, excludedRulesIds, maxNumberOfRules, declarativeRules.length - maxNumberOfRules);
                limitations.push(err);
            }
            declarativeRules = filteredRules;
        }
        // Checks and, if necessary, trims the maximum number of regexp rules
        if (maxNumberOfRegexpRules) {
            const filteredRules = [];
            const excludedRulesIds = [];
            let regexpRulesCounter = 0;
            for (let i = 0; i < declarativeRules.length; i += 1) {
                const rule = declarativeRules[i];
                if (this.isRegexRule(rule)) {
                    regexpRulesCounter += 1;
                    if (regexpRulesCounter > maxNumberOfRegexpRules) {
                        this.removeTruncatedRuleSourcesAndErrors(rule.id, sourcesIndex, convertedRulesErrorsIndex, excludedRulesIds);
                        continue;
                    }
                }
                filteredRules.push(rule);
            }
            if (regexpRulesCounter > maxNumberOfRegexpRules) {
                const msg = 'After conversion, too many regexp rules remain: '
                    + `${regexpRulesCounter} exceeds `
                    + `the limit provided - ${maxNumberOfRegexpRules}`;
                const err = new background_TooManyRegexpRulesError(msg, excludedRulesIds, maxNumberOfRegexpRules, regexpRulesCounter - maxNumberOfRegexpRules);
                limitations.push(err);
            }
            declarativeRules = filteredRules;
        }
        // Make array from index
        sourceMapValues = Array.from(sourcesIndex.values())
            .filter((arr) => arr.length > 0)
            .flat();
        // Make array from index
        errors = Array.from(convertedRulesErrorsIndex.values())
            .filter((arr) => arr.length > 0)
            .flat();
        return {
            sourceMapValues,
            declarativeRules,
            errors: errors.concat(otherErrors),
            limitations,
        };
    }
    /**
     * Filters rules that have been affected by $badfilter rules and
     * groups them by modifiers.
     *
     * @param filtersWithRules List with filters ids and indexed rules.
     *
     * @returns List with filters ids and grouped indexed rules.
     */
    static applyBadFilter(filtersWithRules) {
        let allBadFilterRules = [];
        // Group rules
        const filterIdsWithGroupedRules = filtersWithRules
            .map(({ id, rules }) => {
            const rulesToProcess = background_DeclarativeRulesGrouper.splitRulesByGroups(rules);
            allBadFilterRules = allBadFilterRules.concat(rulesToProcess[background_RulesGroup.BadFilter]);
            const tuple = [id, rulesToProcess];
            return tuple;
        });
        // Define filter function
        const filterByBadFilterFn = (ruleToTest) => {
            const networkRuleToTest = ruleToTest.rule;
            for (const { rule } of allBadFilterRules) {
                if (rule.negatesBadfilter(networkRuleToTest)) {
                    return false;
                }
            }
            return true;
        };
        // For each group of filters' rules apply filter function
        return filterIdsWithGroupedRules.map(([filterId, groupedRules]) => {
            const filtered = groupedRules;
            // Map because RulesGroup values are numbers
            const groups = Object.keys(filtered).map(Number);
            groups.forEach((key) => {
                filtered[key] = filtered[key].filter(filterByBadFilterFn);
            });
            // Clean up bad filters rules
            filtered[background_RulesGroup.BadFilter] = [];
            return [filterId, filtered];
        });
    }
}

/**
 * Contains a dictionary where the key is the hash of the rule and the value is
 * a list of sources for the rule. Storing this dictionary is necessary for fast
 * rule matching, which can be negated by $badfilter.
 */
class background_RulesHashMap {
    map = new Map();
    /**
     * Creates new {@link RulesHashMap}.
     *
     * @param listOfRulesWithHash List of rules hashes and rules sources:
     * filter id with rule index.
     */
    constructor(listOfRulesWithHash) {
        listOfRulesWithHash.forEach(({ hash, source }) => {
            const existingValue = this.map.get(hash);
            if (existingValue) {
                existingValue.push(source);
            }
            else {
                this.map.set(hash, [source]);
            }
        });
    }
    /** @inheritdoc */
    findRules(hash) {
        return this.map.get(hash) || [];
    }
    /**
     * Deserializes dictionary from raw string.
     *
     * @param rawString The original dictionary that was serialized into a string.
     *
     * @returns Deserialized dictionary.
     */
    static deserializeSources(rawString) {
        const plainArray = JSON.parse(rawString);
        const allPairs = plainArray
            .map(([hash, sources]) => {
            return sources.map(([filterId, sourceRuleIndex]) => {
                return {
                    hash,
                    source: {
                        filterId,
                        sourceRuleIndex,
                    },
                };
            });
        })
            .flat();
        return allPairs;
    }
    /** @inheritdoc */
    serialize() {
        const arr = Array.from(this.map);
        const serializedValues = arr
            .map(([hash, source]) => {
            const sources = source.map((s) => {
                return [s.filterId, s.sourceRuleIndex];
            });
            return [hash, sources];
        });
        return JSON.stringify(serializedValues);
    }
}

/**
 * BufferReader is a class responsible for reading content from serialized rules.
 */
class background_BufferReader {
    /**
     * Input byte buffer.
     */
    buffer;
    /**
     * Current position of the reader.
     */
    currentIndex = 0;
    /**
     * Constructor of a BufferReader.
     *
     * @param buffer Uint8Array that contains a UTF-8 encoded string.
     */
    constructor(buffer) {
        this.buffer = buffer;
        this.currentIndex = this.buffer.currentOffset;
    }
    /**
     * Reads the next line in the buffer.
     *
     * @returns Text or null on end.
     */
    readNext() {
        // If the next byte is 0, it means that there's nothing to read.
        if (this.buffer.peekUint8() === 0) {
            return null;
        }
        let ruleNode;
        background_rule_deserializer/* RuleDeserializer */.Y.deserialize(this.buffer, ruleNode = {});
        this.currentIndex = this.buffer.currentOffset;
        if (ruleNode.category) {
            return ruleNode;
        }
        return null;
    }
    /**
     * Returns the current position of this reader or -1 if there's nothing to
     * read.
     *
     * @returns - The current position or -1 if there's nothing to read.
     */
    getCurrentPos() {
        return this.currentIndex;
    }
    /** @inheritdoc */
    getDataLength() {
        return this.buffer.capacity;
    }
}

/**
 * Source map.
 *
 * @note Since serialized rule nodes are not store original rule text, we need this source map between the
 * serialized filter list and the raw filter list.
 */
background_zod_lib/* record */.g1(
/**
 * Rule start index in the converted list's byte buffer.
 */
background_zod_lib/* string */.Yj(), 
/**
 * Rule start index in the raw converted list.
 */
background_zod_lib/* number */.ai());

/**
 * Helper function to get the rule source text from the source string by its line start index.
 *
 * @param lineStartIndex Rule start index.
 * @param source Raw filter list source.
 *
 * @returns Rule string or null if the rule couldn't be found.
 */
const background_getRuleSourceText = (lineStartIndex, source) => {
    // note: checking for LF is enough, because we transform source before storing it, and it's always LF
    let [lineEndIndex] = background_findNextLineBreakIndex(source, lineStartIndex);
    // If the line end index is not found, we assume that the rule is the last line in the source.
    if (lineEndIndex === -1) {
        lineEndIndex = source.length;
    }
    // If the rule start index is equal to or greater than the rule end index, we return null,
    // and the rule is considered not found.
    if (lineStartIndex >= lineEndIndex) {
        return null;
    }
    const ruleSourceText = source.slice(lineStartIndex, lineEndIndex);
    // WARNING!
    // Potential memory leak mitigation for substring operation due to V8 optimizations:
    // When extracting a substring with rule.slice(), there's a concern in some JS environments
    // that the resulting substring might retain a hidden reference to the entire original 'rule' string.
    // This could prevent the garbage collector (GC) from freeing the memory allocated for filter rules.
    // This hidden reference occurs because the substring might not create a new string but rather
    // a view into the original, keeping it in memory longer than necessary.
    // And we receive a memory leak here because we store parsed tags from first N lines of the filter rules
    // which have references to the original large string with filter rules.
    // To ensure that the original large string can be garbage collected, and only the necessary
    // substring is retained, we explicitly force a copy of the substring via split and join,
    // thereby breaking the direct reference to the original string and allowing the GC to free the memory
    // for filter rules when they are no longer in use.
    return ruleSourceText.split('').join('');
};
/**
 * Helper function to get the rule source index (line start index in the source) from the source map by the rule index.
 *
 * @param ruleIdx Rule index.
 * @param sourceMap Source map.
 *
 * @returns Rule source index or RULE_INDEX_NONE (-1).
 *
 * @note Similar to `Array.prototype.indexOf`, we return -1 if the rule index is not found.
 */
const background_getRuleSourceIndex = (ruleIdx, sourceMap) => {
    return sourceMap[ruleIdx] ?? background_RULE_INDEX_NONE;
};

/**
 * FilterScanner returns indexed, only network rules from IFilter's content.
 */
class background_FilterScanner {
    filter;
    filterId;
    /**
     * Constructor of FilterScanner.
     *
     * @param filter From which filter the rules should be scanned.
     * @param filterId Id of filter.
     */
    constructor(filter, filterId) {
        this.filter = filter;
        this.filterId = filterId;
    }
    /**
     * Creates new filter scanner.
     *
     * @param filter From which filter the rules should be scanned.
     *
     * @returns New FilterScanner.
     */
    static async createNew(filter) {
        const content = await filter.getContent();
        return new background_FilterScanner(content, filter.getId());
    }
    /**
     * Gets the entire contents of the filter, extracts only the network rules
     * (ignore cosmetic and host rules) and tries to convert each line into an
     * indexed rule with hash.
     *
     * @param filterFn If this function is specified, it will be applied to each
     * rule after it has been parsed and transformed. This function is needed
     * for example to apply $badfilter: to exclude negated rules from the array
     * of rules that will be returned.
     * @param maxNumberOfScannedNetworkRules Maximum number of network rules to
     * scan, all other rules will be ignored and an error {@link MaxScannedRulesError}
     * will be added to the list of result errors.
     *
     * @returns List of indexed rules with hash. If filterFn was specified then
     * out values will be filtered with this function.
     */
    getIndexedRules(filterFn, maxNumberOfScannedNetworkRules) {
        const { filterList } = this.filter;
        const result = {
            errors: [],
            rules: [],
        };
        const buffer = new background_input_byte_buffer/* InputByteBuffer */.N(filterList);
        const reader = new background_BufferReader(buffer);
        let ruleBufferIndex = reader.getCurrentPos();
        let ruleNode = reader.readNext();
        let curNumberOfScannedNetworkRules = 0;
        while (ruleNode) {
            let indexedNetworkRulesWithHash = [];
            try {
                indexedNetworkRulesWithHash = background_IndexedNetworkRuleWithHash.createFromNode(this.filterId, ruleBufferIndex, ruleNode);
            }
            catch (e) {
                if (e instanceof Error) {
                    result.errors.push(e);
                }
                else {
                    const lineIndex = background_getRuleSourceIndex(ruleBufferIndex, this.filter.sourceMap);
                    const rawRule = background_getRuleSourceText(lineIndex, this.filter.rawFilterList);
                    const originalRawRule = this.filter.conversionMap[lineIndex];
                    // eslint-disable-next-line max-len
                    let errorMessage = `Unknown error during creating indexed rule with hash from raw string: filter id - ${this.filterId}, line index - ${lineIndex}, line - ${rawRule}`;
                    if (originalRawRule) {
                        errorMessage += `, original line - ${originalRawRule}`;
                    }
                    const err = new Error(errorMessage);
                    result.errors.push(err);
                }
                continue;
            }
            finally {
                ruleBufferIndex = reader.getCurrentPos();
                ruleNode = reader.readNext();
            }
            const filteredRules = filterFn
                ? indexedNetworkRulesWithHash.filter(filterFn)
                : indexedNetworkRulesWithHash;
            result.rules.push(...filteredRules);
            curNumberOfScannedNetworkRules += filteredRules.length;
            if (maxNumberOfScannedNetworkRules !== undefined
                && curNumberOfScannedNetworkRules >= maxNumberOfScannedNetworkRules) {
                const lastScannedRule = indexedNetworkRulesWithHash[indexedNetworkRulesWithHash.length - 1];
                const lineIndex = background_getRuleSourceIndex(lastScannedRule.index, this.filter.sourceMap);
                // This error needed for future improvements, for example
                // to show in the UI which rules were skipped.
                const err = new background_MaxScannedRulesError(`Maximum number of scanned network rules reached at line index ${lineIndex}.`, lineIndex);
                result.errors.push(err);
                break;
            }
        }
        return result;
    }
}

/**
 * Scanner for network rules from list of filters.
 */
class background_NetworkRulesScanner {
    /**
     * Asynchronous scans the list of filters for network rules.
     *
     * @param filterList List of {@link IFilter}.
     * @param filterFn If this function is specified, it will be applied to each
     * rule after it has been parsed and transformed. This function is needed
     * for example to apply $badfilter: to exclude negated rules from the array
     * of rules that will be returned.
     * @param maxNumberOfScannedNetworkRules Maximum number of network rules to
     * scan, all other rules will be ignored. It will be applied to each filter
     * separately, not for cumulative scope of rules from all filters, because
     * it looks simpler and more predictable solution to prevent too long scan.
     *
     * @returns List of filters includes the scanned filters and any errors that
     * may occur during the scan.
     */
    static async scanRules(filterList, filterFn, maxNumberOfScannedNetworkRules) {
        const res = {
            errors: [],
            filters: [],
        };
        const promises = filterList.map(async (filter) => {
            const scanner = await background_FilterScanner.createNew(filter);
            const { errors, rules } = scanner.getIndexedRules(filterFn, maxNumberOfScannedNetworkRules);
            res.errors = res.errors.concat(errors);
            const badFilterRules = rules.filter(({ rule }) => {
                return rule.isOptionEnabled(background_NetworkRuleOption.Badfilter);
            });
            return {
                id: filter.getId(),
                rules,
                badFilterRules,
            };
        });
        const tasks = await Promise.allSettled(promises);
        tasks.forEach((task, index) => {
            if (task.status === 'rejected') {
                const filterId = filterList[index].getId();
                res.errors.push(new Error(`Cannot scan rules from filter ${filterId}: ${task.reason}`));
                return;
            }
            res.filters.push(task.value);
        });
        return res;
    }
}

/**
 * @typedef {import('./errors/unavailable-sources-errors').UnavailableFilterSourceError} UnavailableFilterSourceError
 */
/**
 * @typedef {import('./declarative-rule').DeclarativeRule} DeclarativeRule
 */
/* eslint-disable jsdoc/require-description-complete-sentence  */
/**
 * @file Describes the conversion from a filter list {@link IFilter}
 * to rule sets {@link IRuleSet} with declarative rules {@link DeclarativeRule}.
 *
 *                                                                           Conversion
 *
 *
 *
 *
 *       Two entry points        │                FilterConverter             │             RulesConverter
 *                               │                                            │
 *                               │       Perform the conversion at the        │      Perform the conversion at the
 *                               │       filter level.                        │      rules level.
 *                               │                                            │
 *  Converting static rules      │       Validate passed number of rules      │
 *  during extension assembly.   │       and path to web accessible resources.│
 * ┌─────────────────────────┐   │      ┌────────────────────────────────┐    │
 * │                         ├─┬─┼─────►│                                │    │
 * │  convertStaticRuleSet() │ │ │      │      checkConverterOptions()   │    │
 * │                         │ │ │  ┌───┤                                │    │
 * └─────────────────────────┘ │ │  │   └────────────────────────────────┘    │
 *                             │ │  │                                         │
 *  On-the-fly conversion      │ │  │    Filter only network rules and create │
 *  for dynamic rules.         │ │  │    indexed rule with hash.              │
 * ┌─────────────────────────┐ │ │  │    In this method, when converting      │
 * │                         │ │ │  │    dynamic rules, the rules canceled by │
 * │ convertDynamicRuleSets()├─┘ │  │    $badfilter rules from static filters │
 * │                         │   │  │    are filtered out - such rules are    │
 * └─────────────────────────┘   │  │    discarded during filter scanning.    │
 *                               │  │   ┌────────────────────────────────┐    │
 *                               │  └──►│                                │    │
 *                               │      │ NetworkRulesScanner.scanRules()│    │
 *                               │  ┌───┤                                │    │
 *                               │  │   └────────────────────────────────┘    │  Filter rules affected by $badfilter
 *                               │  │                                         │  within one filter, then group the rules
 *                               │  │                                         │  based on modifiers, requiring specific
 *                               │  │    Convert our network rule to DNR.     │  conversion processes such as
 *                               │  │   ┌────────────────────────────────┐    │  post-processing for similar rules.
 *                               │  └──►│                                │    │   ┌────────────────────────────────┐
 *                               │      │           convert()            ├────┼───┤                                │
 *                               │      │                                │    │   │        applyBadFilter()        │
 *                               │      └────────────────────────────────┘    │ ┌─┤                                │
 *                               │                                            │ │ └────────────────────────────────┘
 *                               │                                            │ │
 *                               │                                            │ │ Each group of rules within a single
 *                               │                                            │ │ filter has its converter that performs
 *                               │                                            │ │ the conversion, then combines the
 *                               │                                            │ │ results and returns them.
 *                               │                                            │ │
 *                               │                                            │ │ For details, please go to the
 *                               │                                            │ │ abstract-rule-converter.ts schema.
 *                               │                                            │ │ ┌────────────────────────────────┐
 *                               │                                            │ └►│                                │
 *                               │                                            │   │          convertRules()        │
 *                               │                                            │ ┌─┤                                │
 *                               │                                            │ │ └────────────────────────────────┘
 *                               │                                            │ │
 *                               │                                            │ │ The declarative rules are checked to
 *                               │                                            │ │ ensure they meet the specified
 *                               │                                            │ │ constraints, and if necessary,
 *                               │                                            │ │ some rules are removed.
 *                               │                                            │ │ ┌────────────────────────────────┐
 *                               │                                            │ └►│                                │
 *                               │                                            │   │         checkLimitations()     │
 *                               │   ┌────────────────────────────────────────┼───┤                                │
 *                               │   │                                        │   └────────────────────────────────┘
 *                               │   │   Wrap conversion result into RuleSet. │
 *                               │   │  ┌────────────────────────────────┐    │
 *                               │   └─►│                                │    │
 *                               │      │    collectConvertedResult()    │    │
 *                               │  ┌───┤                                │    │
 *                               │  │   └────────────────────────────────┘    │
 *                               │  │                                         │
 *                               │  │    This method is only called during the│
 *                               │  │    conversion of dynamic rules.         │
 *                               │  │    Applies rules with $badfilter        │
 *                               │  │    modifier from dynamic rulesets to    │
 *                               │  │    all rules from static rulesets and   │
 *                               │  │    returns list of ids of declarative   │
 *                               │  │    rules to disable them.               │
 *                               │  │   ┌──────────────────────────────────┐  │
 *                               │  └──►│                                  │  │
 *                               │      │ collectDeclarativeRulesToCancel()│  │
 *                               │      │                                  │  │
 *                               │      └──────────────────────────────────┘  │
 *                               │                                            │
 */
/* eslint-enable jsdoc/require-description-complete-sentence */
/**
 * Converts a list of IFilters to a single rule set or to a list of rule sets.
 */
class background_DeclarativeFilterConverter {
    /**
     * Same as chrome.declarativeNetRequest.DYNAMIC_RULESET_ID.
     */
    static COMBINED_RULESET_ID = '_dynamic';
    /**
     * Number of scanned rules can be limited via converter options. In this
     * case we increase the limit by 10% to scan more rules in case of some
     * network rules will be combined into one declarative rule. It is safe,
     * because we have double check for maxNumberOfRules on the converted DNR
     * rules.
     */
    static SCANNED_NETWORK_RULES_MULTIPLICATOR = 1.1;
    /**
     * Checks that provided converter options are correct.
     *
     * @param options Contains path to web accessible resources,
     * maximum number of converter rules and regexp rules. @see
     * {@link DeclarativeConverterOptions} for details.
     *
     * @throws An {@link ResourcesPathError} if the resources path does not
     * start with a slash or it ends with a slash
     * OR an {@link EmptyOrNegativeNumberOfRulesError} if maximum number of
     * rules is equal or less than 0.
     * OR an {@link NegativeNumberOfRulesError} if maximum number of
     * regexp rules is less than 0.
     */
    static checkConverterOptions(options) {
        const { resourcesPath, maxNumberOfRules, maxNumberOfUnsafeRules, maxNumberOfRegexpRules, } = options;
        if (resourcesPath !== undefined) {
            const firstChar = 0;
            const lastChar = resourcesPath.length > 0
                ? resourcesPath.length - 1
                : 0;
            if (resourcesPath[firstChar] !== '/') {
                const msg = 'Path to web accessible resources should '
                    + `be started with leading slash: ${resourcesPath}`;
                throw new background_ResourcesPathError(msg);
            }
            if (resourcesPath[lastChar] === '/') {
                const msg = 'Path to web accessible resources should '
                    + `not be ended with slash: ${resourcesPath}`;
                throw new background_ResourcesPathError(msg);
            }
        }
        if (maxNumberOfRules !== undefined && maxNumberOfRules <= 0) {
            const msg = 'Maximum number of rules cannot be equal or less than 0';
            throw new background_EmptyOrNegativeNumberOfRulesError(msg);
        }
        if (maxNumberOfUnsafeRules && maxNumberOfUnsafeRules < 0) {
            const msg = 'Maximum number of unsafe rules cannot be less than 0';
            throw new background_NegativeNumberOfRulesError(msg);
        }
        if (maxNumberOfRegexpRules && maxNumberOfRegexpRules < 0) {
            const msg = 'Maximum number of regexp rules cannot be less than 0';
            throw new background_NegativeNumberOfRulesError(msg);
        }
    }
    /** @inheritdoc */
    // eslint-disable-next-line class-methods-use-this
    async convertStaticRuleSet(filter, options) {
        if (options) {
            background_DeclarativeFilterConverter.checkConverterOptions(options);
        }
        if (options?.maxNumberOfUnsafeRules !== undefined) {
            throw new Error('Static rulesets do not require the maximum number of unsafe rules');
        }
        const { errors, filters } = await background_NetworkRulesScanner.scanRules([filter]);
        const [scannedStaticFilter] = filters;
        const { id, badFilterRules } = scannedStaticFilter;
        const convertedRules = await background_DeclarativeRulesConverter.convert(filters, options);
        const conversionResult = background_DeclarativeFilterConverter.collectConvertedResult(`ruleset_${id}`, [filter], filters, convertedRules, badFilterRules);
        return {
            ruleSet: conversionResult.ruleSet,
            errors: errors.concat(conversionResult.errors),
            limitations: conversionResult.limitations,
        };
    }
    /** @inheritdoc */
    // eslint-disable-next-line class-methods-use-this
    async convertDynamicRuleSets(filterList, staticRuleSets, options) {
        if (options) {
            background_DeclarativeFilterConverter.checkConverterOptions(options);
        }
        const allStaticBadFilterRules = background_DeclarativeFilterConverter.createBadFilterRulesHashMap(staticRuleSets);
        const skipNegatedRulesFn = (r) => {
            const fastMatchedBadFilterRules = allStaticBadFilterRules.get(r.hash);
            if (!fastMatchedBadFilterRules) {
                return true;
            }
            for (let i = 0; i < fastMatchedBadFilterRules.length; i += 1) {
                const rule = fastMatchedBadFilterRules[i];
                const badFilterRule = rule.rule;
                const ruleToCheck = r.rule;
                if (badFilterRule.negatesBadfilter(ruleToCheck)) {
                    return false;
                }
            }
            return true;
        };
        // Note: if we drop some rules because of applying $badfilter - we
        // cannot show info about it to user.
        const scanned = await background_NetworkRulesScanner.scanRules(filterList, skipNegatedRulesFn, 
        // We increase the limit by 10% to scan more rules in case of some
        // network rules will be combined into one declarative rule. It is
        // safe, because we have double check for maxNumberOfRules on the
        // converted DNR rules.
        options?.maxNumberOfRules
            ? Math.ceil(options.maxNumberOfRules * background_DeclarativeFilterConverter.SCANNED_NETWORK_RULES_MULTIPLICATOR)
            : undefined);
        const convertedRules = await background_DeclarativeRulesConverter.convert(scanned.filters, options);
        const dynamicBadFilterRules = scanned.filters
            .map(({ badFilterRules }) => badFilterRules)
            .flat();
        const conversionResult = background_DeclarativeFilterConverter.collectConvertedResult(background_DeclarativeFilterConverter.COMBINED_RULESET_ID, filterList, scanned.filters, convertedRules, dynamicBadFilterRules);
        const { declarativeRulesToCancel, errors } = await background_DeclarativeFilterConverter.collectDeclarativeRulesToCancel(staticRuleSets, dynamicBadFilterRules);
        conversionResult.errors = conversionResult.errors
            .concat(scanned.errors)
            .concat(errors);
        conversionResult.declarativeRulesToCancel = declarativeRulesToCancel;
        return conversionResult;
    }
    /**
     * Collects {@link ConversionResult} from provided list of raw filters,
     * scanned filters, converted rules and bad filter rules.
     * Creates new {@link RuleSet} and wrap all data for {@link RuleSetContentProvider}.
     *
     * @param ruleSetId Rule set id.
     * @param filterList List of raw filters.
     * @param scannedFilters Already scanned filters.
     * @param convertedRules Converted rules.
     * @param badFilterRules List of rules with $badfilter modifier.
     *
     * @returns Item of {@link ConversionResult}.
     */
    static collectConvertedResult(ruleSetId, filterList, scannedFilters, convertedRules, badFilterRules) {
        const { sourceMapValues, declarativeRules, errors, limitations = [], } = convertedRules;
        const ruleSetContent = {
            loadSourceMap: async () => new background_SourceMap(sourceMapValues),
            loadFilterList: async () => filterList,
            loadDeclarativeRules: async () => declarativeRules,
        };
        const listOfRulesWithHash = scannedFilters
            .map(({ id, rules }) => {
            return rules.map((r) => ({
                hash: r.hash,
                source: {
                    sourceRuleIndex: r.index,
                    filterId: id,
                },
            }));
        })
            .flat();
        const rulesHashMap = new background_RulesHashMap(listOfRulesWithHash);
        // calculate number of unsafe rules only for dynamic rules
        const unsafeRulesCount = background_DeclarativeFilterConverter.COMBINED_RULESET_ID === ruleSetId
            ? declarativeRules.filter((r) => !background_DeclarativeRulesConverter.isSafeRule(r)).length
            : 0;
        const regexRulesCount = declarativeRules.filter((r) => background_DeclarativeRulesConverter.isRegexRule(r)).length;
        const ruleSet = new background_RuleSet(ruleSetId, declarativeRules.length, unsafeRulesCount, regexRulesCount, ruleSetContent, badFilterRules, rulesHashMap);
        return {
            ruleSet,
            errors,
            limitations,
        };
    }
    /**
     * Creates dictionary where key is hash of indexed rule and value is array
     * of rules with this hash.
     *
     * @param ruleSets A list of IRuleSets for each of which a list of
     * $badfilter rules.
     *
     * @returns Dictionary with all $badfilter rules which are extracted from
     * rulesets.
     */
    static createBadFilterRulesHashMap(ruleSets) {
        const allStaticBadFilterRules = new Map();
        ruleSets.forEach((ruleSet) => {
            ruleSet.getBadFilterRules().forEach((r) => {
                const existingValue = allStaticBadFilterRules.get(r.hash);
                if (existingValue) {
                    existingValue.push(r);
                }
                else {
                    allStaticBadFilterRules.set(r.hash, [r]);
                }
            });
        });
        return allStaticBadFilterRules;
    }
    /**
     * Checks if some rules (fastMatchedRulesByHash) from the staticRuleSet,
     * which have been fast matched by hash, can be negated with the provided
     * badFilterRule via the `$badfilter` option.
     *
     * @param badFilterRule Network rule with hash {@link IndexedNetworkRuleWithHash}
     * and `$badfilter` option.
     * @param staticRuleSet Static rule set which contains fast matched rules.
     * @param fastMatchedRulesByHash Rules that have been fast matched by hash
     * for potential negation.
     *
     * @returns List of declarative rule IDs that have been canceled by
     * the provided badFilterRule.
     */
    static async checkFastMatchedRulesCanBeCancelled(badFilterRule, staticRuleSet, fastMatchedRulesByHash) {
        const fastMatchedDeclarativeRulesIds = [];
        try {
            const promises = fastMatchedRulesByHash.map(async (source) => {
                return staticRuleSet.getDeclarativeRulesIdsBySourceRuleIndex(source);
            });
            const ids = await Promise.all(promises);
            fastMatchedDeclarativeRulesIds.push(...ids.flat());
        }
        catch (e) {
            // eslint-disable-next-line max-len
            throw new Error(`Not found declarative rule id for some source from list: ${JSON.stringify(fastMatchedDeclarativeRulesIds)}: ${background_declarative_converter_getErrorMessage(e)}`);
        }
        const disableRuleIds = [];
        for (let k = 0; k < fastMatchedDeclarativeRulesIds.length; k += 1) {
            const id = fastMatchedDeclarativeRulesIds[k];
            let matchedSourceRules = [];
            try {
                // eslint-disable-next-line no-await-in-loop
                matchedSourceRules = await staticRuleSet.getRulesById(id);
            }
            catch (e) {
                throw new Error(`Not found sources for declarative rule with id "${id}": ${background_declarative_converter_getErrorMessage(e)}`);
            }
            let indexedNetworkRulesWithHash = [];
            try {
                // eslint-disable-next-line no-await-in-loop
                const arrayWithRules = await Promise.all(matchedSourceRules.map((source) => {
                    return background_RuleSet.getNetworkRuleBySourceRule(source);
                }));
                indexedNetworkRulesWithHash = arrayWithRules.flat();
            }
            catch (e) {
                // eslint-disable-next-line max-len
                throw new Error(`Not found network rules from matched sources "${JSON.stringify(matchedSourceRules)}": ${background_declarative_converter_getErrorMessage(e)}`);
            }
            // NOTE: Here we use .some but not .every to simplify first
            // version of applying $badfilter rules.
            const someRulesMatched = indexedNetworkRulesWithHash
                .flat()
                .some((rule) => badFilterRule.rule.negatesBadfilter(rule));
            if (someRulesMatched) {
                disableRuleIds.push(id);
            }
        }
        return disableRuleIds;
    }
    /**
     * Applies rules with $badfilter modifier from dynamic rulesets to all rules
     * from static rulesets and returns list of ids of declarative rules to
     * disable them.
     *
     * @param staticRuleSets List of converted static rulesets.
     * @param dynamicBadFilterRules List of rules with $badfilter.
     *
     * @returns List of ids of declarative rules to disable them.
     */
    static async collectDeclarativeRulesToCancel(staticRuleSets, dynamicBadFilterRules) {
        const declarativeRulesToCancel = [];
        const errors = [];
        // Check every static ruleset.
        for (let i = 0; i < staticRuleSets.length; i += 1) {
            const staticRuleSet = staticRuleSets[i];
            const disableRuleIds = [];
            // Check every rule with $badfilter from dynamic filters
            // (custom filter and user rules).
            for (let j = 0; j < dynamicBadFilterRules.length; j += 1) {
                const badFilterRule = dynamicBadFilterRules[j];
                const hashMap = staticRuleSet.getRulesHashMap();
                const fastMatchedRulesByHash = hashMap.findRules(badFilterRule.hash);
                if (fastMatchedRulesByHash.length === 0) {
                    continue;
                }
                try {
                    // eslint-disable-next-line no-await-in-loop
                    const ids = await background_DeclarativeFilterConverter.checkFastMatchedRulesCanBeCancelled(badFilterRule, staticRuleSet, fastMatchedRulesByHash);
                    disableRuleIds.push(...ids);
                }
                catch (e) {
                    errors.push(new Error(`Cannot apply badfilter: ${background_declarative_converter_getErrorMessage(e)}`));
                }
            }
            if (disableRuleIds.length > 0) {
                declarativeRulesToCancel.push({
                    rulesetId: staticRuleSet.getId(),
                    disableRuleIds,
                });
            }
        }
        return {
            errors,
            declarativeRulesToCancel,
        };
    }
}

/**
 * Describes an error when filter source is not available.
 */
class background_UnavailableFilterSourceError extends Error {
    filterId;
    /**
     * Describes an error when filter source is not available.
     *
     * @param message Message of error.
     * @param filterId Filter id, the source of which is not available.
     * @param cause Basic error, describes why the source is unavailable.
     */
    constructor(message, filterId, cause) {
        super(message, { cause });
        this.name = this.constructor.name;
        this.filterId = filterId;
        // For proper work of the "instanceof" operator
        Object.setPrototypeOf(this, background_UnavailableFilterSourceError.prototype);
    }
}

/**
 * Saves the original rules and can return all original rules or just one,
 * with lazy content loading.
 */
class background_Filter {
    /**
     * ID of filter.
     */
    id;
    /**
     * Content of filter (lazy loading).
     */
    content = null;
    /**
     * Promise for content loading.
     */
    contentLoadingPromise = null;
    /**
     * Provider of filter content.
     */
    source;
    /**
     * Filter trusted flag.
     */
    trusted;
    /**
     * Creates new FilterList.
     *
     * @param id Number id of filter.
     * @param source Provider of filter content.
     * @param trusted Filter trusted flag.
     */
    constructor(id, source, trusted) {
        this.id = id;
        this.source = source;
        this.trusted = trusted;
    }
    /** @inheritdoc */
    getId() {
        return this.id;
    }
    /** @inheritdoc */
    async getContent() {
        // If content is already loaded, return it
        if (this.content) {
            return this.content;
        }
        // If content is currently loading, return the existing promise
        if (this.contentLoadingPromise) {
            return this.contentLoadingPromise;
        }
        // Assign the promise immediately to avoid race conditions
        this.contentLoadingPromise = (async () => {
            try {
                const content = await this.source.getContent();
                if (!content || content.rawFilterList.length === 0 || content.filterList.length === 0) {
                    throw new Error('Loaded empty content');
                }
                // Assign content and clear the loading promise
                this.content = content;
                this.contentLoadingPromise = null;
                return content;
            }
            catch (e) {
                // Reset the loading promise so future calls can retry
                this.contentLoadingPromise = null;
                throw new background_UnavailableFilterSourceError('Filter content is unavailable', this.id, e);
            }
        })();
        return this.contentLoadingPromise;
    }
    /** @inheritdoc */
    async getRuleByIndex(index) {
        const content = await this.getContent();
        const lineIndex = background_getRuleSourceIndex(index, content.sourceMap);
        const sourceRule = background_getRuleSourceText(lineIndex, content.rawFilterList) ?? background_EMPTY_STRING;
        return sourceRule;
    }
    /** @inheritdoc */
    isTrusted() {
        return this.trusted;
    }
    /** @inheritdoc */
    unloadContent() {
        // If content is not loaded and not loading, there is nothing to unload
        if (!this.content && !this.contentLoadingPromise) {
            return;
        }
        // If loading is in progress
        if (this.contentLoadingPromise) {
            this.contentLoadingPromise.finally(() => {
                this.unloadContent();
            });
            return;
        }
        // Unload content
        this.content = null;
        this.contentLoadingPromise = null;
    }
}

/**
 * @file Various type guards.
 */
/**
 * Checks whether the given value is undefined.
 *
 * @param value Value to check.
 *
 * @returns `true` if the value is 'undefined', `false` otherwise.
 */
/**
 * Checks whether the given value is an array.
 *
 * @param value Value to check.
 *
 * @returns `true` if the value is an array, `false` otherwise.
 */
const background_isArray = (value) => {
    return Array.isArray(value);
};
/**
 * Checks whether the given value is a non-empty array.
 *
 * @param value Value to check.
 *
 * @returns `true` if the value is a non-empty array, `false` otherwise.
 */
const background_isNonEmptyArray = (value) => {
    return background_isArray(value) && value.length > 0;
};

/**
 * Helper method to get the rule set ID with the {@link RULESET_NAME_PREFIX} prefix.
 *
 * @param ruleSetId Rule set id. Can be a number or a string.
 *
 * @returns Rule set ID with the {@link RULESET_NAME_PREFIX} prefix.
 */
function background_getRuleSetId(ruleSetId) {
    let ruleSetIdStr = String(ruleSetId);
    if (!ruleSetIdStr.startsWith(background_RULESET_NAME_PREFIX)) {
        ruleSetIdStr = `${background_RULESET_NAME_PREFIX}${ruleSetIdStr}`;
    }
    return ruleSetIdStr;
}

/**
 * Metadata ruleset ID.
 */
const background_METADATA_RULESET_ID = 0;
/**
 * Checksum map validator.
 */
const background_checksumMapValidator = background_zod_lib/* record */.g1(background_zod_lib/* string */.Yj());
/**
 * Metadata validator.
 */
const background_metadataValidator = background_zod_lib/* object */.Ik({
    /**
     * Checksums for all rulesets.
     */
    checksums: background_checksumMapValidator,
    /**
     * Additional properties.
     * This field stores any extra information not covered by the other fields.
     * The content of this field is not validated, but it must be JSON serializable.
     * Validation should be performed by users.
     */
    additionalProperties: background_zod_lib/* record */.g1(background_zod_lib/* unknown */.L5()),
});
/**
 * Metadata rule validator.
 *
 * @note We use `passthrough` method to allow additional fields in the object.
 */
const background_metadataRuleValidator = background_zod_lib/* object */.Ik({
    metadata: background_metadataValidator,
}).passthrough();
/**
 * Represents a specialized metadata ruleset for managing and validating metadata associated
 * with various rulesets.
 *
 * This class handles byte range maps, checksums, and additional properties,
 * providing methods to manipulate and query this metadata.
 */
class background_MetadataRuleSet {
    metadataRule;
    /**
     * Creates an instance of the MetadataRuleSet class.
     *
     * @param checksums A map of checksums, where each key corresponds to a rule set ID and each value is the checksum
     * for that ruleset. Defaults to an empty object.
     * @param additionalProperties A collection of additional properties, where keys are property names and values are
     * their associated data. These properties are JSON serializable but not validated by the class.
     * Defaults to an empty object.
     *
     * @note
     * This constructor uses references for the provided arguments. If immutability is required, ensure to clone the
     * inputs before passing them.
     */
    constructor(checksums = {}, additionalProperties = {}) {
        this.metadataRule = background_createMetadataRule({
            byteRangeMapsCollection: {},
            checksums,
            additionalProperties: additionalProperties ?? {},
        });
    }
    /**
     * Returns rule set id.
     *
     * @returns Rule set id.
     */
    // Note: we prefer `instance.getId()` over `MetadataRuleSet.getId(instance)` for consistency.
    // eslint-disable-next-line class-methods-use-this
    getId() {
        return background_getRuleSetId(background_METADATA_RULESET_ID);
    }
    /**
     * Sets checksum for the specified rule set.
     *
     * @param ruleSetId Rule set id.
     * @param checksum Checksum.
     */
    setChecksum(ruleSetId, checksum) {
        this.metadataRule.metadata.checksums[ruleSetId] = checksum;
    }
    /**
     * Returns checksum for the specified rule set.
     *
     * @param ruleSetId Rule set id.
     *
     * @returns Checksum or undefined if not found.
     */
    getChecksum(ruleSetId) {
        return this.metadataRule.metadata.checksums[ruleSetId];
    }
    /**
     * Returns all rule set ids in the metadata.
     *
     * @returns Rule set ids.
     */
    getRuleSetIds() {
        return Object.keys(this.metadataRule.metadata.checksums);
    }
    /**
     * Gets additional property.
     *
     * @param key Property key.
     *
     * @returns Property value or undefined if not found.
     */
    getAdditionalProperty(key) {
        return this.metadataRule.metadata.additionalProperties[key];
    }
    /**
     * Sets additional property.
     *
     * @param key Property key.
     * @param value Property value. Should be JSON serializable.
     */
    setAdditionalProperty(key, value) {
        this.metadataRule.metadata.additionalProperties[key] = value;
    }
    /**
     * Checks whether additional property exists.
     *
     * @param key Property key.
     *
     * @returns Whether the property exists.
     */
    hasAdditionalProperty(key) {
        return key in this.metadataRule.metadata.additionalProperties;
    }
    /**
     * Removes additional property.
     *
     * @param key Property key.
     */
    removeAdditionalProperty(key) {
        delete this.metadataRule.metadata.additionalProperties[key];
    }
    /**
     * Serializes the ruleset to a string.
     *
     * @param pretty Whether to prettify the output.
     *
     * @returns Serialized ruleset.
     */
    serialize(pretty = false) {
        return background_serializeJson([this.metadataRule], pretty);
    }
    /**
     * Deserializes the ruleset from a string.
     *
     * @param rawJson Serialized ruleset.
     *
     * @returns Deserialized ruleset.
     *
     * @throws Error if the input is invalid.
     */
    static deserialize(rawJson) {
        const parsed = JSON.parse(rawJson);
        if (!background_isNonEmptyArray(parsed)) {
            throw new Error('Invalid input: expected a non-empty array.');
        }
        const { metadata: { checksums, additionalProperties, }, } = background_metadataRuleValidator.parse(parsed[0]);
        const ruleSet = new background_MetadataRuleSet(checksums, additionalProperties);
        return ruleSet;
    }
}



;// ./Extension/src/common/messages/constants.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ /**
 * Important: do not use z.inferOf, because it brings a lot of side effects with
 * many dependencies to the bundle.
 *
 * Also please try, if possible, to not import here external modules
 * other that types.
 */ const background_APP_MESSAGE_HANDLER_NAME = 'app';
/**
 * Message types used for message passing between extension contexts
 * (popup, filtering log, content scripts, background)
 */ var background_constants_MessageType = /*#__PURE__*/ function(MessageType) {
    MessageType["CreateEventListener"] = "createEventListener";
    MessageType["RemoveListener"] = "removeListener";
    MessageType["OpenExtensionStore"] = "openExtensionStore";
    MessageType["AddAndEnableFilter"] = "addAndEnableFilter";
    MessageType["ApplySettingsJson"] = "applySettingsJson";
    MessageType["OpenFilteringLog"] = "openFilteringLog";
    MessageType["OpenFullscreenUserRules"] = "openFullscreenUserRules";
    MessageType["UpdateFullscreenUserRulesTheme"] = "updateFullscreenUserRulesTheme";
    MessageType["ResetBlockedAdsCount"] = "resetBlockedAdsCount";
    MessageType["ResetSettings"] = "resetSettings";
    MessageType["GetUserRules"] = "getUserRules";
    MessageType["SaveUserRules"] = "saveUserRules";
    MessageType["GetAllowlistDomains"] = "getAllowlistDomains";
    MessageType["SaveAllowlistDomains"] = "saveAllowlistDomains";
    MessageType["CheckFiltersUpdate"] = "checkFiltersUpdate";
    MessageType["DisableFiltersGroup"] = "disableFiltersGroup";
    MessageType["DisableFilter"] = "disableFilter";
    MessageType["LoadCustomFilterInfo"] = "loadCustomFilterInfo";
    MessageType["SubscribeToCustomFilter"] = "subscribeToCustomFilter";
    MessageType["RemoveAntiBannerFilter"] = "removeAntiBannerFilter";
    MessageType["GetIsEngineStarted"] = "getIsEngineStarted";
    MessageType["GetTabInfoForPopup"] = "getTabInfoForPopup";
    MessageType["ChangeApplicationFilteringPaused"] = "changeApplicationFilteringPaused";
    MessageType["OpenRulesLimitsTab"] = "openRulesLimitsTab";
    MessageType["OpenSettingsTab"] = "openSettingsTab";
    MessageType["OpenAssistant"] = "openAssistant";
    MessageType["OpenAbuseTab"] = "openAbuseTab";
    MessageType["OpenSiteReportTab"] = "openSiteReportTab";
    MessageType["OpenComparePage"] = "openComparePage";
    MessageType["ResetUserRulesForPage"] = "resetUserRulesForPage";
    MessageType["RemoveAllowlistDomain"] = "removeAllowlistDomain";
    MessageType["AddAllowlistDomain"] = "addAllowlistDomain";
    MessageType["OnOpenFilteringLogPage"] = "onOpenFilteringLogPage";
    MessageType["GetFilteringLogData"] = "getFilteringLogData";
    MessageType["InitializeFrameScript"] = "initializeFrameScript";
    MessageType["OnCloseFilteringLogPage"] = "onCloseFilteringLogPage";
    MessageType["GetFilteringInfoByTabId"] = "getFilteringInfoByTabId";
    MessageType["SynchronizeOpenTabs"] = "synchronizeOpenTabs";
    MessageType["ClearEventsByTabId"] = "clearEventsByTabId";
    MessageType["RefreshPage"] = "refreshPage";
    MessageType["AddUserRule"] = "addUserRule";
    MessageType["RemoveUserRule"] = "removeUserRule";
    MessageType["EnableFiltersGroup"] = "enableFiltersGroup";
    MessageType["NotifyListeners"] = "notifyListeners";
    MessageType["AddLongLivedConnection"] = "addLongLivedConnection";
    MessageType["GetOptionsData"] = "getOptionsData";
    MessageType["ChangeUserSettings"] = "changeUserSetting";
    MessageType["CheckRequestFilterReady"] = "checkRequestFilterReady";
    MessageType["OpenThankyouPage"] = "openThankYouPage";
    MessageType["OpenSafebrowsingTrusted"] = "openSafebrowsingTrusted";
    MessageType["GetSelectorsAndScripts"] = "getSelectorsAndScripts";
    MessageType["CheckPageScriptWrapperRequest"] = "checkPageScriptWrapperRequest";
    MessageType["ProcessShouldCollapse"] = "processShouldCollapse";
    MessageType["ProcessShouldCollapseMany"] = "processShouldCollapseMany";
    MessageType["AddFilteringSubscription"] = "addFilterSubscription";
    MessageType["SetNotificationViewed"] = "setNotificationViewed";
    MessageType["SaveCssHitsStats"] = "saveCssHitStats";
    MessageType["GetCookieRules"] = "getCookieRules";
    MessageType["SaveCookieLogEvent"] = "saveCookieRuleEvent";
    MessageType["LoadSettingsJson"] = "loadSettingsJson";
    MessageType["AddUrlToTrusted"] = "addUrlToTrusted";
    MessageType["SetPreserveLogState"] = "setPreserveLogState";
    MessageType["GetUserRulesEditorData"] = "getUserRulesEditorData";
    MessageType["GetEditorStorageContent"] = "getEditorStorageContent";
    MessageType["SetEditorStorageContent"] = "setEditorStorageContent";
    MessageType["SetFilteringLogWindowState"] = "setFilteringLogWindowState";
    MessageType["AppInitialized"] = "appInitialized";
    MessageType["UpdateTotalBlocked"] = "updateTotalBlocked";
    MessageType["ScriptletCloseWindow"] = "scriptletCloseWindow";
    MessageType["ShowRuleLimitsAlert"] = "showRuleLimitsAlert";
    MessageType["ShowAlertPopup"] = "showAlertPopup";
    MessageType["ShowVersionUpdatedPopup"] = "showVersionUpdatedPopup";
    MessageType["UpdateListeners"] = "updateListeners";
    MessageType["SetConsentedFilters"] = "setConsentedFilters";
    MessageType["GetIsConsentedFilter"] = "getIsConsentedFilter";
    MessageType["GetRulesLimitsCountersMv3"] = "getRulesLimitsCountersMv3";
    MessageType["CanEnableStaticFilterMv3"] = "canEnableStaticFilterMv3";
    MessageType["CanEnableStaticGroupMv3"] = "canEnableStaticGroupMv3";
    MessageType["ClearRulesLimitsWarningMv3"] = "clearRulesLimitsWarningMv3";
    MessageType["RestoreFiltersMv3"] = "restoreFiltersMv3";
    MessageType["CurrentLimitsMv3"] = "currentLimitsMv3";
    return MessageType;
}({});

;// ./Extension/src/common/messages/send-message.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

/**
 * TODO: Consider moving this file to the background folder, because all messages
 * from the UI should be send via methods of Messenger class instead of using
 * directly sendMessage to proper types checking.
 *
 * {@link sendMessage} sends app message via {@link browser.runtime.sendMessage} and
 * gets response from another extension page message handler
 *
 * @param message - partial {@link Message} record without {@link Message.handlerName} field
 *
 * @returns message handler response
 */ async function background_sendMessage(message) {
    try {
        return await background_browser_polyfill_default().runtime.sendMessage({
            handlerName: background_APP_MESSAGE_HANDLER_NAME,
            ...message
        });
    } catch (e) {
    // do nothing
    }
}
/**
 * {@link sendTabMessage} sends message to specified tab via {@link browser.tabs.sendMessage} and
 * gets response from it
 *
 * @param tabId - tab id
 * @param message - partial {@link Message} record without {@link Message.handlerName} field
 *
 * @returns tab message handler response
 */ async function background_sendTabMessage(tabId, message) {
    return background_browser_polyfill_default().tabs.sendMessage(tabId, {
        handlerName: background_APP_MESSAGE_HANDLER_NAME,
        ...message
    });
}

;// ./Extension/src/common/messages/message-handler.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}



/**
 * Type guard for messages that have a 'type' field with possible {@link MessageType}.
 *
 * @note Added to no bring here huge zod library.
 *
 * @param message Unknown message.
 *
 * @returns True if message has 'type' field with possible {@link MessageType}.
 */ const background_messageHasTypeField = (message)=>{
    return typeof message === 'object' && message !== null && 'type' in message;
};
/**
 * Type guard for messages that have a 'type' field and 'data' field and looks like {@link Message}.
 *
 * @note Added to no bring here huge zod library.
 *
 * @param message Unknown message.
 *
 * @returns True if message has 'type' and 'data' fields and looks like {@link Message}.
 */ const background_messageHasTypeAndDataFields = (message)=>{
    return background_messageHasTypeField(message) && 'data' in message;
};
/**
 * API for handling Messages via {@link browser.runtime.onMessage}
 */ class background_MessageHandler {
    init() {
        background_browser_polyfill_default().runtime.onMessage.addListener(this.handleMessage);
    }
    /**
     * Add message listener.
     * Listeners limited to 1 per message type to prevent race
     * condition while response processing.
     *
     * TODO: implement listeners priority execution strategy
     *
     * @param type - {@link ValidMessageTypes}
     * @param listener - {@link MessageListener}
     *
     * @throws error, if message listener already added
     */ addListener(type, listener) {
        if (this.listeners.has(type)) {
            throw new Error(`Message handler: ${type} listener has already been registered`);
        }
        // Cast through unknown to help TS understand that the listener is of
        // the correct type. It will check types at compile time.
        this.listeners.set(type, listener);
    }
    /**
     * Removes message listener.
     *
     * @param type - {@link ValidMessageTypes}
     */ removeListener(type) {
        this.listeners.delete(type);
    }
    /**
     * Removes all listeners
     */ removeListeners() {
        this.listeners.clear();
    }
    /**
     * Check if the message is of type {@link Message}.
     *
     * @param message Message of basic type {@link Message} or {@link EngineMessage}.
     *
     * @returns True if the message is of type {@link Message}.
     */ static isValidMessageType(message) {
        return message.handlerName === background_APP_MESSAGE_HANDLER_NAME && 'type' in message;
    }
    constructor(){
        background_define_property(this, "listeners", new Map());
        this.handleMessage = this.handleMessage.bind(this);
    }
}

;// ./Extension/src/common/messages/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 



// EXTERNAL MODULE: ./node_modules/.pnpm/core-js@3.40.0/node_modules/core-js/modules/es.array.push.js
var background_es_array_push = __webpack_require__(10474);
// EXTERNAL MODULE: ./node_modules/.pnpm/core-js@3.40.0/node_modules/core-js/modules/web.self.js
var background_web_self = __webpack_require__(91219);
;// ./node_modules/.pnpm/@adguard+logger@1.1.1/node_modules/@adguard/logger/dist/es/index.mjs
/**
 * Checks if error has message.
 *
 * @param error Error object.
 * @returns True if error has message.
 */
function background_es_isErrorWithMessage(error) {
    return (typeof error === 'object'
        && error !== null
        && 'message' in error
        && typeof error.message === 'string');
}
/**
 * Converts error to the error with a message.
 *
 * @param maybeError Possible error.
 * @returns Error with a message.
 */
function background_es_toErrorWithMessage(maybeError) {
    if (background_es_isErrorWithMessage(maybeError)) {
        return maybeError;
    }
    try {
        return new Error(JSON.stringify(maybeError));
    }
    catch {
        // fallback in case there's an error stringifying the maybeError
        // like with circular references, for example.
        return new Error(String(maybeError));
    }
}
/**
 * Converts an error object to an error with a message. This method might be helpful to handle thrown errors.
 *
 * @param error Error object.
 *
 * @returns Message of the error.
 */
function background_es_getErrorMessage(error) {
    return background_es_toErrorWithMessage(error).message;
}

/**
 * Pads a number with leading zeros.
 * @param num The number to pad.
 * @param size The number of digits to pad to.
 * @returns The padded number.
 */
const background_pad = (num, size = 2) => {
    return num.toString().padStart(size, '0');
};
/**
 * Formats a date into an ISO 8601-like string with milliseconds.
 *
 * @param {Date|number} date The date object or timestamp to format.
 * @returns {string} The formatted date string.
 */
const background_formatTime = (date) => {
    const d = (date instanceof Date) ? date : new Date(date);
    const year = d.getFullYear();
    const month = background_pad(d.getMonth() + 1); // Months are 0-based
    const day = background_pad(d.getDate());
    const hour = background_pad(d.getHours());
    const minute = background_pad(d.getMinutes());
    const second = background_pad(d.getSeconds());
    const millisecond = background_pad(d.getMilliseconds(), 3); // Milliseconds are 3 digits
    return `${year}-${month}-${day}T${hour}:${minute}:${second}:${millisecond}`;
};

/**
 * String presentation of log levels, for convenient users usage.
 */
var background_LogLevel;
(function (LogLevel) {
    LogLevel["Error"] = "error";
    LogLevel["Warn"] = "warn";
    LogLevel["Info"] = "info";
    LogLevel["Debug"] = "debug";
    LogLevel["Trace"] = "trace";
})(background_LogLevel || (background_LogLevel = {}));
/**
 * Log levels map, which maps number level to string level.
 */
const background_levelMapNumToString = {
    [1 /* LogLevelNumeric.Error */]: background_LogLevel.Error,
    [2 /* LogLevelNumeric.Warn */]: background_LogLevel.Warn,
    [3 /* LogLevelNumeric.Info */]: background_LogLevel.Info,
    [4 /* LogLevelNumeric.Debug */]: background_LogLevel.Debug,
    [5 /* LogLevelNumeric.Trace */]: background_LogLevel.Trace,
};
/**
 * Log levels map, which maps string level to number level.
 */
const background_levelMapStringToNum = Object.entries(background_levelMapNumToString)
    .reduce((acc, [key, value]) => {
    // Here, key is originally a string since Object.entries() returns [string, string][].
    // We need to cast the key to LogLevelNumeric correctly without causing type mismatches.
    const numericKey = Number(key);
    if (!Number.isNaN(numericKey)) {
        acc[value] = numericKey;
    }
    return acc;
}, {});
/**
 * Simple logger with log levels.
 */
class background_Logger {
    currentLevelValue = 3 /* LogLevelNumeric.Info */;
    writer;
    /**
     * Constructor.
     * @param writer Writer object.
     */
    constructor(writer = console) {
        this.writer = writer;
        // bind the logging methods to avoid losing context
        this.debug = this.debug.bind(this);
        this.info = this.info.bind(this);
        this.warn = this.warn.bind(this);
        this.error = this.error.bind(this);
    }
    /**
     * Print debug messages. Usually used for technical information.
     * Will be printed in 'log' channel.
     *
     * @param args Printed arguments.
     */
    debug(...args) {
        this.print(4 /* LogLevelNumeric.Debug */, "log" /* LogMethod.Log */, args);
    }
    /**
     * Print messages you want to disclose to users.
     *
     * @param args Printed arguments.
     */
    info(...args) {
        this.print(3 /* LogLevelNumeric.Info */, "info" /* LogMethod.Info */, args);
    }
    /**
     * Print warn messages.
     * NOTE: We do not use 'warn' channel, since in the extensions warn is
     * counted as error. Instead of this we use 'info' channel.
     *
     * @param args Printed arguments.
     */
    warn(...args) {
        this.print(2 /* LogLevelNumeric.Warn */, "info" /* LogMethod.Info */, args);
    }
    /**
     * Print error messages.
     *
     * @param args Printed arguments.
     */
    error(...args) {
        this.print(1 /* LogLevelNumeric.Error */, "error" /* LogMethod.Error */, args);
    }
    /**
     * Getter for log level.
     * @returns Logger level.
     */
    get currentLevel() {
        return background_levelMapNumToString[this.currentLevelValue];
    }
    /**
     * Setter for log level. With this method log level can be updated dynamically.
     *
     * @param logLevel Logger level.
     * @throws Error if log level is not supported.
     */
    set currentLevel(logLevel) {
        const level = background_levelMapStringToNum[logLevel];
        if (level === undefined) {
            throw new Error(`Logger supports only the following levels: ${[Object.values(background_LogLevel).join(', ')]}`);
        }
        this.currentLevelValue = level;
    }
    /**
     * Converts error to string, and adds stack trace.
     *
     * @param error Error to print.
     * @private
     * @returns Error message.
     */
    static errorToString(error) {
        const message = background_es_getErrorMessage(error);
        return `${message}\nStack trace:\n${error.stack}`;
    }
    /**
     * Wrapper over log methods.
     *
     * @param level Logger level.
     * @param method Logger method.
     * @param args Printed arguments.
     * @private
     */
    print(level, method, args) {
        // skip writing if the basic conditions are not met
        if (this.currentLevelValue < level) {
            return;
        }
        if (!args || args.length === 0 || !args[0]) {
            return;
        }
        const formattedArgs = args.map((value) => {
            if (value instanceof Error) {
                return background_Logger.errorToString(value);
            }
            if (value && typeof value.message === 'string') {
                return value.message;
            }
            if (typeof value === 'object' && value !== null) {
                return JSON.stringify(value);
            }
            return String(value);
        });
        const formattedTime = `${background_formatTime(new Date())}:`;
        /**
         * Conditions in which trace can happen:
         * 1. Method is not error (because console.error provides call stack trace)
         * 2. Log level is equal or higher that `LogLevel.Trace`.
         * 3. Writer has `trace` method.
         */
        if (method === "error" /* LogMethod.Error */
            || this.currentLevelValue < background_levelMapStringToNum[background_LogLevel.Trace]
            || !this.writer.trace) {
            // Print with regular method
            this.writer[method](formattedTime, ...formattedArgs);
            return;
        }
        if (!this.writer.groupCollapsed || !this.writer.groupEnd) {
            // Print expanded trace
            this.writer.trace(formattedTime, ...formattedArgs);
            return;
        }
        // Print collapsed trace
        this.writer.groupCollapsed(formattedTime, ...formattedArgs);
        this.writer.trace();
        this.writer.groupEnd();
    }
}



;// ./Extension/src/common/logger.ts
/**
 * @file
 *
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

class background_ExtendedLogger extends background_Logger {
    isVerbose() {
        return this.currentLevel === background_LogLevel.Debug || this.currentLevel === background_LogLevel.Trace;
    }
}
const background_logger_logger = new background_ExtendedLogger();
background_logger_logger.currentLevel =  true ? background_LogLevel.Info : 0;
// Expose logger to the window object,
// to have possibility to switch log level from the console.
// Example: adguard.logger.currentLevel = 'debug'
// eslint-disable-next-line no-restricted-globals
Object.assign(self, {
    adguard: {
        ...self.adguard,
        logger: background_logger_logger
    }
});


;// ./Extension/src/common/constants.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ /**
 * Current version of app storage data schema.
 *
 * Schema version is used on extension version update.
 *
 * Note: Do not to be confused with the protocol version of the imported config.
 */ const background_APP_SCHEMA_VERSION = 11;
const background_CLIENT_ID_KEY = 'client-id';
const background_APP_VERSION_KEY = 'app-version';
const background_SCHEMA_VERSION_KEY = 'schema-version';
const background_ADGUARD_SETTINGS_KEY = 'adguard-settings';
const background_PAGE_STATISTIC_KEY = 'page-statistic';
const background_TRUSTED_DOCUMENTS_CACHE_KEY = 'trusted-documents';
const background_SB_LRU_CACHE_KEY = 'sb-lru-cache';
const background_SB_SUSPENDED_CACHE_KEY = 'safebrowsing-suspended-from';
const background_VIEWED_NOTIFICATIONS_KEY = 'viewed-notifications';
const background_LAST_NOTIFICATION_TIME_KEY = 'viewed-notification-time';
const background_FILTERING_LOG_WINDOW_STATE = 'filtering-log-window-state';
const background_HIT_STATISTIC_KEY = 'filters-hit-count';
const background_ANNOYANCES_CONSENT_KEY = 'annoyances-consent';
const background_RULES_LIMITS_KEY = 'rules-limits';
// Filter ids used in the code on the background page and filtering log page
var background_AntiBannerFiltersId = /*#__PURE__*/ function(AntiBannerFiltersId) {
    AntiBannerFiltersId[AntiBannerFiltersId["StealthModeFilterId"] = -1] = "StealthModeFilterId";
    AntiBannerFiltersId[AntiBannerFiltersId["UserFilterId"] = 0] = "UserFilterId";
    AntiBannerFiltersId[AntiBannerFiltersId["EnglishFilterId"] = 2] = "EnglishFilterId";
    AntiBannerFiltersId[AntiBannerFiltersId["TrackingFilterId"] = 3] = "TrackingFilterId";
    AntiBannerFiltersId[AntiBannerFiltersId["SocialFilterId"] = 4] = "SocialFilterId";
    AntiBannerFiltersId[AntiBannerFiltersId["SearchAndSelfPromoFilterId"] = 10] = "SearchAndSelfPromoFilterId";
    AntiBannerFiltersId[AntiBannerFiltersId["AnnoyancesCombinedFilterId"] = 14] = "AnnoyancesCombinedFilterId";
    AntiBannerFiltersId[AntiBannerFiltersId["UrlTrackingFilterId"] = 17] = "UrlTrackingFilterId";
    AntiBannerFiltersId[AntiBannerFiltersId["QuickFixesFilterId"] = 24] = "QuickFixesFilterId";
    AntiBannerFiltersId[AntiBannerFiltersId["AllowlistFilterId"] = 100] = "AllowlistFilterId";
    AntiBannerFiltersId[AntiBannerFiltersId["MobileAdsFilterId"] = 11] = "MobileAdsFilterId";
    return AntiBannerFiltersId;
}({});
// Group ids used in the code on the multiple entry points
var background_AntibannerGroupsId = /*#__PURE__*/ function(AntibannerGroupsId) {
    // custom filters group identifier
    AntibannerGroupsId[AntibannerGroupsId["CustomFiltersGroupId"] = 0] = "CustomFiltersGroupId";
    AntibannerGroupsId[AntibannerGroupsId["AdBlockingFiltersGroupId"] = 1] = "AdBlockingFiltersGroupId";
    AntibannerGroupsId[AntibannerGroupsId["PrivacyFiltersGroupId"] = 2] = "PrivacyFiltersGroupId";
    AntibannerGroupsId[AntibannerGroupsId["SocialFiltersGroupId"] = 3] = "SocialFiltersGroupId";
    AntibannerGroupsId[AntibannerGroupsId["AnnoyancesFiltersGroupId"] = 4] = "AnnoyancesFiltersGroupId";
    AntibannerGroupsId[AntibannerGroupsId["SecurityFiltersGroupId"] = 5] = "SecurityFiltersGroupId";
    // other filters group identifier
    AntibannerGroupsId[AntibannerGroupsId["OtherFiltersGroupId"] = 6] = "OtherFiltersGroupId";
    // language-specific group identifier
    AntibannerGroupsId[AntibannerGroupsId["LanguageFiltersGroupId"] = 7] = "LanguageFiltersGroupId";
    return AntibannerGroupsId;
}({});
/**
 * Recommended filters tag ID.
 *
 * @see https://github.com/AdguardTeam/FiltersRegistry/blob/4528f7ae6b38aec90111a27efb0a7e0958d0cf37/tags/metadata.json#L40
 */ const background_RECOMMENDED_TAG_ID = 10;
/**
 * Enum with the list of the messages which are sent from the background
 * to notify UI about some events, e.g. some field in settings was updated.
 */ var background_constants_NotifierType = /*#__PURE__*/ function(NotifierType) {
    NotifierType["RequestFilterUpdated"] = "event.request.filter.updated";
    NotifierType["UserFilterUpdated"] = "event.user.filter.updated";
    NotifierType["CustomFilterAdded"] = "event.custom.filter.added";
    NotifierType["UpdateAllowlistFilterRules"] = "event.update.allowlist.filter.rules";
    NotifierType["SettingUpdated"] = "event.update.setting.value";
    NotifierType["FiltersUpdateCheckReady"] = "event.update.filters.check";
    // Filtering log events.
    NotifierType["TabAdded"] = "log.tab.added";
    NotifierType["TabClose"] = "log.tab.close";
    NotifierType["TabUpdate"] = "log.tab.update";
    NotifierType["TabReset"] = "log.tab.reset";
    // Fullscreen user rules events
    NotifierType["FullscreenUserRulesEditorUpdated"] = "event.user.rules.editor.updated";
    return NotifierType;
}({});
const background_constants_KEEP_ALIVE_PORT_NAME = 'keep-alive';
var background_NavigationTag = /*#__PURE__*/ function(NavigationTag) {
    NavigationTag["Regular"] = "regular";
    NavigationTag["Party"] = "party";
    return NavigationTag;
}({});
/**
 * Trusted tag for custom filters
 */ const background_TRUSTED_TAG_KEYWORD = 'trusted';
/**
 * Trusted tag id for custom filters.
 */ const background_TRUSTED_TAG_ID = 999;
/**
 * Custom filters group display number
 */ const background_CUSTOM_FILTERS_GROUP_DISPLAY_NUMBER = 99;
/**
 * Custom filters identifiers starts from this number
 */ const background_CUSTOM_FILTERS_START_ID = 1000;
// Unnecessary characters that will be replaced
const background_WASTE_CHARACTERS = /[.*+?^${}()|[\]\\]/g;
// Custom scrollbar width
const background_SCROLLBAR_WIDTH = 12;
const background_BACKGROUND_TAB_ID = (/* unused pure expression or super */ null && (-1));
const background_TOTAL_BLOCKED_STATS_GROUP_ID = 'total';
/**
 *  Time interval between filter updates.
 */ var background_FiltersUpdateTime = /*#__PURE__*/ function(FiltersUpdateTime) {
    FiltersUpdateTime[FiltersUpdateTime["Disabled"] = 0] = "Disabled";
    FiltersUpdateTime[FiltersUpdateTime["OneHour"] = 3600000] = "OneHour";
    FiltersUpdateTime[FiltersUpdateTime["SixHours"] = 21600000] = "SixHours";
    FiltersUpdateTime[FiltersUpdateTime["TwelveHours"] = 43200000] = "TwelveHours";
    FiltersUpdateTime[FiltersUpdateTime["TwentyFourHours"] = 86400000] = "TwentyFourHours";
    FiltersUpdateTime[FiltersUpdateTime["FortyEightHours"] = 172800000] = "FortyEightHours";
    FiltersUpdateTime[FiltersUpdateTime["Default"] = -1] = "Default";
    return FiltersUpdateTime;
}({});
const background_NEWLINE_CHAR_UNIX = '\n';
const background_NEWLINE_CHAR_REGEX = /\r?\n/;
const background_OPTIONS_PAGE = 'pages/options.html';
const background_FILTER_LIST_EXTENSION = '.txt';
/**
 * Special event name for extension initialization, needed for run automatic
 * integration tests.
 */ const background_EXTENSION_INITIALIZED_EVENT = 'initialized';
/**
 * This is just a syntax sugar for setting default value if we not have
 * preprocessed list for user rules or for custom filters.
 */ const background_emptyPreprocessedFilterList = {
    filterList: [],
    sourceMap: {},
    rawFilterList: '',
    conversionMap: {}
};

;// ./node_modules/.pnpm/zod-validation-error@3.4.0_zod@3.21.4/node_modules/zod-validation-error/dist/index.mjs
// lib/isZodErrorLike.ts
function background_isZodErrorLike(err) {
  return err instanceof Error && err.name === "ZodError" && "issues" in err && Array.isArray(err.issues);
}

// lib/ValidationError.ts
var background_ValidationError = class extends Error {
  name;
  details;
  constructor(message, options) {
    super(message, options);
    this.name = "ZodValidationError";
    this.details = background_getIssuesFromErrorOptions(options);
  }
  toString() {
    return this.message;
  }
};
function background_getIssuesFromErrorOptions(options) {
  if (options) {
    const cause = options.cause;
    if (background_isZodErrorLike(cause)) {
      return cause.issues;
    }
  }
  return [];
}

// lib/isValidationError.ts
function background_isValidationError(err) {
  return err instanceof background_ValidationError;
}

// lib/isValidationErrorLike.ts
function background_isValidationErrorLike(err) {
  return err instanceof Error && err.name === "ZodValidationError";
}

// lib/fromZodIssue.ts


// lib/MessageBuilder.ts


// lib/utils/NonEmptyArray.ts
function background_dist_isNonEmptyArray(value) {
  return value.length !== 0;
}

// lib/utils/joinPath.ts
var background_identifierRegex = /[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u;
function background_joinPath(path) {
  if (path.length === 1) {
    return path[0].toString();
  }
  return path.reduce((acc, item) => {
    if (typeof item === "number") {
      return acc + "[" + item.toString() + "]";
    }
    if (item.includes('"')) {
      return acc + '["' + background_escapeQuotes(item) + '"]';
    }
    if (!background_identifierRegex.test(item)) {
      return acc + '["' + item + '"]';
    }
    const separator = acc.length === 0 ? "" : ".";
    return acc + separator + item;
  }, "");
}
function background_escapeQuotes(str) {
  return str.replace(/"/g, '\\"');
}

// lib/config.ts
var background_ISSUE_SEPARATOR = "; ";
var background_MAX_ISSUES_IN_MESSAGE = 99;
var background_PREFIX = "Validation error";
var background_PREFIX_SEPARATOR = ": ";
var background_UNION_SEPARATOR = ", or ";

// lib/MessageBuilder.ts
function background_createMessageBuilder(props = {}) {
  const {
    issueSeparator = background_ISSUE_SEPARATOR,
    unionSeparator = background_UNION_SEPARATOR,
    prefixSeparator = background_PREFIX_SEPARATOR,
    prefix = background_PREFIX,
    includePath = true,
    maxIssuesInMessage = background_MAX_ISSUES_IN_MESSAGE
  } = props;
  return (issues) => {
    const message = issues.slice(0, maxIssuesInMessage).map(
      (issue) => background_getMessageFromZodIssue({
        issue,
        issueSeparator,
        unionSeparator,
        includePath
      })
    ).join(issueSeparator);
    return background_prefixMessage(message, prefix, prefixSeparator);
  };
}
function background_getMessageFromZodIssue(props) {
  const { issue, issueSeparator, unionSeparator, includePath } = props;
  if (issue.code === background_lib/* ZodIssueCode */.eq.invalid_union) {
    return issue.unionErrors.reduce((acc, zodError) => {
      const newIssues = zodError.issues.map(
        (issue2) => background_getMessageFromZodIssue({
          issue: issue2,
          issueSeparator,
          unionSeparator,
          includePath
        })
      ).join(issueSeparator);
      if (!acc.includes(newIssues)) {
        acc.push(newIssues);
      }
      return acc;
    }, []).join(unionSeparator);
  }
  if (issue.code === background_lib/* ZodIssueCode */.eq.invalid_arguments) {
    return [
      issue.message,
      ...issue.argumentsError.issues.map(
        (issue2) => background_getMessageFromZodIssue({
          issue: issue2,
          issueSeparator,
          unionSeparator,
          includePath
        })
      )
    ].join(issueSeparator);
  }
  if (issue.code === background_lib/* ZodIssueCode */.eq.invalid_return_type) {
    return [
      issue.message,
      ...issue.returnTypeError.issues.map(
        (issue2) => background_getMessageFromZodIssue({
          issue: issue2,
          issueSeparator,
          unionSeparator,
          includePath
        })
      )
    ].join(issueSeparator);
  }
  if (includePath && background_dist_isNonEmptyArray(issue.path)) {
    if (issue.path.length === 1) {
      const identifier = issue.path[0];
      if (typeof identifier === "number") {
        return `${issue.message} at index ${identifier}`;
      }
    }
    return `${issue.message} at "${background_joinPath(issue.path)}"`;
  }
  return issue.message;
}
function background_prefixMessage(message, prefix, prefixSeparator) {
  if (prefix !== null) {
    if (message.length > 0) {
      return [prefix, message].join(prefixSeparator);
    }
    return prefix;
  }
  if (message.length > 0) {
    return message;
  }
  return background_PREFIX;
}

// lib/fromZodIssue.ts
function background_fromZodIssue(issue, options = {}) {
  const messageBuilder = background_createMessageBuilderFromOptions(options);
  const message = messageBuilder([issue]);
  return new background_ValidationError(message, { cause: new zod2.ZodError([issue]) });
}
function background_createMessageBuilderFromOptions(options) {
  if ("messageBuilder" in options) {
    return options.messageBuilder;
  }
  return background_createMessageBuilder(options);
}

// lib/errorMap.ts
var background_errorMap = (issue, ctx) => {
  const error = background_fromZodIssue({
    ...issue,
    // fallback to the default error message
    // when issue does not have a message
    message: issue.message ?? ctx.defaultError
  });
  return {
    message: error.message
  };
};

// lib/fromZodError.ts
function background_fromZodError(zodError, options = {}) {
  if (!background_isZodErrorLike(zodError)) {
    throw new TypeError(
      `Invalid zodError param; expected instance of ZodError. Did you mean to use the "${background_fromError.name}" method instead?`
    );
  }
  return background_fromZodErrorWithoutRuntimeCheck(zodError, options);
}
function background_fromZodErrorWithoutRuntimeCheck(zodError, options = {}) {
  const zodIssues = zodError.errors;
  let message;
  if (background_dist_isNonEmptyArray(zodIssues)) {
    const messageBuilder = background_createMessageBuilderFromOptions2(options);
    message = messageBuilder(zodIssues);
  } else {
    message = zodError.message;
  }
  return new background_ValidationError(message, { cause: zodError });
}
function background_createMessageBuilderFromOptions2(options) {
  if ("messageBuilder" in options) {
    return options.messageBuilder;
  }
  return background_createMessageBuilder(options);
}

// lib/toValidationError.ts
var background_toValidationError = (options = {}) => (err) => {
  if (background_isZodErrorLike(err)) {
    return background_fromZodErrorWithoutRuntimeCheck(err, options);
  }
  if (err instanceof Error) {
    return new background_ValidationError(err.message, { cause: err });
  }
  return new background_ValidationError("Unknown error");
};

// lib/fromError.ts
function background_fromError(err, options = {}) {
  return background_toValidationError(options)(err);
}

//# sourceMappingURL=index.mjs.map
;// ./Extension/src/common/error.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 


const background_NETWORK_ERROR_MESSAGES = new Set([
    'network error',
    'Failed to fetch',
    'NetworkError when attempting to fetch resource.'
]);
/**
 * Checks if error has message.
 *
 * @param error Error object.
 */ function background_error_isErrorWithMessage(error) {
    return typeof error === 'object' && error !== null && 'message' in error && typeof error.message === 'string';
}
/**
 * Checks if the error is ErrorLike.
 *
 * @param error Error object.
 */ function background_isErrorLike(error) {
    return background_error_isErrorWithMessage(error) && 'name' in error && typeof error.name === 'string';
}
/**
 * Converts error to the error with message.
 *
 * @param maybeError Possible error.
 */ function background_error_toErrorWithMessage(maybeError) {
    if (background_error_isErrorWithMessage(maybeError)) {
        return maybeError;
    }
    try {
        return new Error(JSON.stringify(maybeError));
    } catch  {
        // fallback in case there's an error stringifying the maybeError
        // like with circular references for example.
        return new Error(String(maybeError));
    }
}
/**
 * Converts error object to error with message. This method might be helpful to handle thrown errors.
 *
 * @param error Error object.
 *
 * @returns Message of the error.
 */ function background_error_getErrorMessage(error) {
    // Special case: pretty print Zod errors
    if (error instanceof background_lib/* ZodError */.G) {
        return background_fromZodError(error).toString();
    }
    return background_error_toErrorWithMessage(error).message;
}
/**
 * Checks if the error is a network error.
 *
 * @param error Error object.
 *
 * @returns True if the error is a network error, false otherwise.
 */ function background_isNetworkError(error) {
    // Check if the error is an instance of ErrorLike and is not a TypeError
    if (!background_isErrorLike(error) || error.name !== 'TypeError') {
        return false;
    }
    // Check if the error message is in the set of network error messages
    return background_NETWORK_ERROR_MESSAGES.has(error.message);
}

;// ./Extension/src/common/guards.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ /**
 * Checks if value is number.
 *
 * @param value
 */ function background_guards_isNumber(value) {
    return value != null && value !== '' && !Number.isNaN(Number(value));
}


;// ./node_modules/.pnpm/@adguard+translate@1.0.2/node_modules/@adguard/translate/dist/index.esm.js
function background_index_esm_defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function background_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}

function background_defineProperties(target, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target, descriptor.key, descriptor);
  }
}

function background_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) background_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) background_defineProperties(Constructor, staticProps);
  return Constructor;
}

function background_arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length) len = arr.length;

  for (var i = 0, arr2 = new Array(len); i < len; i++) {
    arr2[i] = arr[i];
  }

  return arr2;
}

function background_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return background_arrayLikeToArray(arr);
}

function background_iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
}

function background_unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return background_arrayLikeToArray(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return background_arrayLikeToArray(o, minLen);
}

function background_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}

function background_toConsumableArray(arr) {
  return background_arrayWithoutHoles(arr) || background_iterableToArray(arr) || background_unsupportedIterableToArray(arr) || background_nonIterableSpread();
}

var background_NODE_TYPES;

(function (NODE_TYPES) {
  NODE_TYPES["PLACEHOLDER"] = "placeholder";
  NODE_TYPES["TEXT"] = "text";
  NODE_TYPES["TAG"] = "tag";
  NODE_TYPES["VOID_TAG"] = "void_tag";
})(background_NODE_TYPES || (background_NODE_TYPES = {}));

var background_isTextNode = function isTextNode(node) {
  return node.type === background_NODE_TYPES.TEXT;
};
var background_isTagNode = function isTagNode(node) {
  return node.type === background_NODE_TYPES.TAG;
};
var background_isPlaceholderNode = function isPlaceholderNode(node) {
  return node.type === background_NODE_TYPES.PLACEHOLDER;
};
var background_isVoidTagNode = function isVoidTagNode(node) {
  return node.type === background_NODE_TYPES.VOID_TAG;
};
var background_placeholderNode = function placeholderNode(value) {
  return {
    type: background_NODE_TYPES.PLACEHOLDER,
    value: value
  };
};
var background_textNode = function textNode(str) {
  return {
    type: background_NODE_TYPES.TEXT,
    value: str
  };
};
var background_tagNode = function tagNode(tagName, children) {
  var value = tagName.trim();
  return {
    type: background_NODE_TYPES.TAG,
    value: value,
    children: children
  };
};
var background_voidTagNode = function voidTagNode(tagName) {
  var value = tagName.trim();
  return {
    type: background_NODE_TYPES.VOID_TAG,
    value: value
  };
};
/**
 * Checks if target is node
 * @param target
 */

var background_isNode = function isNode(target) {
  if (typeof target === 'string') {
    return false;
  }

  return !!target.type;
};

var background_STATE;

(function (STATE) {
  /**
   * Parser function switches to the text state when parses simple text,
   * or content between open and close tags
   */
  STATE["TEXT"] = "text";
  /**
   * Parser function switches to the tag state when meets open tag brace ("<"), and switches back,
   * when meets closing tag brace (">")
   */

  STATE["TAG"] = "tag";
  /**
   * Parser function switches to the placeholder state when meets in the text
   * open placeholders brace ("{") and switches back to the text state,
   * when meets close placeholder brace ("}")
   */

  STATE["PLACEHOLDER"] = "placeholder";
})(background_STATE || (background_STATE = {}));

var background_CONTROL_CHARS = {
  TAG_OPEN_BRACE: '<',
  TAG_CLOSE_BRACE: '>',
  CLOSING_TAG_MARK: '/',
  PLACEHOLDER_MARK: '%'
};
/**
 * Checks if text length is enough to create text node
 * If text node created, then if stack is not empty it is pushed into stack,
 * otherwise into result
 * @param context
 */

var background_createTextNodeIfPossible = function createTextNodeIfPossible(context) {
  var text = context.text;

  if (text.length > 0) {
    var node = background_textNode(text);

    if (context.stack.length > 0) {
      context.stack.push(node);
    } else {
      context.result.push(node);
    }
  }

  context.text = '';
};
/**
 * Checks if lastFromStack tag has any attributes
 * @param lastFromStack
 */


var background_hasAttributes = function hasAttributes(lastFromStack) {
  // e.g. "a class" or "a href='#'"
  var tagStrParts = lastFromStack.split(' ');
  return tagStrParts.length > 1;
};
/**
 * Handles text state
 */


var background_textStateHandler = function textStateHandler(context) {
  var currChar = context.currChar,
      currIdx = context.currIdx; // switches to the tag state

  if (currChar === background_CONTROL_CHARS.TAG_OPEN_BRACE) {
    context.lastTextStateChangeIdx = currIdx;
    return background_STATE.TAG;
  } // switches to the placeholder state


  if (currChar === background_CONTROL_CHARS.PLACEHOLDER_MARK) {
    context.lastTextStateChangeIdx = currIdx;
    return background_STATE.PLACEHOLDER;
  } // remains in the text state


  context.text += currChar;
  return background_STATE.TEXT;
};
/**
 * Handles placeholder state
 * @param context
 */


var background_placeholderStateHandler = function placeholderStateHandler(context) {
  var currChar = context.currChar,
      currIdx = context.currIdx,
      lastTextStateChangeIdx = context.lastTextStateChangeIdx,
      placeholder = context.placeholder,
      stack = context.stack,
      result = context.result,
      str = context.str;

  if (currChar === background_CONTROL_CHARS.PLACEHOLDER_MARK) {
    // if distance between current index and last state change equal to 1,
    // it means that placeholder mark was escaped by itself e.g. "%%",
    // so we return to the text state
    if (currIdx - lastTextStateChangeIdx === 1) {
      context.text += str.substring(lastTextStateChangeIdx, currIdx);
      return background_STATE.TEXT;
    }

    background_createTextNodeIfPossible(context);
    var node = background_placeholderNode(placeholder); // push node to the appropriate stack

    if (stack.length > 0) {
      stack.push(node);
    } else {
      result.push(node);
    }

    context.placeholder = '';
    return background_STATE.TEXT;
  }

  context.placeholder += currChar;
  return background_STATE.PLACEHOLDER;
};
/**
 * Switches current state to the tag state and returns tag state handler
 */


var background_tagStateHandler = function tagStateHandler(context) {
  var currChar = context.currChar,
      text = context.text,
      stack = context.stack,
      result = context.result,
      lastTextStateChangeIdx = context.lastTextStateChangeIdx,
      currIdx = context.currIdx,
      str = context.str;
  var tag = context.tag; // if found tag end ">"

  if (currChar === background_CONTROL_CHARS.TAG_CLOSE_BRACE) {
    // if the tag is close tag e.g. </a>
    if (tag.indexOf(background_CONTROL_CHARS.CLOSING_TAG_MARK) === 0) {
      // remove slash from tag
      tag = tag.substring(1);
      var children = [];

      if (text.length > 0) {
        children.push(background_textNode(text));
        context.text = '';
      }

      var pairTagFound = false; // looking for the pair to the close tag

      while (!pairTagFound && stack.length > 0) {
        var lastFromStack = stack.pop(); // if tag from stack equal to close tag

        if (lastFromStack === tag) {
          // create tag node
          var node = background_tagNode(tag, children); // and add it to the appropriate stack

          if (stack.length > 0) {
            stack.push(node);
          } else {
            result.push(node);
          }

          children = [];
          pairTagFound = true;
        } else if (background_isNode(lastFromStack)) {
          // add nodes between close tag and open tag to the children
          children.unshift(lastFromStack);
        } else {
          if (typeof lastFromStack === 'string' && background_hasAttributes(lastFromStack)) {
            throw new Error("Tags in string should not have attributes: ".concat(str));
          } else {
            throw new Error("String has unbalanced tags: ".concat(str));
          }
        }

        if (stack.length === 0 && children.length > 0) {
          throw new Error("String has unbalanced tags: ".concat(str));
        }
      }

      context.tag = '';
      return background_STATE.TEXT;
    } // if the tag is void tag e.g. <img/>


    if (tag.lastIndexOf(background_CONTROL_CHARS.CLOSING_TAG_MARK) === tag.length - 1) {
      tag = tag.substring(0, tag.length - 1);
      background_createTextNodeIfPossible(context);

      var _node = background_voidTagNode(tag); // add node to the appropriate stack


      if (stack.length > 0) {
        stack.push(_node);
      } else {
        result.push(_node);
      }

      context.tag = '';
      return background_STATE.TEXT;
    }

    background_createTextNodeIfPossible(context);
    stack.push(tag);
    context.tag = '';
    return background_STATE.TEXT;
  } // If we meet open tag "<" it means that we wrongly moved into tag state


  if (currChar === background_CONTROL_CHARS.TAG_OPEN_BRACE) {
    context.text += str.substring(lastTextStateChangeIdx, currIdx);
    context.lastTextStateChangeIdx = currIdx;
    context.tag = '';
    return background_STATE.TAG;
  }

  context.tag += currChar;
  return background_STATE.TAG;
};
/**
 * Parses string into AST (abstract syntax tree) and returns it
 * e.g.
 * parse("String to <a>translate</a>") ->
 * ```
 *      [
 *           { type: 'text', value: 'String to ' },
 *           { type: 'tag', value: 'a', children: [{ type: 'text', value: 'translate' }] }
 *      ];
 * ```
 * Empty string is parsed into empty AST (abstract syntax tree): "[]"
 * If founds unbalanced tags, it throws error about it
 *
 * @param {string} str - message in simplified ICU like syntax without plural support
 */


var background_parser = function parser() {
  var _STATE_HANDLERS;

  var str = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  var context = {
    /**
     * Stack is used to keep and search nested tag nodes
     */
    stack: [],

    /**
     * Result is stack where function allocates nodes
     */
    result: [],

    /**
     * Current char index
     */
    currIdx: 0,

    /**
     * Saves index of the last state change from the text state,
     * used to restore parsed text if we moved into other state wrongly
     */
    lastTextStateChangeIdx: 0,

    /**
     * Accumulated tag value
     */
    tag: '',

    /**
     * Accumulated text value
     */
    text: '',

    /**
     * Accumulated placeholder value
     */
    placeholder: '',

    /**
     * Parsed string
     */
    str: str
  };
  var STATE_HANDLERS = (_STATE_HANDLERS = {}, background_index_esm_defineProperty(_STATE_HANDLERS, background_STATE.TEXT, background_textStateHandler), background_index_esm_defineProperty(_STATE_HANDLERS, background_STATE.PLACEHOLDER, background_placeholderStateHandler), background_index_esm_defineProperty(_STATE_HANDLERS, background_STATE.TAG, background_tagStateHandler), _STATE_HANDLERS); // Start from text state

  var currentState = background_STATE.TEXT;

  while (context.currIdx < str.length) {
    context.currChar = str[context.currIdx];
    var currentStateHandler = STATE_HANDLERS[currentState];
    currentState = currentStateHandler(context);
    context.currIdx += 1;
  }

  var result = context.result,
      text = context.text,
      stack = context.stack,
      lastTextStateChangeIdx = context.lastTextStateChangeIdx; // Means that tag or placeholder nodes were not closed, so we consider them as text

  if (currentState !== background_STATE.TEXT) {
    var restText = str.substring(lastTextStateChangeIdx);

    if ((restText + text).length > 0) {
      result.push(background_textNode(text + restText));
    }
  } else {
    // eslint-disable-next-line no-lonely-if
    if (text.length > 0) {
      result.push(background_textNode(text));
    }
  }

  if (stack.length > 0) {
    throw new Error("String has unbalanced tags: ".concat(context.str));
  }

  return result;
};

function background_index_esm_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function background_index_esm_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { background_index_esm_ownKeys(Object(source), true).forEach(function (key) { background_index_esm_defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { background_index_esm_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
/**
 * Helper functions used by default to assemble strings from tag nodes
 * @param tagName
 * @param children
 */

var background_createStringElement = function createStringElement(tagName, children) {
  if (children) {
    return "<".concat(tagName, ">").concat(children, "</").concat(tagName, ">");
  }

  return "<".concat(tagName, "/>");
};
/**
 * Creates map with default values for tag converters
 */


var background_createDefaultValues = function createDefaultValues() {
  return {
    p: function p(children) {
      return background_createStringElement('p', children);
    },
    b: function b(children) {
      return background_createStringElement('b', children);
    },
    strong: function strong(children) {
      return background_createStringElement('strong', children);
    },
    tt: function tt(children) {
      return background_createStringElement('tt', children);
    },
    s: function s(children) {
      return background_createStringElement('s', children);
    },
    i: function i(children) {
      return background_createStringElement('i', children);
    }
  };
};
/**
 * This function accepts an AST (abstract syntax tree) which is a result
 * of the parser function call, and converts tree nodes into array of strings replacing node
 * values with provided values.
 * Values is a map with functions or strings, where each key is related to placeholder value
 * or tag value
 * e.g.
 * string "text <tag>tag text</tag> %placeholder%" is parsed into next AST
 *
 *      [
 *          { type: 'text', value: 'text ' },
 *          {
 *              type: 'tag',
 *              value: 'tag',
 *              children: [{ type: 'text', value: 'tag text' }],
 *          },
 *          { type: 'text', value: ' ' },
 *          { type: 'placeholder', value: 'placeholder' }
 *      ];
 *
 * this AST after format and next values
 *
 *      {
 *          // here used template strings, but it can be react components as well
 *          tag: (chunks) => `<b>${chunks}</b>`,
 *          placeholder: 'placeholder text'
 *      }
 *
 * will return next array
 *
 * [ 'text ', '<b>tag text</b>', ' ', 'placeholder text' ]
 *
 * as you can see, <tag> was replaced by <b>, and placeholder was replaced by placeholder text
 *
 * @param ast - AST (abstract syntax tree)
 * @param values
 */


var background_format = function format() {
  var ast = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var values = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var result = [];

  var tmplValues = background_index_esm_objectSpread(background_index_esm_objectSpread({}, background_createDefaultValues()), values);

  var i = 0;

  while (i < ast.length) {
    var currentNode = ast[i]; // if current node is text node, there is nothing to change, append value to the result

    if (background_isTextNode(currentNode)) {
      result.push(currentNode.value);
    } else if (background_isTagNode(currentNode)) {
      var children = background_toConsumableArray(format(currentNode.children, tmplValues));

      var value = tmplValues[currentNode.value];

      if (value) {
        // TODO consider using strong typing
        if (typeof value === 'function') {
          result.push(value(children.join('')));
        } else {
          result.push(value);
        }
      } else {
        throw new Error("Value ".concat(currentNode.value, " wasn't provided"));
      }
    } else if (background_isVoidTagNode(currentNode)) {
      var _value = tmplValues[currentNode.value]; // TODO consider using strong typing

      if (_value && typeof _value === 'string') {
        result.push(_value);
      } else {
        throw new Error("Value ".concat(currentNode.value, " wasn't provided"));
      }
    } else if (background_isPlaceholderNode(currentNode)) {
      var _value2 = tmplValues[currentNode.value]; // TODO consider using strong typing

      if (_value2 && typeof _value2 === 'string') {
        result.push(_value2);
      } else {
        throw new Error("Value ".concat(currentNode.value, " wasn't provided"));
      }
    }

    i += 1;
  }

  return result;
};
/**
 * Function gets AST (abstract syntax tree) or string and formats messages,
 * replacing values accordingly
 * e.g.
 *      const message = formatter('<a>some text</a>', {
 *          a: (chunks) => `<a href="#">${chunks}</a>`,
 *      });
 *      console.log(message); // ['<a href="#">some text</a>']
 * @param message
 * @param [values]
 */


var background_formatter = function formatter(message, values) {
  var ast = background_parser(message);
  var preparedValues = {}; // convert values to strings if not a function

  if (values) {
    Object.keys(values).forEach(function (key) {
      var value = values[key]; // TODO consider using strong typing

      if (typeof value === 'function') {
        preparedValues[key] = value;
      } else {
        preparedValues[key] = String(value);
      }
    });
  }

  return background_format(ast, preparedValues);
};

var background_pluralFormsCount;

var background_AvailableLocales;

(function (AvailableLocales) {
  AvailableLocales["az"] = "az";
  AvailableLocales["bo"] = "bo";
  AvailableLocales["dz"] = "dz";
  AvailableLocales["id"] = "id";
  AvailableLocales["ja"] = "ja";
  AvailableLocales["jv"] = "jv";
  AvailableLocales["ka"] = "ka";
  AvailableLocales["km"] = "km";
  AvailableLocales["kn"] = "kn";
  AvailableLocales["ko"] = "ko";
  AvailableLocales["ms"] = "ms";
  AvailableLocales["th"] = "th";
  AvailableLocales["tr"] = "tr";
  AvailableLocales["vi"] = "vi";
  AvailableLocales["zh"] = "zh";
  AvailableLocales["zh_cn"] = "zh_cn";
  AvailableLocales["zh_tw"] = "zh_tw";
  AvailableLocales["af"] = "af";
  AvailableLocales["bn"] = "bn";
  AvailableLocales["bg"] = "bg";
  AvailableLocales["ca"] = "ca";
  AvailableLocales["da"] = "da";
  AvailableLocales["de"] = "de";
  AvailableLocales["el"] = "el";
  AvailableLocales["en"] = "en";
  AvailableLocales["eo"] = "eo";
  AvailableLocales["es"] = "es";
  AvailableLocales["et"] = "et";
  AvailableLocales["eu"] = "eu";
  AvailableLocales["fa"] = "fa";
  AvailableLocales["fi"] = "fi";
  AvailableLocales["fo"] = "fo";
  AvailableLocales["fur"] = "fur";
  AvailableLocales["fy"] = "fy";
  AvailableLocales["gl"] = "gl";
  AvailableLocales["gu"] = "gu";
  AvailableLocales["ha"] = "ha";
  AvailableLocales["he"] = "he";
  AvailableLocales["hu"] = "hu";
  AvailableLocales["is"] = "is";
  AvailableLocales["it"] = "it";
  AvailableLocales["ku"] = "ku";
  AvailableLocales["lb"] = "lb";
  AvailableLocales["ml"] = "ml";
  AvailableLocales["mn"] = "mn";
  AvailableLocales["mr"] = "mr";
  AvailableLocales["nah"] = "nah";
  AvailableLocales["nb"] = "nb";
  AvailableLocales["ne"] = "ne";
  AvailableLocales["nl"] = "nl";
  AvailableLocales["nn"] = "nn";
  AvailableLocales["no"] = "no";
  AvailableLocales["oc"] = "oc";
  AvailableLocales["om"] = "om";
  AvailableLocales["or"] = "or";
  AvailableLocales["pa"] = "pa";
  AvailableLocales["pap"] = "pap";
  AvailableLocales["ps"] = "ps";
  AvailableLocales["pt"] = "pt";
  AvailableLocales["pt_pt"] = "pt_pt";
  AvailableLocales["pt_br"] = "pt_br";
  AvailableLocales["so"] = "so";
  AvailableLocales["sq"] = "sq";
  AvailableLocales["sv"] = "sv";
  AvailableLocales["sw"] = "sw";
  AvailableLocales["ta"] = "ta";
  AvailableLocales["te"] = "te";
  AvailableLocales["tk"] = "tk";
  AvailableLocales["ur"] = "ur";
  AvailableLocales["zu"] = "zu";
  AvailableLocales["am"] = "am";
  AvailableLocales["bh"] = "bh";
  AvailableLocales["fil"] = "fil";
  AvailableLocales["fr"] = "fr";
  AvailableLocales["gun"] = "gun";
  AvailableLocales["hi"] = "hi";
  AvailableLocales["hy"] = "hy";
  AvailableLocales["ln"] = "ln";
  AvailableLocales["mg"] = "mg";
  AvailableLocales["nso"] = "nso";
  AvailableLocales["xbr"] = "xbr";
  AvailableLocales["ti"] = "ti";
  AvailableLocales["wa"] = "wa";
  AvailableLocales["be"] = "be";
  AvailableLocales["bs"] = "bs";
  AvailableLocales["hr"] = "hr";
  AvailableLocales["ru"] = "ru";
  AvailableLocales["sr"] = "sr";
  AvailableLocales["uk"] = "uk";
  AvailableLocales["cs"] = "cs";
  AvailableLocales["sk"] = "sk";
  AvailableLocales["ga"] = "ga";
  AvailableLocales["lt"] = "lt";
  AvailableLocales["sl"] = "sl";
  AvailableLocales["mk"] = "mk";
  AvailableLocales["mt"] = "mt";
  AvailableLocales["lv"] = "lv";
  AvailableLocales["pl"] = "pl";
  AvailableLocales["cy"] = "cy";
  AvailableLocales["ro"] = "ro";
  AvailableLocales["ar"] = "ar";
  AvailableLocales["sr_latn"] = "sr_latn";
})(background_AvailableLocales || (background_AvailableLocales = {}));

var background_getPluralFormId = function getPluralFormId(locale, number) {
  var _supportedForms;

  if (number === 0) {
    return 0;
  }

  var slavNum = number % 10 === 1 && number % 100 !== 11 ? 1 : number % 10 >= 2 && number % 10 <= 4 && (number % 100 < 10 || number % 100 >= 20) ? 2 : 3;
  var supportedForms = (_supportedForms = {}, background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.az, 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.bo, 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.dz, 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.id, 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.ja, 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.jv, 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.ka, 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.km, 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.kn, 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.ko, 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.ms, 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.th, 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.tr, 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.vi, 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.zh, 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.zh_tw, 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.zh_cn, 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.af, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.bn, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.bg, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.ca, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.da, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.de, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.el, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.en, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.eo, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.es, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.et, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.eu, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.fa, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.fi, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.fo, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.fur, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.fy, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.gl, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.gu, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.ha, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.he, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.hu, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.is, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.it, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.ku, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.lb, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.ml, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.mn, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.mr, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.nah, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.nb, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.ne, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.nl, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.nn, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.no, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.oc, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.om, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.or, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.pa, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.pap, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.ps, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.pt, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.pt_pt, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.pt_br, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.so, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.sq, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.sv, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.sw, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.ta, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.te, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.tk, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.ur, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.zu, number === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.am, number === 0 || number === 1 ? 0 : 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.bh, number === 0 || number === 1 ? 0 : 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.fil, number === 0 || number === 1 ? 0 : 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.fr, number === 0 || number >= 2 ? 2 : 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.gun, number === 0 || number === 1 ? 0 : 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.hi, number === 0 || number === 1 ? 0 : 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.hy, number === 0 || number === 1 ? 0 : 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.ln, number === 0 || number === 1 ? 0 : 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.mg, number === 0 || number === 1 ? 0 : 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.nso, number === 0 || number === 1 ? 0 : 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.xbr, number === 0 || number === 1 ? 0 : 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.ti, number === 0 || number === 1 ? 0 : 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.wa, number === 0 || number === 1 ? 0 : 1), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.be, slavNum), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.bs, slavNum), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.hr, slavNum), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.ru, slavNum), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.sr, slavNum), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.sr_latn, slavNum), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.uk, slavNum), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.cs, number === 1 ? 1 : number >= 2 && number <= 4 ? 2 : 3), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.sk, number === 1 ? 1 : number >= 2 && number <= 4 ? 2 : 3), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.ga, number === 1 ? 1 : number === 2 ? 2 : 3), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.lt, number % 10 === 1 && number % 100 !== 11 ? 1 : number % 10 >= 2 && (number % 100 < 10 || number % 100 >= 20) ? 2 : 3), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.sl, number % 100 === 1 ? 1 : number % 100 === 2 ? 2 : number % 100 === 3 || number % 100 === 4 ? 3 : 4), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.mk, number % 10 === 1 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.mt, number === 1 ? 1 : number === 0 || number % 100 > 1 && number % 100 < 11 ? 2 : number % 100 > 10 && number % 100 < 20 ? 3 : 4), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.lv, number === 0 ? 0 : number % 10 === 1 && number % 100 !== 11 ? 1 : 2), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.pl, number === 1 ? 1 : number % 10 >= 2 && number % 10 <= 4 && (number % 100 < 12 || number % 100 > 14) ? 2 : 3), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.cy, number === 1 ? 0 : number === 2 ? 1 : number === 8 || number === 11 ? 2 : 3), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.ro, number === 1 ? 1 : number === 1 || number % 100 > 0 && number % 100 < 20 ? 2 : 3), background_index_esm_defineProperty(_supportedForms, background_AvailableLocales.ar, number === 0 ? 0 : number === 1 ? 1 : number === 2 ? 2 : number % 100 >= 3 && number % 100 <= 10 ? 3 : number % 100 >= 11 && number % 100 <= 99 ? 4 : 5), _supportedForms);
  return supportedForms[locale];
};

var pages_background_pluralFormsCount = (background_pluralFormsCount = {}, background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.az, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.bo, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.dz, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.id, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.ja, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.jv, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.ka, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.km, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.kn, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.ko, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.ms, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.th, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.tr, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.vi, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.zh, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.zh_cn, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.zh_tw, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.af, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.bn, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.bg, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.ca, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.da, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.de, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.el, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.en, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.eo, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.es, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.et, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.eu, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.fa, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.fi, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.fo, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.fur, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.fy, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.gl, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.gu, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.ha, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.he, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.hu, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.is, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.it, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.ku, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.lb, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.ml, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.mn, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.mr, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.nah, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.nb, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.ne, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.nl, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.nn, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.no, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.oc, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.om, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.or, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.pa, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.pap, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.ps, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.pt, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.pt_pt, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.pt_br, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.so, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.sq, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.sv, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.sw, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.ta, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.te, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.tk, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.ur, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.zu, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.am, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.bh, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.fil, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.fr, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.gun, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.hi, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.hy, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.ln, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.mg, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.nso, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.xbr, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.ti, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.wa, 2), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.be, 4), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.bs, 4), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.hr, 4), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.ru, 4), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.sr, 4), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.sr_latn, 4), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.uk, 4), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.cs, 4), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.sk, 4), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.ga, 4), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.lt, 4), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.sl, 5), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.mk, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.mt, 5), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.lv, 3), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.pl, 4), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.cy, 4), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.ro, 4), background_index_esm_defineProperty(background_pluralFormsCount, background_AvailableLocales.ar, 6), background_pluralFormsCount);
var background_PLURAL_STRING_DELIMITER = '|';
/**
 * Returns string plural forms which are separated by `|`.
 *
 * @param str Message.
 *
 * @returns Array of plural forms.
 */

var background_getForms = function getForms(str) {
  return str.split(background_PLURAL_STRING_DELIMITER);
};
/**
 * Checks whether the string has correct number of plural forms.
 *
 * @param str Translated string.
 * @param locale Locale.
 * @param key Optional, base key.
 *
 * @throws Error if the number of plural forms is incorrect.
 */

var background_checkForms = function checkForms(str, locale, key) {
  var givenCount = background_getForms(str).length;
  var requiredCount = pages_background_pluralFormsCount[locale];

  if (givenCount !== requiredCount) {
    var prefix = typeof key !== 'undefined' ? "Invalid plural string \"".concat(key, "\" for locale '").concat(locale, "'") : "Invalid plural string for locale '".concat(locale, "'");
    throw new Error("".concat(prefix, ": required ").concat(requiredCount, ", given ").concat(givenCount, " in string \"").concat(str, "\""));
  }
};
/**
 * Checks whether plural forms are present in base string
 * by checking the presence of the vertical bar `|`.
 *
 * @param baseStr Base string.
 *
 * @returns True if `baseStr` contains `|`, false otherwise.
 */


var background_hasPluralForm = function hasPluralForm(baseStr) {
  return baseStr.includes(background_PLURAL_STRING_DELIMITER);
};
/**
 * Checks if plural forms are valid.
 *
 * @param targetStr Translated message with plural forms.
 * @param locale Locale.
 * @param key Optional, message key, used for clearer log message.
 *
 * @returns True if plural forms are valid, false otherwise.
 */

var background_isPluralFormValid = function isPluralFormValid(targetStr, locale, key) {
  try {
    background_checkForms(targetStr, locale, key);
    return true;
  } catch (error) {
    return false;
  }
};
/**
 * Returns plural form corresponding to number
 * @param str
 * @param number
 * @param locale - current locale
 * @param key - message key
 */

var background_getForm = function getForm(str, number, locale, key) {
  background_checkForms(str, locale, key);
  var forms = background_getForms(str);
  var currentForm = background_getPluralFormId(locale, number);
  return forms[currentForm].trim();
};

function background_ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function background_objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { background_ownKeys$1(Object(source), true).forEach(function (key) { background_index_esm_defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { background_ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

var background_defaultMessageConstructor = function defaultMessageConstructor(formatted) {
  return formatted.join('');
};

var background_Translator = /*#__PURE__*/function () {
  function Translator(i18n, // eslint-disable-next-line @typescript-eslint/no-explicit-any
  messageConstructor, values) {
    background_classCallCheck(this, Translator);

    this.i18n = i18n;
    this.messageConstructor = messageConstructor || background_defaultMessageConstructor;
    this.values = values || {};
  }
  /**
   * Retrieves message and translates it, substituting parameters where necessary
   * @param key - translation message key
   * @param params - values used to substitute placeholders and tags
   */


  background_createClass(Translator, [{
    key: "getMessage",
    value: function getMessage(key) {
      var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var message = this.i18n.getMessage(key);

      if (!message) {
        message = this.i18n.getBaseMessage(key);

        if (!message) {
          throw new Error("Was unable to find message for key: \"".concat(key, "\""));
        }
      }

      var formatted = background_formatter(message, background_objectSpread$1(background_objectSpread$1({}, this.values), params));
      return this.messageConstructor(formatted);
    }
    /**
     * Retrieves correct plural form and translates it
     * @param key - translation message key
     * @param number - plural form number
     * @param params - values used to substitute placeholders or tags if necessary,
     * if params has "count" property it will be overridden by number (plural form number)
     */

  }, {
    key: "getPlural",
    value: function getPlural(key, number) {
      var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
      var message = this.i18n.getMessage(key);
      var language = this.i18n.getUILanguage();

      if (!message) {
        message = this.i18n.getBaseMessage(key);

        if (!message) {
          throw new Error("Was unable to find message for key: \"".concat(key, "\""));
        }

        language = this.i18n.getBaseUILanguage();
      }

      var form = background_getForm(message, number, language, key);
      var formatted = background_formatter(form, background_objectSpread$1(background_objectSpread$1(background_objectSpread$1({}, this.values), params), {}, {
        count: number
      }));
      return this.messageConstructor(formatted);
    }
  }]);

  return Translator;
}();

function background_ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function background_objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { background_ownKeys$2(Object(source), true).forEach(function (key) { background_index_esm_defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { background_ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
/**
 * Creates translation function for strings used in the React components
 * We do not import React directly, because translator module can be used
 * in the modules without React too
 *
 * e.g.
 * const translateReact = createReactTranslator(getMessage, React);
 * in locales folder you should have messages.json file
 * ```
 * message:
 *     "popup_auth_agreement_consent": {
 *          "message": "You agree to our <eula>EULA</eula>",
 *      },
 * ```
 *
 * this message can be retrieved and translated into react components next way:
 *
 * const component = translateReact('popup_auth_agreement_consent', {
 *          eula: (chunks) => (
 *              <button
 *                  className="auth__privacy-link"
 *                  onClick={handleEulaClick}
 *              >
 *                  {chunks}
 *              </button>
 *          ),
 *       });
 *
 * Note how functions in the values argument can be used with handlers
 *
 * @param i18n - object with methods which get translated message by key and return current locale
 * @param React - instance of react library
 */

var background_createReactTranslator = function createReactTranslator(i18n, react, defaults) {
  /**
   * Helps to build nodes without values
   *
   * @param tagName
   * @param children
   */
  var createReactElement = function createReactElement(tagName, children) {
    if (children) {
      return react.createElement(tagName, null, react.Children.toArray(children));
    }

    return react.createElement(tagName, null);
  };
  /**
   * Function creates default values to be used if user didn't provide function values for tags
   */


  var createDefaultValues = function createDefaultValues() {
    // eslint-disable-next-line @typescript-eslint/ban-types
    var externalDefaults = {};

    if (defaults) {
      defaults.tags.forEach(function (t) {
        externalDefaults[t.key] = function (children) {
          return createReactElement(t.createdTag, children);
        };
      });
    }

    if (defaults !== null && defaults !== void 0 && defaults.override) {
      return externalDefaults;
    }

    return background_objectSpread$2({
      p: function p(children) {
        return createReactElement('p', children);
      },
      b: function b(children) {
        return createReactElement('b', children);
      },
      strong: function strong(children) {
        return createReactElement('strong', children);
      },
      tt: function tt(children) {
        return createReactElement('tt', children);
      },
      s: function s(children) {
        return createReactElement('s', children);
      },
      i: function i(children) {
        return createReactElement('i', children);
      }
    }, externalDefaults);
  };

  var reactMessageConstructor = function reactMessageConstructor(formatted) {
    var reactChildren = react.Children.toArray(formatted); // if there is only strings in the array we join them

    if (reactChildren.every(function (child) {
      return typeof child === 'string';
    })) {
      return reactChildren.join('');
    }

    return reactChildren;
  };

  var defaultValues = createDefaultValues();
  return new background_Translator(i18n, reactMessageConstructor, defaultValues);
};

var background_r,
    background_f;

function background_A(n, l) {
  return l = l || [], null == n || "boolean" == typeof n || (Array.isArray(n) ? n.some(function (n) {
    background_A(n, l);
  }) : l.push(n)), l;
}

background_r = "function" == typeof Promise ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, background_f = 0;

function background_ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function background_objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { background_ownKeys$3(Object(source), true).forEach(function (key) { background_index_esm_defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { background_ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
/**
 * Creates translation function for strings used in the Preact components
 * We do not import Preact directly, because translator module can be used
 * in the modules without Preact too
 *
 * e.g.
 * const translatePreact = createPreactTranslator(getMessage, Preact);
 * in locales folder you should have messages.json file
 * ```
 * message:
 *     "popup_auth_agreement_consent": {
 *          "message": "You agree to our <eula>EULA</eula>",
 *      },
 * ```
 *
 * this message can be retrieved and translated into preact components next way:
 *
 * const component = translatePreact('popup_auth_agreement_consent', {
 *          eula: (chunks) => (
 *              <button
 *                  className="auth__privacy-link"
 *                  onClick={handleEulaClick}
 *              >
 *                  {chunks}
 *              </button>
 *          ),
 *       });
 *
 * Note how functions in the values argument can be used with handlers
 *
 * @param i18n - object with methods which get translated message by key and return current locale
 * @param Preact - instance of preact library
 */

var background_createPreactTranslator = function createPreactTranslator(i18n, preact, defaults) {
  /**
   * Helps to build nodes without values
   *
   * @param tagName
   * @param children
   */
  var createPreactElement = function createPreactElement(tagName, children) {
    if (children) {
      return preact.createElement(tagName, null, background_A(children));
    }

    return preact.createElement(tagName, null);
  };
  /**
   * Function creates default values to be used if user didn't provide function values for tags
   */


  var createDefaultValues = function createDefaultValues() {
    // eslint-disable-next-line @typescript-eslint/ban-types
    var externalDefaults = {};

    if (defaults) {
      defaults.tags.forEach(function (t) {
        externalDefaults[t.key] = function (children) {
          return createPreactElement(t.createdTag, children);
        };
      });
    }

    if (defaults !== null && defaults !== void 0 && defaults.override) {
      return externalDefaults;
    }

    return background_objectSpread$3({
      p: function p(children) {
        return createPreactElement('p', children);
      },
      b: function b(children) {
        return createPreactElement('b', children);
      },
      strong: function strong(children) {
        return createPreactElement('strong', children);
      },
      tt: function tt(children) {
        return createPreactElement('tt', children);
      },
      s: function s(children) {
        return createPreactElement('s', children);
      },
      i: function i(children) {
        return createPreactElement('i', children);
      }
    }, externalDefaults);
  };

  var preactMessageConstructor = function preactMessageConstructor(formatted) {
    var preactChildren = background_A(formatted); // if there is only strings in the array we join them

    if (preactChildren.every(function (child) {
      return typeof child === 'string';
    })) {
      return preactChildren.join('');
    }

    return preactChildren;
  };

  var defaultValues = createDefaultValues();
  return new background_Translator(i18n, preactMessageConstructor, defaultValues);
};

/**
 * Creates translator instance strings, by default for simple strings
 * @param i18n - function which returns translated message by key
 * @param messageConstructor - function that will collect messages
 * @param values - map with default values for tag converters
 */

var background_createTranslator = function createTranslator(i18n, messageConstructor, values) {
  return new background_Translator(i18n, messageConstructor, values);
};

var background_translate = {
  createTranslator: background_createTranslator,
  createReactTranslator: background_createReactTranslator,
  createPreactTranslator: background_createPreactTranslator
};

function background_index_esm_typeof(obj) {
  "@babel/helpers - typeof";

  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    background_index_esm_typeof = function _typeof(obj) {
      return typeof obj;
    };
  } else {
    background_index_esm_typeof = function _typeof(obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
    };
  }

  return background_index_esm_typeof(obj);
}

/**
 * Compares two AST (abstract syntax tree) structures,
 * view tests for examples
 * @param baseAst
 * @param targetAst
 */

var background_areAstStructuresSame = function areAstStructuresSame(baseAst, targetAst) {
  var textNodeFilter = function textNodeFilter(node) {
    return !background_isTextNode(node);
  };

  var filteredBaseAst = baseAst.filter(textNodeFilter);
  var filteredTargetAst = targetAst.filter(textNodeFilter); // if AST structures have different lengths, they are not equal

  if (filteredBaseAst.length !== filteredTargetAst.length) {
    return false;
  }

  var _loop = function _loop(i) {
    var baseNode = filteredBaseAst[i];
    var targetNode = filteredTargetAst.find(function (node) {
      return node.type === baseNode.type && node.value === baseNode.value;
    });

    if (!targetNode) {
      return {
        v: false
      };
    }

    if (targetNode.children && baseNode.children) {
      var areChildrenSame = areAstStructuresSame(baseNode.children, targetNode.children);

      if (!areChildrenSame) {
        return {
          v: false
        };
      }
    }
  };

  for (var i = 0; i < filteredBaseAst.length; i += 1) {
    var _ret = _loop(i);

    if (background_index_esm_typeof(_ret) === "object") return _ret.v;
  }

  return true;
};
/**
 * Validates translation against base string by AST (abstract syntax tree) structure.
 *
 * @param baseMessage Base message.
 * @param translatedMessage Translated message.
 * @param locale Locale of `translatedMessage`.
 *
 * @returns True if translated message is valid, false otherwise:
 * - if base message has no plural forms, it will return true if AST structures are same;
 * - if base message has plural forms, first of all
 *   the function checks if the number of plural forms is correct for the `locale`,
 *   and then it validates AST plural forms structures for base and translated messages.
 *
 * @throws Error for invalid tags in base or translated messages,
 * or if translated message has invalid plural forms.
 */


var background_isTranslationValid = function isTranslationValid(baseMessage, translatedMessage, locale) {
  if (background_hasPluralForm(baseMessage)) {
    var isPluralFormsValid = background_isPluralFormValid(translatedMessage, locale);

    if (!isPluralFormsValid) {
      throw new Error('Invalid plural forms');
    }

    var baseForms = background_getForms(baseMessage);
    var translatedForms = background_getForms(translatedMessage); // check a zero form structures of base and translated messages

    if (!isTranslationValid(baseForms[0], translatedForms[0], locale)) {
      return false;
    } // and check other forms structures of translated messages against the first form of base message


    for (var i = 1; i < translatedForms.length; i += 1) {
      if (!isTranslationValid(baseForms[1], translatedForms[i], locale)) {
        return false;
      }
    } // if no errors, return true after all checks


    return true;
  }

  var baseMessageAst = background_parser(baseMessage);
  var translatedMessageAst = background_parser(translatedMessage);
  return background_areAstStructuresSame(baseMessageAst, translatedMessageAst);
};
var background_validator = {
  isTranslationValid: background_isTranslationValid,
  isPluralFormValid: background_isPluralFormValid
};



;// ./Extension/src/common/translators/i18n.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

const background_BASE_LOCALE = 'en';
const background_baseMessages = __webpack_require__(21987);
const background_uiLanguage = background_browser_polyfill_default().i18n.getUILanguage();
/**
 * Retrieves the localized message for the given key.
 *
 * @param key - The key corresponding to the message in the localization files
 *
 * @returns The localized message, or an empty string if the message is the same as the base locale (indicating no
 * translation)
 *
 * @throws {Error} If there is no such key in the messages
 */ const background_getMessage = (key)=>{
    const receivedMessage = background_browser_polyfill_default().i18n.getMessage(key);
    if (background_uiLanguage !== background_BASE_LOCALE) {
        var _baseMessages_key;
        const baseMessage = (_baseMessages_key = background_baseMessages[key]) === null || _baseMessages_key === void 0 ? void 0 : _baseMessages_key.message;
        if (!baseMessage) {
            throw new Error(`There is no such key "${key}" in the messages`);
        }
        // The same strings mean that the message is not translated.
        // We return an empty string for @adguard/translator to fall back to the base message and base locale.
        // Without this, browser.i18n.getMessage returns the base locale message and the wrong UI language,
        // and @adguard/translator fails on plural forms validations.
        if (receivedMessage === baseMessage) {
            return '';
        }
    }
    return receivedMessage;
};
const background_i18n = {
    getMessage: background_getMessage,
    /**
     * Retrieves the UI language, truncated to a 2-letter code.
     * This is because react translator supports only 2-letter codes.
     *
     * @returns The 2-letter UI language code
     */ getUILanguage: ()=>{
        return background_uiLanguage.substring(0, 2);
    },
    getBaseMessage: (key)=>{
        // thus we can test the base messages with keys without translations
        if (false) {}
        return background_browser_polyfill_default().i18n.getMessage(key);
    },
    getBaseUILanguage: ()=>background_BASE_LOCALE
};

;// ./Extension/src/common/translators/translator.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

/**
 * Retrieves localized message by key, formats it and converts into string
 */ const background_translator = background_translate.createTranslator(background_i18n);

;// ./Extension/src/background/storages/app.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_app_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
var background_AppContextKey = /*#__PURE__*/ function(AppContextKey) {
    AppContextKey["IsInit"] = "isInit";
    AppContextKey["ClientId"] = "clientId";
    return AppContextKey;
}({});
/**
 * Memory storage for app global context.
 */ class background_AppContext {
    /**
     * Returns app context value.
     *
     * @param key Context key.
     *
     * @returns Context value.
     */ get(key) {
        return this.data[key];
    }
    /**
     * Sets app context value.
     *
     * @param key Context key.
     * @param value Context value.
     */ set(key, value) {
        this.data[key] = value;
    }
    constructor(){
        // Initialize with default data
        background_app_define_property(this, "data", {
            ["isInit"]: false
        });
    }
}
const background_appContext = new background_AppContext();

;// ./Extension/src/background/schema/preprocessor.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_preprocessor_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}

/**
 * In some cases we want to preprocessing input before validation
 * For example, cast loaded filter metadata item id field from string to number before validation:
 *
 * { filterId: "1", ... } -> { filterId: 1, ... }.
 */ class background_SchemaPreprocessor {
    /**
     * If {@link value} is string, cast it to number, else returns original value.
     *
     * @param value Preprocessed value.
     *
     * @returns Number value, if string passed, else returns original value.
     */ static castStringToNumber(value) {
        if (typeof value === 'string') {
            return Number(JSON.parse(value));
        }
        return value;
    }
    /**
     * If {@link value} is string, cast it to boolean, else returns original value.
     *
     * @param value Preprocessed value.
     *
     * @returns Boolean value, if string passed, else returns original value.
     */ static castStringToBoolean(value) {
        if (typeof value === 'string') {
            try {
                return Boolean(JSON.parse(value));
            } catch (e) {
                return value;
            }
        }
        return value;
    }
}
/**
     * Runtime {@link zod} validator with {@link SchemaPreprocessor.castStringToBoolean} preprocessor.
     */ background_preprocessor_define_property(background_SchemaPreprocessor, "booleanValidator", background_lib/* default.preprocess */.Ay.preprocess(background_SchemaPreprocessor.castStringToBoolean, background_lib/* default.boolean */.Ay.boolean()));
/**
     * Runtime {@link zod} validator with {@link SchemaPreprocessor.castStringToNumber} preprocessor.
     */ background_preprocessor_define_property(background_SchemaPreprocessor, "numberValidator", background_lib/* default.preprocess */.Ay.preprocess(background_SchemaPreprocessor.castStringToNumber, background_lib/* default.number */.Ay.number()));

;// ./Extension/src/background/schema/settings/enum.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ /**
 * Separate file with only enum to exclude imports of zod to other files.
 */ var background_SettingOption = /*#__PURE__*/ function(SettingOption) {
    // General settings.
    SettingOption["AppearanceTheme"] = "appearance-theme";
    SettingOption["DisableShowPageStats"] = "disable-show-page-statistic";
    SettingOption["DisableDetectFilters"] = "detect-filters-disabled";
    SettingOption["DisableSafebrowsing"] = "safebrowsing-disabled";
    SettingOption["FiltersUpdatePeriod"] = "filters-update-period";
    // Is filtering disabled or not.
    SettingOption["DisableFiltering"] = "adguard-disabled";
    // Extension specific settings.
    SettingOption["UseOptimizedFilters"] = "use-optimized-filters";
    SettingOption["DisableCollectHits"] = "hits-count-disabled";
    SettingOption["DisableShowContextMenu"] = "context-menu-disabled";
    // Flag used to show link to comparison of desktop and browser extension versions.
    SettingOption["DisableShowAdguardPromoInfo"] = "show-info-about-adguard-disabled";
    SettingOption["DisableShowAppUpdatedNotification"] = "show-app-updated-disabled";
    SettingOption["HideRateBlock"] = "hide-rate-block";
    SettingOption["UserRulesEditorWrap"] = "user-rules-editor-wrap";
    // Allowlist section.
    SettingOption["AllowlistDomains"] = "allowlist-domains";
    SettingOption["InvertedAllowlistDomains"] = "block-list-domains";
    SettingOption["AllowlistEnabled"] = "allowlist-enabled";
    SettingOption["DefaultAllowlistMode"] = "default-allowlist-mode";
    // Tracking protection (formerly Stealth mode).
    SettingOption["DisableStealthMode"] = "stealth-disable-stealth-mode";
    SettingOption["HideReferrer"] = "stealth-hide-referrer";
    SettingOption["HideSearchQueries"] = "stealth-hide-search-queries";
    SettingOption["SendDoNotTrack"] = "stealth-send-do-not-track";
    SettingOption["RemoveXClientData"] = "stealth-remove-x-client";
    SettingOption["BlockWebRTC"] = "stealth-block-webrtc";
    SettingOption["SelfDestructThirdPartyCookies"] = "stealth-block-third-party-cookies";
    SettingOption["SelfDestructThirdPartyCookiesTime"] = "stealth-block-third-party-cookies-time";
    SettingOption["SelfDestructFirstPartyCookies"] = "stealth-block-first-party-cookies";
    SettingOption["SelfDestructFirstPartyCookiesTime"] = "stealth-block-first-party-cookies-time";
    // Filters' statuses and states.
    SettingOption["FiltersState"] = "filters-state";
    SettingOption["FiltersVersion"] = "filters-version";
    SettingOption["GroupsState"] = "groups-state";
    SettingOption["UserFilterEnabled"] = "user-filter-enabled";
    // Filters metadata.
    SettingOption["Metadata"] = "filters-metadata";
    SettingOption["I18nMetadata"] = "filters-i18n-metadata";
    SettingOption["CustomFilters"] = "custom-filters";
    return SettingOption;
}({});

;// ./Extension/src/background/schema/settings/main.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 


const background_appearanceValidator = background_lib/* default.enum */.Ay["enum"]([
    'system',
    'dark',
    'light'
]);
/**
 * Setting options may be stringified, use preprocessors for correct type casting.
 */ const background_settingsValidator = background_lib/* default.object */.Ay.object({
    // ----- General settings section -----
    /**
     * See {@link GeneralSettingsConfig[GeneralSettingsOption.AppearanceTheme]}.
     */ [background_SettingOption.AppearanceTheme]: background_appearanceValidator,
    /**
     * See {@link GeneralSettingsConfig[GeneralSettingsOption.ShowBlockedAdsCount]}.
     */ [background_SettingOption.DisableShowPageStats]: background_SchemaPreprocessor.booleanValidator,
    /**
     * See {@link GeneralSettingsConfig[GeneralSettingsOption.AutodetectFilters]}.
     */ [background_SettingOption.DisableDetectFilters]: background_SchemaPreprocessor.booleanValidator,
    /**
     * See {@link GeneralSettingsConfig[GeneralSettingsOption.SafebrowsingEnabled]}.
     */ [background_SettingOption.DisableSafebrowsing]: background_SchemaPreprocessor.booleanValidator,
    /**
     * See {@link GeneralSettingsConfig[GeneralSettingsOption.FiltersUpdatePeriod]}.
     */ [background_SettingOption.FiltersUpdatePeriod]: background_SchemaPreprocessor.numberValidator,
    // ----- General settings section -----
    // ----- Extension specific settings section -----
    /**
     * See {@link ExtensionSpecificSettingsConfig[ExtensionSpecificSettingsOption.UseOptimizedFilters]}.
     */ [background_SettingOption.UseOptimizedFilters]: background_SchemaPreprocessor.booleanValidator,
    /**
     * See {@link ExtensionSpecificSettingsConfig[ExtensionSpecificSettingsOption.CollectHitsCount]}.
     */ [background_SettingOption.DisableCollectHits]: background_SchemaPreprocessor.booleanValidator,
    /**
     * See {@link ExtensionSpecificSettingsConfig[ExtensionSpecificSettingsOption.ShowContextMenu]}.
     */ [background_SettingOption.DisableShowContextMenu]: background_SchemaPreprocessor.booleanValidator,
    /**
     * See {@link ExtensionSpecificSettingsConfig[ExtensionSpecificSettingsOption.ShowInfoAboutAdguard]}.
     */ [background_SettingOption.DisableShowAdguardPromoInfo]: background_SchemaPreprocessor.booleanValidator,
    /**
     * See {@link ExtensionSpecificSettingsConfig[ExtensionSpecificSettingsOption.ShowAppUpdatedInfo]}.
     */ [background_SettingOption.DisableShowAppUpdatedNotification]: background_SchemaPreprocessor.booleanValidator,
    /**
     * See {@link ExtensionSpecificSettingsConfig[ExtensionSpecificSettingsOption.HideRateAdguard]}.
     */ [background_SettingOption.HideRateBlock]: background_SchemaPreprocessor.booleanValidator,
    /**
     * See {@link ExtensionSpecificSettingsConfig[ExtensionSpecificSettingsOption.UserRulesEditorWrap]}.
     */ [background_SettingOption.UserRulesEditorWrap]: background_SchemaPreprocessor.booleanValidator,
    // ----- Extension specific settings section -----
    // ----- Allowlist section -----
    /**
     * See {@link AllowlistConfig[AllowlistOption.Domains]}.
     */ [background_SettingOption.AllowlistDomains]: background_lib/* default.string */.Ay.string(),
    /**
     * See {@link AllowlistConfig[AllowlistOption.InvertedDomains]}.
     */ [background_SettingOption.InvertedAllowlistDomains]: background_lib/* default.string */.Ay.string(),
    /**
     * See {@link AllowlistConfig[AllowlistOption.Enabled]}.
     */ [background_SettingOption.AllowlistEnabled]: background_SchemaPreprocessor.booleanValidator,
    /**
     * See {@link AllowlistConfig[AllowlistOption.Inverted]}.
     */ [background_SettingOption.DefaultAllowlistMode]: background_SchemaPreprocessor.booleanValidator,
    // ----- Allowlist section -----
    // ----- Stealth section -----
    /**
     * See {@link StealthConfig[StealthOption.DisableStealthMode]}.
     */ [background_SettingOption.DisableStealthMode]: background_SchemaPreprocessor.booleanValidator,
    /**
     * See {@link StealthConfig[StealthOption.HideReferrer]}.
     */ [background_SettingOption.HideReferrer]: background_SchemaPreprocessor.booleanValidator,
    /**
     * See {@link StealthConfig[StealthOption.HideSearchQueries]}.
     */ [background_SettingOption.HideSearchQueries]: background_SchemaPreprocessor.booleanValidator,
    /**
     * See {@link StealthConfig[StealthOption.SendDoNotTrack]}.
     */ [background_SettingOption.SendDoNotTrack]: background_SchemaPreprocessor.booleanValidator,
    /**
     * See {@link StealthConfig[StealthOption.BlockWebRTC]}.
     */ [background_SettingOption.BlockWebRTC]: background_SchemaPreprocessor.booleanValidator,
    /**
     * See {@link StealthConfig[StealthOption.RemoveXClientData]}.
     */ [background_SettingOption.RemoveXClientData]: background_SchemaPreprocessor.booleanValidator,
    /**
     * See {@link StealthConfig[StealthOption.SelfDestructThirdPartyCookies]}.
     */ [background_SettingOption.SelfDestructThirdPartyCookies]: background_SchemaPreprocessor.booleanValidator,
    /**
     * See {@link StealthConfig[StealthOption.SelfDestructThirdPartyCookiesTime]}.
     */ [background_SettingOption.SelfDestructThirdPartyCookiesTime]: background_lib/* default.number */.Ay.number(),
    /**
     * See {@link StealthConfig[StealthOption.SelfDestructFirstPartyCookies]}.
     */ [background_SettingOption.SelfDestructFirstPartyCookies]: background_SchemaPreprocessor.booleanValidator,
    /**
     * See {@link StealthConfig[StealthOption.SelfDestructFirstPartyCookiesTime]}.
     */ [background_SettingOption.SelfDestructFirstPartyCookiesTime]: background_lib/* default.number */.Ay.number(),
    // ----- Stealth section -----
    // ----- Statuses section -----
    /**
     * See {@link UserFilterConfig[UserFilterOption.Enabled]}.
     */ [background_SettingOption.UserFilterEnabled]: background_SchemaPreprocessor.booleanValidator,
    /**
     * See {@link FilterStateStorageData}.
     */ [background_SettingOption.FiltersState]: background_lib/* default.string */.Ay.string().optional(),
    /**
     * See {@link FilterVersionStorageData}.
     */ [background_SettingOption.FiltersVersion]: background_lib/* default.string */.Ay.string().optional(),
    /**
     * See {@link GroupStateStorageData}.
     */ [background_SettingOption.GroupsState]: background_lib/* default.string */.Ay.string().optional(),
    // ----- Statuses section -----
    // ----- Metadata section -----
    /**
     * See {@link Metadata}.
     */ [background_SettingOption.Metadata]: background_lib/* default.string */.Ay.string().optional(),
    /**
     * See {@link I18nMetadata}.
     */ [background_SettingOption.I18nMetadata]: background_lib/* default.string */.Ay.string().optional(),
    /**
     * See {@link CustomFilterMetadataStorageData}.
     */ [background_SettingOption.CustomFilters]: background_lib/* default.string */.Ay.string().optional(),
    // ----- Metadata section -----
    /**
     * Is filtering enabled or not. Is needed for fast toggling filtering
     * without reload entire extension.
     */ [background_SettingOption.DisableFiltering]: background_SchemaPreprocessor.booleanValidator
});

;// ./Extension/src/background/schema/settings/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 


;// ./Extension/src/background/schema/configuration/general-settings.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 


// General settings configuration
var background_GeneralSettingsOption = /*#__PURE__*/ function(GeneralSettingsOption) {
    GeneralSettingsOption["AppLanguage"] = "app-language";
    GeneralSettingsOption["AllowAcceptableAds"] = "allow-acceptable-ads";
    GeneralSettingsOption["ShowBlockedAdsCount"] = "show-blocked-ads-count";
    GeneralSettingsOption["AutodetectFilters"] = "autodetect-filters";
    GeneralSettingsOption["SafebrowsingEnabled"] = "safebrowsing-enabled";
    GeneralSettingsOption["FiltersUpdatePeriod"] = "filters-update-period";
    GeneralSettingsOption["AppearanceTheme"] = "appearance-theme";
    return GeneralSettingsOption;
}({});
const background_generalSettingsConfigValidator = background_lib/* default.object */.Ay.object({
    /**
     * The two-letter code of the application language that is used to display
     * the translations in the user interface.
     */ ["app-language"]: background_lib/* default.string */.Ay.string().optional(),
    /**
     * This option allows for "Search advertising and self-promotion":
     * advertising that the user sees among search results when using online
     * search engines, as well as a kind of "first-party" advertising on sites
     * that promote that particular site or closely related sites, social
     * networks, and so on.
     *
     * @see https://adguard.com/kb/general/ad-filtering/search-ads/
     */ ["allow-acceptable-ads"]: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * Whether or not to show the number of blocked ads on the extension icon.
     */ ["show-blocked-ads-count"]: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * Should the extension automatically enable a language filter that matches
     * the top-level domain.
     */ ["autodetect-filters"]: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * This setting enables module that protects against malicious and phishing
     * sites by checking the url hash in a database of malicious or phishing
     * sites.
     *
     * @see https://adguard.com/kb/general/browsing-security/
     */ ["safebrowsing-enabled"]: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * Time interval between filter updates.
     */ ["filters-update-period"]: background_lib/* default.nativeEnum */.Ay.nativeEnum(background_FiltersUpdateTime),
    // TODO: Should be not optional?
    /**
     * Appearance theme of the application.
     */ ["appearance-theme"]: background_appearanceValidator.optional()
});

;// ./Extension/src/background/schema/configuration/extension-specific-settings.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
/**
 * Extension specific settings configuration.
 */ var background_ExtensionSpecificSettingsOption = /*#__PURE__*/ function(ExtensionSpecificSettingsOption) {
    ExtensionSpecificSettingsOption["UseOptimizedFilters"] = "use-optimized-filters";
    ExtensionSpecificSettingsOption["CollectHitsCount"] = "collect-hits-count";
    ExtensionSpecificSettingsOption["ShowContextMenu"] = "show-context-menu";
    ExtensionSpecificSettingsOption["ShowInfoAboutAdguard"] = "show-info-about-adguard";
    ExtensionSpecificSettingsOption["ShowAppUpdatedInfo"] = "show-app-updated-info";
    ExtensionSpecificSettingsOption["HideRateAdguard"] = "hide-rate-adguard";
    ExtensionSpecificSettingsOption["UserRulesEditorWrap"] = "user-rules-editor-wrap";
    return ExtensionSpecificSettingsOption;
}({});
const background_extensionSpecificSettingsConfigValidator = background_lib/* default.object */.Ay.object({
    /**
     * If the flag is set to true, the application uses the optimized versions
     * of filter lists — the lists which contain needed and popular rules.
     *
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#not_optimized-hint for details.
     */ ["use-optimized-filters"]: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * If the flag is set to true, the application will send anonymous
     * statistics about the use of ad filters, which will help us to improve and
     * optimize them: for example, to remove obsolete rules in order to reduce
     * the time it takes to apply the rules.
     *
     * @see https://adguard.com/kb/general/ad-filtering/tracking-filter-statistics/ for clarification.
     */ ["collect-hits-count"]: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * Whether or not to add filtering options (add domain to allowlist,
     * enable or disable filtering) to the context menu (available by
     * right-clicking) in the browser.
     */ ["show-context-menu"]: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * If set to true - a banner will be displayed in the extensions
     * settings with information about AdGuard's system ad blocking app.
     */ ["show-info-about-adguard"]: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * If set to true - the extension will show app update notifications.
     */ ["show-app-updated-info"]: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * If set to true - the extension will hide the block about requesting
     * feedback with rating in the extension settings.
     */ ["hide-rate-adguard"]: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * If set to true - the extension will enable word wrap in the user rules
     * editor to display a window without horizontal scroll bars.
     */ ["user-rules-editor-wrap"]: background_lib/* default.boolean */.Ay.boolean()
});

;// ./Extension/src/background/schema/configuration/custom-filters.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
/**
 * Keys of options for custom filter in the configuration.
 */ var background_CustomFilterOption = /*#__PURE__*/ function(CustomFilterOption) {
    CustomFilterOption["CustomUrl"] = "customUrl";
    CustomFilterOption["Title"] = "title";
    CustomFilterOption["Trusted"] = "trusted";
    CustomFilterOption["Enabled"] = "enabled";
    return CustomFilterOption;
}({});
const background_customFiltersConfigValidator = background_lib/* default.array */.Ay.array(background_lib/* default.object */.Ay.object({
    /**
         * The filter subscription URL from which the application retrieved
         * the rules when adding the filter and should retrieve the rules when
         * updating it.
         */ ["customUrl"]: background_lib/* default.string */.Ay.string(),
    /**
         * Name of the filter.
         */ ["title"]: background_lib/* default.string */.Ay.string().optional(),
    /**
         * If this filter is not trusted - tsurlfilter will not execute JS rules
         * and will not apply header removal rules from this filter.
         * Otherwise, no restrictions.
         *
         * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#trusted-filters.
         */ ["trusted"]: background_lib/* default.boolean */.Ay.boolean(),
    /**
         * Is filter enabled or not.
         */ ["enabled"]: background_lib/* default.boolean */.Ay.boolean()
}));

;// ./Extension/src/background/schema/configuration/user-filter.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
// User filter configuration
var background_UserFilterOption = /*#__PURE__*/ function(UserFilterOption) {
    UserFilterOption["Rules"] = "rules";
    UserFilterOption["DisabledRules"] = "disabled-rules";
    UserFilterOption["Enabled"] = "enabled";
    return UserFilterOption;
}({});
const background_userFilterValidator = background_lib/* default.object */.Ay.object({
    /**
     * User rules concatenated with '\n'.
     */ ["rules"]: background_lib/* default.string */.Ay.string(),
    /**
     * In previous versions, rules could be marked as disabled.
     * Currently not in use.
     *
     * @deprecated
     */ ["disabled-rules"]: background_lib/* default.string */.Ay.string(),
    /**
     * Is enabled user rules or not.
     */ ["enabled"]: background_lib/* default.boolean */.Ay.boolean().optional()
});

;// ./Extension/src/background/schema/configuration/allowlist.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
// Allowlist configuration
var background_AllowlistOption = /*#__PURE__*/ function(AllowlistOption) {
    AllowlistOption["Inverted"] = "inverted";
    AllowlistOption["Domains"] = "domains";
    AllowlistOption["InvertedDomains"] = "inverted-domains";
    AllowlistOption["Enabled"] = "enabled";
    return AllowlistOption;
}({});
const background_allowlistValidator = background_lib/* default.object */.Ay.object({
    /**
     * If `AllowlistOption.Inverted` === false (the default state),
     * the extension will use this list of domains to disable ad blocking on
     * them. In other words, the extension will apply ad blocking everywhere,
     * EXCEPT the domains on this list.
     */ ["domains"]: background_lib/* default.array */.Ay.array(background_lib/* default.string */.Ay.string()),
    /**
     * If `AllowlistOption.Inverted` === true, the extension will use this list
     * to disable ad blocking for all sites but not these sites. In other words,
     * the extension will work ONLY on domains from this list.
     */ ["inverted-domains"]: background_lib/* default.array */.Ay.array(background_lib/* default.string */.Ay.string()),
    /**
     * Is allowlist list enabled or not.
     */ ["enabled"]: background_lib/* default.boolean */.Ay.boolean().optional(),
    /**
     * If this flag is true, the application will work ONLY with domains from
     * the 'domains' list, otherwise it will work everywhere EXCLUDING domains
     * from the list.
     */ ["inverted"]: background_lib/* default.boolean */.Ay.boolean().optional()
});

;// ./Extension/src/background/schema/configuration/filters.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 



// AdGuard filters configuration
var background_FiltersOption = /*#__PURE__*/ function(FiltersOption) {
    FiltersOption["EnabledGroups"] = "enabled-groups";
    FiltersOption["EnabledFilters"] = "enabled-filters";
    FiltersOption["CustomFilters"] = "custom-filters";
    FiltersOption["UserFilter"] = "user-filter";
    FiltersOption["Allowlist"] = "allowlist";
    return FiltersOption;
}({});
const background_filtersConfigValidator = background_lib/* default.object */.Ay.object({
    /**
     * List of IDs of enabled filter groups.
     */ ["enabled-groups"]: background_lib/* default.array */.Ay.array(background_lib/* default.number */.Ay.number().int()),
    /**
     * List of IDs of enabled filters.
     */ ["enabled-filters"]: background_lib/* default.array */.Ay.array(background_lib/* default.number */.Ay.number().int()),
    /**
     * List of objects with information about custom filters.
     */ ["custom-filters"]: background_customFiltersConfigValidator,
    /**
     * An object with concatenated user rules and their status - enabled or not.
     */ ["user-filter"]: background_userFilterValidator,
    /**
     * Object with the allowlist domains, the inverted allowlist domains and
     * which one applies.
     */ ["allowlist"]: background_allowlistValidator
});

;// ./Extension/src/background/schema/configuration/stealth.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
// Stealth configuration
var background_stealth_StealthOption = /*#__PURE__*/ function(StealthOption) {
    StealthOption["DisableStealthMode"] = "stealth-disable-stealth-mode";
    StealthOption["HideReferrer"] = "stealth-hide-referrer";
    StealthOption["HideSearchQueries"] = "stealth-hide-search-queries";
    StealthOption["SendDoNotTrack"] = "stealth-send-do-not-track";
    StealthOption["BlockWebRTC"] = "stealth-block-webrtc";
    StealthOption["RemoveXClientData"] = "stealth-remove-x-client";
    StealthOption["SelfDestructThirdPartyCookies"] = "stealth-block-third-party-cookies";
    StealthOption["SelfDestructThirdPartyCookiesTime"] = "stealth-block-third-party-cookies-time";
    StealthOption["SelfDestructFirstPartyCookies"] = "stealth-block-first-party-cookies";
    StealthOption["SelfDestructFirstPartyCookiesTime"] = "stealth-block-first-party-cookies-time";
    StealthOption["BlockKnownTrackers"] = "block-known-trackers";
    StealthOption["StripTrackingParams"] = "strip-tracking-parameters";
    return StealthOption;
}({});
const background_stealthConfigValidator = background_lib/* default.object */.Ay.object({
    /**
     * Whether Tracking protection (formerly Stealth mode) is disabled or not.
     */ ["stealth-disable-stealth-mode"]: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * Should the application hide the origin referrer in third-party requests
     * by replacing the referrer url with the url from the requested url.
     */ ["stealth-hide-referrer"]: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * Should the application hide the original referrer from the search page
     * containing the search query in third-party queries, replacing
     * the referrer url with the url from the requested url.
     */ ["stealth-hide-search-queries"]: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * Includes HTTP headers 'DNT' and 'Sec-GPC' in all requests.
     *
     * @see https://www.wikiwand.com/en/Do_Not_Track
     * @see https://globalprivacycontrol.org
     */ ["stealth-send-do-not-track"]: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * Blocks the possibility of leaking your IP address through WebRTC, even if
     * you use a proxy server or VPN.
     */ ["stealth-block-webrtc"]: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * For Google Chrome, it removes the 'X-Client-Data' header from
     * the requests, which contains information about the browser version
     * and modifications.
     */ ["stealth-remove-x-client"]: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * Whether or not the application should set a fixed lifetime from
     * `StealthOption.SelfDestructThirdPartyCookiesTime` for third-party
     * cookies.
     */ ["stealth-block-third-party-cookies"]: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * Time in milliseconds to delete third-party cookies.
     */ ["stealth-block-third-party-cookies-time"]: background_lib/* default.number */.Ay.number(),
    /**
     * Whether or not the application should set a fixed lifetime from
     * `StealthOption.SelfDestructFirstPartyCookiesTime` for first-party
     * cookies.
     */ ["stealth-block-first-party-cookies"]: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * Time in milliseconds to delete first-party cookies.
     */ ["stealth-block-first-party-cookies-time"]: background_lib/* default.number */.Ay.number(),
    /**
     * If true application will enable AdGuard Tracking Protection filter
     * {@link AntiBannerFiltersId.TrackingFilterId}.
     */ ["block-known-trackers"]: background_lib/* default.boolean */.Ay.boolean().optional(),
    /**
     * If true application will enable AdGuard URL Tracking filter
     * {@link AntiBannerFiltersId.UrlTrackingFilterId}.
     */ ["strip-tracking-parameters"]: background_lib/* default.boolean */.Ay.boolean()
});

;// ./Extension/src/background/schema/configuration/main.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 




// Root configuration
const background_PROTOCOL_VERSION = '2.0';
var background_RootOption = /*#__PURE__*/ function(RootOption) {
    RootOption["ProtocolVersion"] = "protocol-version";
    RootOption["GeneralSettings"] = "general-settings";
    RootOption["ExtensionSpecificSettings"] = "extension-specific-settings";
    RootOption["Filters"] = "filters";
    RootOption["Stealth"] = "stealth";
    return RootOption;
}({});
const background_configValidator = background_lib/* default.object */.Ay.object({
    /**
     * Describes the current version of the object. This is necessary to check
     * if we need to migrate from the old settings.
     */ ["protocol-version"]: background_lib/* default.literal */.Ay.literal(background_PROTOCOL_VERSION),
    /**
     * Contains general application settings: appearance theme, language, time
     * to check for updates to filters and some filtering options.
     */ ["general-settings"]: background_generalSettingsConfigValidator,
    /**
     * Contains some additional extension settings and UI settings.
     */ ["extension-specific-settings"]: background_extensionSpecificSettingsConfigValidator,
    /**
     * Contains all information about filters: regular, custom, user filter and
     * allowlist.
     */ ["filters"]: background_filtersConfigValidator,
    /**
     * Contains various secure browsing settings: cookie deletion time, privacy
     * headers, referrer hiding, and the ability to enable additional filters.
     */ ["stealth"]: background_stealthConfigValidator.optional()
});

;// ./Extension/src/background/schema/configuration/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 








;// ./Extension/src/background/schema/metadata/filter.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
const background_baseMetadataValidator = background_lib/* default.object */.Ay.object({
    /**
     * Description of the filter.
     */ description: background_lib/* default.string */.Ay.string(),
    /**
     * Display number is used to arrange the filters in the layout.
     */ displayNumber: background_lib/* default.number */.Ay.number(),
    /**
     * The time in seconds during which the filter content remains fresh
     * and does not need to be updated. Used to auto-renew filters if the user
     * has not selected a custom update period for filters.
     */ expires: background_lib/* default.number */.Ay.number(),
    /**
     * Id of the filter.
     */ filterId: background_lib/* default.number */.Ay.number(),
    /**
     * Id of the filter's group.
     */ groupId: background_lib/* default.number */.Ay.number(),
    /**
     * URL address of the filter's homepage.
     */ homepage: background_lib/* default.string */.Ay.string(),
    /**
     * Name of the filter.
     */ name: background_lib/* default.string */.Ay.string(),
    /**
     * Filter tags are used to group filters by different characteristics:
     * language, target, platform, etc.
     */ tags: background_lib/* default.number */.Ay.number().array(),
    /**
     * Version filter. Supports up to {@link Version.MAX_LENGTH} parts per
     * version.
     */ version: background_lib/* default.string */.Ay.string(),
    /**
     * Diff-Path - Path to the patches if exists.
     *
     * @see {@link https://github.com/ameshkov/diffupdates/tree/b81243c50d23e0a8be0fe95a80d55abd00b08981?tab=readme-ov-file#-diff-path | Specs}.
     */ diffPath: background_lib/* default.string */.Ay.string().optional()
});
const background_regularFilterMetadataValidator = background_baseMetadataValidator.merge(background_lib/* default.object */.Ay.object({
    /**
         * Two-letter language codes that are associated with the filter.
         */ languages: background_lib/* default.string */.Ay.string().array(),
    /**
         * Timestamp of adding filters in MS.
         * String format, since these values are retrieved from the backend.
         */ timeAdded: background_lib/* default.string */.Ay.string(),
    /**
         * When the filter was last updated in milliseconds since the start of
         * the UNIX epoch.
         * String format, since these values are retrieved from the backend.
         */ timeUpdated: background_lib/* default.string */.Ay.string(),
    /**
         * The filter subscription URL from which the application retrieved
         * the rules when adding the filter and should retrieve the rules when
         * updating it.
         */ subscriptionUrl: background_lib/* default.string */.Ay.string()
}));

;// ./Extension/src/background/schema/metadata/tag.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
const background_tagMetadataValidator = background_lib/* default.object */.Ay.object({
    /**
     * Id of the tag.
     */ tagId: background_lib/* default.number */.Ay.number(),
    /**
     * Tag value, e.g., `lang:en`, `recommended`.
     */ keyword: background_lib/* default.string */.Ay.string(),
    /**
     * Description of the tag.
     */ description: background_lib/* default.string */.Ay.string().optional(),
    /**
     * Name of the tag.
     */ name: background_lib/* default.string */.Ay.string().optional()
});

;// ./Extension/src/background/schema/metadata/group.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
const background_groupMetadataValidator = background_lib/* default.object */.Ay.object({
    /**
     * Display number is used to arrange the groups in the layout.
     */ displayNumber: background_lib/* default.number */.Ay.number(),
    /**
     * Id of the group.
     */ groupId: background_lib/* default.number */.Ay.number(),
    /**
     * Name of the group.
     */ groupName: background_lib/* default.string */.Ay.string()
});

;// ./Extension/src/background/schema/metadata/metadata.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 



const background_metadata_metadataValidator = background_lib/* default.object */.Ay.object({
    /**
     * Array of {@link RegularFilterMetadata}.
     */ filters: background_regularFilterMetadataValidator.array(),
    /**
     * Array of {@link GroupMetadata}.
     */ groups: background_groupMetadataValidator.array(),
    /**
     * Array of {@link TagMetadata}.
     */ tags: background_tagMetadataValidator.array()
});

;// ./Extension/src/background/schema/metadata/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 




;// ./Extension/src/background/schema/i18n-metadata/filter.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
const background_filterInfoValidator = background_lib/* default.object */.Ay.object({
    /**
     * Description of the filter.
     */ description: background_lib/* default.string */.Ay.string(),
    /**
     * Name of the filter.
     */ name: background_lib/* default.string */.Ay.string()
});
const background_regularFilterI18nMetadataValidator = background_lib/* default.record */.Ay.record(/**
     * Locale code.
     */ background_lib/* default.string */.Ay.string(), background_filterInfoValidator);

;// ./Extension/src/background/schema/i18n-metadata/tag.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
const background_tagInfoValidator = background_lib/* default.object */.Ay.object({
    /**
     * Description of the tag.
     */ description: background_lib/* default.string */.Ay.string(),
    /**
     * Name of the tag.
     */ name: background_lib/* default.string */.Ay.string()
});
const background_tagI18nMetadataValidator = background_lib/* default.record */.Ay.record(/**
     * Locale code.
     */ background_lib/* default.string */.Ay.string(), background_tagInfoValidator);

;// ./Extension/src/background/schema/i18n-metadata/group.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
const background_groupName = background_lib/* default.object */.Ay.object({
    /**
     * The name of the filter group.
     */ name: background_lib/* default.string */.Ay.string()
});
const background_groupI18nMetadataValidator = background_lib/* default.record */.Ay.record(/**
     * Locale code.
     */ background_lib/* default.string */.Ay.string(), background_groupName);

;// ./Extension/src/background/schema/i18n-metadata/i18n-metadata.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 




const background_filtersI18nRecordValidator = background_lib/* default.record */.Ay.record(background_SchemaPreprocessor.numberValidator, background_regularFilterI18nMetadataValidator);
const background_groupsI18nRecordValidator = background_lib/* default.record */.Ay.record(background_SchemaPreprocessor.numberValidator, background_groupI18nMetadataValidator);
const background_tagsI18nRecordValidator = background_lib/* default.record */.Ay.record(background_SchemaPreprocessor.numberValidator, background_tagI18nMetadataValidator);
const background_i18nMetadataValidator = background_lib/* default.object */.Ay.object({
    /**
     * Item of {@link FiltersI18n}.
     */ filters: background_filtersI18nRecordValidator,
    /**
     * Item of {@link GroupsI18n}.
     */ groups: background_groupsI18nRecordValidator,
    /**
     * Item of {@link TagsI18n}.
     */ tags: background_tagsI18nRecordValidator
});

;// ./Extension/src/background/schema/i18n-metadata/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 




;// ./Extension/src/background/schema/filter-version/filter-version.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

/**
 * Runtime validator for persistent filter version data.
 */ const background_filterVersionDataValidator = background_lib/* default.object */.Ay.object({
    /**
     * Version of filter. Usually consists of 4 parts: 1.2.3.4.
     */ version: background_lib/* default.string */.Ay.string(),
    /**
     * The time in millisecond of the last forced update: if the user clicks
     * the forced update check from the user interface or if the user enabled
     * the filter or group.
     */ lastCheckTime: background_lib/* default.number */.Ay.number(),
    /**
     * The time in millisecond of the last check by the scheduler: every
     * {@link FilterUpdateService.CHECK_PERIOD_MS period} the time of the last
     * check will be overwritten by the scheduler.
     */ lastScheduledCheckTime: background_lib/* default.number */.Ay.number(),
    /**
     * The time in millisecond of the last update filter from remote resources.
     */ lastUpdateTime: background_lib/* default.number */.Ay.number(),
    /**
     * The time in seconds during which the filter content remains fresh
     * and does not need to be updated. Used to auto-renew filters if the user
     * has not selected a custom update period for filters.
     */ expires: background_lib/* default.number */.Ay.number(),
    /**
     * Diff-Path - Path to the patches if exists.
     *
     * @see {@link https://github.com/ameshkov/diffupdates/tree/b81243c50d23e0a8be0fe95a80d55abd00b08981?tab=readme-ov-file#-diff-path | Specs}.
     */ diffPath: background_lib/* default.string */.Ay.string().optional(),
    /**
     * Flag that indicates that the filter could not be updated by patches
     * and should wait for the full update.
     *
     * @see {@link https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2717}
     */ shouldWaitFullUpdate: background_lib/* default.boolean */.Ay.boolean().optional()
});
/**
 * Runtime validator for persistent key value storage of filter version data.
 *
 * Key is filter metadata id.
 * Value is {@link FilterVersionData}.
 */ const background_filterVersionStorageDataValidator = background_lib/* default.record */.Ay.record(background_SchemaPreprocessor.numberValidator, background_filterVersionDataValidator);

;// ./Extension/src/background/schema/filter-version/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ // Filter version schema entry point
// Filter version validators and types


;// ./Extension/src/background/schema/filter-state/filter-state.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

/**
 * Runtime validator for persistent filter state data.
 */ const background_filterStateDataValidator = background_lib/* default.object */.Ay.object({
    /**
     * Is filter enabled or not.
     */ enabled: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * Is filter rules loaded into browser storage or not.
     *
     * TODO: Check if it can be deleted, because we add all filters to
     * the browser storage and this field is always true.
     */ installed: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * Is filter loaded.
     *
     * TODO: Check if it can be deleted.
     */ loaded: background_lib/* default.boolean */.Ay.boolean()
});
/**
 * Runtime validator for persistent key value storage of filter state data.
 *
 * Key is filter metadata id.
 * Value is {@link FilterStateData}.
 */ const background_filterStateStorageDataValidator = background_lib/* default.record */.Ay.record(background_SchemaPreprocessor.numberValidator, background_filterStateDataValidator);

;// ./Extension/src/background/schema/filter-state/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ // Filter state schema entry point
// Filter state validators and types


;// ./Extension/src/background/schema/group-state/group-state.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

/**
 * Runtime validator for persistent group state data.
 */ const background_groupStateDataValidator = background_lib/* default.object */.Ay.object({
    /**
     * Is group enabled or not.
     */ enabled: background_lib/* default.boolean */.Ay.boolean(),
    /**
     * Whether the group has ever been switched. Can be affected
     * programmatically, e.g. After importing settings.
     */ touched: background_lib/* default.boolean */.Ay.boolean()
});
/**
 * Runtime validator for persistent key value storage of group state data.
 *
 * Key is group metadata id.
 * Value is {@link GroupStateData}.
 */ const background_groupStateStorageDataValidator = background_lib/* default.record */.Ay.record(background_SchemaPreprocessor.numberValidator, background_groupStateDataValidator);

;// ./Extension/src/background/schema/group-state/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ // Group state schema entry point
// Group state validators and types


;// ./Extension/src/background/schema/trusted-domains/trusted-domains.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
/**
 * Runtime validator for persistent trusted domains data.
 */ const background_trustedDomainDataValidator = background_lib/* default.object */.Ay.object({
    /**
     * String domain which was excluded from filtering.
     */ domain: background_lib/* default.string */.Ay.string(),
    /**
     * For what time domain was excluded in milliseconds.
     */ expires: background_lib/* default.number */.Ay.number()
});

;// ./Extension/src/background/schema/trusted-domains/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

;// ./Extension/src/background/schema/page-stats/page-stats.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
/**
 * Describes the relationship between the number of blocked requests and
 * the name of the group (similar to the tag).
 */ const background_pageStatsDataItemValidator = background_lib/* default.record */.Ay.record(background_lib/* default.string */.Ay.string(), background_lib/* default.number */.Ay.number());
const background_pageStatsDataValidator = background_lib/* default.object */.Ay.object({
    /**
     * Blocked requests grouped by hours.
     */ hours: background_pageStatsDataItemValidator.array(),
    /**
     * Blocked requests grouped by days.
     */ days: background_pageStatsDataItemValidator.array(),
    /**
     * Blocked requests grouped by months.
     */ months: background_pageStatsDataItemValidator.array(),
    /**
     * The time stamp of the last update. In milliseconds.
     */ updated: background_lib/* default.number */.Ay.number()
});
const background_pageStatsValidator = background_lib/* default.object */.Ay.object({
    /**
     * Total blocked requests.
     */ totalBlocked: background_lib/* default.number */.Ay.number().optional(),
    /**
     * Blocked requests grouped by time.
     */ data: background_pageStatsDataValidator.optional()
});

;// ./Extension/src/background/schema/page-stats/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ // Page stats schema entry point
// page stats validators and types


;// ./Extension/src/background/schema/hit-stats/hit-stats.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
const background_filterRulesHitsValidator = background_lib/* default.record */.Ay.record(/**
     * Index of rule.
     */ background_lib/* default.string */.Ay.string(), /**
     * The number of matches of this rule.
     */ background_lib/* default.number */.Ay.number());
const background_filterHitsValidator = background_lib/* default.record */.Ay.record(/**
     * Filter's id.
     */ background_lib/* default.string */.Ay.string(), background_filterRulesHitsValidator.optional());
const background_hitStatsValidator = background_lib/* default.object */.Ay.object({
    /**
     * Contains an object with filter IDs as keys and their
     * {@link filterRulesHitsValidator} as values.
     */ filters: background_filterHitsValidator.optional()
}).strict();
const background_filtersVersionsValidator = background_lib/* default.record */.Ay.record(/**
     * Filter's id.
     */ background_lib/* default.string */.Ay.string(), /**
     * Version of the filter.
     */ background_lib/* default.string */.Ay.string());
const background_hitStatsStorageDataValidator = background_lib/* default.object */.Ay.object({
    /**
     * The number of hits in relation to the hit rule.
     */ stats: background_hitStatsValidator.optional(),
    /**
     * Contains an object with filter IDs as keys and their versions as values.
     */ versions: background_filtersVersionsValidator.optional(),
    /**
     * The total number of hits with no link to the rules.
     */ totalHits: background_lib/* default.number */.Ay.number().optional()
}).strict();

;// ./Extension/src/background/schema/hit-stats/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ // Hit stats schema entry point
// hit stats validators and types


;// ./Extension/src/background/schema/custom-filter-metadata/custom-filter-metadata.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

const background_customFilterMetadataValidator = background_baseMetadataValidator.merge(background_lib/* default.object */.Ay.object({
    /**
         * The filter subscription URL from which the application retrieved
         * the rules when adding the filter and should retrieve the rules when
         * updating it.
         */ customUrl: background_lib/* default.string */.Ay.string(),
    /**
         * If this filter is not trusted - tsurlfilter will not execute JS rules
         * and will not apply header removal rules from this filter.
         * Otherwise, no restrictions.
         */ trusted: background_lib/* default.boolean */.Ay.boolean(),
    /**
         * When the filter was last updated in milliseconds since the start of
         * the UNIX epoch.
         */ timeUpdated: background_lib/* default.number */.Ay.number(),
    /**
         * Contains MD5 checksum for the filter content.
         */ checksum: background_lib/* default.string */.Ay.string().or(background_lib/* default.null */.Ay["null"]())
}));
const background_customFilterMetadataStorageDataValidator = background_customFilterMetadataValidator.array();

;// ./Extension/src/background/schema/custom-filter-metadata/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ // Custom filter metadata schema entry point
// Custom filter metadata validators and types


;// ./Extension/src/background/schema/local-script-rules/local-script-rules.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
const background_localScriptRulesValidator = background_lib/* default.object */.Ay.object({
    /**
     * Contains a comment describing the purpose of the local script rules file.
     */ comment: background_lib/* default.string */.Ay.string(),
    /**
     * JS rules from all of our filters are pre-assembled into this object to be
     * checked in Firefox AMO to see if they can be executed.
     */ rules: background_lib/* default.record */.Ay.record(/**
         * Key is the cosmetic rule body.
         */ background_lib/* default.string */.Ay.string(), /**
         * Value is the array of cosmetic rule scope (on which domains it should be applied).
         * If multiple rules are using the same body, their scopes are pushed to this array,
         * if they are not already there.
         */ background_lib/* default.object */.Ay.object({
        /**
             * The array of domains on which the rule can be executed.
             */ permittedDomains: background_lib/* default.array */.Ay.array(background_lib/* default.string */.Ay.string()),
        /**
             * The array of domains on which the rule cannot be executed.
             */ restrictedDomains: background_lib/* default.array */.Ay.array(background_lib/* default.string */.Ay.string())
    }).array())
}).strict();

;// ./Extension/src/background/schema/local-script-rules/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

;// ./Extension/src/background/schema/notification/notification-text-record.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
const background_notificationTextRecordValidator = background_lib/* default.object */.Ay.object({
    /**
     * Notification title.
     */ title: background_lib/* default.string */.Ay.string(),
    /**
     * Notification description.
     */ desc: background_lib/* default.string */.Ay.string().optional(),
    /**
     * Text for the notification button.
     */ btn: background_lib/* default.string */.Ay.string()
}).strict();

;// ./Extension/src/background/schema/notification/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

;// ./Extension/src/background/schema/safebrowsing/safebrowsing.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
/**
 * Safebrowsing cache data schema validator.
 */ const background_safebrowsingCacheDataValidator = background_lib/* default.string */.Ay.string();
/**
 * Safebrowsing persisted storage data schema validator.
 */ const background_safebrowsingStorageDataValidator = background_lib/* default.tuple */.Ay.tuple([
    /**
     * Cache key.
     */ background_lib/* default.string */.Ay.string(),
    /**
     * Cache value.
     *
     * @note lru-cache using `.dump()` method to export cache data and `.load()` to import it,
     * and both methods use the following data structure:
     * {@link http://isaacs.github.io/node-lru-cache/interfaces/LRUCache.Entry.html}
     */ background_lib/* default.object */.Ay.object({
        /**
         * Size of cache record.
         */ size: background_lib/* default.number */.Ay.number().optional(),
        /**
         * Record creation time in milliseconds.
         */ start: background_lib/* default.number */.Ay.number().optional(),
        /**
         * TTL of cache record in milliseconds.
         */ ttl: background_lib/* default.number */.Ay.number().optional(),
        /**
         * Cache data.
         */ value: background_safebrowsingCacheDataValidator
    }).strict()
]).array();

;// ./Extension/src/background/schema/safebrowsing/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

;// ./Extension/src/background/schema/annoyances-consent/annoyances-consent.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
const background_annoyancesConsentStorageDataValidator = background_lib/* default.array */.Ay.array(background_lib/* default.number */.Ay.number());

;// ./Extension/src/background/schema/annoyances-consent/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ // Annoyances consent schema entry point
// annoyances consent validators and types


;// ./Extension/src/background/schema/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
















;// ./Extension/src/background/utils/string-storage.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_string_storage_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}

/**
 * Class for managing data that is persisted as string in another key value storage.
 */ class background_StringStorage {
    /**
     * Returns cached data.
     *
     * @returns Cached data.
     *
     * @throws Error, if cache is not initialized.
     */ getData() {
        if (!this.data) {
            throw new Error('Data is not set!');
        }
        return this.data;
    }
    /**
     * Sets parsed data to cache.
     *
     * @param data Parsed storage data.
     */ setCache(data) {
        this.data = data;
    }
    /**
     * Sets {@link data} to cache and saves it's stringified version in {@link storage}.
     *
     * @param data Parsed data.
     *
     * @returns Promise, resolved when stringified {@link data} is saved in {@link storage} and {@link Mode} is async.
     */ setData(data) {
        this.setCache(data);
        return this.save();
    }
    /**
     * Saves stringified {@link data} in {@link storage}.
     *
     * @returns Promise, resolved when stringified {@link data} is saved in {@link storage} and {@link Mode} is async.
     */ save() {
        return this.storage.set(this.key, JSON.stringify(this.data));
    }
    /**
     * Reads raw data from {@link storage}.
     *
     * Note: this method returns 'unknown', because in fact we don't know, what data stored in {@link storage}.
     * You should validate it after reading by this method.
     * In case of {@link StringStorage} we expect string.
     *
     * @returns Promise, resolved with raw data from {@link storage}, if {@link Mode} is async,
     * else returns raw data.
     */ read() {
        return this.storage.get(this.key);
    }
    /**
     * Creates new StringStorage.
     *
     * @param key Parent storage key.
     * @param storage Parent storage.
     */ constructor(key, storage){
        // parent storage key
        background_string_storage_define_property(this, "key", void 0);
        // parent storage
        background_string_storage_define_property(this, "storage", void 0);
        // cached parsed data
        background_string_storage_define_property(this, "data", void 0);
        this.key = key;
        this.storage = storage;
    }
}

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isObject.js
/**
 * Checks if `value` is the
 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(_.noop);
 * // => true
 *
 * _.isObject(null);
 * // => false
 */
function background_isObject(value) {
  var type = typeof value;
  return value != null && (type == 'object' || type == 'function');
}

/* harmony default export */ const background_lodash_es_isObject = (background_isObject);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_freeGlobal.js
/** Detect free variable `global` from Node.js. */
var background_freeGlobal = typeof global == 'object' && global && global.Object === Object && global;

/* harmony default export */ const pages_background_freeGlobal = (background_freeGlobal);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_root.js


/** Detect free variable `self`. */
var background_freeSelf = typeof self == 'object' && self && self.Object === Object && self;

/** Used as a reference to the global object. */
var background_root = pages_background_freeGlobal || background_freeSelf || Function('return this')();

/* harmony default export */ const pages_background_root = (background_root);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/now.js


/**
 * Gets the timestamp of the number of milliseconds that have elapsed since
 * the Unix epoch (1 January 1970 00:00:00 UTC).
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Date
 * @returns {number} Returns the timestamp.
 * @example
 *
 * _.defer(function(stamp) {
 *   console.log(_.now() - stamp);
 * }, _.now());
 * // => Logs the number of milliseconds it took for the deferred invocation.
 */
var background_now = function() {
  return pages_background_root.Date.now();
};

/* harmony default export */ const background_lodash_es_now = (background_now);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_trimmedEndIndex.js
/** Used to match a single whitespace character. */
var background_reWhitespace = /\s/;

/**
 * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
 * character of `string`.
 *
 * @private
 * @param {string} string The string to inspect.
 * @returns {number} Returns the index of the last non-whitespace character.
 */
function background_trimmedEndIndex(string) {
  var index = string.length;

  while (index-- && background_reWhitespace.test(string.charAt(index))) {}
  return index;
}

/* harmony default export */ const pages_background_trimmedEndIndex = (background_trimmedEndIndex);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseTrim.js


/** Used to match leading whitespace. */
var background_reTrimStart = /^\s+/;

/**
 * The base implementation of `_.trim`.
 *
 * @private
 * @param {string} string The string to trim.
 * @returns {string} Returns the trimmed string.
 */
function background_baseTrim(string) {
  return string
    ? string.slice(0, pages_background_trimmedEndIndex(string) + 1).replace(background_reTrimStart, '')
    : string;
}

/* harmony default export */ const pages_background_baseTrim = (background_baseTrim);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Symbol.js


/** Built-in value references. */
var background_Symbol_Symbol = pages_background_root.Symbol;

/* harmony default export */ const background_Symbol = (background_Symbol_Symbol);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getRawTag.js


/** Used for built-in method references. */
var background_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var background_getRawTag_hasOwnProperty = background_objectProto.hasOwnProperty;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var background_nativeObjectToString = background_objectProto.toString;

/** Built-in value references. */
var background_symToStringTag = background_Symbol ? background_Symbol.toStringTag : undefined;

/**
 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the raw `toStringTag`.
 */
function background_getRawTag(value) {
  var isOwn = background_getRawTag_hasOwnProperty.call(value, background_symToStringTag),
      tag = value[background_symToStringTag];

  try {
    value[background_symToStringTag] = undefined;
    var unmasked = true;
  } catch (e) {}

  var result = background_nativeObjectToString.call(value);
  if (unmasked) {
    if (isOwn) {
      value[background_symToStringTag] = tag;
    } else {
      delete value[background_symToStringTag];
    }
  }
  return result;
}

/* harmony default export */ const pages_background_getRawTag = (background_getRawTag);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_objectToString.js
/** Used for built-in method references. */
var background_objectToString_objectProto = Object.prototype;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var background_objectToString_nativeObjectToString = background_objectToString_objectProto.toString;

/**
 * Converts `value` to a string using `Object.prototype.toString`.
 *
 * @private
 * @param {*} value The value to convert.
 * @returns {string} Returns the converted string.
 */
function background_objectToString(value) {
  return background_objectToString_nativeObjectToString.call(value);
}

/* harmony default export */ const pages_background_objectToString = (background_objectToString);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGetTag.js




/** `Object#toString` result references. */
var background_nullTag = '[object Null]',
    background_undefinedTag = '[object Undefined]';

/** Built-in value references. */
var background_baseGetTag_symToStringTag = background_Symbol ? background_Symbol.toStringTag : undefined;

/**
 * The base implementation of `getTag` without fallbacks for buggy environments.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
function background_baseGetTag(value) {
  if (value == null) {
    return value === undefined ? background_undefinedTag : background_nullTag;
  }
  return (background_baseGetTag_symToStringTag && background_baseGetTag_symToStringTag in Object(value))
    ? pages_background_getRawTag(value)
    : pages_background_objectToString(value);
}

/* harmony default export */ const pages_background_baseGetTag = (background_baseGetTag);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isObjectLike.js
/**
 * Checks if `value` is object-like. A value is object-like if it's not `null`
 * and has a `typeof` result of "object".
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
 * @example
 *
 * _.isObjectLike({});
 * // => true
 *
 * _.isObjectLike([1, 2, 3]);
 * // => true
 *
 * _.isObjectLike(_.noop);
 * // => false
 *
 * _.isObjectLike(null);
 * // => false
 */
function background_isObjectLike(value) {
  return value != null && typeof value == 'object';
}

/* harmony default export */ const background_lodash_es_isObjectLike = (background_isObjectLike);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isSymbol.js



/** `Object#toString` result references. */
var background_symbolTag = '[object Symbol]';

/**
 * Checks if `value` is classified as a `Symbol` primitive or object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
 * @example
 *
 * _.isSymbol(Symbol.iterator);
 * // => true
 *
 * _.isSymbol('abc');
 * // => false
 */
function background_isSymbol(value) {
  return typeof value == 'symbol' ||
    (background_lodash_es_isObjectLike(value) && pages_background_baseGetTag(value) == background_symbolTag);
}

/* harmony default export */ const background_lodash_es_isSymbol = (background_isSymbol);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/toNumber.js




/** Used as references for various `Number` constants. */
var background_NAN = 0 / 0;

/** Used to detect bad signed hexadecimal string values. */
var background_reIsBadHex = /^[-+]0x[0-9a-f]+$/i;

/** Used to detect binary string values. */
var background_reIsBinary = /^0b[01]+$/i;

/** Used to detect octal string values. */
var background_reIsOctal = /^0o[0-7]+$/i;

/** Built-in method references without a dependency on `root`. */
var background_freeParseInt = parseInt;

/**
 * Converts `value` to a number.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to process.
 * @returns {number} Returns the number.
 * @example
 *
 * _.toNumber(3.2);
 * // => 3.2
 *
 * _.toNumber(Number.MIN_VALUE);
 * // => 5e-324
 *
 * _.toNumber(Infinity);
 * // => Infinity
 *
 * _.toNumber('3.2');
 * // => 3.2
 */
function background_toNumber(value) {
  if (typeof value == 'number') {
    return value;
  }
  if (background_lodash_es_isSymbol(value)) {
    return background_NAN;
  }
  if (background_lodash_es_isObject(value)) {
    var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
    value = background_lodash_es_isObject(other) ? (other + '') : other;
  }
  if (typeof value != 'string') {
    return value === 0 ? value : +value;
  }
  value = pages_background_baseTrim(value);
  var isBinary = background_reIsBinary.test(value);
  return (isBinary || background_reIsOctal.test(value))
    ? background_freeParseInt(value.slice(2), isBinary ? 2 : 8)
    : (background_reIsBadHex.test(value) ? background_NAN : +value);
}

/* harmony default export */ const background_lodash_es_toNumber = (background_toNumber);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/debounce.js




/** Error message constants. */
var background_FUNC_ERROR_TEXT = 'Expected a function';

/* Built-in method references for those with the same name as other `lodash` methods. */
var background_nativeMax = Math.max,
    background_nativeMin = Math.min;

/**
 * Creates a debounced function that delays invoking `func` until after `wait`
 * milliseconds have elapsed since the last time the debounced function was
 * invoked. The debounced function comes with a `cancel` method to cancel
 * delayed `func` invocations and a `flush` method to immediately invoke them.
 * Provide `options` to indicate whether `func` should be invoked on the
 * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
 * with the last arguments provided to the debounced function. Subsequent
 * calls to the debounced function return the result of the last `func`
 * invocation.
 *
 * **Note:** If `leading` and `trailing` options are `true`, `func` is
 * invoked on the trailing edge of the timeout only if the debounced function
 * is invoked more than once during the `wait` timeout.
 *
 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
 * until to the next tick, similar to `setTimeout` with a timeout of `0`.
 *
 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
 * for details over the differences between `_.debounce` and `_.throttle`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to debounce.
 * @param {number} [wait=0] The number of milliseconds to delay.
 * @param {Object} [options={}] The options object.
 * @param {boolean} [options.leading=false]
 *  Specify invoking on the leading edge of the timeout.
 * @param {number} [options.maxWait]
 *  The maximum time `func` is allowed to be delayed before it's invoked.
 * @param {boolean} [options.trailing=true]
 *  Specify invoking on the trailing edge of the timeout.
 * @returns {Function} Returns the new debounced function.
 * @example
 *
 * // Avoid costly calculations while the window size is in flux.
 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
 *
 * // Invoke `sendMail` when clicked, debouncing subsequent calls.
 * jQuery(element).on('click', _.debounce(sendMail, 300, {
 *   'leading': true,
 *   'trailing': false
 * }));
 *
 * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
 * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
 * var source = new EventSource('/stream');
 * jQuery(source).on('message', debounced);
 *
 * // Cancel the trailing debounced invocation.
 * jQuery(window).on('popstate', debounced.cancel);
 */
function background_debounce(func, wait, options) {
  var lastArgs,
      lastThis,
      maxWait,
      result,
      timerId,
      lastCallTime,
      lastInvokeTime = 0,
      leading = false,
      maxing = false,
      trailing = true;

  if (typeof func != 'function') {
    throw new TypeError(background_FUNC_ERROR_TEXT);
  }
  wait = background_lodash_es_toNumber(wait) || 0;
  if (background_lodash_es_isObject(options)) {
    leading = !!options.leading;
    maxing = 'maxWait' in options;
    maxWait = maxing ? background_nativeMax(background_lodash_es_toNumber(options.maxWait) || 0, wait) : maxWait;
    trailing = 'trailing' in options ? !!options.trailing : trailing;
  }

  function invokeFunc(time) {
    var args = lastArgs,
        thisArg = lastThis;

    lastArgs = lastThis = undefined;
    lastInvokeTime = time;
    result = func.apply(thisArg, args);
    return result;
  }

  function leadingEdge(time) {
    // Reset any `maxWait` timer.
    lastInvokeTime = time;
    // Start the timer for the trailing edge.
    timerId = setTimeout(timerExpired, wait);
    // Invoke the leading edge.
    return leading ? invokeFunc(time) : result;
  }

  function remainingWait(time) {
    var timeSinceLastCall = time - lastCallTime,
        timeSinceLastInvoke = time - lastInvokeTime,
        timeWaiting = wait - timeSinceLastCall;

    return maxing
      ? background_nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
      : timeWaiting;
  }

  function shouldInvoke(time) {
    var timeSinceLastCall = time - lastCallTime,
        timeSinceLastInvoke = time - lastInvokeTime;

    // Either this is the first call, activity has stopped and we're at the
    // trailing edge, the system time has gone backwards and we're treating
    // it as the trailing edge, or we've hit the `maxWait` limit.
    return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
      (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
  }

  function timerExpired() {
    var time = background_lodash_es_now();
    if (shouldInvoke(time)) {
      return trailingEdge(time);
    }
    // Restart the timer.
    timerId = setTimeout(timerExpired, remainingWait(time));
  }

  function trailingEdge(time) {
    timerId = undefined;

    // Only invoke if we have `lastArgs` which means `func` has been
    // debounced at least once.
    if (trailing && lastArgs) {
      return invokeFunc(time);
    }
    lastArgs = lastThis = undefined;
    return result;
  }

  function cancel() {
    if (timerId !== undefined) {
      clearTimeout(timerId);
    }
    lastInvokeTime = 0;
    lastArgs = lastCallTime = lastThis = timerId = undefined;
  }

  function flush() {
    return timerId === undefined ? result : trailingEdge(background_lodash_es_now());
  }

  function debounced() {
    var time = background_lodash_es_now(),
        isInvoking = shouldInvoke(time);

    lastArgs = arguments;
    lastThis = this;
    lastCallTime = time;

    if (isInvoking) {
      if (timerId === undefined) {
        return leadingEdge(lastCallTime);
      }
      if (maxing) {
        // Handle invocations in a tight loop.
        clearTimeout(timerId);
        timerId = setTimeout(timerExpired, wait);
        return invokeFunc(lastCallTime);
      }
    }
    if (timerId === undefined) {
      timerId = setTimeout(timerExpired, wait);
    }
    return result;
  }
  debounced.cancel = cancel;
  debounced.flush = flush;
  return debounced;
}

/* harmony default export */ const background_lodash_es_debounce = (background_debounce);

;// ./Extension/src/background/storages/browser-storage.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_browser_storage_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
/**
 * Wrapper for StorageArea with dev-friendly interface.
 *
 * @template Data The type of the value stored in the storage.
 */ class background_BrowserStorage {
    /**
     * Sets data to storage.
     *
     * @param key Storage key.
     * @param value Storage value.
     */ async set(key, value) {
        await this.storage.set({
            [key]: value
        });
    }
    /**
     * Returns data from storage.
     *
     * @param key Storage key.
     *
     * @returns Storage value.
     */ async get(key) {
        return this.storage.get(key).then((data)=>data[key]);
    }
    /**
     * Removes data from storage.
     *
     * @param key Storage key.
     */ async remove(key) {
        await this.storage.remove(key);
    }
    /**
     * Sets multiple key-value pairs in the storage.
     *
     * @param data The key-value pairs to set.
     *
     * @returns True if all operations were successful, false otherwise.
     *
     * @example
     * ```ts
     * const storage = new Storage();
     * await storage.setMultiple({
     *    key1: 'value1',
     *    key2: 'value2',
     * });
     * ```
     */ // TODO: Implement some kind of transaction to ensure atomicity, if possible
    // Note: We only use this method for Firefox if "Never Remember History" is enabled
    async setMultiple(data) {
        try {
            await this.storage.set(data);
            return true;
        } catch (e) {
            return false;
        }
    }
    /**
     * Removes multiple key-value pairs from the storage.
     *
     * @param keys The keys to remove.
     *
     * @returns True if all operations were successful, false otherwise.
     */ async removeMultiple(keys) {
        await this.storage.remove(keys);
        return true;
    }
    /**
     * Get the entire contents of the storage.
     *
     * @returns Promise that resolves with the entire contents of the storage.
     */ async entries() {
        return this.storage.get(null);
    }
    /**
     * Get all keys from the storage.
     *
     * @returns Promise that resolves with all keys from the storage.
     */ async keys() {
        return Object.keys(await this.entries());
    }
    /**
     * Checks if the storage has a key.
     *
     * @param key The key to check.
     *
     * @returns True if the key exists, false otherwise.
     */ async has(key) {
        return this.storage.get(key).then((data)=>key in data);
    }
    /**
     * Clears the storage.
     */ async clear() {
        await this.storage.clear();
    }
    /**
     * Constructs an instance of the BrowserStorage class.
     *
     * @param storage The storage area to use.
     */ constructor(storage){
        background_browser_storage_define_property(this, "storage", void 0);
        this.storage = storage;
    }
}

;// ./node_modules/.pnpm/nanoid@3.3.6/node_modules/nanoid/index.browser.js

let background_random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
let background_customRandom = (alphabet, defaultSize, getRandom) => {
  let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
  let step = -~((1.6 * mask * defaultSize) / alphabet.length)
  return (size = defaultSize) => {
    let id = ''
    while (true) {
      let bytes = getRandom(step)
      let j = step
      while (j--) {
        id += alphabet[bytes[j] & mask] || ''
        if (id.length === size) return id
      }
    }
  }
}
let background_customAlphabet = (alphabet, size = 21) =>
  background_customRandom(alphabet, size, background_random)
let background_nanoid = (size = 21) =>
  crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
    byte &= 63
    if (byte < 36) {
      id += byte.toString(36)
    } else if (byte < 62) {
      id += (byte - 26).toString(36).toUpperCase()
    } else if (byte > 62) {
      id += '-'
    } else {
      id += '_'
    }
    return id
  }, '')


;// ./node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/double-indexed-kv.js
class background_DoubleIndexedKV {
    constructor() {
        this.keyToValue = new Map();
        this.valueToKey = new Map();
    }
    set(key, value) {
        this.keyToValue.set(key, value);
        this.valueToKey.set(value, key);
    }
    getByKey(key) {
        return this.keyToValue.get(key);
    }
    getByValue(value) {
        return this.valueToKey.get(value);
    }
    clear() {
        this.keyToValue.clear();
        this.valueToKey.clear();
    }
}

;// ./node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/registry.js

class background_Registry {
    constructor(generateIdentifier) {
        this.generateIdentifier = generateIdentifier;
        this.kv = new background_DoubleIndexedKV();
    }
    register(value, identifier) {
        if (this.kv.getByValue(value)) {
            return;
        }
        if (!identifier) {
            identifier = this.generateIdentifier(value);
        }
        this.kv.set(identifier, value);
    }
    clear() {
        this.kv.clear();
    }
    getIdentifier(value) {
        return this.kv.getByValue(value);
    }
    getValue(identifier) {
        return this.kv.getByKey(identifier);
    }
}

;// ./node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/class-registry.js

class background_ClassRegistry extends background_Registry {
    constructor() {
        super(c => c.name);
        this.classToAllowedProps = new Map();
    }
    register(value, options) {
        if (typeof options === 'object') {
            if (options.allowProps) {
                this.classToAllowedProps.set(value, options.allowProps);
            }
            super.register(value, options.identifier);
        }
        else {
            super.register(value, options);
        }
    }
    getAllowedProps(value) {
        return this.classToAllowedProps.get(value);
    }
}

;// ./node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/util.js
function background_valuesOfObj(record) {
    if ('values' in Object) {
        // eslint-disable-next-line es5/no-es6-methods
        return Object.values(record);
    }
    const values = [];
    // eslint-disable-next-line no-restricted-syntax
    for (const key in record) {
        if (record.hasOwnProperty(key)) {
            values.push(record[key]);
        }
    }
    return values;
}
function background_find(record, predicate) {
    const values = background_valuesOfObj(record);
    if ('find' in values) {
        // eslint-disable-next-line es5/no-es6-methods
        return values.find(predicate);
    }
    const valuesNotNever = values;
    for (let i = 0; i < valuesNotNever.length; i++) {
        const value = valuesNotNever[i];
        if (predicate(value)) {
            return value;
        }
    }
    return undefined;
}
function background_forEach(record, run) {
    Object.entries(record).forEach(([key, value]) => run(value, key));
}
function background_includes(arr, value) {
    return arr.indexOf(value) !== -1;
}
function background_findArr(record, predicate) {
    for (let i = 0; i < record.length; i++) {
        const value = record[i];
        if (predicate(value)) {
            return value;
        }
    }
    return undefined;
}

;// ./node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/custom-transformer-registry.js

class background_CustomTransformerRegistry {
    constructor() {
        this.transfomers = {};
    }
    register(transformer) {
        this.transfomers[transformer.name] = transformer;
    }
    findApplicable(v) {
        return background_find(this.transfomers, transformer => transformer.isApplicable(v));
    }
    findByName(name) {
        return this.transfomers[name];
    }
}

;// ./node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/is.js
const background_getType = (payload) => Object.prototype.toString.call(payload).slice(8, -1);
const background_isUndefined = (payload) => typeof payload === 'undefined';
const background_isNull = (payload) => payload === null;
const background_isPlainObject = (payload) => {
    if (typeof payload !== 'object' || payload === null)
        return false;
    if (payload === Object.prototype)
        return false;
    if (Object.getPrototypeOf(payload) === null)
        return true;
    return Object.getPrototypeOf(payload) === Object.prototype;
};
const background_isEmptyObject = (payload) => background_isPlainObject(payload) && Object.keys(payload).length === 0;
const background_is_isArray = (payload) => Array.isArray(payload);
const background_is_isString = (payload) => typeof payload === 'string';
const background_is_isNumber = (payload) => typeof payload === 'number' && !isNaN(payload);
const background_isBoolean = (payload) => typeof payload === 'boolean';
const background_isRegExp = (payload) => payload instanceof RegExp;
const background_isMap = (payload) => payload instanceof Map;
const background_isSet = (payload) => payload instanceof Set;
const background_is_isSymbol = (payload) => background_getType(payload) === 'Symbol';
const background_isDate = (payload) => payload instanceof Date && !isNaN(payload.valueOf());
const background_isError = (payload) => payload instanceof Error;
const background_isNaNValue = (payload) => typeof payload === 'number' && isNaN(payload);
const background_isPrimitive = (payload) => background_isBoolean(payload) ||
    background_isNull(payload) ||
    background_isUndefined(payload) ||
    background_is_isNumber(payload) ||
    background_is_isString(payload) ||
    background_is_isSymbol(payload);
const background_isBigint = (payload) => typeof payload === 'bigint';
const background_isInfinite = (payload) => payload === Infinity || payload === -Infinity;
const background_isTypedArray = (payload) => ArrayBuffer.isView(payload) && !(payload instanceof DataView);
const background_isURL = (payload) => payload instanceof URL;

;// ./node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/pathstringifier.js
const background_escapeKey = (key) => key.replace(/\./g, '\\.');
const background_stringifyPath = (path) => path
    .map(String)
    .map(background_escapeKey)
    .join('.');
const background_parsePath = (string) => {
    const result = [];
    let segment = '';
    for (let i = 0; i < string.length; i++) {
        let char = string.charAt(i);
        const isEscapedDot = char === '\\' && string.charAt(i + 1) === '.';
        if (isEscapedDot) {
            segment += '.';
            i++;
            continue;
        }
        const isEndOfSegment = char === '.';
        if (isEndOfSegment) {
            result.push(segment);
            segment = '';
            continue;
        }
        segment += char;
    }
    const lastSegment = segment;
    result.push(lastSegment);
    return result;
};

;// ./node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/transformer.js


function background_simpleTransformation(isApplicable, annotation, transform, untransform) {
    return {
        isApplicable,
        annotation,
        transform,
        untransform,
    };
}
const background_simpleRules = [
    background_simpleTransformation(background_isUndefined, 'undefined', () => null, () => undefined),
    background_simpleTransformation(background_isBigint, 'bigint', v => v.toString(), v => {
        if (typeof BigInt !== 'undefined') {
            return BigInt(v);
        }
        console.error('Please add a BigInt polyfill.');
        return v;
    }),
    background_simpleTransformation(background_isDate, 'Date', v => v.toISOString(), v => new Date(v)),
    background_simpleTransformation(background_isError, 'Error', (v, superJson) => {
        const baseError = {
            name: v.name,
            message: v.message,
        };
        superJson.allowedErrorProps.forEach(prop => {
            baseError[prop] = v[prop];
        });
        return baseError;
    }, (v, superJson) => {
        const e = new Error(v.message);
        e.name = v.name;
        e.stack = v.stack;
        superJson.allowedErrorProps.forEach(prop => {
            e[prop] = v[prop];
        });
        return e;
    }),
    background_simpleTransformation(background_isRegExp, 'regexp', v => '' + v, regex => {
        const body = regex.slice(1, regex.lastIndexOf('/'));
        const flags = regex.slice(regex.lastIndexOf('/') + 1);
        return new RegExp(body, flags);
    }),
    background_simpleTransformation(background_isSet, 'set', 
    // (sets only exist in es6+)
    // eslint-disable-next-line es5/no-es6-methods
    v => [...v.values()], v => new Set(v)),
    background_simpleTransformation(background_isMap, 'map', v => [...v.entries()], v => new Map(v)),
    background_simpleTransformation((v) => background_isNaNValue(v) || background_isInfinite(v), 'number', v => {
        if (background_isNaNValue(v)) {
            return 'NaN';
        }
        if (v > 0) {
            return 'Infinity';
        }
        else {
            return '-Infinity';
        }
    }, Number),
    background_simpleTransformation((v) => v === 0 && 1 / v === -Infinity, 'number', () => {
        return '-0';
    }, Number),
    background_simpleTransformation(background_isURL, 'URL', v => v.toString(), v => new URL(v)),
];
function background_compositeTransformation(isApplicable, annotation, transform, untransform) {
    return {
        isApplicable,
        annotation,
        transform,
        untransform,
    };
}
const background_symbolRule = background_compositeTransformation((s, superJson) => {
    if (background_is_isSymbol(s)) {
        const isRegistered = !!superJson.symbolRegistry.getIdentifier(s);
        return isRegistered;
    }
    return false;
}, (s, superJson) => {
    const identifier = superJson.symbolRegistry.getIdentifier(s);
    return ['symbol', identifier];
}, v => v.description, (_, a, superJson) => {
    const value = superJson.symbolRegistry.getValue(a[1]);
    if (!value) {
        throw new Error('Trying to deserialize unknown symbol');
    }
    return value;
});
const background_constructorToName = [
    Int8Array,
    Uint8Array,
    Int16Array,
    Uint16Array,
    Int32Array,
    Uint32Array,
    Float32Array,
    Float64Array,
    Uint8ClampedArray,
].reduce((obj, ctor) => {
    obj[ctor.name] = ctor;
    return obj;
}, {});
const background_typedArrayRule = background_compositeTransformation(background_isTypedArray, v => ['typed-array', v.constructor.name], v => [...v], (v, a) => {
    const ctor = background_constructorToName[a[1]];
    if (!ctor) {
        throw new Error('Trying to deserialize unknown typed array');
    }
    return new ctor(v);
});
function background_isInstanceOfRegisteredClass(potentialClass, superJson) {
    if (potentialClass?.constructor) {
        const isRegistered = !!superJson.classRegistry.getIdentifier(potentialClass.constructor);
        return isRegistered;
    }
    return false;
}
const background_classRule = background_compositeTransformation(background_isInstanceOfRegisteredClass, (clazz, superJson) => {
    const identifier = superJson.classRegistry.getIdentifier(clazz.constructor);
    return ['class', identifier];
}, (clazz, superJson) => {
    const allowedProps = superJson.classRegistry.getAllowedProps(clazz.constructor);
    if (!allowedProps) {
        return { ...clazz };
    }
    const result = {};
    allowedProps.forEach(prop => {
        result[prop] = clazz[prop];
    });
    return result;
}, (v, a, superJson) => {
    const clazz = superJson.classRegistry.getValue(a[1]);
    if (!clazz) {
        throw new Error('Trying to deserialize unknown class - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564');
    }
    return Object.assign(Object.create(clazz.prototype), v);
});
const background_customRule = background_compositeTransformation((value, superJson) => {
    return !!superJson.customTransformerRegistry.findApplicable(value);
}, (value, superJson) => {
    const transformer = superJson.customTransformerRegistry.findApplicable(value);
    return ['custom', transformer.name];
}, (value, superJson) => {
    const transformer = superJson.customTransformerRegistry.findApplicable(value);
    return transformer.serialize(value);
}, (v, a, superJson) => {
    const transformer = superJson.customTransformerRegistry.findByName(a[1]);
    if (!transformer) {
        throw new Error('Trying to deserialize unknown custom value');
    }
    return transformer.deserialize(v);
});
const background_compositeRules = [background_classRule, background_symbolRule, background_customRule, background_typedArrayRule];
const background_transformValue = (value, superJson) => {
    const applicableCompositeRule = background_findArr(background_compositeRules, rule => rule.isApplicable(value, superJson));
    if (applicableCompositeRule) {
        return {
            value: applicableCompositeRule.transform(value, superJson),
            type: applicableCompositeRule.annotation(value, superJson),
        };
    }
    const applicableSimpleRule = background_findArr(background_simpleRules, rule => rule.isApplicable(value, superJson));
    if (applicableSimpleRule) {
        return {
            value: applicableSimpleRule.transform(value, superJson),
            type: applicableSimpleRule.annotation,
        };
    }
    return undefined;
};
const background_simpleRulesByAnnotation = {};
background_simpleRules.forEach(rule => {
    background_simpleRulesByAnnotation[rule.annotation] = rule;
});
const background_untransformValue = (json, type, superJson) => {
    if (background_is_isArray(type)) {
        switch (type[0]) {
            case 'symbol':
                return background_symbolRule.untransform(json, type, superJson);
            case 'class':
                return background_classRule.untransform(json, type, superJson);
            case 'custom':
                return background_customRule.untransform(json, type, superJson);
            case 'typed-array':
                return background_typedArrayRule.untransform(json, type, superJson);
            default:
                throw new Error('Unknown transformation: ' + type);
        }
    }
    else {
        const transformation = background_simpleRulesByAnnotation[type];
        if (!transformation) {
            throw new Error('Unknown transformation: ' + type);
        }
        return transformation.untransform(json, superJson);
    }
};

;// ./node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/accessDeep.js


const background_getNthKey = (value, n) => {
    const keys = value.keys();
    while (n > 0) {
        keys.next();
        n--;
    }
    return keys.next().value;
};
function background_validatePath(path) {
    if (background_includes(path, '__proto__')) {
        throw new Error('__proto__ is not allowed as a property');
    }
    if (background_includes(path, 'prototype')) {
        throw new Error('prototype is not allowed as a property');
    }
    if (background_includes(path, 'constructor')) {
        throw new Error('constructor is not allowed as a property');
    }
}
const background_getDeep = (object, path) => {
    background_validatePath(path);
    for (let i = 0; i < path.length; i++) {
        const key = path[i];
        if (background_isSet(object)) {
            object = background_getNthKey(object, +key);
        }
        else if (background_isMap(object)) {
            const row = +key;
            const type = +path[++i] === 0 ? 'key' : 'value';
            const keyOfRow = background_getNthKey(object, row);
            switch (type) {
                case 'key':
                    object = keyOfRow;
                    break;
                case 'value':
                    object = object.get(keyOfRow);
                    break;
            }
        }
        else {
            object = object[key];
        }
    }
    return object;
};
const background_setDeep = (object, path, mapper) => {
    background_validatePath(path);
    if (path.length === 0) {
        return mapper(object);
    }
    let parent = object;
    for (let i = 0; i < path.length - 1; i++) {
        const key = path[i];
        if (background_is_isArray(parent)) {
            const index = +key;
            parent = parent[index];
        }
        else if (background_isPlainObject(parent)) {
            parent = parent[key];
        }
        else if (background_isSet(parent)) {
            const row = +key;
            parent = background_getNthKey(parent, row);
        }
        else if (background_isMap(parent)) {
            const isEnd = i === path.length - 2;
            if (isEnd) {
                break;
            }
            const row = +key;
            const type = +path[++i] === 0 ? 'key' : 'value';
            const keyOfRow = background_getNthKey(parent, row);
            switch (type) {
                case 'key':
                    parent = keyOfRow;
                    break;
                case 'value':
                    parent = parent.get(keyOfRow);
                    break;
            }
        }
    }
    const lastKey = path[path.length - 1];
    if (background_is_isArray(parent)) {
        parent[+lastKey] = mapper(parent[+lastKey]);
    }
    else if (background_isPlainObject(parent)) {
        parent[lastKey] = mapper(parent[lastKey]);
    }
    if (background_isSet(parent)) {
        const oldValue = background_getNthKey(parent, +lastKey);
        const newValue = mapper(oldValue);
        if (oldValue !== newValue) {
            parent.delete(oldValue);
            parent.add(newValue);
        }
    }
    if (background_isMap(parent)) {
        const row = +path[path.length - 2];
        const keyToRow = background_getNthKey(parent, row);
        const type = +lastKey === 0 ? 'key' : 'value';
        switch (type) {
            case 'key': {
                const newKey = mapper(keyToRow);
                parent.set(newKey, parent.get(keyToRow));
                if (newKey !== keyToRow) {
                    parent.delete(keyToRow);
                }
                break;
            }
            case 'value': {
                parent.set(keyToRow, mapper(parent.get(keyToRow)));
                break;
            }
        }
    }
    return object;
};

;// ./node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/plainer.js






function background_traverse(tree, walker, origin = []) {
    if (!tree) {
        return;
    }
    if (!background_is_isArray(tree)) {
        background_forEach(tree, (subtree, key) => background_traverse(subtree, walker, [...origin, ...background_parsePath(key)]));
        return;
    }
    const [nodeValue, children] = tree;
    if (children) {
        background_forEach(children, (child, key) => {
            background_traverse(child, walker, [...origin, ...background_parsePath(key)]);
        });
    }
    walker(nodeValue, origin);
}
function background_applyValueAnnotations(plain, annotations, superJson) {
    background_traverse(annotations, (type, path) => {
        plain = background_setDeep(plain, path, v => background_untransformValue(v, type, superJson));
    });
    return plain;
}
function background_applyReferentialEqualityAnnotations(plain, annotations) {
    function apply(identicalPaths, path) {
        const object = background_getDeep(plain, background_parsePath(path));
        identicalPaths.map(background_parsePath).forEach(identicalObjectPath => {
            plain = background_setDeep(plain, identicalObjectPath, () => object);
        });
    }
    if (background_is_isArray(annotations)) {
        const [root, other] = annotations;
        root.forEach(identicalPath => {
            plain = background_setDeep(plain, background_parsePath(identicalPath), () => plain);
        });
        if (other) {
            background_forEach(other, apply);
        }
    }
    else {
        background_forEach(annotations, apply);
    }
    return plain;
}
const background_isDeep = (object, superJson) => background_isPlainObject(object) ||
    background_is_isArray(object) ||
    background_isMap(object) ||
    background_isSet(object) ||
    background_isInstanceOfRegisteredClass(object, superJson);
function background_addIdentity(object, path, identities) {
    const existingSet = identities.get(object);
    if (existingSet) {
        existingSet.push(path);
    }
    else {
        identities.set(object, [path]);
    }
}
function background_generateReferentialEqualityAnnotations(identitites, dedupe) {
    const result = {};
    let rootEqualityPaths = undefined;
    identitites.forEach(paths => {
        if (paths.length <= 1) {
            return;
        }
        // if we're not deduping, all of these objects continue existing.
        // putting the shortest path first makes it easier to parse for humans
        // if we're deduping though, only the first entry will still exist, so we can't do this optimisation.
        if (!dedupe) {
            paths = paths
                .map(path => path.map(String))
                .sort((a, b) => a.length - b.length);
        }
        const [representativePath, ...identicalPaths] = paths;
        if (representativePath.length === 0) {
            rootEqualityPaths = identicalPaths.map(background_stringifyPath);
        }
        else {
            result[background_stringifyPath(representativePath)] = identicalPaths.map(background_stringifyPath);
        }
    });
    if (rootEqualityPaths) {
        if (background_isEmptyObject(result)) {
            return [rootEqualityPaths];
        }
        else {
            return [rootEqualityPaths, result];
        }
    }
    else {
        return background_isEmptyObject(result) ? undefined : result;
    }
}
const background_walker = (object, identities, superJson, dedupe, path = [], objectsInThisPath = [], seenObjects = new Map()) => {
    const primitive = background_isPrimitive(object);
    if (!primitive) {
        background_addIdentity(object, path, identities);
        const seen = seenObjects.get(object);
        if (seen) {
            // short-circuit result if we've seen this object before
            return dedupe
                ? {
                    transformedValue: null,
                }
                : seen;
        }
    }
    if (!background_isDeep(object, superJson)) {
        const transformed = background_transformValue(object, superJson);
        const result = transformed
            ? {
                transformedValue: transformed.value,
                annotations: [transformed.type],
            }
            : {
                transformedValue: object,
            };
        if (!primitive) {
            seenObjects.set(object, result);
        }
        return result;
    }
    if (background_includes(objectsInThisPath, object)) {
        // prevent circular references
        return {
            transformedValue: null,
        };
    }
    const transformationResult = background_transformValue(object, superJson);
    const transformed = transformationResult?.value ?? object;
    const transformedValue = background_is_isArray(transformed) ? [] : {};
    const innerAnnotations = {};
    background_forEach(transformed, (value, index) => {
        if (index === '__proto__' ||
            index === 'constructor' ||
            index === 'prototype') {
            throw new Error(`Detected property ${index}. This is a prototype pollution risk, please remove it from your object.`);
        }
        const recursiveResult = background_walker(value, identities, superJson, dedupe, [...path, index], [...objectsInThisPath, object], seenObjects);
        transformedValue[index] = recursiveResult.transformedValue;
        if (background_is_isArray(recursiveResult.annotations)) {
            innerAnnotations[index] = recursiveResult.annotations;
        }
        else if (background_isPlainObject(recursiveResult.annotations)) {
            background_forEach(recursiveResult.annotations, (tree, key) => {
                innerAnnotations[background_escapeKey(index) + '.' + key] = tree;
            });
        }
    });
    const result = background_isEmptyObject(innerAnnotations)
        ? {
            transformedValue,
            annotations: !!transformationResult
                ? [transformationResult.type]
                : undefined,
        }
        : {
            transformedValue,
            annotations: !!transformationResult
                ? [transformationResult.type, innerAnnotations]
                : innerAnnotations,
        };
    if (!primitive) {
        seenObjects.set(object, result);
    }
    return result;
};

;// ./node_modules/.pnpm/is-what@4.1.16/node_modules/is-what/dist/index.js
function background_dist_getType(payload) {
  return Object.prototype.toString.call(payload).slice(8, -1);
}

function background_isAnyObject(payload) {
  return background_dist_getType(payload) === "Object";
}

function background_dist_isArray(payload) {
  return background_dist_getType(payload) === "Array";
}

function background_isBlob(payload) {
  return background_dist_getType(payload) === "Blob";
}

function background_dist_isBoolean(payload) {
  return background_dist_getType(payload) === "Boolean";
}

function background_dist_isDate(payload) {
  return background_dist_getType(payload) === "Date" && !isNaN(payload);
}

function background_isEmptyArray(payload) {
  return background_dist_isArray(payload) && payload.length === 0;
}

function background_dist_isPlainObject(payload) {
  if (background_dist_getType(payload) !== "Object")
    return false;
  const prototype = Object.getPrototypeOf(payload);
  return !!prototype && prototype.constructor === Object && prototype === Object.prototype;
}

function background_dist_isEmptyObject(payload) {
  return background_dist_isPlainObject(payload) && Object.keys(payload).length === 0;
}

function background_isEmptyString(payload) {
  return payload === "";
}

function background_dist_isError(payload) {
  return background_dist_getType(payload) === "Error" || payload instanceof Error;
}

function background_isFile(payload) {
  return background_dist_getType(payload) === "File";
}

function background_isFullArray(payload) {
  return background_dist_isArray(payload) && payload.length > 0;
}

function background_isFullObject(payload) {
  return background_dist_isPlainObject(payload) && Object.keys(payload).length > 0;
}

function background_dist_isString(payload) {
  return background_dist_getType(payload) === "String";
}

function background_isFullString(payload) {
  return background_dist_isString(payload) && payload !== "";
}

function background_isFunction(payload) {
  return typeof payload === "function";
}

function background_isType(payload, type) {
  if (!(type instanceof Function)) {
    throw new TypeError("Type must be a function");
  }
  if (!Object.prototype.hasOwnProperty.call(type, "prototype")) {
    throw new TypeError("Type is not a class");
  }
  const name = type.name;
  return background_dist_getType(payload) === name || Boolean(payload && payload.constructor === type);
}

function background_isInstanceOf(value, classOrClassName) {
  if (typeof classOrClassName === "function") {
    for (let p = value; p; p = Object.getPrototypeOf(p)) {
      if (background_isType(p, classOrClassName)) {
        return true;
      }
    }
    return false;
  } else {
    for (let p = value; p; p = Object.getPrototypeOf(p)) {
      if (background_dist_getType(p) === classOrClassName) {
        return true;
      }
    }
    return false;
  }
}

function background_dist_isMap(payload) {
  return background_dist_getType(payload) === "Map";
}

function background_dist_isNaNValue(payload) {
  return background_dist_getType(payload) === "Number" && isNaN(payload);
}

function background_dist_isNumber(payload) {
  return background_dist_getType(payload) === "Number" && !isNaN(payload);
}

function background_isNegativeNumber(payload) {
  return background_dist_isNumber(payload) && payload < 0;
}

function background_dist_isNull(payload) {
  return background_dist_getType(payload) === "Null";
}

function background_isOneOf(a, b, c, d, e) {
  return (value) => a(value) || b(value) || !!c && c(value) || !!d && d(value) || !!e && e(value);
}

function background_dist_isUndefined(payload) {
  return background_dist_getType(payload) === "Undefined";
}

const background_isNullOrUndefined = background_isOneOf(background_dist_isNull, background_dist_isUndefined);

function background_dist_isObject(payload) {
  return background_dist_isPlainObject(payload);
}

function background_dist_isObjectLike(payload) {
  return background_isAnyObject(payload);
}

function background_isPositiveNumber(payload) {
  return background_dist_isNumber(payload) && payload > 0;
}

function background_dist_isSymbol(payload) {
  return background_dist_getType(payload) === "Symbol";
}

function background_dist_isPrimitive(payload) {
  return background_dist_isBoolean(payload) || background_dist_isNull(payload) || background_dist_isUndefined(payload) || background_dist_isNumber(payload) || background_dist_isString(payload) || background_dist_isSymbol(payload);
}

function background_isPromise(payload) {
  return background_dist_getType(payload) === "Promise";
}

function background_dist_isRegExp(payload) {
  return background_dist_getType(payload) === "RegExp";
}

function background_dist_isSet(payload) {
  return background_dist_getType(payload) === "Set";
}

function background_isWeakMap(payload) {
  return background_dist_getType(payload) === "WeakMap";
}

function background_isWeakSet(payload) {
  return background_dist_getType(payload) === "WeakSet";
}



;// ./node_modules/.pnpm/copy-anything@3.0.5/node_modules/copy-anything/dist/index.js


function background_assignProp(carry, key, newVal, originalObject, includeNonenumerable) {
  const propType = {}.propertyIsEnumerable.call(originalObject, key) ? "enumerable" : "nonenumerable";
  if (propType === "enumerable")
    carry[key] = newVal;
  if (includeNonenumerable && propType === "nonenumerable") {
    Object.defineProperty(carry, key, {
      value: newVal,
      enumerable: false,
      writable: true,
      configurable: true
    });
  }
}
function background_copy(target, options = {}) {
  if (background_dist_isArray(target)) {
    return target.map((item) => background_copy(item, options));
  }
  if (!background_dist_isPlainObject(target)) {
    return target;
  }
  const props = Object.getOwnPropertyNames(target);
  const symbols = Object.getOwnPropertySymbols(target);
  return [...props, ...symbols].reduce((carry, key) => {
    if (background_dist_isArray(options.props) && !options.props.includes(key)) {
      return carry;
    }
    const val = target[key];
    const newVal = background_copy(val, options);
    background_assignProp(carry, key, newVal, target, options.nonenumerable);
    return carry;
  }, {});
}



;// ./node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/index.js





class background_SuperJSON {
    /**
     * @param dedupeReferentialEqualities  If true, SuperJSON will make sure only one instance of referentially equal objects are serialized and the rest are replaced with `null`.
     */
    constructor({ dedupe = false, } = {}) {
        this.classRegistry = new background_ClassRegistry();
        this.symbolRegistry = new background_Registry(s => s.description ?? '');
        this.customTransformerRegistry = new background_CustomTransformerRegistry();
        this.allowedErrorProps = [];
        this.dedupe = dedupe;
    }
    serialize(object) {
        const identities = new Map();
        const output = background_walker(object, identities, this, this.dedupe);
        const res = {
            json: output.transformedValue,
        };
        if (output.annotations) {
            res.meta = {
                ...res.meta,
                values: output.annotations,
            };
        }
        const equalityAnnotations = background_generateReferentialEqualityAnnotations(identities, this.dedupe);
        if (equalityAnnotations) {
            res.meta = {
                ...res.meta,
                referentialEqualities: equalityAnnotations,
            };
        }
        return res;
    }
    deserialize(payload) {
        const { json, meta } = payload;
        let result = background_copy(json);
        if (meta?.values) {
            result = background_applyValueAnnotations(result, meta.values, this);
        }
        if (meta?.referentialEqualities) {
            result = background_applyReferentialEqualityAnnotations(result, meta.referentialEqualities);
        }
        return result;
    }
    stringify(object) {
        return JSON.stringify(this.serialize(object));
    }
    parse(string) {
        return this.deserialize(JSON.parse(string));
    }
    registerClass(v, options) {
        this.classRegistry.register(v, options);
    }
    registerSymbol(v, identifier) {
        this.symbolRegistry.register(v, identifier);
    }
    registerCustom(transformer, name) {
        this.customTransformerRegistry.register({
            name,
            ...transformer,
        });
    }
    allowErrorProps(...props) {
        this.allowedErrorProps.push(...props);
    }
}
background_SuperJSON.defaultInstance = new background_SuperJSON();
background_SuperJSON.serialize = background_SuperJSON.defaultInstance.serialize.bind(background_SuperJSON.defaultInstance);
background_SuperJSON.deserialize = background_SuperJSON.defaultInstance.deserialize.bind(background_SuperJSON.defaultInstance);
background_SuperJSON.stringify = background_SuperJSON.defaultInstance.stringify.bind(background_SuperJSON.defaultInstance);
background_SuperJSON.parse = background_SuperJSON.defaultInstance.parse.bind(background_SuperJSON.defaultInstance);
background_SuperJSON.registerClass = background_SuperJSON.defaultInstance.registerClass.bind(background_SuperJSON.defaultInstance);
background_SuperJSON.registerSymbol = background_SuperJSON.defaultInstance.registerSymbol.bind(background_SuperJSON.defaultInstance);
background_SuperJSON.registerCustom = background_SuperJSON.defaultInstance.registerCustom.bind(background_SuperJSON.defaultInstance);
background_SuperJSON.allowErrorProps = background_SuperJSON.defaultInstance.allowErrorProps.bind(background_SuperJSON.defaultInstance);

const background_serialize = background_SuperJSON.serialize;
const background_deserialize = background_SuperJSON.deserialize;
const background_stringify = background_SuperJSON.stringify;
const background_parse = background_SuperJSON.parse;
const background_registerClass = background_SuperJSON.registerClass;
const background_registerCustom = background_SuperJSON.registerCustom;
const background_registerSymbol = background_SuperJSON.registerSymbol;
const background_allowErrorProps = background_SuperJSON.allowErrorProps;

;// ./node_modules/.pnpm/idb@8.0.2/node_modules/idb/build/index.js
const background_instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);

let background_idbProxyableTypes;
let background_cursorAdvanceMethods;
// This is a function to prevent it throwing up in node environments.
function background_getIdbProxyableTypes() {
    return (background_idbProxyableTypes ||
        (background_idbProxyableTypes = [
            IDBDatabase,
            IDBObjectStore,
            IDBIndex,
            IDBCursor,
            IDBTransaction,
        ]));
}
// This is a function to prevent it throwing up in node environments.
function background_getCursorAdvanceMethods() {
    return (background_cursorAdvanceMethods ||
        (background_cursorAdvanceMethods = [
            IDBCursor.prototype.advance,
            IDBCursor.prototype.continue,
            IDBCursor.prototype.continuePrimaryKey,
        ]));
}
const background_transactionDoneMap = new WeakMap();
const background_transformCache = new WeakMap();
const background_reverseTransformCache = new WeakMap();
function background_promisifyRequest(request) {
    const promise = new Promise((resolve, reject) => {
        const unlisten = () => {
            request.removeEventListener('success', success);
            request.removeEventListener('error', error);
        };
        const success = () => {
            resolve(background_wrap(request.result));
            unlisten();
        };
        const error = () => {
            reject(request.error);
            unlisten();
        };
        request.addEventListener('success', success);
        request.addEventListener('error', error);
    });
    // This mapping exists in reverseTransformCache but doesn't exist in transformCache. This
    // is because we create many promises from a single IDBRequest.
    background_reverseTransformCache.set(promise, request);
    return promise;
}
function background_cacheDonePromiseForTransaction(tx) {
    // Early bail if we've already created a done promise for this transaction.
    if (background_transactionDoneMap.has(tx))
        return;
    const done = new Promise((resolve, reject) => {
        const unlisten = () => {
            tx.removeEventListener('complete', complete);
            tx.removeEventListener('error', error);
            tx.removeEventListener('abort', error);
        };
        const complete = () => {
            resolve();
            unlisten();
        };
        const error = () => {
            reject(tx.error || new DOMException('AbortError', 'AbortError'));
            unlisten();
        };
        tx.addEventListener('complete', complete);
        tx.addEventListener('error', error);
        tx.addEventListener('abort', error);
    });
    // Cache it for later retrieval.
    background_transactionDoneMap.set(tx, done);
}
let background_idbProxyTraps = {
    get(target, prop, receiver) {
        if (target instanceof IDBTransaction) {
            // Special handling for transaction.done.
            if (prop === 'done')
                return background_transactionDoneMap.get(target);
            // Make tx.store return the only store in the transaction, or undefined if there are many.
            if (prop === 'store') {
                return receiver.objectStoreNames[1]
                    ? undefined
                    : receiver.objectStore(receiver.objectStoreNames[0]);
            }
        }
        // Else transform whatever we get back.
        return background_wrap(target[prop]);
    },
    set(target, prop, value) {
        target[prop] = value;
        return true;
    },
    has(target, prop) {
        if (target instanceof IDBTransaction &&
            (prop === 'done' || prop === 'store')) {
            return true;
        }
        return prop in target;
    },
};
function background_replaceTraps(callback) {
    background_idbProxyTraps = callback(background_idbProxyTraps);
}
function background_wrapFunction(func) {
    // Due to expected object equality (which is enforced by the caching in `wrap`), we
    // only create one new func per func.
    // Cursor methods are special, as the behaviour is a little more different to standard IDB. In
    // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the
    // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense
    // with real promises, so each advance methods returns a new promise for the cursor object, or
    // undefined if the end of the cursor has been reached.
    if (background_getCursorAdvanceMethods().includes(func)) {
        return function (...args) {
            // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
            // the original object.
            func.apply(background_unwrap(this), args);
            return background_wrap(this.request);
        };
    }
    return function (...args) {
        // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
        // the original object.
        return background_wrap(func.apply(background_unwrap(this), args));
    };
}
function background_transformCachableValue(value) {
    if (typeof value === 'function')
        return background_wrapFunction(value);
    // This doesn't return, it just creates a 'done' promise for the transaction,
    // which is later returned for transaction.done (see idbObjectHandler).
    if (value instanceof IDBTransaction)
        background_cacheDonePromiseForTransaction(value);
    if (background_instanceOfAny(value, background_getIdbProxyableTypes()))
        return new Proxy(value, background_idbProxyTraps);
    // Return the same value back if we're not going to transform it.
    return value;
}
function background_wrap(value) {
    // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because
    // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.
    if (value instanceof IDBRequest)
        return background_promisifyRequest(value);
    // If we've already transformed this value before, reuse the transformed value.
    // This is faster, but it also provides object equality.
    if (background_transformCache.has(value))
        return background_transformCache.get(value);
    const newValue = background_transformCachableValue(value);
    // Not all types are transformed.
    // These may be primitive types, so they can't be WeakMap keys.
    if (newValue !== value) {
        background_transformCache.set(value, newValue);
        background_reverseTransformCache.set(newValue, value);
    }
    return newValue;
}
const background_unwrap = (value) => background_reverseTransformCache.get(value);

/**
 * Open a database.
 *
 * @param name Name of the database.
 * @param version Schema version.
 * @param callbacks Additional callbacks.
 */
function background_openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {
    const request = indexedDB.open(name, version);
    const openPromise = background_wrap(request);
    if (upgrade) {
        request.addEventListener('upgradeneeded', (event) => {
            upgrade(background_wrap(request.result), event.oldVersion, event.newVersion, background_wrap(request.transaction), event);
        });
    }
    if (blocked) {
        request.addEventListener('blocked', (event) => blocked(
        // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
        event.oldVersion, event.newVersion, event));
    }
    openPromise
        .then((db) => {
        if (terminated)
            db.addEventListener('close', () => terminated());
        if (blocking) {
            db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));
        }
    })
        .catch(() => { });
    return openPromise;
}
/**
 * Delete a database.
 *
 * @param name Name of the database.
 */
function background_deleteDB(name, { blocked } = {}) {
    const request = indexedDB.deleteDatabase(name);
    if (blocked) {
        request.addEventListener('blocked', (event) => blocked(
        // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
        event.oldVersion, event));
    }
    return background_wrap(request).then(() => undefined);
}

const background_readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];
const background_writeMethods = ['put', 'add', 'delete', 'clear'];
const background_cachedMethods = new Map();
function background_getMethod(target, prop) {
    if (!(target instanceof IDBDatabase &&
        !(prop in target) &&
        typeof prop === 'string')) {
        return;
    }
    if (background_cachedMethods.get(prop))
        return background_cachedMethods.get(prop);
    const targetFuncName = prop.replace(/FromIndex$/, '');
    const useIndex = prop !== targetFuncName;
    const isWrite = background_writeMethods.includes(targetFuncName);
    if (
    // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
    !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||
        !(isWrite || background_readMethods.includes(targetFuncName))) {
        return;
    }
    const method = async function (storeName, ...args) {
        // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(
        const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');
        let target = tx.store;
        if (useIndex)
            target = target.index(args.shift());
        // Must reject if op rejects.
        // If it's a write operation, must reject if tx.done rejects.
        // Must reject with op rejection first.
        // Must resolve with op value.
        // Must handle both promises (no unhandled rejections)
        return (await Promise.all([
            target[targetFuncName](...args),
            isWrite && tx.done,
        ]))[0];
    };
    background_cachedMethods.set(prop, method);
    return method;
}
background_replaceTraps((oldTraps) => ({
    ...oldTraps,
    get: (target, prop, receiver) => background_getMethod(target, prop) || oldTraps.get(target, prop, receiver),
    has: (target, prop) => !!background_getMethod(target, prop) || oldTraps.has(target, prop),
}));

const background_advanceMethodProps = ['continue', 'continuePrimaryKey', 'advance'];
const background_methodMap = {};
const background_advanceResults = new WeakMap();
const background_ittrProxiedCursorToOriginalProxy = new WeakMap();
const background_cursorIteratorTraps = {
    get(target, prop) {
        if (!background_advanceMethodProps.includes(prop))
            return target[prop];
        let cachedFunc = background_methodMap[prop];
        if (!cachedFunc) {
            cachedFunc = background_methodMap[prop] = function (...args) {
                background_advanceResults.set(this, background_ittrProxiedCursorToOriginalProxy.get(this)[prop](...args));
            };
        }
        return cachedFunc;
    },
};
async function* background_iterate(...args) {
    // tslint:disable-next-line:no-this-assignment
    let cursor = this;
    if (!(cursor instanceof IDBCursor)) {
        cursor = await cursor.openCursor(...args);
    }
    if (!cursor)
        return;
    cursor = cursor;
    const proxiedCursor = new Proxy(cursor, background_cursorIteratorTraps);
    background_ittrProxiedCursorToOriginalProxy.set(proxiedCursor, cursor);
    // Map this double-proxy back to the original, so other cursor methods work.
    background_reverseTransformCache.set(proxiedCursor, background_unwrap(cursor));
    while (cursor) {
        yield proxiedCursor;
        // If one of the advancing methods was not called, call continue().
        cursor = await (background_advanceResults.get(proxiedCursor) || cursor.continue());
        background_advanceResults.delete(proxiedCursor);
    }
}
function background_isIteratorProp(target, prop) {
    return ((prop === Symbol.asyncIterator &&
        background_instanceOfAny(target, [IDBIndex, IDBObjectStore, IDBCursor])) ||
        (prop === 'iterate' && background_instanceOfAny(target, [IDBIndex, IDBObjectStore])));
}
background_replaceTraps((oldTraps) => ({
    ...oldTraps,
    get(target, prop, receiver) {
        if (background_isIteratorProp(target, prop))
            return background_iterate;
        return oldTraps.get(target, prop, receiver);
    },
    has(target, prop) {
        return background_isIteratorProp(target, prop) || oldTraps.has(target, prop);
    },
}));



;// ./Extension/src/background/storages/idb-storage.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_idb_storage_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}


/**
 * Provides a storage mechanism using IndexedDB. This class implements the
 * StorageInterface with asynchronous methods to interact with the database.
 *
 * @template Data The type of the value stored in the storage.
 */ class background_IDBStorage {
    /**
     * Ensures the database is opened before any operations. If the database
     * is not already opened, it opens the database.
     *
     * @returns The opened database instance.
     */ async getOpenedDb() {
        if (this.db) {
            return this.db;
        }
        if (this.dbGetterPromise) {
            return this.dbGetterPromise;
        }
        this.dbGetterPromise = (async ()=>{
            this.db = await background_openDB(this.name, this.version, {
                upgrade: (db)=>{
                    // Make sure the store exists
                    if (!db.objectStoreNames.contains(this.store)) {
                        db.createObjectStore(this.store);
                    }
                }
            });
            this.dbGetterPromise = null;
            return this.db;
        })();
        return this.dbGetterPromise;
    }
    /**
     * Retrieves a value by key from the store.
     *
     * @param key The key of the value to retrieve.
     *
     * @returns The value associated with the key.
     */ async get(key) {
        const db = await this.getOpenedDb();
        return db.get(this.store, key);
    }
    /**
     * Sets a value in the store with the specified key.
     *
     * @param key The key under which to store the value.
     * @param value The value to store.
     */ async set(key, value) {
        const db = await this.getOpenedDb();
        await db.put(this.store, value, key);
    }
    /**
     * Removes a value from the store by key.
     *
     * @param key The key of the value to remove.
     */ async remove(key) {
        const db = await this.getOpenedDb();
        await db.delete(this.store, key);
    }
    /**
     * Atomic set operation for multiple key-value pairs.
     * This method is using transaction to ensure atomicity, if any of the operations fail,
     * the entire operation is rolled back. This helps to prevent data corruption / inconsistency.
     *
     * @param data The key-value pairs to set.
     *
     * @returns True if all operations were successful, false otherwise.
     *
     * @example
     * ```ts
     * const storage = new IDBStorage();
     * await storage.setMultiple({
     *    key1: 'value1',
     *    key2: 'value2',
     * });
     * ```
     */ async setMultiple(data) {
        const db = await this.getOpenedDb();
        const tx = db.transaction(this.store, 'readwrite');
        try {
            await Promise.all(Object.entries(data).map(([key, value])=>tx.store.put(value, key)));
            await tx.done;
        } catch (e) {
            background_logger_logger.error('Error while setting multiple keys in the storage:', e);
            tx.abort();
            return false;
        }
        return true;
    }
    /**
     * Removes multiple key-value pairs from the storage.
     *
     * @param keys The keys to remove.
     *
     * @returns True if all operations were successful, false otherwise.
     */ async removeMultiple(keys) {
        const db = await this.getOpenedDb();
        const tx = db.transaction(this.store, 'readwrite');
        try {
            await Promise.all(keys.map((key)=>tx.store.delete(key)));
            await tx.done;
        } catch (e) {
            background_logger_logger.error('Error while removing multiple keys from the storage:', e);
            tx.abort();
            return false;
        }
        return true;
    }
    /**
     * Get the entire contents of the storage.
     *
     * @returns Promise that resolves with the entire contents of the storage.
     */ async entries() {
        const db = await this.getOpenedDb();
        const entries = {};
        const tx = db.transaction(this.store, 'readonly');
        // eslint-disable-next-line no-restricted-syntax
        for await (const cursor of tx.store){
            const key = String(cursor.key);
            entries[key] = cursor.value;
        }
        return entries;
    }
    /**
     * Get all keys in the storage.
     *
     * @returns Promise that resolves with all keys in the storage.
     */ async keys() {
        const db = await this.getOpenedDb();
        const idbKeys = await db.getAllKeys(this.store);
        return idbKeys.map((key)=>key.toString());
    }
    /**
     * Check if a key exists in the storage.
     *
     * @param key The key to check.
     *
     * @returns True if the key exists, false otherwise.
     */ async has(key) {
        const db = await this.getOpenedDb();
        const idbKey = await db.getKey(this.store, key);
        return idbKey !== undefined;
    }
    /**
     * Clears the storage.
     */ async clear() {
        const db = await this.getOpenedDb();
        await db.clear(this.store);
    }
    /**
     * Constructs an instance of the IDBStorage class.
     *
     * @param [name=IDBStorage.DEFAULT_IDB_NAME] The name of the database.
     * @param [version=1] The version of the database.
     * @param [store=IDBStorage.DEFAULT_STORE_NAME] The name of the store within the database.
     */ constructor(name = background_IDBStorage.DEFAULT_IDB_NAME, version = background_IDBStorage.DEFAULT_IDB_VERSION, store = background_IDBStorage.DEFAULT_STORE_NAME){
        /**
     * Holds the instance of the IndexedDB database.
     */ background_idb_storage_define_property(this, "db", null);
        /**
     * Promise to get IndexedDB database.
     */ background_idb_storage_define_property(this, "dbGetterPromise", null);
        /**
     * The name of the database.
     */ background_idb_storage_define_property(this, "name", void 0);
        /**
     * The version of the database. Used for upgrades.
     */ background_idb_storage_define_property(this, "version", void 0);
        /**
     * The name of the store within the database.
     */ background_idb_storage_define_property(this, "store", void 0);
        this.name = name;
        this.version = version;
        this.store = store;
    }
}
/**
     * The default name of the store within the database.
     */ background_idb_storage_define_property(background_IDBStorage, "DEFAULT_STORE_NAME", 'defaultStore');
/**
     * The default version of the database.
     */ background_idb_storage_define_property(background_IDBStorage, "DEFAULT_IDB_VERSION", 1);
/**
     * The default name of the database.
     */ background_idb_storage_define_property(background_IDBStorage, "DEFAULT_IDB_NAME", 'adguardIDB');

;// ./Extension/src/background/storages/hybrid-storage.ts
/* eslint-disable @typescript-eslint/no-explicit-any */ /**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ /**
 * This file implements a hybrid storage solution that abstracts over different storage mechanisms,
 * providing a unified API for storage operations. It automatically chooses between IndexedDB storage and
 * a fallback storage mechanism based on the environment's capabilities.
 */ function background_hybrid_storage_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}






/**
 * Implements a hybrid storage mechanism that can switch between IndexedDB and a fallback storage
 * based on browser capabilities and environment constraints. This class adheres to the StorageInterface,
 * allowing for asynchronous get and set operations.
 *
 * @template Data The type of the value stored in the storage.
 */ class background_HybridStorage {
    /**
     * Checks if the given storage is an instance of IDBStorage.
     *
     * @param storage The storage instance to check.
     *
     * @returns True if the storage is an instance of IDBStorage, false otherwise.
     */ static isIdbStorage(storage) {
        return storage instanceof background_IDBStorage;
    }
    /**
     * Determines the appropriate storage mechanism to use. If IndexedDB is supported, it uses IDBStorage;
     * otherwise, it falls back to a generic Storage mechanism. This selection is made once and cached
     * for subsequent operations.
     *
     * @returns The storage instance to be used for data operations.
     */ async getStorage() {
        if (this.storage) {
            return this.storage;
        }
        if (await background_HybridStorage.isIDBSupported()) {
            this.storage = new background_IDBStorage();
        } else {
            this.storage = new background_BrowserStorage(this.fallbackStorage);
        }
        return this.storage;
    }
    /**
     * Checks if the given value is a SuperJSONResult.
     *
     * @param value The value to check.
     *
     * @returns True if the value is a SuperJSONResult, false otherwise.
     */ static isSuperJSONResult(value) {
        return typeof value === 'object' && value !== null && background_HybridStorage.SUPERJSON_META_KEY in value;
    }
    /**
     * Checks if IndexedDB is supported in the current environment.
     * This is determined by trying to open a test database; if successful, IndexedDB is supported.
     * The result of this check is cached to prevent multiple checks.
     *
     * @returns True if IndexedDB is supported, false otherwise.
     */ static async isIDBSupported() {
        if (background_HybridStorage.isIDBCapabilityChecked) {
            return background_HybridStorage.idbSupported;
        }
        if (background_HybridStorage.idbCapabilityCheckerPromise) {
            return background_HybridStorage.idbCapabilityCheckerPromise;
        }
        background_HybridStorage.idbCapabilityCheckerPromise = (async ()=>{
            try {
                const testDbName = `${background_HybridStorage.TEST_IDB_NAME_PREFIX}${background_nanoid()}`;
                const testDb = await background_openDB(testDbName, background_HybridStorage.TEST_IDB_VERSION);
                testDb.close();
                await background_deleteDB(testDbName);
                background_HybridStorage.idbSupported = true;
            } catch (e) {
                background_HybridStorage.idbSupported = false;
            }
            background_HybridStorage.isIDBCapabilityChecked = true;
            return background_HybridStorage.idbSupported;
        })();
        return background_HybridStorage.idbCapabilityCheckerPromise;
    }
    /**
     * Asynchronously sets a value for a given key in the selected storage mechanism.
     *
     * @param key The key under which the value is stored.
     * @param value The value to be stored.
     *
     * @returns A promise that resolves when the operation is complete.
     */ async set(key, value) {
        const storage = await this.getStorage();
        // If the selected storage mechanism is IndexedDB, we store the value as is,
        // as IndexedDB can store complex objects.
        if (background_HybridStorage.isIdbStorage(storage)) {
            return storage.set(key, value);
        }
        const serialized = background_HybridStorage.serialize(value);
        // If the serialized value contains a meta key, it means that the value provided
        // contains special data that are not JSON-serializable and require SuperJSON serialization,
        // like typed arrays, dates, and other complex objects.
        // In this case, we store the SuperJSON-serialized value.
        if (background_HybridStorage.SUPERJSON_META_KEY in serialized) {
            return storage.set(key, serialized);
        }
        // If the serialized value does not contain a meta key, it means that the value
        // provided was a primitive value or a plain object that is JSON-serializable,
        // and it does not contain any special data that requires SuperJSON serialization.
        // In this case, we store the value as is.
        return storage.set(key, value);
    }
    /**
     * Asynchronously retrieves the value for a given key from the selected storage mechanism.
     *
     * @param key The key whose value is to be retrieved.
     *
     * @returns A promise that resolves with the retrieved value, or undefined if the key does not exist.
     */ async get(key) {
        const storage = await this.getStorage();
        // If the selected storage mechanism is IndexedDB, we return the value as is,
        // as IndexedDB can store complex objects.
        if (background_HybridStorage.isIdbStorage(storage)) {
            return storage.get(key);
        }
        const value = await storage.get(key);
        // Do not attempt to deserialize undefined values.
        if (value === undefined) {
            return undefined;
        }
        // If the value is a SuperJSON-serialized object, we need to deserialize it.
        if (background_HybridStorage.isSuperJSONResult(value)) {
            return background_HybridStorage.deserialize(value);
        }
        // Otherwise, we return the value as is.
        return value;
    }
    /**
     * Asynchronously removes the value for a given key from the selected storage mechanism.
     *
     * @param key The key whose value is to be removed.
     */ async remove(key) {
        const storage = await this.getStorage();
        await storage.remove(key);
    }
    /**
     * Atomic set operation for multiple key-value pairs.
     * This method are using transaction to ensure atomicity, if any of the operations fail,
     * the entire operation is rolled back. This helps to prevent data corruption / inconsistency.
     *
     * @param data The key-value pairs to set.
     *
     * @returns True if all operations were successful, false otherwise.
     *
     * @example
     * ```ts
     * const storage = new HybridStorage();
     * await storage.setMultiple({
     *    key1: 'value1',
     *    key2: 'value2',
     * });
     * ```
     */ async setMultiple(data) {
        const storage = await this.getStorage();
        if (background_HybridStorage.isIdbStorage(storage)) {
            var _ref;
            return (_ref = await storage.setMultiple(data)) !== null && _ref !== void 0 ? _ref : false;
        }
        const cloneData = Object.entries(data).reduce((acc, [key, value])=>{
            const serialized = background_SuperJSON.serialize(value);
            // If the serialized value contains a meta key, it means that the value provided
            // contains special data that are not JSON-serializable and require SuperJSON serialization,
            // like typed arrays, dates, and other complex objects.
            // In this case, we store the SuperJSON-serialized value.
            if (background_HybridStorage.SUPERJSON_META_KEY in serialized) {
                acc[key] = serialized;
                return acc;
            }
            // If the serialized value does not contain a meta key, it means that the value
            // provided was a primitive value or a plain object that is JSON-serializable,
            // and it does not contain any special data that requires SuperJSON serialization.
            // In this case, we store the value as is.
            acc[key] = value;
            return acc;
        }, {});
        var _ref1;
        return (_ref1 = await storage.setMultiple(cloneData)) !== null && _ref1 !== void 0 ? _ref1 : false;
    }
    /**
     * Removes multiple key-value pairs from the storage.
     *
     * @param keys The keys to remove.
     *
     * @returns True if all operations were successful, false otherwise.
     */ async removeMultiple(keys) {
        const storage = await this.getStorage();
        var _ref;
        return (_ref = await storage.removeMultiple(keys)) !== null && _ref !== void 0 ? _ref : false;
    }
    /**
     * Get the entire contents of the storage.
     *
     * @returns Promise that resolves with the entire contents of the storage.
     */ async entries() {
        const storage = await this.getStorage();
        if (background_HybridStorage.isIdbStorage(storage)) {
            return storage.entries();
        }
        const entries = await storage.entries();
        return Object.entries(entries).reduce((acc, [key, value])=>{
            acc[key] = background_HybridStorage.isSuperJSONResult(value) ? background_HybridStorage.deserialize(value) : value;
            return acc;
        }, {});
    }
    /**
     * Get all keys from the storage.
     *
     * @returns Promise that resolves with all keys from the storage.
     */ async keys() {
        const storage = await this.getStorage();
        return storage.keys();
    }
    /**
     * Check if a key exists in the storage.
     *
     * @param key The key to check.
     *
     * @returns True if the key exists, false otherwise.
     */ async has(key) {
        const storage = await this.getStorage();
        return storage.has(key);
    }
    /**
     * Clears the storage.
     */ async clear() {
        const storage = await this.getStorage();
        await storage.clear();
    }
    /**
     * Constructs an instance of the HybridStorage class.
     *
     * @param fallbackStorage The storage area to use when IndexedDB is not supported.
     */ constructor(fallbackStorage){
        /**
     * Holds the instance of the selected storage mechanism.
     *
     * @note We use SuperJSON to serialize and deserialize the data when using the fallback storage mechanism,
     * because it only supports storing JSON-serializable data.
     */ background_hybrid_storage_define_property(this, "storage", null);
        /**
     * The storage area to use when IndexedDB is not supported.
     */ background_hybrid_storage_define_property(this, "fallbackStorage", void 0);
        this.fallbackStorage = fallbackStorage;
    }
}
/**
     * A flag indicating whether IndexedDB support has already been checked.
     */ background_hybrid_storage_define_property(background_HybridStorage, "isIDBCapabilityChecked", false);
/**
     * A promise that resolves to whether IndexedDB is supported in the environment.
     * This promise is used to cache the result of the support check to prevent multiple checks.
     */ background_hybrid_storage_define_property(background_HybridStorage, "idbCapabilityCheckerPromise", null);
/**
     * A flag that stores the result of the IndexedDB support check.
     * If true, IndexedDB is supported in the environment.
     */ background_hybrid_storage_define_property(background_HybridStorage, "idbSupported", false);
/**
     * Prefix for the test IndexedDB database name.
     * This test database is used to check if IndexedDB is supported in the current environment.
     */ background_hybrid_storage_define_property(background_HybridStorage, "TEST_IDB_NAME_PREFIX", 'test_');
/**
     * Version number for the test IndexedDB database.
     */ background_hybrid_storage_define_property(background_HybridStorage, "TEST_IDB_VERSION", 1);
/**
     * The key used to store metadata in SuperJSON-serialized data.
     */ background_hybrid_storage_define_property(background_HybridStorage, "SUPERJSON_META_KEY", 'meta');
/**
     * Serializes the given data using SuperJSON.
     *
     * @param data The data to serialize.
     *
     * @returns The serialized data.
     */ background_hybrid_storage_define_property(background_HybridStorage, "serialize", (data)=>background_SuperJSON.serialize(data));
/**
     * Deserializes the given data using SuperJSON.
     *
     * @param data The data to deserialize.
     *
     * @returns The deserialized data.
     */ background_hybrid_storage_define_property(background_HybridStorage, "deserialize", (data)=>background_SuperJSON.deserialize(data));

;// ./Extension/src/background/storages/shared-instances.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 




/**
 * Storage instance for accessing `browser.storage.local`.
 */ const background_browserStorage = new background_BrowserStorage((background_browser_polyfill_default()).storage.local);
/**
 * Storage instance for accessing `IndexedDB` with fallback to `browser.storage.local`.
 */ const background_hybridStorage = new background_HybridStorage((background_browser_polyfill_default()).storage.local);
// Expose storage instances to the global scope for debugging purposes,
// because it's hard to access them from the console in the background
// page or impossible from Application tab -> IndexedDB (showing empty page).
if (false) {}

;// ./Extension/src/background/storages/settings.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_settings_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}




/**
 * Storage for app settings.
 */ class background_SettingsStorage {
    /**
     * Sets setting to storage.
     *
     * @param key Setting key.
     * @param value Setting value.
     *
     * @throws Error if settings are not initialized.
     */ set(key, value) {
        if (!this.settings) {
            throw background_SettingsStorage.createNotInitializedError();
        }
        this.settings[key] = value;
        this.save();
    }
    /**
     * Returns setting from storage.
     *
     * @param key Setting key.
     *
     * @returns Setting value.
     *
     * @throws Error if settings are not initialized.
     */ get(key) {
        if (!this.settings) {
            throw background_SettingsStorage.createNotInitializedError();
        }
        return this.settings[key];
    }
    /**
     * Remove setting from storage.
     *
     * @param key Setting key.
     *
     * @throws Error if settings are not initialized.
     */ remove(key) {
        if (!this.settings) {
            throw background_SettingsStorage.createNotInitializedError();
        }
        if (this.settings[key]) {
            delete this.settings[key];
            this.save();
        }
    }
    /**
     * Returns current settings.
     *
     * @returns Current settings.
     *
     * @throws Error if settings are not initialized.
     */ getData() {
        if (!this.settings) {
            throw background_SettingsStorage.createNotInitializedError();
        }
        return this.settings;
    }
    /**
     * Set settings to memory cache.
     *
     * @param settings Settings data.
     */ setCache(settings) {
        this.settings = settings;
    }
    /**
     * Set settings to cache and save in browser.storage.local.
     *
     * @param settings Settings data.
     */ setData(settings) {
        this.setCache(settings);
        this.save();
    }
    /**
     * Helper function to create a basic {@link Error} with a custom message.
     *
     * @returns A basic {@link Error} with a custom message.
     */ static createNotInitializedError() {
        return new Error('settings is not initialized');
    }
    constructor(){
        /**
     * Saves settings in browser.storage.local with {@link saveTimeoutMs} debounce.
     */ background_settings_define_property(this, "save", background_lodash_es_debounce(()=>{
            background_browserStorage.set(background_ADGUARD_SETTINGS_KEY, this.settings);
        }, background_SettingsStorage.saveTimeoutMs));
        background_settings_define_property(this, "settings", void 0);
    }
}
background_settings_define_property(background_SettingsStorage, "saveTimeoutMs", 100);
const background_settingsStorage = new background_SettingsStorage();

;// ./Extension/src/background/storages/allowlist.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 


/**
 * Instance of {@link StringStorage}, that stores
 * stringified allowlist in {@link settingsStorage} under
 * {@link SettingOption.AllowlistDomains} key.
 */ const background_allowlistDomainsStorage = new background_StringStorage(background_SettingOption.AllowlistDomains, background_settingsStorage);

;// ./Extension/src/background/storages/custom-filter-metadata.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 



/**
 * Class for synchronous control {@link CustomFilterMetadataStorageData},
 * that is persisted as string in another key value storage.
 *
 * @see {@link StringStorage}
 */ class background_CustomFilterMetadataStorage extends background_StringStorage {
    /**
     * Returns custom filter metadata by filter id.
     *
     * @param filterId Filter id.
     *
     * @returns Custom filter metadata.
     */ getById(filterId) {
        return this.getData().find((f)=>f.filterId === filterId);
    }
    /**
     * Returns custom filter metadata by filter subscription url.
     *
     * @param url Subscription url.
     *
     * @returns Custom filter metadata or undefined, if metadata is not found.
     */ getByUrl(url) {
        return this.getData().find((f)=>f.customUrl === url);
    }
    /**
     * Set custom filter metadata with filterId key.
     *
     * @param filter Custom filter metadata.
     */ set(filter) {
        const data = this.getData().filter((f)=>f.filterId !== filter.filterId);
        data.push(filter);
        this.setData(data);
    }
    /**
     * Remove custom filter metadata.
     *
     * @param filterId Filter id.
     */ remove(filterId) {
        const data = this.getData().filter((f)=>f.filterId !== filterId);
        this.setData(data);
    }
}
const background_customFilterMetadataStorage = new background_CustomFilterMetadataStorage(background_SettingOption.CustomFilters, background_settingsStorage);

;// ./Extension/src/background/storages/editor.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ /**
 * Class used to persist user rules editor content in memory
 * during switches between common and fullscreen modes.
 */ function background_editor_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
class background_EditorStorage {
    /**
     * Sets user rules editor content.
     *
     * @param data User rules editor content.
     */ set(data) {
        this.data = data;
    }
    /**
     * Returns user rules editor content.
     *
     * @returns User rules editor content.
     */ get() {
        return this.data;
    }
    constructor(){
        // current content
        background_editor_define_property(this, "data", void 0);
    }
}
const background_editorStorage = new background_EditorStorage();

;// ./Extension/src/background/storages/filter-state.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_filter_state_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}






/**
 * Class for synchronous control {@link FilterStateStorageData},
 * that is persisted as string in another key value storage.
 *
 * @see {@link StringStorage}
 */ class background_FilterStateStorage extends background_StringStorage {
    /**
     * Returns specified filter state.
     *
     * @param filterId Filter id.
     *
     * @returns Specified filter state.
     *
     * @throws Error if filter state data is not initialized.
     */ get(filterId) {
        if (!this.data) {
            throw background_FilterStateStorage.createNotInitializedError();
        }
        return this.data[filterId];
    }
    /**
     * Sets specified filter state.
     *
     * @param filterId Filter id.
     * @param state Filter state.
     *
     * @throws Error if filter state data is not initialized.
     */ set(filterId, state) {
        if (!this.data) {
            throw background_FilterStateStorage.createNotInitializedError();
        }
        this.data[filterId] = state;
        this.save();
    }
    /**
     * Deletes specified filter state.
     *
     * @param filterId Filter id.
     *
     * @throws Error if filter state data is not initialized.
     */ delete(filterId) {
        if (!this.data) {
            throw background_FilterStateStorage.createNotInitializedError();
        }
        delete this.data[filterId];
        this.save();
    }
    /**
     * Returns list of enabled filters ids.
     *
     * @returns List of enabled filters ids.
     *
     * @throws Error if filter state data is not initialized.
     */ getEnabledFilters() {
        if (!this.data) {
            throw background_FilterStateStorage.createNotInitializedError();
        }
        return Object.entries(this.data).filter(([, state])=>state.enabled).map(([id])=>Number(id));
    }
    /**
     * Returns list of loaded into browserStorage filters ids.
     *
     * @returns List of loaded into browserStorage filters ids.
     *
     * @throws Error if filter state data is not initialized.
     */ getLoadFilters() {
        if (!this.data) {
            throw background_FilterStateStorage.createNotInitializedError();
        }
        return Object.entries(this.data).filter(([, state])=>state.loaded).map(([id])=>Number(id));
    }
    /**
     * Returns list of installed filters ids.
     *
     * @returns List of installed filters ids.
     *
     * @throws Error if filter state data is not initialized.
     */ getInstalledFilters() {
        if (!this.data) {
            throw background_FilterStateStorage.createNotInitializedError();
        }
        return Object.entries(this.data).filter(([, state])=>state.installed).map(([id])=>Number(id));
    }
    /**
     * Enables specified filters.
     *
     * @param filterIds List of filter ids to enable.
     *
     * @throws Error if filter state data is not initialized.
     */ enableFilters(filterIds) {
        if (!this.data) {
            throw background_FilterStateStorage.createNotInitializedError();
        }
        for(let i = 0; i < filterIds.length; i += 1){
            const filterId = filterIds[i];
            if (!filterId) {
                continue;
            }
            const data = this.data[filterId];
            if (data) {
                data.enabled = true;
            }
        }
        this.save();
    }
    /**
     * Disables specified filters.
     *
     * @param filtersIds List of filters to disable.
     *
     * @throws Error if filter state data is not initialized.
     */ disableFilters(filtersIds) {
        if (!this.data) {
            throw background_FilterStateStorage.createNotInitializedError();
        }
        for(let i = 0; i < filtersIds.length; i += 1){
            const filterId = filtersIds[i];
            if (!filterId) {
                continue;
            }
            const data = this.data[filterId];
            if (data) {
                data.enabled = false;
            }
        }
        this.save();
    }
    /**
     * Sets {@link defaultState} for new filters, found in passed {@link Metadata}.
     *
     * @param states Current {@link FilterStateStorageData}.
     * @param metadata App {@link Metadata}.
     *
     * @returns Updated {@link FilterStateStorageData}.
     */ static applyMetadata(states, metadata) {
        const { filters } = metadata;
        /**
         * Don't create filter state context for allowlist and user rules lists
         * Their state is controlled by separate modules.
         */ const supportedFiltersMetadata = filters.filter(({ filterId })=>{
            return !background_FilterStateStorage.unsupportedFiltersIds.includes(filterId);
        });
        supportedFiltersMetadata.forEach(({ filterId })=>{
            if (!states[filterId]) {
                states[filterId] = {
                    ...background_FilterStateStorage.defaultState
                };
            }
        });
        return states;
    }
    /**
     * Helper function to create a basic {@link Error} with a custom message.
     *
     * @returns A basic {@link Error} with a custom message.
     */ static createNotInitializedError() {
        return new Error('Filter state data is not initialized');
    }
}
// This filters have own complex state management
background_filter_state_define_property(background_FilterStateStorage, "unsupportedFiltersIds", [
    background_AntiBannerFiltersId.AllowlistFilterId,
    background_AntiBannerFiltersId.UserFilterId
]);
// default filter state
background_filter_state_define_property(background_FilterStateStorage, "defaultState", {
    enabled: false,
    installed: false,
    loaded: false
});
/**
 * {@link FilterStateStorage} Instance, that stores
 * stringified {@link FilterStateStorageData} in {@link settingsStorage} under
 * {@link SettingOption.FiltersState} key.
 */ const background_filterStateStorage = new background_FilterStateStorage(background_SettingOption.FiltersState, background_settingsStorage);

;// ./Extension/src/background/storages/filter-version.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 




/**
 * Class for synchronous control {@link FilterVersionStorageData},
 * that is persisted as string in another key value storage.
 *
 * @see {@link StringStorage}
 */ class background_FilterVersionStorage extends background_StringStorage {
    /**
     * Returns specified filter version.
     *
     * @param filterId Filter id.
     *
     * @returns Specified filter state or undefined, if it is not found.
     *
     * @throws Error if filter version data is not initialized.
     */ get(filterId) {
        if (!this.data) {
            throw background_FilterVersionStorage.createNotInitializedError();
        }
        return this.data[filterId];
    }
    /**
     * Sets specified filter version.
     *
     * @param filterId Filter id.
     * @param data Filter version data.
     *
     * @throws Error if filter version data is not initialized.
     */ set(filterId, data) {
        if (!this.data) {
            throw background_FilterVersionStorage.createNotInitializedError();
        }
        this.data[filterId] = data;
        this.save();
    }
    /**
     * Deletes specified filter version.
     *
     * @param filterId Filter id.
     *
     * @throws Error if filter version data is not initialized.
     */ delete(filterId) {
        if (!this.data) {
            throw background_FilterVersionStorage.createNotInitializedError();
        }
        delete this.data[filterId];
        this.save();
    }
    /**
     * Update last check time stamp for specified filters with current time.
     *
     * @param filterDetails List of filter details to update check time for.
     *
     * @throws Error if filter version data is not initialized.
     */ refreshLastCheckTime(filterDetails) {
        if (!this.data) {
            throw background_FilterVersionStorage.createNotInitializedError();
        }
        const now = Date.now();
        for(let i = 0; i < filterDetails.length; i += 1){
            const filterDetail = filterDetails[i];
            if (!filterDetail) {
                continue;
            }
            const { filterId, ignorePatches } = filterDetail;
            const data = this.data[filterId];
            if (!data) {
                background_logger_logger.warn(`Failed to refresh last check time for filter ${filterId}.`);
                continue;
            }
            if (ignorePatches) {
                data.lastCheckTime = now;
            } else {
                data.lastScheduledCheckTime = now;
            }
        }
        this.save();
    }
    /**
     * Sets version data for new filters, found in passed {@link Metadata}.
     *
     * @param data Current {@link FilterVersionStorageData}.
     * @param metadata App {@link Metadata}.
     *
     * @returns Updated {@link FilterVersionStorageData}.
     */ static applyMetadata(data, metadata) {
        const { filters } = metadata;
        filters.forEach(({ filterId, version, expires, timeUpdated })=>{
            if (!data[filterId]) {
                data[filterId] = {
                    version,
                    expires,
                    lastUpdateTime: new Date(timeUpdated).getTime(),
                    lastCheckTime: Date.now(),
                    lastScheduledCheckTime: Date.now()
                };
            }
        });
        return data;
    }
    /**
     * Helper function to create a basic {@link Error} with a custom message.
     *
     * @returns A basic {@link Error} with a custom message.
     */ static createNotInitializedError() {
        return new Error('Filter version data is not initialized');
    }
}
/**
 * {@link FilterVersionStorage} Instance, that stores
 * stringified {@link FilterVersionStorageData} in {@link settingsStorage} under
 * {@link SettingOption.FiltersVersion} key.
 */ const background_filterVersionStorage = new background_FilterVersionStorage(background_SettingOption.FiltersVersion, background_settingsStorage);

// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+tsurlfilter@3.3.3_@adguard+re2-wasm@1.2.0/node_modules/@adguard/tsurlfilter/dist/es/index.js + 32 modules
var background_es = __webpack_require__(84333);
;// ./Extension/src/background/storages/filters.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_filters_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}



/**
 * Encapsulates interaction with stored filter rules.
 */ class background_FiltersStorage {
    /**
     * Returns key with prefix.
     * Key format: <prefix>_<filterId>, e.g. `filterList_1`.
     *
     * @param keyPrefix Key prefix.
     * @param filterId Filter id.
     *
     * @returns Key with prefix.
     */ static getKey(keyPrefix, filterId) {
        return `${keyPrefix}${background_FiltersStorage.KEY_COMBINER}${filterId}`;
    }
    /**
     * Sets specified filter list with the specified ID in the storage.
     *
     * @param filterId Filter id.
     * @param filter Raw filter list or preprocessed filter list.
     *
     * @throws Error if the transaction failed.
     */ static async set(filterId, filter) {
        const data = {};
        let preprocessed;
        if (typeof filter === 'string') {
            preprocessed = background_es/* FilterListPreprocessor */.aQ.preprocess(filter);
        } else {
            preprocessed = filter;
        }
        // eslint-disable-next-line no-restricted-syntax
        for (const [key, value] of Object.entries(preprocessed)){
            const storageKey = background_FiltersStorage.getKey(key, filterId);
            data[storageKey] = value;
        }
        const succeeded = await background_hybridStorage.setMultiple(data);
        if (!succeeded) {
            throw new Error('Transaction failed');
        }
    }
    /**
     * Checks if the filter list with the specified ID exists in the storage.
     *
     * @param filterId Filter id.
     *
     * @returns `true` if the filter list exists, `false` otherwise.
     */ static async has(filterId) {
        const storageKey = background_FiltersStorage.getKey(background_FiltersStorage.KEY_FILTER_LIST, filterId);
        return background_hybridStorage.has(storageKey);
    }
    /**
     * Gets the whole preprocessed filter list for the specified filter ID.
     *
     * @param filterId Filter id.
     *
     * @returns Preprocessed filter list or `undefined` if the filter list does not exist.
     */ static async get(filterId) {
        // eslint-disable-next-line prefer-const
        let [rawFilterList, filterList, conversionMap, sourceMap] = await Promise.all([
            background_FiltersStorage.getRawFilterList(filterId),
            background_FiltersStorage.getFilterList(filterId),
            background_FiltersStorage.getConversionMap(filterId),
            background_FiltersStorage.getSourceMap(filterId)
        ]);
        if (rawFilterList === undefined || filterList === undefined || sourceMap === undefined) {
            return undefined;
        }
        if (conversionMap === undefined) {
            conversionMap = {};
        }
        return {
            filterList,
            rawFilterList,
            conversionMap,
            sourceMap
        };
    }
    /**
     * Removes the filter list with the specified ID from the storage.
     *
     * @note This method does nothing in MV3 version if the filter ID is a static filter ID,
     * because static filters are managed by TSWebExtension.
     *
     * @param filterId Filter id.
     */ static async remove(filterId) {
        await background_hybridStorage.removeMultiple([
            background_FiltersStorage.getKey(background_FiltersStorage.KEY_FILTER_LIST, filterId),
            background_FiltersStorage.getKey(background_FiltersStorage.KEY_RAW_FILTER_LIST, filterId),
            background_FiltersStorage.getKey(background_FiltersStorage.KEY_CONVERSION_MAP, filterId),
            background_FiltersStorage.getKey(background_FiltersStorage.KEY_SOURCE_MAP, filterId)
        ]);
    }
    /**
     * Gets the raw filter list for the specified filter ID.
     *
     * @param filterId Filter id.
     *
     * @returns Raw filter list or `undefined` if the filter list does not exist.
     */ static async getRawFilterList(filterId) {
        const storageKey = background_FiltersStorage.getKey(background_FiltersStorage.KEY_RAW_FILTER_LIST, filterId);
        return background_hybridStorage.get(storageKey);
    }
    /**
     * Gets the byte array of the filter list for the specified filter ID.
     *
     * @param filterId Filter id.
     *
     * @returns Byte array of the filter list or `undefined` if the filter list does not exist.
     */ static async getFilterList(filterId) {
        const storageKey = background_FiltersStorage.getKey(background_FiltersStorage.KEY_FILTER_LIST, filterId);
        return background_hybridStorage.get(storageKey);
    }
    /**
     * Gets the conversion map for the specified filter ID.
     *
     * @param filterId Filter id.
     *
     * @returns Conversion map or `undefined` if the filter list does not exist.
     */ static async getConversionMap(filterId) {
        const storageKey = background_FiltersStorage.getKey(background_FiltersStorage.KEY_CONVERSION_MAP, filterId);
        return background_hybridStorage.get(storageKey);
    }
    /**
     * Gets the source map for the specified filter ID.
     *
     * @param filterId Filter id.
     *
     * @returns Source map or `undefined` if the filter list does not exist.
     */ static async getSourceMap(filterId) {
        const storageKey = background_FiltersStorage.getKey(background_FiltersStorage.KEY_SOURCE_MAP, filterId);
        return background_hybridStorage.get(storageKey);
    }
}
background_filters_define_property(background_FiltersStorage, "KEY_COMBINER", '_');
/**
     * Key for the filter list.
     * Should be the same as in `PreprocessedFilterList`.
     */ background_filters_define_property(background_FiltersStorage, "KEY_FILTER_LIST", 'filterList');
background_filters_define_property(background_FiltersStorage, "KEY_RAW_FILTER_LIST", 'rawFilterList');
background_filters_define_property(background_FiltersStorage, "KEY_CONVERSION_MAP", 'conversionMap');
background_filters_define_property(background_FiltersStorage, "KEY_SOURCE_MAP", 'sourceMap');

;// ./Extension/src/background/storages/raw-filters.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 



/**
 * Prefix for storage keys where raw filter lists are stored.
 * These filter lists are stored in raw format, and they are used in the diff update process.
 *
 * @example
 * raw_filterrules_1.txt
 */ const background_RAW_FILTER_KEY_PREFIX = 'raw_filterrules_';
/**
 * Regular expression that helps to extract filter id from the key.
 */ const background_RE_FILTER_KEY = new RegExp(`^${background_RAW_FILTER_KEY_PREFIX}(?<filterId>\\d+)${background_FILTER_LIST_EXTENSION}$`);
/**
 * Zod schema for string array.
 */ const background_stringArraySchema = background_lib/* default.string */.Ay.string().optional().transform((data)=>data !== null && data !== void 0 ? data : undefined);
/**
 * Encapsulates interaction with stored filter rules before applying directives.
 */ class background_RawFiltersStorage {
    /**
     * Sets specified filter list to {@link hybridStorage}.
     *
     * @param filterId Filter id.
     * @param filter Filter rules strings.
     */ static async set(filterId, filter) {
        const key = background_RawFiltersStorage.getFilterKey(filterId);
        await background_hybridStorage.set(key, filter);
    }
    /**
     * Retrieves raw filter from the {@link hybridStorage}. Parses it and returns string if data is
     * valid or undefined otherwise.
     *
     * @param filterId Filter id.
     *
     * @returns Promise, resolved with filter rules strings or undefined if data is invalid.
     */ static async get(filterId) {
        const key = background_RawFiltersStorage.getFilterKey(filterId);
        const data = await background_hybridStorage.get(key);
        const parseResult = background_stringArraySchema.safeParse(data);
        if (!parseResult.success) {
            background_logger_logger.info('Received data had a format that was not expected:', parseResult.error.message);
            return undefined;
        }
        return parseResult.data;
    }
    /**
     * Removes specified filter list from {@link hybridStorage}.
     *
     * @param filterId Filter id.
     *
     * @returns Promise, resolved when filter list is removed.
     */ static async remove(filterId) {
        const key = background_RawFiltersStorage.getFilterKey(filterId);
        return background_hybridStorage.remove(key);
    }
    /**
     * Returns {@link hybridStorage} key from specified filter list.
     *
     * @param filterId Filter id.
     *
     * @returns Storage key from specified filter list.
     */ static getFilterKey(filterId) {
        return `${background_RAW_FILTER_KEY_PREFIX}${filterId}${background_FILTER_LIST_EXTENSION}`;
    }
    /**
     * Helper method to extract filter id from the key.
     *
     * @param key Storage key.
     *
     * @returns Filter id or `null` if the key is invalid.
     */ static extractFilterIdFromFilterKey(key) {
        var _match_groups;
        const match = key.match(background_RE_FILTER_KEY);
        var _match_groups_filterId;
        return match ? parseInt((_match_groups_filterId = (_match_groups = match.groups) === null || _match_groups === void 0 ? void 0 : _match_groups.filterId) !== null && _match_groups_filterId !== void 0 ? _match_groups_filterId : '', 10) : null;
    }
}

;// ./Extension/src/background/storages/group-state.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_group_state_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}




/**
 * Class for synchronous control {@link GroupStateStorageData},
 * that is persisted as string in another key value storage.
 *
 * @see {@link StringStorage}
 */ class background_GroupStateStorage extends background_StringStorage {
    /**
     * Returns specified group state.
     *
     * @param groupId Group id.
     *
     * @returns Specified group state.
     *
     * @throws Error if group state data is not initialized.
     */ get(groupId) {
        if (!this.data) {
            throw background_GroupStateStorage.createNotInitializedError();
        }
        return this.data[groupId];
    }
    /**
     * Sets specified group state.
     *
     * @param groupId Group id.
     * @param state Group state.
     *
     * @throws Error if group state data is not initialized.
     */ set(groupId, state) {
        if (!this.data) {
            throw background_GroupStateStorage.createNotInitializedError();
        }
        this.data[groupId] = state;
        this.save();
    }
    /**
     * Delete specified group state.
     *
     * @param groupId Group id.
     *
     * @throws Error if group state data is not initialized.
     */ delete(groupId) {
        if (!this.data) {
            throw background_GroupStateStorage.createNotInitializedError();
        }
        delete this.data[groupId];
        this.save();
    }
    /**
     * Returns list of enabled groups ids.
     *
     * @returns List of enabled groups ids.
     *
     * @throws Error if group state data is not initialized.
     */ getEnabledGroups() {
        if (!this.data) {
            throw background_GroupStateStorage.createNotInitializedError();
        }
        return Object.entries(this.data).filter(([, state])=>state.enabled).map(([id])=>Number(id));
    }
    /**
     * Enables specified groups.
     *
     * @param groupIds List of groups to enable.
     * @param touched Mark groups as touched on enabling.
     *
     * @throws Error if group state data is not initialized.
     */ enableGroups(groupIds, touched = true) {
        if (!this.data) {
            throw background_GroupStateStorage.createNotInitializedError();
        }
        for(let i = 0; i < groupIds.length; i += 1){
            const groupId = groupIds[i];
            if (groupId !== undefined) {
                this.data[groupId] = {
                    enabled: true,
                    touched
                };
            }
        }
        this.save();
    }
    /**
     * Disables specified groups.
     *
     * @param groupIds List of groups to disable.
     * @param touched Mark groups as touched on disabling.
     *
     * @throws Error if group state data is not initialized.
     */ disableGroups(groupIds, touched = true) {
        if (!this.data) {
            throw background_GroupStateStorage.createNotInitializedError();
        }
        for(let i = 0; i < groupIds.length; i += 1){
            const groupId = groupIds[i];
            if (groupId !== undefined) {
                this.data[groupId] = {
                    enabled: false,
                    touched
                };
            }
        }
        this.save();
    }
    /**
     * Sets {@link defaultState} for new groups, found in passed {@link Metadata}.
     *
     * @param states Current {@link GroupStateStorageData}.
     * @param metadata App {@link Metadata}.
     *
     * @returns Updated {@link GroupStateStorageData}.
     */ static applyMetadata(states, metadata) {
        const { groups } = metadata;
        groups.forEach(({ groupId })=>{
            if (!states[groupId]) {
                states[groupId] = {
                    ...background_GroupStateStorage.defaultState
                };
            }
        });
        return states;
    }
    /**
     * Helper function to create a basic {@link Error} with a custom message.
     *
     * @returns A basic {@link Error} with a custom message.
     */ static createNotInitializedError() {
        return new Error('Group state data is not initialized');
    }
}
// default group state
background_group_state_define_property(background_GroupStateStorage, "defaultState", {
    enabled: false,
    touched: false
});
/**
 * {@link GroupStateStorage} Instance, that stores
 * stringified {@link GroupStateStorageData} in {@link settingsStorage} under
 * {@link SettingOption.GroupsState} key.
 */ const background_groupStateStorage = new background_GroupStateStorage(background_SettingOption.GroupsState, background_settingsStorage);

;// ./Extension/src/background/storages/i18n-metadata.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 


/**
 * Instance of {@link StringStorage}, that stores
 * stringified {@link I18nMetadata} in {@link settingsStorage} under
 * {@link SettingOption.I18nMetadata} key.
 */ const background_i18nMetadataStorage = new background_StringStorage(background_SettingOption.I18nMetadata, background_settingsStorage);

;// ./Extension/src/background/storages/inverted-allowlist.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 


/**
 * Instance of {@link StringStorage}, that stores
 * stringified inverted allowlist in {@link settingsStorage} under
 * {@link SettingOption.InvertedAllowlistDomains} key.
 */ const background_invertedAllowlistDomainsStorage = new background_StringStorage(background_SettingOption.InvertedAllowlistDomains, background_settingsStorage);

;// ./Extension/src/background/utils/i18n.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ /**
 * Helper class for working with i18n locales.
 */ 
class background_I18n {
    /**
     * Returns matched `locale` from `locales` list.
     *
     * @param locales Array of locale codes represented as strings.
     * @param locale Target locale.
     *
     * @returns Normalized locale code if found, otherwise null.
     */ static find(locales, locale) {
        const normalizedLocales = locales.map((l)=>background_I18n.normalizeLanguageCode(l));
        const lang = this.normalizeLanguageCode(locale);
        if (normalizedLocales.includes(lang)) {
            return lang;
        }
        const [localePart] = lang.split('_');
        if (localePart && normalizedLocales.includes(localePart)) {
            return localePart;
        }
        return null;
    }
    /**
     * Normalizes language code.
     *
     * @param locale Language code.
     *
     * @returns Normalized language code.
     */ static normalizeLanguageCode(locale) {
        return locale.toLowerCase().replace('-', '_');
    }
}

;// ./Extension/src/background/storages/metadata.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 





/**
 * Class for synchronous control {@link Metadata} storage,
 * that is persisted as string in another key value storage.
 *
 * @see {@link StringStorage}
 */ class background_MetadataStorage extends background_StringStorage {
    /**
     * Returns regular filters metadata.
     *
     * @returns Regular filters metadata.
     *
     * @throws Error if metadata is not initialized.
     */ getFilters() {
        if (!this.data) {
            throw background_MetadataStorage.createNotInitializedError();
        }
        return this.data.filters;
    }
    /**
     * Returns specified regular filter metadata.
     *
     * @param filterId Filter id.
     *
     * @returns Specified regular filter metadata.
     *
     * @throws Error if metadata is not initialized.
     */ getFilter(filterId) {
        if (!this.data) {
            throw background_MetadataStorage.createNotInitializedError();
        }
        return this.data.filters.find((el)=>el.filterId === filterId);
    }
    /**
     * Returns groups metadata.
     *
     * @returns Groups metadata.
     *
     * @throws Error if metadata is not initialized.
     */ getGroups() {
        if (!this.data) {
            throw background_MetadataStorage.createNotInitializedError();
        }
        return this.data.groups;
    }
    /**
     * Returns specified group metadata.
     *
     * @param groupId Group id.
     *
     * @returns Specified group metadata.
     *
     * @throws Error if metadata is not initialized.
     */ getGroup(groupId) {
        if (!this.data) {
            throw background_MetadataStorage.createNotInitializedError();
        }
        return this.data.groups.find((el)=>el.groupId === groupId);
    }
    /**
     * Returns tags metadata.
     *
     * @returns Tags metadata.
     *
     * @throws Error if metadata is not initialized.
     */ getTags() {
        if (!this.data) {
            throw background_MetadataStorage.createNotInitializedError();
        }
        return this.data.tags;
    }
    /**
     * Returns specified tag metadata.
     *
     * @param tagId Tag id.
     *
     * @returns Specified tag metadata.
     *
     * @throws Error if metadata is not initialized.
     */ getTag(tagId) {
        if (!this.data) {
            throw background_MetadataStorage.createNotInitializedError();
        }
        return this.data.tags.find((el)=>el.tagId === tagId);
    }
    /**
     * Returns list of filters for the specified languages.
     *
     * @param locale Locale string.
     *
     * @returns List of language specific filters ids.
     */ getFilterIdsForLanguage(locale) {
        if (!locale) {
            return [];
        }
        return this.getFilters().filter(({ languages })=>languages.length > 0 && background_I18n.find(languages, locale)).map(({ filterId })=>filterId);
    }
    /**
     * Refreshes metadata objects with i18n metadata.
     *
     * @param metadata Current {@link Metadata}.
     * @param i18nMetadata Applied {@link I18nMetadata}.
     *
     * @returns Updated {@link Metadata}.
     */ static applyI18nMetadata(metadata, i18nMetadata) {
        const tagsI18n = i18nMetadata.tags;
        const filtersI18n = i18nMetadata.filters;
        const groupsI18n = i18nMetadata.groups;
        const { tags, groups, filters } = metadata;
        const uiLanguage = background_browser_polyfill_default().i18n.getUILanguage();
        tags.forEach((tag)=>background_MetadataStorage.applyFilterTagLocalization(tag, tagsI18n, uiLanguage));
        filters.forEach((filter)=>background_MetadataStorage.applyFilterLocalization(filter, filtersI18n, uiLanguage));
        groups.forEach((group)=>background_MetadataStorage.applyGroupLocalization(group, groupsI18n, uiLanguage));
        return metadata;
    }
    /**
     * Localize tag.
     *
     * @param tag Tag metadata.
     * @param tagsI18n Tag i18n metadata.
     * @param uiLanguage UI language.
     */ static applyFilterTagLocalization(tag, tagsI18n, uiLanguage) {
        const { tagId } = tag;
        const rawLocalizations = tagsI18n[tagId];
        if (!rawLocalizations) {
            return;
        }
        const localizations = background_MetadataStorage.normalizeLocalization(rawLocalizations);
        const locale = background_I18n.find(Object.keys(localizations), uiLanguage);
        if (!locale) {
            return;
        }
        const localization = localizations[locale];
        if (localization) {
            tag.name = localization.name;
            tag.description = localization.description;
        }
    }
    /**
     * Localize filter.
     *
     * @param filter Regular filter metadata.
     * @param filtersI18n Regular filter i18n metadata.
     * @param uiLanguage UI language.
     */ static applyFilterLocalization(filter, filtersI18n, uiLanguage) {
        const { filterId } = filter;
        const rawLocalizations = filtersI18n[filterId];
        if (!rawLocalizations) {
            return;
        }
        const localizations = background_MetadataStorage.normalizeLocalization(rawLocalizations);
        const locale = background_I18n.find(Object.keys(localizations), uiLanguage);
        if (!locale) {
            return;
        }
        const localization = localizations[locale];
        if (localization) {
            filter.name = localization.name;
            filter.description = localization.description;
        }
    }
    /**
     * Localize group.
     *
     * @param group Group metadata.
     * @param groupsI18n Group i18n metadata.
     * @param uiLanguage UI language.
     */ static applyGroupLocalization(group, groupsI18n, uiLanguage) {
        const { groupId } = group;
        const rawLocalizations = groupsI18n[groupId];
        if (!rawLocalizations) {
            return;
        }
        const localizations = background_MetadataStorage.normalizeLocalization(rawLocalizations);
        const locale = background_I18n.find(Object.keys(localizations), uiLanguage);
        if (!locale) {
            return;
        }
        const localization = localizations[locale];
        if (localization) {
            group.groupName = localization.name;
        }
    }
    /**
     * Normalizes localization object.
     *
     * @param localization Input localization object.
     *
     * @returns Normalized localization object.
     */ static normalizeLocalization(localization) {
        const normalizedLocalization = {};
        Object.entries(localization).forEach(([key, value])=>{
            normalizedLocalization[background_I18n.normalizeLanguageCode(key)] = value;
        });
        return normalizedLocalization;
    }
    /**
     * Helper function to create a basic {@link Error} with a custom message.
     *
     * @returns A basic {@link Error} with a custom message.
     */ static createNotInitializedError() {
        return new Error('Metadata is not initialized');
    }
}
/**
 * {@link MetadataStorage} Instance, that stores
 * stringified {@link Metadata} in {@link settingsStorage} under
 * {@link SettingOption.Metadata} key.
 */ const background_metadataStorage = new background_MetadataStorage(background_SettingOption.Metadata, background_settingsStorage);

// EXTERNAL MODULE: ./node_modules/.pnpm/lru-cache@11.0.2/node_modules/lru-cache/dist/esm/index.js
var background_esm = __webpack_require__(38037);
;// ./Extension/src/background/storages/safebrowsing.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_safebrowsing_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}







/**
 * Class for control persisted {@link LRUCache} safebrowsing cache.
 */ class background_SbCache {
    /**
     * Reads safebrowsing {@link LRUCache} stringified entries from {@link browserStorage},
     * parse it and sets to {@link this.cache}.
     *
     * @returns Promise, resolved when data successfully initialized.
     */ async init() {
        const storageData = await background_browserStorage.get(background_SB_LRU_CACHE_KEY);
        if (typeof storageData !== 'string') {
            return;
        }
        try {
            const rawData = JSON.parse(storageData);
            const data = background_safebrowsingStorageDataValidator.parse(rawData);
            this.cache.load(data);
            // Note: `.load()` method doesn't remove stale records, so we need to do it manually
            this.cache.purgeStale();
        } catch (e) {
            background_logger_logger.error('Failed to initialize safebrowsing storage', e);
            // if data is corrupted, purge it
            // if error is json parsing error or zod validation error
            if (e instanceof SyntaxError || e instanceof background_lib/* ZodError */.G) {
                await background_SbCache.purgeStorage();
                background_logger_logger.info('Safebrowsing storage was purged, because of data corruption');
            }
        }
    }
    /**
     * Purges {@link browserStorage} data.
     */ static async purgeStorage() {
        try {
            await background_browserStorage.remove(background_SB_LRU_CACHE_KEY);
        } catch (e) {
            background_logger_logger.error('Failed to purge safebrowsing storage', e);
        }
    }
    /**
     * Saves stringified safebrowsing {@link this.cache} entries in {@link browserStorage}.
     */ async save() {
        await background_browserStorage.set(background_SB_LRU_CACHE_KEY, JSON.stringify(this.cache.dump()));
    }
    /**
     * Returns value from {@link this.cache}.
     *
     * @param key Cache key.
     *
     * @returns Cache value.
     */ get(key) {
        return this.cache.get(key);
    }
    /**
     * Sets value to {@link this.cache}.
     *
     * @param key Cache key.
     * @param list Cache list value.
     *
     * @returns Updated {@link this.cache} instance.
     */ async set(key, list) {
        const data = list;
        let options;
        if (list !== background_SbCache.SB_ALLOW_LIST) {
            options = {
                ttl: background_SbCache.CACHE_TTL_MS
            };
        }
        this.cache.set(key, data, options);
        if (this.cache.size % 20 === 0) {
            await this.save();
        }
        return this;
    }
    /**
     * Clear {@link this.cache} and {@link browserStorage} data.
     */ async clear() {
        this.cache.clear();
        await this.save();
    }
    /**
     * Constructor.
     */ constructor(){
        /**
     * {@link LRUCache} instance.
     */ background_safebrowsing_define_property(this, "cache", void 0);
        this.cache = new background_esm/* LRUCache */.q({
            max: background_SbCache.CACHE_LIMIT,
            allowStale: false
        });
    }
}
/**
     * A key that indicates that the domain is in the allow list.
     */ background_safebrowsing_define_property(background_SbCache, "SB_ALLOW_LIST", 'allowlist');
/**
     * Time to live of cache record.
     * This time: 40 minutes.
     */ background_safebrowsing_define_property(background_SbCache, "CACHE_TTL_MS", 40 * 60 * 1000);
/**
     * Number of maximum allowed cache records.
     */ background_safebrowsing_define_property(background_SbCache, "CACHE_LIMIT", 1000);
const background_sbCache = new background_SbCache();
const background_sbRequestCache = new background_esm/* LRUCache */.q({
    max: background_SbCache.CACHE_LIMIT
});

;// ./node_modules/.pnpm/date-fns@2.29.3/node_modules/date-fns/esm/_lib/requiredArgs/index.js
function background_requiredArgs(required, args) {
  if (args.length < required) {
    throw new TypeError(required + ' argument' + (required > 1 ? 's' : '') + ' required, but only ' + args.length + ' present');
  }
}
;// ./node_modules/.pnpm/date-fns@2.29.3/node_modules/date-fns/esm/toDate/index.js
function background_toDate_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { background_toDate_typeof = function _typeof(obj) { return typeof obj; }; } else { background_toDate_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return background_toDate_typeof(obj); }


/**
 * @name toDate
 * @category Common Helpers
 * @summary Convert the given argument to an instance of Date.
 *
 * @description
 * Convert the given argument to an instance of Date.
 *
 * If the argument is an instance of Date, the function returns its clone.
 *
 * If the argument is a number, it is treated as a timestamp.
 *
 * If the argument is none of the above, the function returns Invalid Date.
 *
 * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.
 *
 * @param {Date|Number} argument - the value to convert
 * @returns {Date} the parsed date in the local time zone
 * @throws {TypeError} 1 argument required
 *
 * @example
 * // Clone the date:
 * const result = toDate(new Date(2014, 1, 11, 11, 30, 30))
 * //=> Tue Feb 11 2014 11:30:30
 *
 * @example
 * // Convert the timestamp to date:
 * const result = toDate(1392098430000)
 * //=> Tue Feb 11 2014 11:30:30
 */

function background_toDate(argument) {
  background_requiredArgs(1, arguments);
  var argStr = Object.prototype.toString.call(argument); // Clone the date

  if (argument instanceof Date || background_toDate_typeof(argument) === 'object' && argStr === '[object Date]') {
    // Prevent the date to lose the milliseconds when passed to new Date() in IE10
    return new Date(argument.getTime());
  } else if (typeof argument === 'number' || argStr === '[object Number]') {
    return new Date(argument);
  } else {
    if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') {
      // eslint-disable-next-line no-console
      console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"); // eslint-disable-next-line no-console

      console.warn(new Error().stack);
    }

    return new Date(NaN);
  }
}
;// ./node_modules/.pnpm/date-fns@2.29.3/node_modules/date-fns/esm/startOfHour/index.js


/**
 * @name startOfHour
 * @category Hour Helpers
 * @summary Return the start of an hour for the given date.
 *
 * @description
 * Return the start of an hour for the given date.
 * The result will be in the local timezone.
 *
 * @param {Date|Number} date - the original date
 * @returns {Date} the start of an hour
 * @throws {TypeError} 1 argument required
 *
 * @example
 * // The start of an hour for 2 September 2014 11:55:00:
 * const result = startOfHour(new Date(2014, 8, 2, 11, 55))
 * //=> Tue Sep 02 2014 11:00:00
 */

function background_startOfHour(dirtyDate) {
  background_requiredArgs(1, arguments);
  var date = background_toDate(dirtyDate);
  date.setMinutes(0, 0, 0);
  return date;
}
;// ./node_modules/.pnpm/date-fns@2.29.3/node_modules/date-fns/esm/isSameHour/index.js


/**
 * @name isSameHour
 * @category Hour Helpers
 * @summary Are the given dates in the same hour (and same day)?
 *
 * @description
 * Are the given dates in the same hour (and same day)?
 *
 * @param {Date|Number} dateLeft - the first date to check
 * @param {Date|Number} dateRight - the second date to check
 * @returns {Boolean} the dates are in the same hour (and same day)
 * @throws {TypeError} 2 arguments required
 *
 * @example
 * // Are 4 September 2014 06:00:00 and 4 September 06:30:00 in the same hour?
 * const result = isSameHour(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 6, 30))
 * //=> true
 *
 * @example
 * // Are 4 September 2014 06:00:00 and 5 September 06:00:00 in the same hour?
 * const result = isSameHour(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 5, 6, 0))
 * //=> false
 */

function background_isSameHour(dirtyDateLeft, dirtyDateRight) {
  background_requiredArgs(2, arguments);
  var dateLeftStartOfHour = background_startOfHour(dirtyDateLeft);
  var dateRightStartOfHour = background_startOfHour(dirtyDateRight);
  return dateLeftStartOfHour.getTime() === dateRightStartOfHour.getTime();
}
;// ./node_modules/.pnpm/date-fns@2.29.3/node_modules/date-fns/esm/constants/index.js
/**
 * Days in 1 week.
 *
 * @name daysInWeek
 * @constant
 * @type {number}
 * @default
 */
var background_daysInWeek = 7;
/**
 * Days in 1 year
 * One years equals 365.2425 days according to the formula:
 *
 * > Leap year occures every 4 years, except for years that are divisable by 100 and not divisable by 400.
 * > 1 mean year = (365+1/4-1/100+1/400) days = 365.2425 days
 *
 * @name daysInYear
 * @constant
 * @type {number}
 * @default
 */

var background_daysInYear = 365.2425;
/**
 * Maximum allowed time.
 *
 * @name maxTime
 * @constant
 * @type {number}
 * @default
 */

var background_maxTime = Math.pow(10, 8) * 24 * 60 * 60 * 1000;
/**
 * Milliseconds in 1 minute
 *
 * @name millisecondsInMinute
 * @constant
 * @type {number}
 * @default
 */

var background_millisecondsInMinute = 60000;
/**
 * Milliseconds in 1 hour
 *
 * @name millisecondsInHour
 * @constant
 * @type {number}
 * @default
 */

var background_millisecondsInHour = 3600000;
/**
 * Milliseconds in 1 second
 *
 * @name millisecondsInSecond
 * @constant
 * @type {number}
 * @default
 */

var background_millisecondsInSecond = 1000;
/**
 * Minimum allowed time.
 *
 * @name minTime
 * @constant
 * @type {number}
 * @default
 */

var background_minTime = -background_maxTime;
/**
 * Minutes in 1 hour
 *
 * @name minutesInHour
 * @constant
 * @type {number}
 * @default
 */

var background_minutesInHour = 60;
/**
 * Months in 1 quarter
 *
 * @name monthsInQuarter
 * @constant
 * @type {number}
 * @default
 */

var background_monthsInQuarter = 3;
/**
 * Months in 1 year
 *
 * @name monthsInYear
 * @constant
 * @type {number}
 * @default
 */

var background_monthsInYear = 12;
/**
 * Quarters in 1 year
 *
 * @name quartersInYear
 * @constant
 * @type {number}
 * @default
 */

var background_quartersInYear = 4;
/**
 * Seconds in 1 hour
 *
 * @name secondsInHour
 * @constant
 * @type {number}
 * @default
 */

var background_secondsInHour = 3600;
/**
 * Seconds in 1 minute
 *
 * @name secondsInMinute
 * @constant
 * @type {number}
 * @default
 */

var background_secondsInMinute = 60;
/**
 * Seconds in 1 day
 *
 * @name secondsInDay
 * @constant
 * @type {number}
 * @default
 */

var background_secondsInDay = background_secondsInHour * 24;
/**
 * Seconds in 1 week
 *
 * @name secondsInWeek
 * @constant
 * @type {number}
 * @default
 */

var background_secondsInWeek = background_secondsInDay * 7;
/**
 * Seconds in 1 year
 *
 * @name secondsInYear
 * @constant
 * @type {number}
 * @default
 */

var background_secondsInYear = background_secondsInDay * background_daysInYear;
/**
 * Seconds in 1 month
 *
 * @name secondsInMonth
 * @constant
 * @type {number}
 * @default
 */

var background_secondsInMonth = background_secondsInYear / 12;
/**
 * Seconds in 1 quarter
 *
 * @name secondsInQuarter
 * @constant
 * @type {number}
 * @default
 */

var background_secondsInQuarter = background_secondsInMonth * 3;
;// ./node_modules/.pnpm/date-fns@2.29.3/node_modules/date-fns/esm/differenceInMilliseconds/index.js


/**
 * @name differenceInMilliseconds
 * @category Millisecond Helpers
 * @summary Get the number of milliseconds between the given dates.
 *
 * @description
 * Get the number of milliseconds between the given dates.
 *
 * @param {Date|Number} dateLeft - the later date
 * @param {Date|Number} dateRight - the earlier date
 * @returns {Number} the number of milliseconds
 * @throws {TypeError} 2 arguments required
 *
 * @example
 * // How many milliseconds are between
 * // 2 July 2014 12:30:20.600 and 2 July 2014 12:30:21.700?
 * const result = differenceInMilliseconds(
 *   new Date(2014, 6, 2, 12, 30, 21, 700),
 *   new Date(2014, 6, 2, 12, 30, 20, 600)
 * )
 * //=> 1100
 */

function background_differenceInMilliseconds(dateLeft, dateRight) {
  background_requiredArgs(2, arguments);
  return background_toDate(dateLeft).getTime() - background_toDate(dateRight).getTime();
}
;// ./node_modules/.pnpm/date-fns@2.29.3/node_modules/date-fns/esm/_lib/roundingMethods/index.js
var background_roundingMap = {
  ceil: Math.ceil,
  round: Math.round,
  floor: Math.floor,
  trunc: function trunc(value) {
    return value < 0 ? Math.ceil(value) : Math.floor(value);
  } // Math.trunc is not supported by IE

};
var background_defaultRoundingMethod = 'trunc';
function background_getRoundingMethod(method) {
  return method ? background_roundingMap[method] : background_roundingMap[background_defaultRoundingMethod];
}
;// ./node_modules/.pnpm/date-fns@2.29.3/node_modules/date-fns/esm/differenceInHours/index.js




/**
 * @name differenceInHours
 * @category Hour Helpers
 * @summary Get the number of hours between the given dates.
 *
 * @description
 * Get the number of hours between the given dates.
 *
 * @param {Date|Number} dateLeft - the later date
 * @param {Date|Number} dateRight - the earlier date
 * @param {Object} [options] - an object with options.
 * @param {String} [options.roundingMethod='trunc'] - a rounding method (`ceil`, `floor`, `round` or `trunc`)
 * @returns {Number} the number of hours
 * @throws {TypeError} 2 arguments required
 *
 * @example
 * // How many hours are between 2 July 2014 06:50:00 and 2 July 2014 19:00:00?
 * const result = differenceInHours(
 *   new Date(2014, 6, 2, 19, 0),
 *   new Date(2014, 6, 2, 6, 50)
 * )
 * //=> 12
 */

function background_differenceInHours(dateLeft, dateRight, options) {
  background_requiredArgs(2, arguments);
  var diff = background_differenceInMilliseconds(dateLeft, dateRight) / background_millisecondsInHour;
  return background_getRoundingMethod(options === null || options === void 0 ? void 0 : options.roundingMethod)(diff);
}
;// ./node_modules/.pnpm/date-fns@2.29.3/node_modules/date-fns/esm/startOfDay/index.js


/**
 * @name startOfDay
 * @category Day Helpers
 * @summary Return the start of a day for the given date.
 *
 * @description
 * Return the start of a day for the given date.
 * The result will be in the local timezone.
 *
 * @param {Date|Number} date - the original date
 * @returns {Date} the start of a day
 * @throws {TypeError} 1 argument required
 *
 * @example
 * // The start of a day for 2 September 2014 11:55:00:
 * const result = startOfDay(new Date(2014, 8, 2, 11, 55, 0))
 * //=> Tue Sep 02 2014 00:00:00
 */

function background_startOfDay(dirtyDate) {
  background_requiredArgs(1, arguments);
  var date = background_toDate(dirtyDate);
  date.setHours(0, 0, 0, 0);
  return date;
}
;// ./node_modules/.pnpm/date-fns@2.29.3/node_modules/date-fns/esm/isSameDay/index.js


/**
 * @name isSameDay
 * @category Day Helpers
 * @summary Are the given dates in the same day (and year and month)?
 *
 * @description
 * Are the given dates in the same day (and year and month)?
 *
 * @param {Date|Number} dateLeft - the first date to check
 * @param {Date|Number} dateRight - the second date to check
 * @returns {Boolean} the dates are in the same day (and year and month)
 * @throws {TypeError} 2 arguments required
 *
 * @example
 * // Are 4 September 06:00:00 and 4 September 18:00:00 in the same day?
 * const result = isSameDay(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 18, 0))
 * //=> true
 *
 * @example
 * // Are 4 September and 4 October in the same day?
 * const result = isSameDay(new Date(2014, 8, 4), new Date(2014, 9, 4))
 * //=> false
 *
 * @example
 * // Are 4 September, 2014 and 4 September, 2015 in the same day?
 * const result = isSameDay(new Date(2014, 8, 4), new Date(2015, 8, 4))
 * //=> false
 */

function background_isSameDay(dirtyDateLeft, dirtyDateRight) {
  background_requiredArgs(2, arguments);
  var dateLeftStartOfDay = background_startOfDay(dirtyDateLeft);
  var dateRightStartOfDay = background_startOfDay(dirtyDateRight);
  return dateLeftStartOfDay.getTime() === dateRightStartOfDay.getTime();
}
;// ./node_modules/.pnpm/date-fns@2.29.3/node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js
/**
 * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds.
 * They usually appear for dates that denote time before the timezones were introduced
 * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891
 * and GMT+01:00:00 after that date)
 *
 * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above,
 * which would lead to incorrect calculations.
 *
 * This function returns the timezone offset in milliseconds that takes seconds in account.
 */
function background_getTimezoneOffsetInMilliseconds(date) {
  var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
  utcDate.setUTCFullYear(date.getFullYear());
  return date.getTime() - utcDate.getTime();
}
;// ./node_modules/.pnpm/date-fns@2.29.3/node_modules/date-fns/esm/differenceInCalendarDays/index.js



var background_MILLISECONDS_IN_DAY = 86400000;
/**
 * @name differenceInCalendarDays
 * @category Day Helpers
 * @summary Get the number of calendar days between the given dates.
 *
 * @description
 * Get the number of calendar days between the given dates. This means that the times are removed
 * from the dates and then the difference in days is calculated.
 *
 * @param {Date|Number} dateLeft - the later date
 * @param {Date|Number} dateRight - the earlier date
 * @returns {Number} the number of calendar days
 * @throws {TypeError} 2 arguments required
 *
 * @example
 * // How many calendar days are between
 * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?
 * const result = differenceInCalendarDays(
 *   new Date(2012, 6, 2, 0, 0),
 *   new Date(2011, 6, 2, 23, 0)
 * )
 * //=> 366
 * // How many calendar days are between
 * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?
 * const result = differenceInCalendarDays(
 *   new Date(2011, 6, 3, 0, 1),
 *   new Date(2011, 6, 2, 23, 59)
 * )
 * //=> 1
 */

function background_differenceInCalendarDays(dirtyDateLeft, dirtyDateRight) {
  background_requiredArgs(2, arguments);
  var startOfDayLeft = background_startOfDay(dirtyDateLeft);
  var startOfDayRight = background_startOfDay(dirtyDateRight);
  var timestampLeft = startOfDayLeft.getTime() - background_getTimezoneOffsetInMilliseconds(startOfDayLeft);
  var timestampRight = startOfDayRight.getTime() - background_getTimezoneOffsetInMilliseconds(startOfDayRight); // Round the number of days to the nearest integer
  // because the number of milliseconds in a day is not constant
  // (e.g. it's different in the day of the daylight saving time clock shift)

  return Math.round((timestampLeft - timestampRight) / background_MILLISECONDS_IN_DAY);
}
;// ./node_modules/.pnpm/date-fns@2.29.3/node_modules/date-fns/esm/differenceInDays/index.js


 // Like `compareAsc` but uses local time not UTC, which is needed
// for accurate equality comparisons of UTC timestamps that end up
// having the same representation in local time, e.g. one hour before
// DST ends vs. the instant that DST ends.

function background_compareLocalAsc(dateLeft, dateRight) {
  var diff = dateLeft.getFullYear() - dateRight.getFullYear() || dateLeft.getMonth() - dateRight.getMonth() || dateLeft.getDate() - dateRight.getDate() || dateLeft.getHours() - dateRight.getHours() || dateLeft.getMinutes() - dateRight.getMinutes() || dateLeft.getSeconds() - dateRight.getSeconds() || dateLeft.getMilliseconds() - dateRight.getMilliseconds();

  if (diff < 0) {
    return -1;
  } else if (diff > 0) {
    return 1; // Return 0 if diff is 0; return NaN if diff is NaN
  } else {
    return diff;
  }
}
/**
 * @name differenceInDays
 * @category Day Helpers
 * @summary Get the number of full days between the given dates.
 *
 * @description
 * Get the number of full day periods between two dates. Fractional days are
 * truncated towards zero.
 *
 * One "full day" is the distance between a local time in one day to the same
 * local time on the next or previous day. A full day can sometimes be less than
 * or more than 24 hours if a daylight savings change happens between two dates.
 *
 * To ignore DST and only measure exact 24-hour periods, use this instead:
 * `Math.floor(differenceInHours(dateLeft, dateRight)/24)|0`.
 *
 *
 * @param {Date|Number} dateLeft - the later date
 * @param {Date|Number} dateRight - the earlier date
 * @returns {Number} the number of full days according to the local timezone
 * @throws {TypeError} 2 arguments required
 *
 * @example
 * // How many full days are between
 * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?
 * const result = differenceInDays(
 *   new Date(2012, 6, 2, 0, 0),
 *   new Date(2011, 6, 2, 23, 0)
 * )
 * //=> 365
 * // How many full days are between
 * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?
 * const result = differenceInDays(
 *   new Date(2011, 6, 3, 0, 1),
 *   new Date(2011, 6, 2, 23, 59)
 * )
 * //=> 0
 * // How many full days are between
 * // 1 March 2020 0:00 and 1 June 2020 0:00 ?
 * // Note: because local time is used, the
 * // result will always be 92 days, even in
 * // time zones where DST starts and the
 * // period has only 92*24-1 hours.
 * const result = differenceInDays(
 *   new Date(2020, 5, 1),
 *   new Date(2020, 2, 1)
 * )
//=> 92
 */


function background_differenceInDays(dirtyDateLeft, dirtyDateRight) {
  background_requiredArgs(2, arguments);
  var dateLeft = background_toDate(dirtyDateLeft);
  var dateRight = background_toDate(dirtyDateRight);
  var sign = background_compareLocalAsc(dateLeft, dateRight);
  var difference = Math.abs(background_differenceInCalendarDays(dateLeft, dateRight));
  dateLeft.setDate(dateLeft.getDate() - sign * difference); // Math.abs(diff in full days - diff in calendar days) === 1 if last calendar day is not full
  // If so, result must be decreased by 1 in absolute value

  var isLastDayNotFull = Number(background_compareLocalAsc(dateLeft, dateRight) === -sign);
  var result = sign * (difference - isLastDayNotFull); // Prevent negative zero

  return result === 0 ? 0 : result;
}
;// ./node_modules/.pnpm/date-fns@2.29.3/node_modules/date-fns/esm/isSameMonth/index.js


/**
 * @name isSameMonth
 * @category Month Helpers
 * @summary Are the given dates in the same month (and year)?
 *
 * @description
 * Are the given dates in the same month (and year)?
 *
 * @param {Date|Number} dateLeft - the first date to check
 * @param {Date|Number} dateRight - the second date to check
 * @returns {Boolean} the dates are in the same month (and year)
 * @throws {TypeError} 2 arguments required
 *
 * @example
 * // Are 2 September 2014 and 25 September 2014 in the same month?
 * const result = isSameMonth(new Date(2014, 8, 2), new Date(2014, 8, 25))
 * //=> true
 *
 * @example
 * // Are 2 September 2014 and 25 September 2015 in the same month?
 * const result = isSameMonth(new Date(2014, 8, 2), new Date(2015, 8, 25))
 * //=> false
 */

function background_isSameMonth(dirtyDateLeft, dirtyDateRight) {
  background_requiredArgs(2, arguments);
  var dateLeft = background_toDate(dirtyDateLeft);
  var dateRight = background_toDate(dirtyDateRight);
  return dateLeft.getFullYear() === dateRight.getFullYear() && dateLeft.getMonth() === dateRight.getMonth();
}
;// ./node_modules/.pnpm/date-fns@2.29.3/node_modules/date-fns/esm/differenceInCalendarMonths/index.js


/**
 * @name differenceInCalendarMonths
 * @category Month Helpers
 * @summary Get the number of calendar months between the given dates.
 *
 * @description
 * Get the number of calendar months between the given dates.
 *
 * @param {Date|Number} dateLeft - the later date
 * @param {Date|Number} dateRight - the earlier date
 * @returns {Number} the number of calendar months
 * @throws {TypeError} 2 arguments required
 *
 * @example
 * // How many calendar months are between 31 January 2014 and 1 September 2014?
 * const result = differenceInCalendarMonths(
 *   new Date(2014, 8, 1),
 *   new Date(2014, 0, 31)
 * )
 * //=> 8
 */

function background_differenceInCalendarMonths(dirtyDateLeft, dirtyDateRight) {
  background_requiredArgs(2, arguments);
  var dateLeft = background_toDate(dirtyDateLeft);
  var dateRight = background_toDate(dirtyDateRight);
  var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear();
  var monthDiff = dateLeft.getMonth() - dateRight.getMonth();
  return yearDiff * 12 + monthDiff;
}
;// ./node_modules/.pnpm/date-fns@2.29.3/node_modules/date-fns/esm/compareAsc/index.js


/**
 * @name compareAsc
 * @category Common Helpers
 * @summary Compare the two dates and return -1, 0 or 1.
 *
 * @description
 * Compare the two dates and return 1 if the first date is after the second,
 * -1 if the first date is before the second or 0 if dates are equal.
 *
 * @param {Date|Number} dateLeft - the first date to compare
 * @param {Date|Number} dateRight - the second date to compare
 * @returns {Number} the result of the comparison
 * @throws {TypeError} 2 arguments required
 *
 * @example
 * // Compare 11 February 1987 and 10 July 1989:
 * const result = compareAsc(new Date(1987, 1, 11), new Date(1989, 6, 10))
 * //=> -1
 *
 * @example
 * // Sort the array of dates:
 * const result = [
 *   new Date(1995, 6, 2),
 *   new Date(1987, 1, 11),
 *   new Date(1989, 6, 10)
 * ].sort(compareAsc)
 * //=> [
 * //   Wed Feb 11 1987 00:00:00,
 * //   Mon Jul 10 1989 00:00:00,
 * //   Sun Jul 02 1995 00:00:00
 * // ]
 */

function background_compareAsc(dirtyDateLeft, dirtyDateRight) {
  background_requiredArgs(2, arguments);
  var dateLeft = background_toDate(dirtyDateLeft);
  var dateRight = background_toDate(dirtyDateRight);
  var diff = dateLeft.getTime() - dateRight.getTime();

  if (diff < 0) {
    return -1;
  } else if (diff > 0) {
    return 1; // Return 0 if diff is 0; return NaN if diff is NaN
  } else {
    return diff;
  }
}
;// ./node_modules/.pnpm/date-fns@2.29.3/node_modules/date-fns/esm/endOfDay/index.js


/**
 * @name endOfDay
 * @category Day Helpers
 * @summary Return the end of a day for the given date.
 *
 * @description
 * Return the end of a day for the given date.
 * The result will be in the local timezone.
 *
 * @param {Date|Number} date - the original date
 * @returns {Date} the end of a day
 * @throws {TypeError} 1 argument required
 *
 * @example
 * // The end of a day for 2 September 2014 11:55:00:
 * const result = endOfDay(new Date(2014, 8, 2, 11, 55, 0))
 * //=> Tue Sep 02 2014 23:59:59.999
 */

function background_endOfDay(dirtyDate) {
  background_requiredArgs(1, arguments);
  var date = background_toDate(dirtyDate);
  date.setHours(23, 59, 59, 999);
  return date;
}
;// ./node_modules/.pnpm/date-fns@2.29.3/node_modules/date-fns/esm/endOfMonth/index.js


/**
 * @name endOfMonth
 * @category Month Helpers
 * @summary Return the end of a month for the given date.
 *
 * @description
 * Return the end of a month for the given date.
 * The result will be in the local timezone.
 *
 * @param {Date|Number} date - the original date
 * @returns {Date} the end of a month
 * @throws {TypeError} 1 argument required
 *
 * @example
 * // The end of a month for 2 September 2014 11:55:00:
 * const result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0))
 * //=> Tue Sep 30 2014 23:59:59.999
 */

function background_endOfMonth(dirtyDate) {
  background_requiredArgs(1, arguments);
  var date = background_toDate(dirtyDate);
  var month = date.getMonth();
  date.setFullYear(date.getFullYear(), month + 1, 0);
  date.setHours(23, 59, 59, 999);
  return date;
}
;// ./node_modules/.pnpm/date-fns@2.29.3/node_modules/date-fns/esm/isLastDayOfMonth/index.js




/**
 * @name isLastDayOfMonth
 * @category Month Helpers
 * @summary Is the given date the last day of a month?
 *
 * @description
 * Is the given date the last day of a month?
 *
 * @param {Date|Number} date - the date to check
 * @returns {Boolean} the date is the last day of a month
 * @throws {TypeError} 1 argument required
 *
 * @example
 * // Is 28 February 2014 the last day of a month?
 * const result = isLastDayOfMonth(new Date(2014, 1, 28))
 * //=> true
 */

function background_isLastDayOfMonth(dirtyDate) {
  background_requiredArgs(1, arguments);
  var date = background_toDate(dirtyDate);
  return background_endOfDay(date).getTime() === background_endOfMonth(date).getTime();
}
;// ./node_modules/.pnpm/date-fns@2.29.3/node_modules/date-fns/esm/differenceInMonths/index.js





/**
 * @name differenceInMonths
 * @category Month Helpers
 * @summary Get the number of full months between the given dates.
 *
 * @description
 * Get the number of full months between the given dates using trunc as a default rounding method.
 *
 * @param {Date|Number} dateLeft - the later date
 * @param {Date|Number} dateRight - the earlier date
 * @returns {Number} the number of full months
 * @throws {TypeError} 2 arguments required
 *
 * @example
 * // How many full months are between 31 January 2014 and 1 September 2014?
 * const result = differenceInMonths(new Date(2014, 8, 1), new Date(2014, 0, 31))
 * //=> 7
 */

function background_differenceInMonths(dirtyDateLeft, dirtyDateRight) {
  background_requiredArgs(2, arguments);
  var dateLeft = background_toDate(dirtyDateLeft);
  var dateRight = background_toDate(dirtyDateRight);
  var sign = background_compareAsc(dateLeft, dateRight);
  var difference = Math.abs(background_differenceInCalendarMonths(dateLeft, dateRight));
  var result; // Check for the difference of less than month

  if (difference < 1) {
    result = 0;
  } else {
    if (dateLeft.getMonth() === 1 && dateLeft.getDate() > 27) {
      // This will check if the date is end of Feb and assign a higher end of month date
      // to compare it with Jan
      dateLeft.setDate(30);
    }

    dateLeft.setMonth(dateLeft.getMonth() - sign * difference); // Math.abs(diff in full months - diff in calendar months) === 1 if last calendar month is not full
    // If so, result must be decreased by 1 in absolute value

    var isLastMonthNotFull = background_compareAsc(dateLeft, dateRight) === -sign; // Check for cases of one full calendar month

    if (background_isLastDayOfMonth(background_toDate(dirtyDateLeft)) && difference === 1 && background_compareAsc(dirtyDateLeft, dateRight) === 1) {
      isLastMonthNotFull = false;
    }

    result = sign * (difference - Number(isLastMonthNotFull));
  } // Prevent negative zero


  return result === 0 ? 0 : result;
}
;// ./Extension/src/background/storages/page-stats.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_page_stats_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}






/**
 * Class for asynchronous control {@link PageStats} storage data,
 * that is persisted as string in another key value storage.
 *
 * @see {@link StringStorage}
 */ class background_PageStatsStorage extends background_StringStorage {
    /**
     * Returns number of total blocked requests.
     *
     * @returns Number of total blocked requests or undefined, if it is not set.
     */ getTotalBlocked() {
        return this.getData().totalBlocked;
    }
    /**
     * Sets number of total blocked requests.
     *
     * @param value Number of total blocked requests.
     *
     * @returns Promise, resolved when total blocked requests number is successfully set.
     *
     * @throws Error if page stats data is not initialized.
     */ setTotalBlocked(value) {
        if (!this.data) {
            throw background_PageStatsStorage.createNotInitializedError();
        }
        this.data.totalBlocked = value;
        return this.save();
    }
    /**
     * Sets page statistics data.
     * If page statistics data is empty, creates new.
     *
     * @param data Page stats data.
     *
     * @returns Promise, resolved when data is successfully set.
     *
     * @throws Error if page stats data is not initialized.
     */ setStatisticsData(data) {
        if (!this.data) {
            throw background_PageStatsStorage.createNotInitializedError();
        }
        this.data.data = data;
        return this.save();
    }
    /**
     * Returns page statistics data.
     * If page statistics data is not defined, creates new.
     *
     * @returns Page statistics data.
     *
     * @throws Error if page stats data is not initialized.
     */ getStatisticsData() {
        if (!this.data) {
            throw background_PageStatsStorage.createNotInitializedError();
        }
        if (!this.data.data) {
            this.data.data = background_PageStatsStorage.createStatsData(null, 0);
        }
        return this.data.data;
    }
    /**
     * Creates page statistics data for specified stats category.
     *
     * @param categoryId Stats category.
     * @param blocked Number of request blocks.
     *
     * @returns Page statistics data.
     */ static createStatsData(categoryId, blocked) {
        const data = {
            hours: [],
            days: [],
            months: [],
            updated: Date.now()
        };
        for(let i = 1; i < background_PageStatsStorage.MAX_HOURS_HISTORY; i += 1){
            data.hours.push(background_PageStatsStorage.createStatsDataItem(null, 0));
        }
        data.hours.push(background_PageStatsStorage.createStatsDataItem(categoryId, blocked));
        for(let j = 1; j < background_PageStatsStorage.MAX_DAYS_HISTORY; j += 1){
            data.days.push(background_PageStatsStorage.createStatsDataItem(null, 0));
        }
        data.days.push(background_PageStatsStorage.createStatsDataItem(categoryId, blocked));
        for(let k = 1; k < background_PageStatsStorage.MAX_MONTHS_HISTORY; k += 1){
            data.months.push(background_PageStatsStorage.createStatsDataItem(null, 0));
        }
        data.months.push(background_PageStatsStorage.createStatsDataItem(categoryId, blocked));
        return data;
    }
    /**
     * Updates page statistics data for specified stats category.
     *
     * @param categoryId Stats category id.
     * @param blocked Number of request blocks.
     * @param data Current page statistics data.
     *
     * @returns Updated page statistics data.
     */ static updateStatsData(categoryId, blocked, data) {
        const lastUpdated = data.updated;
        const timestamp = Date.now();
        const lastHourStats = data.hours[data.hours.length - 1];
        if (background_isSameHour(timestamp, lastUpdated) && lastHourStats) {
            data.hours[data.hours.length - 1] = background_PageStatsStorage.updateStatsDataItem(categoryId, blocked, lastHourStats);
        } else {
            let diffHours = background_differenceInHours(timestamp, lastUpdated);
            while(diffHours >= 2){
                data.hours.push(background_PageStatsStorage.createStatsDataItem(null, 0));
                diffHours -= 1;
            }
            data.hours.push(background_PageStatsStorage.createStatsDataItem(categoryId, blocked));
            if (data.hours.length > background_PageStatsStorage.MAX_HOURS_HISTORY) {
                data.hours = data.hours.slice(-background_PageStatsStorage.MAX_HOURS_HISTORY);
            }
        }
        const lastDayStats = data.days[data.days.length - 1];
        if (background_isSameDay(timestamp, lastUpdated) && lastDayStats) {
            data.days[data.days.length - 1] = background_PageStatsStorage.updateStatsDataItem(categoryId, blocked, lastDayStats);
        } else {
            let diffDays = background_differenceInDays(timestamp, lastUpdated);
            while(diffDays >= 2){
                data.days.push(background_PageStatsStorage.createStatsDataItem(null, 0));
                diffDays -= 1;
            }
            data.days.push(background_PageStatsStorage.createStatsDataItem(categoryId, blocked));
            if (data.days.length > background_PageStatsStorage.MAX_DAYS_HISTORY) {
                data.days = data.days.slice(-background_PageStatsStorage.MAX_DAYS_HISTORY);
            }
        }
        const lastMonthStats = data.months[data.months.length - 1];
        if (background_isSameMonth(timestamp, lastUpdated) && lastMonthStats) {
            data.months[data.months.length - 1] = background_PageStatsStorage.updateStatsDataItem(categoryId, blocked, lastMonthStats);
        } else {
            let diffMonths = background_differenceInMonths(timestamp, lastUpdated);
            while(diffMonths >= 2){
                data.months.push(background_PageStatsStorage.createStatsDataItem(null, 0));
                diffMonths -= 1;
            }
            data.months.push(background_PageStatsStorage.createStatsDataItem(categoryId, blocked));
        }
        data.updated = timestamp;
        return data;
    }
    /**
     * Creates page statistics data item for specified stats category.
     *
     * @param categoryId Stats category.
     * @param blocked Number of request blocks.
     *
     * @returns Updated page statistics data item.
     */ static createStatsDataItem(categoryId, blocked) {
        const data = {};
        if (categoryId !== null) {
            data[String(categoryId)] = blocked;
        }
        data[background_PageStatsStorage.TOTAL_GROUP_ID] = blocked;
        return data;
    }
    /**
     * Updates page statistics data item for specified stats category.
     *
     * @param categoryId Stats category.
     * @param blocked Number of request blocks.
     * @param data Current page statistics data item.
     *
     * @returns Updated page statistics data item.
     */ static updateStatsDataItem(categoryId, blocked, data) {
        data[String(categoryId)] = (data[String(categoryId)] || 0) + blocked;
        data[background_PageStatsStorage.TOTAL_GROUP_ID] = (data[background_PageStatsStorage.TOTAL_GROUP_ID] || 0) + blocked;
        return data;
    }
    /**
     * Helper function to create a basic {@link Error} with a custom message.
     *
     * @returns A basic {@link Error} with a custom message.
     */ static createNotInitializedError() {
        return new Error('Page stats is not initialized');
    }
}
background_page_stats_define_property(background_PageStatsStorage, "TOTAL_GROUP_ID", background_TOTAL_BLOCKED_STATS_GROUP_ID);
background_page_stats_define_property(background_PageStatsStorage, "MAX_HOURS_HISTORY", 24);
background_page_stats_define_property(background_PageStatsStorage, "MAX_DAYS_HISTORY", 30);
background_page_stats_define_property(background_PageStatsStorage, "MAX_MONTHS_HISTORY", 3);
/**
 * {@link PageStatsStorage} Instance, that stores
 * stringified {@link PageStats} in {@link browserStorage} under
 * {@link PAGE_STATISTIC_KEY} key.
 */ const background_pageStatsStorage = new background_PageStatsStorage(background_PAGE_STATISTIC_KEY, background_browserStorage);

;// ./Extension/src/common/forward.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ /**
 * IMPORTANT: do not change the values as tds is already configured for that specific strings.
 */ function background_forward_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
var background_ForwardAction = /*#__PURE__*/ function(ForwardAction) {
    ForwardAction["UninstallExtension"] = "adguard_uninstal_ext";
    // used for thank you page
    ForwardAction["ThankYou"] = "thank_you_page";
    // used for thank you page for MV3
    ForwardAction["ThankYouMv3"] = "thank_you_page_mv3";
    // used for "More information" on the page blocked by Safebrowsing
    ForwardAction["SiteReport"] = "site_report_page";
    // used for "Report an issue" in popup or context menu on the page
    ForwardAction["IssueReport"] = "report";
    // used for "Report a bug" on options page in General section
    ForwardAction["BugReport"] = "bug_report";
    ForwardAction["BugReportMv3"] = "bug_report_mv3";
    ForwardAction["Privacy"] = "privacy";
    ForwardAction["Acknowledgments"] = "acknowledgments";
    ForwardAction["Github"] = "github_options";
    ForwardAction["Website"] = "adguard_site";
    ForwardAction["Discuss"] = "discuss";
    ForwardAction["Compare"] = "compare";
    ForwardAction["Changelog"] = "github_version_popup";
    ForwardAction["GlobalPrivacyControl"] = "global_privacy_control";
    ForwardAction["DoNotTrack"] = "do_not_track";
    ForwardAction["HowToCreateRules"] = "userfilter_description";
    ForwardAction["FilterPolicy"] = "filter_policy";
    ForwardAction["AdguardSite"] = "adguard_site";
    ForwardAction["SelfPromotion"] = "self_promotion";
    ForwardAction["ProtectionWorks"] = "protection_works";
    ForwardAction["CollectHitsLearnMore"] = "filter_rules";
    ForwardAction["OperaStore"] = "opera_store";
    ForwardAction["FirefoxStore"] = "firefox_store";
    /**
     * Main supported release version — "AdGuard AdBlocker".
     */ ForwardAction["ChromeStore"] = "chrome_store";
    // TODO: can be removed in few months after v5.0 MV3 release
    // since it will no longer be used
    /**
     * Supported MV3 beta version.
     *
     * Previously known as "AdGuard AdBlocker MV3 Experimental",
     * currently — "AdGuard AdBlocker (MV3 Beta)".
     */ ForwardAction["ChromeMv3Store"] = "chrome_mv3_store";
    /**
     * Supported MV2 release version.
     *
     * Previously known as "AdGuard AdBlocker (Beta)".
     */ ForwardAction["ChromeMv2Store"] = "chrome_mv2_store";
    ForwardAction["EdgeStore"] = "edge_store";
    ForwardAction["IOS"] = "ios_about";
    ForwardAction["Android"] = "android_about";
    ForwardAction["GetTheApp"] = "get_the_app";
    ForwardAction["GithubVersion"] = "github_version_popup";
    ForwardAction["GithubVersionBeta"] = "github_version_popup_beta";
    ForwardAction["LearnAboutAdGuard"] = "learn_about_adguard";
    ForwardAction["FilteringLogAssumedRule"] = "filtering_log_assumed_rule";
    ForwardAction["Birthday25"] = "birthday_25";
    ForwardAction["CustomFiltersMv3Disabled"] = "custom_mv3_disabled";
    return ForwardAction;
}({});
var background_ForwardFrom = /*#__PURE__*/ function(ForwardFrom) {
    ForwardFrom["Background"] = "background";
    ForwardFrom["Options"] = "options_screen";
    ForwardFrom["OptionsFooter"] = "options_screen_footer";
    ForwardFrom["ContextMenu"] = "context_menu";
    ForwardFrom["Popup"] = "popup";
    ForwardFrom["Safebrowsing"] = "safebrowsing";
    ForwardFrom["Adblocker"] = "adblocked";
    ForwardFrom["VersionPopup"] = "version_popup";
    ForwardFrom["FilteringLog"] = "filtering_log";
    return ForwardFrom;
}({});
var background_ForwardApp = /*#__PURE__*/ function(ForwardApp) {
    ForwardApp["BrowserExtension"] = "browser_extension";
    return ForwardApp;
}({});
/**
 * Class for creating forward links
 */ class background_Forward {
    static get(params) {
        const queryString = Object.entries({
            ...background_Forward.defaultParams,
            ...params
        }).map(([key, value])=>`${key}=${value}`).join('&');
        return `${background_Forward.url}?${queryString}`;
    }
}
background_forward_define_property(background_Forward, "url", 'https://link.adtidy.org/forward.html');
background_forward_define_property(background_Forward, "defaultParams", {
    app: "browser_extension"
});

// EXTERNAL MODULE: ./node_modules/.pnpm/ua-parser-js@1.0.36/node_modules/ua-parser-js/src/ua-parser.js
var background_ua_parser = __webpack_require__(92976);
var background_ua_parser_default = /*#__PURE__*/__webpack_require__.n(background_ua_parser);
;// ./constants.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ // TODO: generate tools/bundle/manifest.common.json with this constants
const background_WEB_ACCESSIBLE_RESOURCES_OUTPUT = 'web-accessible-resources';
const background_WEB_ACCESSIBLE_RESOURCES_OUTPUT_REDIRECTS = `${background_WEB_ACCESSIBLE_RESOURCES_OUTPUT}/redirects`;
const background_BACKGROUND_OUTPUT = 'pages/background';
const background_OPTIONS_OUTPUT = 'pages/options';
const background_POPUP_OUTPUT = 'pages/popup';
const background_FILTERING_LOG_OUTPUT = 'pages/filtering-log';
const background_POST_INSTALL_OUTPUT = 'pages/post-install';
const background_FULLSCREEN_USER_RULES_OUTPUT = 'pages/fullscreen-user-rules';
const background_SAFEBROWSING_OUTPUT = 'pages/safebrowsing';
const background_DOCUMENT_BLOCK_OUTPUT = 'pages/ad-blocked';
const background_SUBSCRIBE_OUTPUT = 'pages/subscribe';
const background_CONTENT_SCRIPT_START_OUTPUT = 'pages/content-script-start';
const background_CONTENT_SCRIPT_END_OUTPUT = 'pages/content-script-end';
const background_THANKYOU_OUTPUT = 'pages/thankyou';
const background_ASSISTANT_INJECT_OUTPUT = 'pages/assistant-inject';
const background_GPC_SCRIPT_OUTPUT = 'pages/gpc';
const background_HIDE_DOCUMENT_REFERRER_OUTPUT = 'pages/hide-document-referrer';
const background_DEVTOOLS_OUTPUT = 'pages/devtools';
const background_DEVTOOLS_ELEMENT_SIDEBAR_OUTPUT = 'pages/devtools-elements-sidebar';
const background_SHARED_EDITOR_OUTPUT = 'shared/editor';
const background_REACT_VENDOR_OUTPUT = 'vendors/react';
const background_MOBX_VENDOR_OUTPUT = 'vendors/mobx';
const background_XSTATE_VENDOR_OUTPUT = 'vendors/xstate';
const background_TSURLFILTER_VENDOR_OUTPUT = 'vendors/tsurlfilter';
const background_AGTREE_VENDOR_OUTPUT = 'vendors/agtree';
const background_CSS_TOKENIZER_VENDOR_OUTPUT = 'vendors/css-tokenizer';
const background_TSWEBEXTENSION_VENDOR_OUTPUT = 'vendors/tswebextension';
const background_TEXT_ENCODING_POLYFILL_VENDOR_OUTPUT = 'vendors/text-encoding-polyfill';
const background_SCRIPTLETS_VENDOR_OUTPUT = 'vendors/scriptlets';
// Placed here to use in the node environment and in the browser
// Important: extensions '.js' used for correct work of Cloudflare cache, but
// real format of these files is JSON.
// See AG-1901 for details.
const background_REMOTE_METADATA_FILE_NAME = 'filters.js';
const background_REMOTE_I18N_METADATA_FILE_NAME = 'filters_i18n.js';
// But locally we prefer to use '.json' extension.
const background_LOCAL_METADATA_FILE_NAME = 'filters.json';
const background_LOCAL_I18N_METADATA_FILE_NAME = 'filters_i18n.json';
/**
 * List of AdGuard filters IDs.
 *
 * `12` is absent because Safari filter if obsolete and not used anymore.
 */ const background_ADGUARD_FILTERS_IDS = [
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10,
    11,
    13,
    14,
    15,
    16,
    17,
    18,
    19,
    20,
    21,
    22,
    23,
    224
];
/**
 * Minimum supported browser versions.
 *
 * IMPORTANT! Update browser compatibility in the README.md file when changing the versions.
 */ const background_MIN_SUPPORTED_VERSION = {
    CHROMIUM_MV2: 79,
    CHROMIUM_MV3: 121,
    FIREFOX: 78,
    FIREFOX_MOBILE: 113,
    OPERA: 67,
    EDGE_CHROMIUM: 80
};

;// ./Extension/src/common/user-agent.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_user_agent_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}



/**
 * Helper class for user agent data.
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/API/User-Agent_Client_Hints_API#browser_compatibility
 */ class background_UserAgent {
    /**
     * Returns current browser name.
     *
     * @returns user agent browser name.
     */ static getBrowserName() {
        return background_UserAgent.isFirefoxMobile ? 'Firefox Mobile' : background_UserAgent.parser.getBrowser().name;
    }
    /**
     * Returns current OS name.
     *
     * @returns OS name as string if possible to detect, undefined otherwise.
     */ static getSystemName() {
        return background_UserAgent.parser.getOS().name;
    }
    /**
     * Returns current OS version.
     *
     * @returns OS version as string if possible to detect, undefined otherwise.
     */ static getSystemVersion() {
        return background_UserAgent.parser.getOS().version;
    }
    /**
     * Returns current platform version.
     * Uses NavigatorUAData.getHighEntropyValues() to get platform version.
     *
     * @returns Actual platform version as string if possible to detect, undefined otherwise.
     */ static async getPlatformVersion() {
        let platformVersion;
        try {
            // @ts-ignore
            const ua = await navigator.userAgentData.getHighEntropyValues([
                background_UserAgent.PLATFORM_VERSION
            ]);
            platformVersion = ua[background_UserAgent.PLATFORM_VERSION];
        } catch (e) {
        // do nothing
        }
        return platformVersion;
    }
    /**
     * Returns actual Windows version if it is parsed from user agent as Windows 10.
     *
     * @see {@link https://learn.microsoft.com/en-us/microsoft-edge/web-platform/how-to-detect-win11#sample-code-for-detecting-windows-11}.
     *
     * @returns Actual Windows version.
     */ static async getActualWindowsVersion(version) {
        let actualVersion = version;
        const platformVersion = await background_UserAgent.getPlatformVersion();
        if (typeof platformVersion !== 'undefined') {
            const rawMajorPlatformVersion = platformVersion.split('.')[0];
            const majorPlatformVersion = rawMajorPlatformVersion && parseInt(rawMajorPlatformVersion, 10);
            if (!majorPlatformVersion || Number.isNaN(majorPlatformVersion)) {
                return actualVersion;
            }
            if (majorPlatformVersion >= background_UserAgent.MIN_WINDOWS_11_PLATFORM_VERSION) {
                actualVersion = background_UserAgent.WINDOWS_11_OS_VERSION;
            }
        }
        return actualVersion;
    }
    /**
     * Returns actual MacOS version if it is possible to detect, otherwise returns passed `version`.
     *
     * @param version MacOS version parsed from user agent.
     *
     * @returns Actual MacOS version.
     */ static async getActualMacosVersion(version) {
        let actualVersion = version;
        const platformVersion = await background_UserAgent.getPlatformVersion();
        if (typeof platformVersion !== 'undefined') {
            actualVersion = platformVersion;
        }
        return actualVersion;
    }
    /**
     * Returns current system info — OS name and version.
     *
     * @returns System info as string if possible to detect, undefined otherwise.
     */ static async getSystemInfo() {
        let systemInfo = '';
        const osName = background_UserAgent.getSystemName();
        let osVersion = background_UserAgent.getSystemVersion();
        if (typeof osName !== 'undefined') {
            systemInfo += osName;
        }
        if (typeof osVersion !== 'undefined') {
            // windows 11 is parsed as windows 10 from user agent
            if (background_UserAgent.isWindows && osVersion === background_UserAgent.WINDOWS_10_OS_VERSION) {
                osVersion = await background_UserAgent.getActualWindowsVersion(osVersion);
            } else if (background_UserAgent.isMacOs) {
                // mac os version can be parsed from user agent as 10.15.7
                // so it also might be more specific version like 13.5.2
                osVersion = await background_UserAgent.getActualMacosVersion(osVersion);
            }
            systemInfo += ` ${osVersion}`;
        }
        if (systemInfo.length === 0) {
            return undefined;
        }
        return systemInfo;
    }
    /**
     * Check if the current platform is Android.
     * This method is more accurate than using UserAgent string,
     * because it uses the browser API to get the platform info.
     *
     * @returns True if the current platform is Android.
     */ static async getIsAndroid() {
        try {
            const { os } = await background_browser_polyfill_default().runtime.getPlatformInfo();
            return os === background_UserAgent.ANDROID_OS_NAME;
        } catch  {
            // If runtime.getPlatformInfo() is not supported, we fallback to the UserAgent string.
            return background_UserAgent.isAndroid;
        }
    }
    /**
     * Check if the current browser is as given.
     *
     * @param browserName Browser Name.
     *
     * @returns true, if current browser has specified name.
     */ static isTargetBrowser(browserName) {
        return background_UserAgent.parser.getBrowser().name === browserName;
    }
    /**
     * Check if current platform is as given.
     *
     * @param platformName Platform name.
     *
     * @returns true, if current browser has specified name.
     */ static isTargetPlatform(platformName) {
        return background_UserAgent.getSystemName() === platformName;
    }
    /**
     * Check if current engine is as given.
     *
     * @param engineName Engine name.
     *
     * @returns true, if current engine has specified name.
     */ static isTargetEngine(engineName) {
        return background_UserAgent.parser.getEngine().name === engineName;
    }
    static isTargetDeviceType(deviceType) {
        return background_UserAgent.parser.getDevice().type === deviceType;
    }
    /**
     * Returns a major browser version.
     *
     * @returns browser version number or undefined.
     */ static getVersion() {
        var _browser_version;
        const browser = this.parser.getBrowser();
        const versionNumber = Number((_browser_version = browser.version) === null || _browser_version === void 0 ? void 0 : _browser_version.split('.')[0]);
        return Number.isNaN(versionNumber) ? undefined : versionNumber;
    }
}
background_user_agent_define_property(background_UserAgent, "WINDOWS_10_OS_VERSION", '10');
background_user_agent_define_property(background_UserAgent, "WINDOWS_11_OS_VERSION", '11');
background_user_agent_define_property(background_UserAgent, "PLATFORM_VERSION", 'platformVersion');
background_user_agent_define_property(background_UserAgent, "MIN_WINDOWS_11_PLATFORM_VERSION", 13);
background_user_agent_define_property(background_UserAgent, "ANDROID_OS_NAME", 'android');
background_user_agent_define_property(background_UserAgent, "parser", new (background_ua_parser_default())(navigator.userAgent));
background_user_agent_define_property(background_UserAgent, "version", background_UserAgent.getVersion());
background_user_agent_define_property(background_UserAgent, "isChrome", background_UserAgent.isTargetBrowser('Chrome'));
background_user_agent_define_property(background_UserAgent, "isFirefox", background_UserAgent.isTargetBrowser('Firefox'));
background_user_agent_define_property(background_UserAgent, "isOpera", background_UserAgent.isTargetBrowser('Opera'));
background_user_agent_define_property(background_UserAgent, "isYandex", background_UserAgent.isTargetBrowser('Yandex'));
background_user_agent_define_property(background_UserAgent, "isEdge", background_UserAgent.isTargetBrowser('Edge'));
background_user_agent_define_property(background_UserAgent, "isEdgeChromium", background_UserAgent.isEdge && !!(background_UserAgent.version && background_UserAgent.version >= 79));
background_user_agent_define_property(background_UserAgent, "isMacOs", background_UserAgent.isTargetPlatform('Mac OS'));
background_user_agent_define_property(background_UserAgent, "isWindows", background_UserAgent.isTargetPlatform('Windows'));
background_user_agent_define_property(background_UserAgent, "isAndroid", background_UserAgent.isTargetPlatform('Android'));
background_user_agent_define_property(background_UserAgent, "isChromium", background_UserAgent.isTargetEngine('Blink'));
background_user_agent_define_property(background_UserAgent, "isMobileDevice", background_UserAgent.isTargetDeviceType('mobile'));
background_user_agent_define_property(background_UserAgent, "isFirefoxMobile", background_UserAgent.isFirefox && background_UserAgent.isMobileDevice);
background_user_agent_define_property(background_UserAgent, "isSupportedBrowser", background_UserAgent.isChrome && Number(background_UserAgent.version) >= background_MIN_SUPPORTED_VERSION.CHROMIUM_MV2 || background_UserAgent.isEdgeChromium && Number(background_UserAgent.version) >= background_MIN_SUPPORTED_VERSION.EDGE_CHROMIUM || background_UserAgent.isFirefox && Number(background_UserAgent.version) >= background_MIN_SUPPORTED_VERSION.FIREFOX || background_UserAgent.isFirefoxMobile && Number(background_UserAgent.version) >= background_MIN_SUPPORTED_VERSION.FIREFOX_MOBILE || background_UserAgent.isOpera && Number(background_UserAgent.version) >= background_MIN_SUPPORTED_VERSION.OPERA);
background_user_agent_define_property(background_UserAgent, "browserName", background_UserAgent.getBrowserName());

;// ./Extension/src/common/api/extension/windows.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 



/**
 * Helper class for browser.windows API.
 */ class background_WindowsApi {
    /**
     * Calls browser.windows.create with fallback to browser.tabs.create.
     * In case of fallback, compatible data will be reused.
     *
     *
     * This covers cases:
     * - Firefox for Android, where browser.windows API is not available.
     *   https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2536
     * - Edge for Android, for some reason browser.windows.create does not open a new tab.
     *
     * @param createData Browser.windows.create argument.
     *
     * @returns Created window, tab or null, if no calls were made.
     */ static async create(createData) {
        const isAndroid = await background_UserAgent.getIsAndroid();
        // Do not use browser.windows API on Android, as it is not supported (Firefox) / does not work (Edge).
        if ((background_browser_polyfill_default()).windows && !isAndroid) {
            return background_browser_polyfill_default().windows.create(createData);
        }
        const createProperties = createData || {};
        const { url, cookieStoreId } = createProperties;
        const firstUrl = Array.isArray(url) ? url[0] : url;
        const isUrlSpecified = typeof firstUrl === 'string';
        try {
            if (isUrlSpecified) {
                return await background_browser_polyfill_default().tabs.create({
                    url: firstUrl,
                    cookieStoreId
                });
            }
            return null;
        } catch (e) {
            const message = background_error_getErrorMessage(e);
            // Android Edge does not support cookieStoreId property.
            if (message.includes("Unexpected property: 'cookieStoreId'") && isUrlSpecified) {
                return background_browser_polyfill_default().tabs.create({
                    url: Array.isArray(url) ? url[0] : url
                });
            }
            return null;
        }
    }
}

// EXTERNAL MODULE: ./node_modules/.pnpm/core-js@3.40.0/node_modules/core-js/modules/web.url-search-params.delete.js
var background_web_url_search_params_delete = __webpack_require__(4659);
// EXTERNAL MODULE: ./node_modules/.pnpm/core-js@3.40.0/node_modules/core-js/modules/web.url-search-params.has.js
var background_web_url_search_params_has = __webpack_require__(43526);
// EXTERNAL MODULE: ./node_modules/.pnpm/core-js@3.40.0/node_modules/core-js/modules/web.url-search-params.size.js
var background_web_url_search_params_size = __webpack_require__(9561);
// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+scriptlets@2.1.6/node_modules/@adguard/scriptlets/dist/index.js
var background_scriptlets_dist = __webpack_require__(61702);
;// ./node_modules/.pnpm/@adguard+tswebextension@3.1.0-alpha.3_@adguard+re2-wasm@1.2.0/node_modules/@adguard/tswebextension/dist/common/constants.js
/**
 * Filter ID which is used for User rules.
 */
const background_USER_FILTER_ID = 0;
/**
 * Filter ID which is used for Allowlist.
 */
const background_ALLOWLIST_FILTER_ID = 100;
/**
 * Custom filters identifiers starts from this number.
 */
const background_constants_CUSTOM_FILTERS_START_ID = 1000;
/**
 * Filter ID for AdGuard Quick Fixes filter.
 *
 * @see {@link https://github.com/AdguardTeam/FiltersRegistry/blob/master/filters/filter_24_QuickFixes/metadata.json}
 */
const background_QUICK_FIXES_FILTER_ID = 24;
/**
 * Tab ID for background page.
 */
const background_constants_BACKGROUND_TAB_ID = -1;
/**
 * Line feed character.
 */
const background_constants_LF = '\n';
/**
 * Semicolon character.
 */
const background_SEMICOLON = ';';
/**
 * Timeout used for deletion of request context data and frame context data from the storage.
 */
const background_FRAME_DELETION_TIMEOUT_MS = 3000;
/**
 * Document level frame id.
 */
const background_MAIN_FRAME_ID = 0;
/**
 * Value of the parent frame id if no parent frame exists.
 *
 * @see {@link https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/onBeforeRequest#parentframeid}
 */
const background_NO_PARENT_FRAME_ID = -1;



;// ./node_modules/.pnpm/@adguard+tswebextension@3.1.0-alpha.3_@adguard+re2-wasm@1.2.0/node_modules/@adguard/tswebextension/dist/common/logger.js


/**
 * Export logger implementation.
 */
const background_common_logger_logger = new background_Logger(console);
/**
 * Stringify object via JSON.stringify without specified keys.
 *
 * @param obj Object to stringify.
 * @param excludedKeys Keys to exclude.
 *
 * @returns Stringified object without excludedKeys (checking nested keys too).
 */
const background_stringifyObjectWithoutKeys = (obj, excludedKeys) => {
    return JSON.stringify(obj, (key, value) => (excludedKeys.includes(key) ? undefined : value), 2);
};



;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/identity.js
/**
 * This method returns the first argument it receives.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Util
 * @param {*} value Any value.
 * @returns {*} Returns `value`.
 * @example
 *
 * var object = { 'a': 1 };
 *
 * console.log(_.identity(object) === object);
 * // => true
 */
function background_identity(value) {
  return value;
}

/* harmony default export */ const background_lodash_es_identity = (background_identity);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheClear.js
/**
 * Removes all key-value entries from the list cache.
 *
 * @private
 * @name clear
 * @memberOf ListCache
 */
function background_listCacheClear() {
  this.__data__ = [];
  this.size = 0;
}

/* harmony default export */ const pages_background_listCacheClear = (background_listCacheClear);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/eq.js
/**
 * Performs a
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * comparison between two values to determine if they are equivalent.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * var object = { 'a': 1 };
 * var other = { 'a': 1 };
 *
 * _.eq(object, object);
 * // => true
 *
 * _.eq(object, other);
 * // => false
 *
 * _.eq('a', 'a');
 * // => true
 *
 * _.eq('a', Object('a'));
 * // => false
 *
 * _.eq(NaN, NaN);
 * // => true
 */
function background_eq(value, other) {
  return value === other || (value !== value && other !== other);
}

/* harmony default export */ const background_lodash_es_eq = (background_eq);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_assocIndexOf.js


/**
 * Gets the index at which the `key` is found in `array` of key-value pairs.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} key The key to search for.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function background_assocIndexOf(array, key) {
  var length = array.length;
  while (length--) {
    if (background_lodash_es_eq(array[length][0], key)) {
      return length;
    }
  }
  return -1;
}

/* harmony default export */ const pages_background_assocIndexOf = (background_assocIndexOf);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheDelete.js


/** Used for built-in method references. */
var background_arrayProto = Array.prototype;

/** Built-in value references. */
var background_splice = background_arrayProto.splice;

/**
 * Removes `key` and its value from the list cache.
 *
 * @private
 * @name delete
 * @memberOf ListCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function background_listCacheDelete(key) {
  var data = this.__data__,
      index = pages_background_assocIndexOf(data, key);

  if (index < 0) {
    return false;
  }
  var lastIndex = data.length - 1;
  if (index == lastIndex) {
    data.pop();
  } else {
    background_splice.call(data, index, 1);
  }
  --this.size;
  return true;
}

/* harmony default export */ const pages_background_listCacheDelete = (background_listCacheDelete);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheGet.js


/**
 * Gets the list cache value for `key`.
 *
 * @private
 * @name get
 * @memberOf ListCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function background_listCacheGet(key) {
  var data = this.__data__,
      index = pages_background_assocIndexOf(data, key);

  return index < 0 ? undefined : data[index][1];
}

/* harmony default export */ const pages_background_listCacheGet = (background_listCacheGet);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheHas.js


/**
 * Checks if a list cache value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf ListCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function background_listCacheHas(key) {
  return pages_background_assocIndexOf(this.__data__, key) > -1;
}

/* harmony default export */ const pages_background_listCacheHas = (background_listCacheHas);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheSet.js


/**
 * Sets the list cache `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf ListCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the list cache instance.
 */
function background_listCacheSet(key, value) {
  var data = this.__data__,
      index = pages_background_assocIndexOf(data, key);

  if (index < 0) {
    ++this.size;
    data.push([key, value]);
  } else {
    data[index][1] = value;
  }
  return this;
}

/* harmony default export */ const pages_background_listCacheSet = (background_listCacheSet);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_ListCache.js






/**
 * Creates an list cache object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function background_ListCache(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;

  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `ListCache`.
background_ListCache.prototype.clear = pages_background_listCacheClear;
background_ListCache.prototype['delete'] = pages_background_listCacheDelete;
background_ListCache.prototype.get = pages_background_listCacheGet;
background_ListCache.prototype.has = pages_background_listCacheHas;
background_ListCache.prototype.set = pages_background_listCacheSet;

/* harmony default export */ const pages_background_ListCache = (background_ListCache);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackClear.js


/**
 * Removes all key-value entries from the stack.
 *
 * @private
 * @name clear
 * @memberOf Stack
 */
function background_stackClear() {
  this.__data__ = new pages_background_ListCache;
  this.size = 0;
}

/* harmony default export */ const pages_background_stackClear = (background_stackClear);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackDelete.js
/**
 * Removes `key` and its value from the stack.
 *
 * @private
 * @name delete
 * @memberOf Stack
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function background_stackDelete(key) {
  var data = this.__data__,
      result = data['delete'](key);

  this.size = data.size;
  return result;
}

/* harmony default export */ const pages_background_stackDelete = (background_stackDelete);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackGet.js
/**
 * Gets the stack value for `key`.
 *
 * @private
 * @name get
 * @memberOf Stack
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function background_stackGet(key) {
  return this.__data__.get(key);
}

/* harmony default export */ const pages_background_stackGet = (background_stackGet);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackHas.js
/**
 * Checks if a stack value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Stack
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function background_stackHas(key) {
  return this.__data__.has(key);
}

/* harmony default export */ const pages_background_stackHas = (background_stackHas);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isFunction.js



/** `Object#toString` result references. */
var background_asyncTag = '[object AsyncFunction]',
    background_funcTag = '[object Function]',
    background_genTag = '[object GeneratorFunction]',
    background_proxyTag = '[object Proxy]';

/**
 * Checks if `value` is classified as a `Function` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
 * @example
 *
 * _.isFunction(_);
 * // => true
 *
 * _.isFunction(/abc/);
 * // => false
 */
function background_isFunction_isFunction(value) {
  if (!background_lodash_es_isObject(value)) {
    return false;
  }
  // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 9 which returns 'object' for typed arrays and other constructors.
  var tag = pages_background_baseGetTag(value);
  return tag == background_funcTag || tag == background_genTag || tag == background_asyncTag || tag == background_proxyTag;
}

/* harmony default export */ const background_lodash_es_isFunction = (background_isFunction_isFunction);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_coreJsData.js


/** Used to detect overreaching core-js shims. */
var background_coreJsData = pages_background_root['__core-js_shared__'];

/* harmony default export */ const pages_background_coreJsData = (background_coreJsData);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isMasked.js


/** Used to detect methods masquerading as native. */
var background_maskSrcKey = (function() {
  var uid = /[^.]+$/.exec(pages_background_coreJsData && pages_background_coreJsData.keys && pages_background_coreJsData.keys.IE_PROTO || '');
  return uid ? ('Symbol(src)_1.' + uid) : '';
}());

/**
 * Checks if `func` has its source masked.
 *
 * @private
 * @param {Function} func The function to check.
 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
 */
function background_isMasked(func) {
  return !!background_maskSrcKey && (background_maskSrcKey in func);
}

/* harmony default export */ const pages_background_isMasked = (background_isMasked);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_toSource.js
/** Used for built-in method references. */
var background_funcProto = Function.prototype;

/** Used to resolve the decompiled source of functions. */
var background_funcToString = background_funcProto.toString;

/**
 * Converts `func` to its source code.
 *
 * @private
 * @param {Function} func The function to convert.
 * @returns {string} Returns the source code.
 */
function background_toSource(func) {
  if (func != null) {
    try {
      return background_funcToString.call(func);
    } catch (e) {}
    try {
      return (func + '');
    } catch (e) {}
  }
  return '';
}

/* harmony default export */ const pages_background_toSource = (background_toSource);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsNative.js





/**
 * Used to match `RegExp`
 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
 */
var background_reRegExpChar = /[\\^$.*+?()[\]{}|]/g;

/** Used to detect host constructors (Safari). */
var background_reIsHostCtor = /^\[object .+?Constructor\]$/;

/** Used for built-in method references. */
var background_baseIsNative_funcProto = Function.prototype,
    background_baseIsNative_objectProto = Object.prototype;

/** Used to resolve the decompiled source of functions. */
var background_baseIsNative_funcToString = background_baseIsNative_funcProto.toString;

/** Used to check objects for own properties. */
var background_baseIsNative_hasOwnProperty = background_baseIsNative_objectProto.hasOwnProperty;

/** Used to detect if a method is native. */
var background_reIsNative = RegExp('^' +
  background_baseIsNative_funcToString.call(background_baseIsNative_hasOwnProperty).replace(background_reRegExpChar, '\\$&')
  .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);

/**
 * The base implementation of `_.isNative` without bad shim checks.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a native function,
 *  else `false`.
 */
function background_baseIsNative(value) {
  if (!background_lodash_es_isObject(value) || pages_background_isMasked(value)) {
    return false;
  }
  var pattern = background_lodash_es_isFunction(value) ? background_reIsNative : background_reIsHostCtor;
  return pattern.test(pages_background_toSource(value));
}

/* harmony default export */ const pages_background_baseIsNative = (background_baseIsNative);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getValue.js
/**
 * Gets the value at `key` of `object`.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {string} key The key of the property to get.
 * @returns {*} Returns the property value.
 */
function background_getValue(object, key) {
  return object == null ? undefined : object[key];
}

/* harmony default export */ const pages_background_getValue = (background_getValue);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getNative.js



/**
 * Gets the native function at `key` of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {string} key The key of the method to get.
 * @returns {*} Returns the function if it's native, else `undefined`.
 */
function background_getNative(object, key) {
  var value = pages_background_getValue(object, key);
  return pages_background_baseIsNative(value) ? value : undefined;
}

/* harmony default export */ const pages_background_getNative = (background_getNative);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Map.js



/* Built-in method references that are verified to be native. */
var background_Map_Map = pages_background_getNative(pages_background_root, 'Map');

/* harmony default export */ const background_Map = (background_Map_Map);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nativeCreate.js


/* Built-in method references that are verified to be native. */
var background_nativeCreate = pages_background_getNative(Object, 'create');

/* harmony default export */ const pages_background_nativeCreate = (background_nativeCreate);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashClear.js


/**
 * Removes all key-value entries from the hash.
 *
 * @private
 * @name clear
 * @memberOf Hash
 */
function background_hashClear() {
  this.__data__ = pages_background_nativeCreate ? pages_background_nativeCreate(null) : {};
  this.size = 0;
}

/* harmony default export */ const pages_background_hashClear = (background_hashClear);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashDelete.js
/**
 * Removes `key` and its value from the hash.
 *
 * @private
 * @name delete
 * @memberOf Hash
 * @param {Object} hash The hash to modify.
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function background_hashDelete(key) {
  var result = this.has(key) && delete this.__data__[key];
  this.size -= result ? 1 : 0;
  return result;
}

/* harmony default export */ const pages_background_hashDelete = (background_hashDelete);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashGet.js


/** Used to stand-in for `undefined` hash values. */
var background_HASH_UNDEFINED = '__lodash_hash_undefined__';

/** Used for built-in method references. */
var background_hashGet_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var background_hashGet_hasOwnProperty = background_hashGet_objectProto.hasOwnProperty;

/**
 * Gets the hash value for `key`.
 *
 * @private
 * @name get
 * @memberOf Hash
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function background_hashGet(key) {
  var data = this.__data__;
  if (pages_background_nativeCreate) {
    var result = data[key];
    return result === background_HASH_UNDEFINED ? undefined : result;
  }
  return background_hashGet_hasOwnProperty.call(data, key) ? data[key] : undefined;
}

/* harmony default export */ const pages_background_hashGet = (background_hashGet);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashHas.js


/** Used for built-in method references. */
var background_hashHas_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var background_hashHas_hasOwnProperty = background_hashHas_objectProto.hasOwnProperty;

/**
 * Checks if a hash value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Hash
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function background_hashHas(key) {
  var data = this.__data__;
  return pages_background_nativeCreate ? (data[key] !== undefined) : background_hashHas_hasOwnProperty.call(data, key);
}

/* harmony default export */ const pages_background_hashHas = (background_hashHas);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashSet.js


/** Used to stand-in for `undefined` hash values. */
var background_hashSet_HASH_UNDEFINED = '__lodash_hash_undefined__';

/**
 * Sets the hash `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Hash
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the hash instance.
 */
function background_hashSet(key, value) {
  var data = this.__data__;
  this.size += this.has(key) ? 0 : 1;
  data[key] = (pages_background_nativeCreate && value === undefined) ? background_hashSet_HASH_UNDEFINED : value;
  return this;
}

/* harmony default export */ const pages_background_hashSet = (background_hashSet);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Hash.js






/**
 * Creates a hash object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function background_Hash(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;

  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `Hash`.
background_Hash.prototype.clear = pages_background_hashClear;
background_Hash.prototype['delete'] = pages_background_hashDelete;
background_Hash.prototype.get = pages_background_hashGet;
background_Hash.prototype.has = pages_background_hashHas;
background_Hash.prototype.set = pages_background_hashSet;

/* harmony default export */ const pages_background_Hash = (background_Hash);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheClear.js




/**
 * Removes all key-value entries from the map.
 *
 * @private
 * @name clear
 * @memberOf MapCache
 */
function background_mapCacheClear() {
  this.size = 0;
  this.__data__ = {
    'hash': new pages_background_Hash,
    'map': new (background_Map || pages_background_ListCache),
    'string': new pages_background_Hash
  };
}

/* harmony default export */ const pages_background_mapCacheClear = (background_mapCacheClear);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isKeyable.js
/**
 * Checks if `value` is suitable for use as unique object key.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
 */
function background_isKeyable(value) {
  var type = typeof value;
  return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
    ? (value !== '__proto__')
    : (value === null);
}

/* harmony default export */ const pages_background_isKeyable = (background_isKeyable);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getMapData.js


/**
 * Gets the data for `map`.
 *
 * @private
 * @param {Object} map The map to query.
 * @param {string} key The reference key.
 * @returns {*} Returns the map data.
 */
function background_getMapData(map, key) {
  var data = map.__data__;
  return pages_background_isKeyable(key)
    ? data[typeof key == 'string' ? 'string' : 'hash']
    : data.map;
}

/* harmony default export */ const pages_background_getMapData = (background_getMapData);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheDelete.js


/**
 * Removes `key` and its value from the map.
 *
 * @private
 * @name delete
 * @memberOf MapCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function background_mapCacheDelete(key) {
  var result = pages_background_getMapData(this, key)['delete'](key);
  this.size -= result ? 1 : 0;
  return result;
}

/* harmony default export */ const pages_background_mapCacheDelete = (background_mapCacheDelete);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheGet.js


/**
 * Gets the map value for `key`.
 *
 * @private
 * @name get
 * @memberOf MapCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function background_mapCacheGet(key) {
  return pages_background_getMapData(this, key).get(key);
}

/* harmony default export */ const pages_background_mapCacheGet = (background_mapCacheGet);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheHas.js


/**
 * Checks if a map value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf MapCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function background_mapCacheHas(key) {
  return pages_background_getMapData(this, key).has(key);
}

/* harmony default export */ const pages_background_mapCacheHas = (background_mapCacheHas);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheSet.js


/**
 * Sets the map `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf MapCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the map cache instance.
 */
function background_mapCacheSet(key, value) {
  var data = pages_background_getMapData(this, key),
      size = data.size;

  data.set(key, value);
  this.size += data.size == size ? 0 : 1;
  return this;
}

/* harmony default export */ const pages_background_mapCacheSet = (background_mapCacheSet);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_MapCache.js






/**
 * Creates a map cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function background_MapCache(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;

  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `MapCache`.
background_MapCache.prototype.clear = pages_background_mapCacheClear;
background_MapCache.prototype['delete'] = pages_background_mapCacheDelete;
background_MapCache.prototype.get = pages_background_mapCacheGet;
background_MapCache.prototype.has = pages_background_mapCacheHas;
background_MapCache.prototype.set = pages_background_mapCacheSet;

/* harmony default export */ const pages_background_MapCache = (background_MapCache);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackSet.js




/** Used as the size to enable large array optimizations. */
var background_LARGE_ARRAY_SIZE = 200;

/**
 * Sets the stack `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Stack
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the stack cache instance.
 */
function background_stackSet(key, value) {
  var data = this.__data__;
  if (data instanceof pages_background_ListCache) {
    var pairs = data.__data__;
    if (!background_Map || (pairs.length < background_LARGE_ARRAY_SIZE - 1)) {
      pairs.push([key, value]);
      this.size = ++data.size;
      return this;
    }
    data = this.__data__ = new pages_background_MapCache(pairs);
  }
  data.set(key, value);
  this.size = data.size;
  return this;
}

/* harmony default export */ const pages_background_stackSet = (background_stackSet);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Stack.js







/**
 * Creates a stack cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function background_Stack(entries) {
  var data = this.__data__ = new pages_background_ListCache(entries);
  this.size = data.size;
}

// Add methods to `Stack`.
background_Stack.prototype.clear = pages_background_stackClear;
background_Stack.prototype['delete'] = pages_background_stackDelete;
background_Stack.prototype.get = pages_background_stackGet;
background_Stack.prototype.has = pages_background_stackHas;
background_Stack.prototype.set = pages_background_stackSet;

/* harmony default export */ const pages_background_Stack = (background_Stack);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayEach.js
/**
 * A specialized version of `_.forEach` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns `array`.
 */
function background_arrayEach(array, iteratee) {
  var index = -1,
      length = array == null ? 0 : array.length;

  while (++index < length) {
    if (iteratee(array[index], index, array) === false) {
      break;
    }
  }
  return array;
}

/* harmony default export */ const pages_background_arrayEach = (background_arrayEach);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_defineProperty.js


var pages_background_defineProperty = (function() {
  try {
    var func = pages_background_getNative(Object, 'defineProperty');
    func({}, '', {});
    return func;
  } catch (e) {}
}());

/* harmony default export */ const background_lodash_es_defineProperty = (pages_background_defineProperty);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseAssignValue.js


/**
 * The base implementation of `assignValue` and `assignMergeValue` without
 * value checks.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {string} key The key of the property to assign.
 * @param {*} value The value to assign.
 */
function background_baseAssignValue(object, key, value) {
  if (key == '__proto__' && background_lodash_es_defineProperty) {
    background_lodash_es_defineProperty(object, key, {
      'configurable': true,
      'enumerable': true,
      'value': value,
      'writable': true
    });
  } else {
    object[key] = value;
  }
}

/* harmony default export */ const pages_background_baseAssignValue = (background_baseAssignValue);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_assignValue.js



/** Used for built-in method references. */
var background_assignValue_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var background_assignValue_hasOwnProperty = background_assignValue_objectProto.hasOwnProperty;

/**
 * Assigns `value` to `key` of `object` if the existing value is not equivalent
 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * for equality comparisons.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {string} key The key of the property to assign.
 * @param {*} value The value to assign.
 */
function background_assignValue(object, key, value) {
  var objValue = object[key];
  if (!(background_assignValue_hasOwnProperty.call(object, key) && background_lodash_es_eq(objValue, value)) ||
      (value === undefined && !(key in object))) {
    pages_background_baseAssignValue(object, key, value);
  }
}

/* harmony default export */ const pages_background_assignValue = (background_assignValue);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_copyObject.js



/**
 * Copies properties of `source` to `object`.
 *
 * @private
 * @param {Object} source The object to copy properties from.
 * @param {Array} props The property identifiers to copy.
 * @param {Object} [object={}] The object to copy properties to.
 * @param {Function} [customizer] The function to customize copied values.
 * @returns {Object} Returns `object`.
 */
function background_copyObject(source, props, object, customizer) {
  var isNew = !object;
  object || (object = {});

  var index = -1,
      length = props.length;

  while (++index < length) {
    var key = props[index];

    var newValue = customizer
      ? customizer(object[key], source[key], key, object, source)
      : undefined;

    if (newValue === undefined) {
      newValue = source[key];
    }
    if (isNew) {
      pages_background_baseAssignValue(object, key, newValue);
    } else {
      pages_background_assignValue(object, key, newValue);
    }
  }
  return object;
}

/* harmony default export */ const pages_background_copyObject = (background_copyObject);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseTimes.js
/**
 * The base implementation of `_.times` without support for iteratee shorthands
 * or max array length checks.
 *
 * @private
 * @param {number} n The number of times to invoke `iteratee`.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the array of results.
 */
function background_baseTimes(n, iteratee) {
  var index = -1,
      result = Array(n);

  while (++index < n) {
    result[index] = iteratee(index);
  }
  return result;
}

/* harmony default export */ const pages_background_baseTimes = (background_baseTimes);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsArguments.js



/** `Object#toString` result references. */
var background_argsTag = '[object Arguments]';

/**
 * The base implementation of `_.isArguments`.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 */
function background_baseIsArguments(value) {
  return background_lodash_es_isObjectLike(value) && pages_background_baseGetTag(value) == background_argsTag;
}

/* harmony default export */ const pages_background_baseIsArguments = (background_baseIsArguments);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArguments.js



/** Used for built-in method references. */
var background_isArguments_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var background_isArguments_hasOwnProperty = background_isArguments_objectProto.hasOwnProperty;

/** Built-in value references. */
var background_propertyIsEnumerable = background_isArguments_objectProto.propertyIsEnumerable;

/**
 * Checks if `value` is likely an `arguments` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 *  else `false`.
 * @example
 *
 * _.isArguments(function() { return arguments; }());
 * // => true
 *
 * _.isArguments([1, 2, 3]);
 * // => false
 */
var background_isArguments = pages_background_baseIsArguments(function() { return arguments; }()) ? pages_background_baseIsArguments : function(value) {
  return background_lodash_es_isObjectLike(value) && background_isArguments_hasOwnProperty.call(value, 'callee') &&
    !background_propertyIsEnumerable.call(value, 'callee');
};

/* harmony default export */ const background_lodash_es_isArguments = (background_isArguments);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArray.js
/**
 * Checks if `value` is classified as an `Array` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
 * @example
 *
 * _.isArray([1, 2, 3]);
 * // => true
 *
 * _.isArray(document.body.children);
 * // => false
 *
 * _.isArray('abc');
 * // => false
 *
 * _.isArray(_.noop);
 * // => false
 */
var background_isArray_isArray = Array.isArray;

/* harmony default export */ const background_lodash_es_isArray = (background_isArray_isArray);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/stubFalse.js
/**
 * This method returns `false`.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {boolean} Returns `false`.
 * @example
 *
 * _.times(2, _.stubFalse);
 * // => [false, false]
 */
function background_stubFalse() {
  return false;
}

/* harmony default export */ const background_lodash_es_stubFalse = (background_stubFalse);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isBuffer.js



/** Detect free variable `exports`. */
var background_freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var background_freeModule = background_freeExports && typeof module == 'object' && module && !module.nodeType && module;

/** Detect the popular CommonJS extension `module.exports`. */
var background_moduleExports = background_freeModule && background_freeModule.exports === background_freeExports;

/** Built-in value references. */
var background_Buffer = background_moduleExports ? pages_background_root.Buffer : undefined;

/* Built-in method references for those with the same name as other `lodash` methods. */
var background_nativeIsBuffer = background_Buffer ? background_Buffer.isBuffer : undefined;

/**
 * Checks if `value` is a buffer.
 *
 * @static
 * @memberOf _
 * @since 4.3.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
 * @example
 *
 * _.isBuffer(new Buffer(2));
 * // => true
 *
 * _.isBuffer(new Uint8Array(2));
 * // => false
 */
var background_isBuffer = background_nativeIsBuffer || background_lodash_es_stubFalse;

/* harmony default export */ const background_lodash_es_isBuffer = (background_isBuffer);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isIndex.js
/** Used as references for various `Number` constants. */
var background_MAX_SAFE_INTEGER = 9007199254740991;

/** Used to detect unsigned integer values. */
var background_reIsUint = /^(?:0|[1-9]\d*)$/;

/**
 * Checks if `value` is a valid array-like index.
 *
 * @private
 * @param {*} value The value to check.
 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
 */
function background_isIndex(value, length) {
  var type = typeof value;
  length = length == null ? background_MAX_SAFE_INTEGER : length;

  return !!length &&
    (type == 'number' ||
      (type != 'symbol' && background_reIsUint.test(value))) &&
        (value > -1 && value % 1 == 0 && value < length);
}

/* harmony default export */ const pages_background_isIndex = (background_isIndex);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isLength.js
/** Used as references for various `Number` constants. */
var background_isLength_MAX_SAFE_INTEGER = 9007199254740991;

/**
 * Checks if `value` is a valid array-like length.
 *
 * **Note:** This method is loosely based on
 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
 * @example
 *
 * _.isLength(3);
 * // => true
 *
 * _.isLength(Number.MIN_VALUE);
 * // => false
 *
 * _.isLength(Infinity);
 * // => false
 *
 * _.isLength('3');
 * // => false
 */
function background_isLength(value) {
  return typeof value == 'number' &&
    value > -1 && value % 1 == 0 && value <= background_isLength_MAX_SAFE_INTEGER;
}

/* harmony default export */ const background_lodash_es_isLength = (background_isLength);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsTypedArray.js




/** `Object#toString` result references. */
var background_baseIsTypedArray_argsTag = '[object Arguments]',
    background_arrayTag = '[object Array]',
    background_boolTag = '[object Boolean]',
    background_dateTag = '[object Date]',
    background_errorTag = '[object Error]',
    background_baseIsTypedArray_funcTag = '[object Function]',
    background_mapTag = '[object Map]',
    background_numberTag = '[object Number]',
    background_objectTag = '[object Object]',
    background_regexpTag = '[object RegExp]',
    background_setTag = '[object Set]',
    background_stringTag = '[object String]',
    background_weakMapTag = '[object WeakMap]';

var background_arrayBufferTag = '[object ArrayBuffer]',
    background_dataViewTag = '[object DataView]',
    background_float32Tag = '[object Float32Array]',
    background_float64Tag = '[object Float64Array]',
    background_int8Tag = '[object Int8Array]',
    background_int16Tag = '[object Int16Array]',
    background_int32Tag = '[object Int32Array]',
    background_uint8Tag = '[object Uint8Array]',
    background_uint8ClampedTag = '[object Uint8ClampedArray]',
    background_uint16Tag = '[object Uint16Array]',
    background_uint32Tag = '[object Uint32Array]';

/** Used to identify `toStringTag` values of typed arrays. */
var background_typedArrayTags = {};
background_typedArrayTags[background_float32Tag] = background_typedArrayTags[background_float64Tag] =
background_typedArrayTags[background_int8Tag] = background_typedArrayTags[background_int16Tag] =
background_typedArrayTags[background_int32Tag] = background_typedArrayTags[background_uint8Tag] =
background_typedArrayTags[background_uint8ClampedTag] = background_typedArrayTags[background_uint16Tag] =
background_typedArrayTags[background_uint32Tag] = true;
background_typedArrayTags[background_baseIsTypedArray_argsTag] = background_typedArrayTags[background_arrayTag] =
background_typedArrayTags[background_arrayBufferTag] = background_typedArrayTags[background_boolTag] =
background_typedArrayTags[background_dataViewTag] = background_typedArrayTags[background_dateTag] =
background_typedArrayTags[background_errorTag] = background_typedArrayTags[background_baseIsTypedArray_funcTag] =
background_typedArrayTags[background_mapTag] = background_typedArrayTags[background_numberTag] =
background_typedArrayTags[background_objectTag] = background_typedArrayTags[background_regexpTag] =
background_typedArrayTags[background_setTag] = background_typedArrayTags[background_stringTag] =
background_typedArrayTags[background_weakMapTag] = false;

/**
 * The base implementation of `_.isTypedArray` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
 */
function background_baseIsTypedArray(value) {
  return background_lodash_es_isObjectLike(value) &&
    background_lodash_es_isLength(value.length) && !!background_typedArrayTags[pages_background_baseGetTag(value)];
}

/* harmony default export */ const pages_background_baseIsTypedArray = (background_baseIsTypedArray);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseUnary.js
/**
 * The base implementation of `_.unary` without support for storing metadata.
 *
 * @private
 * @param {Function} func The function to cap arguments for.
 * @returns {Function} Returns the new capped function.
 */
function background_baseUnary(func) {
  return function(value) {
    return func(value);
  };
}

/* harmony default export */ const pages_background_baseUnary = (background_baseUnary);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nodeUtil.js


/** Detect free variable `exports`. */
var background_nodeUtil_freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var background_nodeUtil_freeModule = background_nodeUtil_freeExports && typeof module == 'object' && module && !module.nodeType && module;

/** Detect the popular CommonJS extension `module.exports`. */
var background_nodeUtil_moduleExports = background_nodeUtil_freeModule && background_nodeUtil_freeModule.exports === background_nodeUtil_freeExports;

/** Detect free variable `process` from Node.js. */
var background_freeProcess = background_nodeUtil_moduleExports && pages_background_freeGlobal.process;

/** Used to access faster Node.js helpers. */
var background_nodeUtil = (function() {
  try {
    // Use `util.types` for Node.js 10+.
    var types = background_nodeUtil_freeModule && background_nodeUtil_freeModule.require && background_nodeUtil_freeModule.require('util').types;

    if (types) {
      return types;
    }

    // Legacy `process.binding('util')` for Node.js < 10.
    return background_freeProcess && background_freeProcess.binding && background_freeProcess.binding('util');
  } catch (e) {}
}());

/* harmony default export */ const pages_background_nodeUtil = (background_nodeUtil);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isTypedArray.js




/* Node.js helper references. */
var background_nodeIsTypedArray = pages_background_nodeUtil && pages_background_nodeUtil.isTypedArray;

/**
 * Checks if `value` is classified as a typed array.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
 * @example
 *
 * _.isTypedArray(new Uint8Array);
 * // => true
 *
 * _.isTypedArray([]);
 * // => false
 */
var background_isTypedArray_isTypedArray = background_nodeIsTypedArray ? pages_background_baseUnary(background_nodeIsTypedArray) : pages_background_baseIsTypedArray;

/* harmony default export */ const background_lodash_es_isTypedArray = (background_isTypedArray_isTypedArray);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayLikeKeys.js







/** Used for built-in method references. */
var background_arrayLikeKeys_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var background_arrayLikeKeys_hasOwnProperty = background_arrayLikeKeys_objectProto.hasOwnProperty;

/**
 * Creates an array of the enumerable property names of the array-like `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @param {boolean} inherited Specify returning inherited property names.
 * @returns {Array} Returns the array of property names.
 */
function background_arrayLikeKeys(value, inherited) {
  var isArr = background_lodash_es_isArray(value),
      isArg = !isArr && background_lodash_es_isArguments(value),
      isBuff = !isArr && !isArg && background_lodash_es_isBuffer(value),
      isType = !isArr && !isArg && !isBuff && background_lodash_es_isTypedArray(value),
      skipIndexes = isArr || isArg || isBuff || isType,
      result = skipIndexes ? pages_background_baseTimes(value.length, String) : [],
      length = result.length;

  for (var key in value) {
    if ((inherited || background_arrayLikeKeys_hasOwnProperty.call(value, key)) &&
        !(skipIndexes && (
           // Safari 9 has enumerable `arguments.length` in strict mode.
           key == 'length' ||
           // Node.js 0.10 has enumerable non-index properties on buffers.
           (isBuff && (key == 'offset' || key == 'parent')) ||
           // PhantomJS 2 has enumerable non-index properties on typed arrays.
           (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
           // Skip index properties.
           pages_background_isIndex(key, length)
        ))) {
      result.push(key);
    }
  }
  return result;
}

/* harmony default export */ const pages_background_arrayLikeKeys = (background_arrayLikeKeys);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isPrototype.js
/** Used for built-in method references. */
var background_isPrototype_objectProto = Object.prototype;

/**
 * Checks if `value` is likely a prototype object.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
 */
function background_isPrototype(value) {
  var Ctor = value && value.constructor,
      proto = (typeof Ctor == 'function' && Ctor.prototype) || background_isPrototype_objectProto;

  return value === proto;
}

/* harmony default export */ const pages_background_isPrototype = (background_isPrototype);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_overArg.js
/**
 * Creates a unary function that invokes `func` with its argument transformed.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {Function} transform The argument transform.
 * @returns {Function} Returns the new function.
 */
function background_overArg(func, transform) {
  return function(arg) {
    return func(transform(arg));
  };
}

/* harmony default export */ const pages_background_overArg = (background_overArg);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nativeKeys.js


/* Built-in method references for those with the same name as other `lodash` methods. */
var background_nativeKeys = pages_background_overArg(Object.keys, Object);

/* harmony default export */ const pages_background_nativeKeys = (background_nativeKeys);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseKeys.js



/** Used for built-in method references. */
var background_baseKeys_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var background_baseKeys_hasOwnProperty = background_baseKeys_objectProto.hasOwnProperty;

/**
 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */
function background_baseKeys(object) {
  if (!pages_background_isPrototype(object)) {
    return pages_background_nativeKeys(object);
  }
  var result = [];
  for (var key in Object(object)) {
    if (background_baseKeys_hasOwnProperty.call(object, key) && key != 'constructor') {
      result.push(key);
    }
  }
  return result;
}

/* harmony default export */ const pages_background_baseKeys = (background_baseKeys);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArrayLike.js



/**
 * Checks if `value` is array-like. A value is considered array-like if it's
 * not a function and has a `value.length` that's an integer greater than or
 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
 * @example
 *
 * _.isArrayLike([1, 2, 3]);
 * // => true
 *
 * _.isArrayLike(document.body.children);
 * // => true
 *
 * _.isArrayLike('abc');
 * // => true
 *
 * _.isArrayLike(_.noop);
 * // => false
 */
function background_isArrayLike(value) {
  return value != null && background_lodash_es_isLength(value.length) && !background_lodash_es_isFunction(value);
}

/* harmony default export */ const background_lodash_es_isArrayLike = (background_isArrayLike);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/keys.js




/**
 * Creates an array of the own enumerable property names of `object`.
 *
 * **Note:** Non-object values are coerced to objects. See the
 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
 * for more details.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.keys(new Foo);
 * // => ['a', 'b'] (iteration order is not guaranteed)
 *
 * _.keys('hi');
 * // => ['0', '1']
 */
function background_keys(object) {
  return background_lodash_es_isArrayLike(object) ? pages_background_arrayLikeKeys(object) : pages_background_baseKeys(object);
}

/* harmony default export */ const background_lodash_es_keys = (background_keys);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseAssign.js



/**
 * The base implementation of `_.assign` without support for multiple sources
 * or `customizer` functions.
 *
 * @private
 * @param {Object} object The destination object.
 * @param {Object} source The source object.
 * @returns {Object} Returns `object`.
 */
function background_baseAssign(object, source) {
  return object && pages_background_copyObject(source, background_lodash_es_keys(source), object);
}

/* harmony default export */ const pages_background_baseAssign = (background_baseAssign);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nativeKeysIn.js
/**
 * This function is like
 * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
 * except that it includes inherited enumerable properties.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */
function background_nativeKeysIn(object) {
  var result = [];
  if (object != null) {
    for (var key in Object(object)) {
      result.push(key);
    }
  }
  return result;
}

/* harmony default export */ const pages_background_nativeKeysIn = (background_nativeKeysIn);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseKeysIn.js




/** Used for built-in method references. */
var background_baseKeysIn_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var background_baseKeysIn_hasOwnProperty = background_baseKeysIn_objectProto.hasOwnProperty;

/**
 * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */
function background_baseKeysIn(object) {
  if (!background_lodash_es_isObject(object)) {
    return pages_background_nativeKeysIn(object);
  }
  var isProto = pages_background_isPrototype(object),
      result = [];

  for (var key in object) {
    if (!(key == 'constructor' && (isProto || !background_baseKeysIn_hasOwnProperty.call(object, key)))) {
      result.push(key);
    }
  }
  return result;
}

/* harmony default export */ const pages_background_baseKeysIn = (background_baseKeysIn);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/keysIn.js




/**
 * Creates an array of the own and inherited enumerable property names of `object`.
 *
 * **Note:** Non-object values are coerced to objects.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.keysIn(new Foo);
 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
 */
function background_keysIn(object) {
  return background_lodash_es_isArrayLike(object) ? pages_background_arrayLikeKeys(object, true) : pages_background_baseKeysIn(object);
}

/* harmony default export */ const background_lodash_es_keysIn = (background_keysIn);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseAssignIn.js



/**
 * The base implementation of `_.assignIn` without support for multiple sources
 * or `customizer` functions.
 *
 * @private
 * @param {Object} object The destination object.
 * @param {Object} source The source object.
 * @returns {Object} Returns `object`.
 */
function background_baseAssignIn(object, source) {
  return object && pages_background_copyObject(source, background_lodash_es_keysIn(source), object);
}

/* harmony default export */ const pages_background_baseAssignIn = (background_baseAssignIn);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_cloneBuffer.js


/** Detect free variable `exports`. */
var background_cloneBuffer_freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var background_cloneBuffer_freeModule = background_cloneBuffer_freeExports && typeof module == 'object' && module && !module.nodeType && module;

/** Detect the popular CommonJS extension `module.exports`. */
var background_cloneBuffer_moduleExports = background_cloneBuffer_freeModule && background_cloneBuffer_freeModule.exports === background_cloneBuffer_freeExports;

/** Built-in value references. */
var background_cloneBuffer_Buffer = background_cloneBuffer_moduleExports ? pages_background_root.Buffer : undefined,
    background_allocUnsafe = background_cloneBuffer_Buffer ? background_cloneBuffer_Buffer.allocUnsafe : undefined;

/**
 * Creates a clone of  `buffer`.
 *
 * @private
 * @param {Buffer} buffer The buffer to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Buffer} Returns the cloned buffer.
 */
function background_cloneBuffer(buffer, isDeep) {
  if (isDeep) {
    return buffer.slice();
  }
  var length = buffer.length,
      result = background_allocUnsafe ? background_allocUnsafe(length) : new buffer.constructor(length);

  buffer.copy(result);
  return result;
}

/* harmony default export */ const pages_background_cloneBuffer = (background_cloneBuffer);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_copyArray.js
/**
 * Copies the values of `source` to `array`.
 *
 * @private
 * @param {Array} source The array to copy values from.
 * @param {Array} [array=[]] The array to copy values to.
 * @returns {Array} Returns `array`.
 */
function background_copyArray(source, array) {
  var index = -1,
      length = source.length;

  array || (array = Array(length));
  while (++index < length) {
    array[index] = source[index];
  }
  return array;
}

/* harmony default export */ const pages_background_copyArray = (background_copyArray);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayFilter.js
/**
 * A specialized version of `_.filter` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 */
function background_arrayFilter(array, predicate) {
  var index = -1,
      length = array == null ? 0 : array.length,
      resIndex = 0,
      result = [];

  while (++index < length) {
    var value = array[index];
    if (predicate(value, index, array)) {
      result[resIndex++] = value;
    }
  }
  return result;
}

/* harmony default export */ const pages_background_arrayFilter = (background_arrayFilter);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/stubArray.js
/**
 * This method returns a new empty array.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {Array} Returns the new empty array.
 * @example
 *
 * var arrays = _.times(2, _.stubArray);
 *
 * console.log(arrays);
 * // => [[], []]
 *
 * console.log(arrays[0] === arrays[1]);
 * // => false
 */
function background_stubArray() {
  return [];
}

/* harmony default export */ const background_lodash_es_stubArray = (background_stubArray);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getSymbols.js



/** Used for built-in method references. */
var background_getSymbols_objectProto = Object.prototype;

/** Built-in value references. */
var background_getSymbols_propertyIsEnumerable = background_getSymbols_objectProto.propertyIsEnumerable;

/* Built-in method references for those with the same name as other `lodash` methods. */
var background_nativeGetSymbols = Object.getOwnPropertySymbols;

/**
 * Creates an array of the own enumerable symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of symbols.
 */
var background_getSymbols = !background_nativeGetSymbols ? background_lodash_es_stubArray : function(object) {
  if (object == null) {
    return [];
  }
  object = Object(object);
  return pages_background_arrayFilter(background_nativeGetSymbols(object), function(symbol) {
    return background_getSymbols_propertyIsEnumerable.call(object, symbol);
  });
};

/* harmony default export */ const pages_background_getSymbols = (background_getSymbols);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_copySymbols.js



/**
 * Copies own symbols of `source` to `object`.
 *
 * @private
 * @param {Object} source The object to copy symbols from.
 * @param {Object} [object={}] The object to copy symbols to.
 * @returns {Object} Returns `object`.
 */
function background_copySymbols(source, object) {
  return pages_background_copyObject(source, pages_background_getSymbols(source), object);
}

/* harmony default export */ const pages_background_copySymbols = (background_copySymbols);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayPush.js
/**
 * Appends the elements of `values` to `array`.
 *
 * @private
 * @param {Array} array The array to modify.
 * @param {Array} values The values to append.
 * @returns {Array} Returns `array`.
 */
function background_arrayPush(array, values) {
  var index = -1,
      length = values.length,
      offset = array.length;

  while (++index < length) {
    array[offset + index] = values[index];
  }
  return array;
}

/* harmony default export */ const pages_background_arrayPush = (background_arrayPush);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getPrototype.js


/** Built-in value references. */
var background_getPrototype = pages_background_overArg(Object.getPrototypeOf, Object);

/* harmony default export */ const pages_background_getPrototype = (background_getPrototype);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getSymbolsIn.js





/* Built-in method references for those with the same name as other `lodash` methods. */
var background_getSymbolsIn_nativeGetSymbols = Object.getOwnPropertySymbols;

/**
 * Creates an array of the own and inherited enumerable symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of symbols.
 */
var background_getSymbolsIn = !background_getSymbolsIn_nativeGetSymbols ? background_lodash_es_stubArray : function(object) {
  var result = [];
  while (object) {
    pages_background_arrayPush(result, pages_background_getSymbols(object));
    object = pages_background_getPrototype(object);
  }
  return result;
};

/* harmony default export */ const pages_background_getSymbolsIn = (background_getSymbolsIn);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_copySymbolsIn.js



/**
 * Copies own and inherited symbols of `source` to `object`.
 *
 * @private
 * @param {Object} source The object to copy symbols from.
 * @param {Object} [object={}] The object to copy symbols to.
 * @returns {Object} Returns `object`.
 */
function background_copySymbolsIn(source, object) {
  return pages_background_copyObject(source, pages_background_getSymbolsIn(source), object);
}

/* harmony default export */ const pages_background_copySymbolsIn = (background_copySymbolsIn);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGetAllKeys.js



/**
 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
 * symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Function} keysFunc The function to get the keys of `object`.
 * @param {Function} symbolsFunc The function to get the symbols of `object`.
 * @returns {Array} Returns the array of property names and symbols.
 */
function background_baseGetAllKeys(object, keysFunc, symbolsFunc) {
  var result = keysFunc(object);
  return background_lodash_es_isArray(object) ? result : pages_background_arrayPush(result, symbolsFunc(object));
}

/* harmony default export */ const pages_background_baseGetAllKeys = (background_baseGetAllKeys);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getAllKeys.js




/**
 * Creates an array of own enumerable property names and symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names and symbols.
 */
function background_getAllKeys(object) {
  return pages_background_baseGetAllKeys(object, background_lodash_es_keys, pages_background_getSymbols);
}

/* harmony default export */ const pages_background_getAllKeys = (background_getAllKeys);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getAllKeysIn.js




/**
 * Creates an array of own and inherited enumerable property names and
 * symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names and symbols.
 */
function background_getAllKeysIn(object) {
  return pages_background_baseGetAllKeys(object, background_lodash_es_keysIn, pages_background_getSymbolsIn);
}

/* harmony default export */ const pages_background_getAllKeysIn = (background_getAllKeysIn);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_DataView.js



/* Built-in method references that are verified to be native. */
var background_DataView_DataView = pages_background_getNative(pages_background_root, 'DataView');

/* harmony default export */ const background_DataView = (background_DataView_DataView);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Promise.js



/* Built-in method references that are verified to be native. */
var background_Promise_Promise = pages_background_getNative(pages_background_root, 'Promise');

/* harmony default export */ const background_Promise = (background_Promise_Promise);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Set.js



/* Built-in method references that are verified to be native. */
var background_Set_Set = pages_background_getNative(pages_background_root, 'Set');

/* harmony default export */ const background_Set = (background_Set_Set);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_WeakMap.js



/* Built-in method references that are verified to be native. */
var background_WeakMap_WeakMap = pages_background_getNative(pages_background_root, 'WeakMap');

/* harmony default export */ const background_WeakMap = (background_WeakMap_WeakMap);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getTag.js








/** `Object#toString` result references. */
var background_getTag_mapTag = '[object Map]',
    background_getTag_objectTag = '[object Object]',
    background_promiseTag = '[object Promise]',
    background_getTag_setTag = '[object Set]',
    background_getTag_weakMapTag = '[object WeakMap]';

var background_getTag_dataViewTag = '[object DataView]';

/** Used to detect maps, sets, and weakmaps. */
var background_dataViewCtorString = pages_background_toSource(background_DataView),
    background_mapCtorString = pages_background_toSource(background_Map),
    background_promiseCtorString = pages_background_toSource(background_Promise),
    background_setCtorString = pages_background_toSource(background_Set),
    background_weakMapCtorString = pages_background_toSource(background_WeakMap);

/**
 * Gets the `toStringTag` of `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
var background_getTag = pages_background_baseGetTag;

// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((background_DataView && background_getTag(new background_DataView(new ArrayBuffer(1))) != background_getTag_dataViewTag) ||
    (background_Map && background_getTag(new background_Map) != background_getTag_mapTag) ||
    (background_Promise && background_getTag(background_Promise.resolve()) != background_promiseTag) ||
    (background_Set && background_getTag(new background_Set) != background_getTag_setTag) ||
    (background_WeakMap && background_getTag(new background_WeakMap) != background_getTag_weakMapTag)) {
  background_getTag = function(value) {
    var result = pages_background_baseGetTag(value),
        Ctor = result == background_getTag_objectTag ? value.constructor : undefined,
        ctorString = Ctor ? pages_background_toSource(Ctor) : '';

    if (ctorString) {
      switch (ctorString) {
        case background_dataViewCtorString: return background_getTag_dataViewTag;
        case background_mapCtorString: return background_getTag_mapTag;
        case background_promiseCtorString: return background_promiseTag;
        case background_setCtorString: return background_getTag_setTag;
        case background_weakMapCtorString: return background_getTag_weakMapTag;
      }
    }
    return result;
  };
}

/* harmony default export */ const pages_background_getTag = (background_getTag);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_initCloneArray.js
/** Used for built-in method references. */
var background_initCloneArray_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var background_initCloneArray_hasOwnProperty = background_initCloneArray_objectProto.hasOwnProperty;

/**
 * Initializes an array clone.
 *
 * @private
 * @param {Array} array The array to clone.
 * @returns {Array} Returns the initialized clone.
 */
function background_initCloneArray(array) {
  var length = array.length,
      result = new array.constructor(length);

  // Add properties assigned by `RegExp#exec`.
  if (length && typeof array[0] == 'string' && background_initCloneArray_hasOwnProperty.call(array, 'index')) {
    result.index = array.index;
    result.input = array.input;
  }
  return result;
}

/* harmony default export */ const pages_background_initCloneArray = (background_initCloneArray);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Uint8Array.js


/** Built-in value references. */
var background_Uint8Array_Uint8Array = pages_background_root.Uint8Array;

/* harmony default export */ const background_Uint8Array = (background_Uint8Array_Uint8Array);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_cloneArrayBuffer.js


/**
 * Creates a clone of `arrayBuffer`.
 *
 * @private
 * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
 * @returns {ArrayBuffer} Returns the cloned array buffer.
 */
function background_cloneArrayBuffer(arrayBuffer) {
  var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
  new background_Uint8Array(result).set(new background_Uint8Array(arrayBuffer));
  return result;
}

/* harmony default export */ const pages_background_cloneArrayBuffer = (background_cloneArrayBuffer);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_cloneDataView.js


/**
 * Creates a clone of `dataView`.
 *
 * @private
 * @param {Object} dataView The data view to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the cloned data view.
 */
function background_cloneDataView(dataView, isDeep) {
  var buffer = isDeep ? pages_background_cloneArrayBuffer(dataView.buffer) : dataView.buffer;
  return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}

/* harmony default export */ const pages_background_cloneDataView = (background_cloneDataView);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_cloneRegExp.js
/** Used to match `RegExp` flags from their coerced string values. */
var background_reFlags = /\w*$/;

/**
 * Creates a clone of `regexp`.
 *
 * @private
 * @param {Object} regexp The regexp to clone.
 * @returns {Object} Returns the cloned regexp.
 */
function background_cloneRegExp(regexp) {
  var result = new regexp.constructor(regexp.source, background_reFlags.exec(regexp));
  result.lastIndex = regexp.lastIndex;
  return result;
}

/* harmony default export */ const pages_background_cloneRegExp = (background_cloneRegExp);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_cloneSymbol.js


/** Used to convert symbols to primitives and strings. */
var background_symbolProto = background_Symbol ? background_Symbol.prototype : undefined,
    background_symbolValueOf = background_symbolProto ? background_symbolProto.valueOf : undefined;

/**
 * Creates a clone of the `symbol` object.
 *
 * @private
 * @param {Object} symbol The symbol object to clone.
 * @returns {Object} Returns the cloned symbol object.
 */
function background_cloneSymbol(symbol) {
  return background_symbolValueOf ? Object(background_symbolValueOf.call(symbol)) : {};
}

/* harmony default export */ const pages_background_cloneSymbol = (background_cloneSymbol);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_cloneTypedArray.js


/**
 * Creates a clone of `typedArray`.
 *
 * @private
 * @param {Object} typedArray The typed array to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the cloned typed array.
 */
function background_cloneTypedArray(typedArray, isDeep) {
  var buffer = isDeep ? pages_background_cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
  return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}

/* harmony default export */ const pages_background_cloneTypedArray = (background_cloneTypedArray);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_initCloneByTag.js






/** `Object#toString` result references. */
var background_initCloneByTag_boolTag = '[object Boolean]',
    background_initCloneByTag_dateTag = '[object Date]',
    background_initCloneByTag_mapTag = '[object Map]',
    background_initCloneByTag_numberTag = '[object Number]',
    background_initCloneByTag_regexpTag = '[object RegExp]',
    background_initCloneByTag_setTag = '[object Set]',
    background_initCloneByTag_stringTag = '[object String]',
    background_initCloneByTag_symbolTag = '[object Symbol]';

var background_initCloneByTag_arrayBufferTag = '[object ArrayBuffer]',
    background_initCloneByTag_dataViewTag = '[object DataView]',
    background_initCloneByTag_float32Tag = '[object Float32Array]',
    background_initCloneByTag_float64Tag = '[object Float64Array]',
    background_initCloneByTag_int8Tag = '[object Int8Array]',
    background_initCloneByTag_int16Tag = '[object Int16Array]',
    background_initCloneByTag_int32Tag = '[object Int32Array]',
    background_initCloneByTag_uint8Tag = '[object Uint8Array]',
    background_initCloneByTag_uint8ClampedTag = '[object Uint8ClampedArray]',
    background_initCloneByTag_uint16Tag = '[object Uint16Array]',
    background_initCloneByTag_uint32Tag = '[object Uint32Array]';

/**
 * Initializes an object clone based on its `toStringTag`.
 *
 * **Note:** This function only supports cloning values with tags of
 * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
 *
 * @private
 * @param {Object} object The object to clone.
 * @param {string} tag The `toStringTag` of the object to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the initialized clone.
 */
function background_initCloneByTag(object, tag, isDeep) {
  var Ctor = object.constructor;
  switch (tag) {
    case background_initCloneByTag_arrayBufferTag:
      return pages_background_cloneArrayBuffer(object);

    case background_initCloneByTag_boolTag:
    case background_initCloneByTag_dateTag:
      return new Ctor(+object);

    case background_initCloneByTag_dataViewTag:
      return pages_background_cloneDataView(object, isDeep);

    case background_initCloneByTag_float32Tag: case background_initCloneByTag_float64Tag:
    case background_initCloneByTag_int8Tag: case background_initCloneByTag_int16Tag: case background_initCloneByTag_int32Tag:
    case background_initCloneByTag_uint8Tag: case background_initCloneByTag_uint8ClampedTag: case background_initCloneByTag_uint16Tag: case background_initCloneByTag_uint32Tag:
      return pages_background_cloneTypedArray(object, isDeep);

    case background_initCloneByTag_mapTag:
      return new Ctor;

    case background_initCloneByTag_numberTag:
    case background_initCloneByTag_stringTag:
      return new Ctor(object);

    case background_initCloneByTag_regexpTag:
      return pages_background_cloneRegExp(object);

    case background_initCloneByTag_setTag:
      return new Ctor;

    case background_initCloneByTag_symbolTag:
      return pages_background_cloneSymbol(object);
  }
}

/* harmony default export */ const pages_background_initCloneByTag = (background_initCloneByTag);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseCreate.js


/** Built-in value references. */
var background_objectCreate = Object.create;

/**
 * The base implementation of `_.create` without support for assigning
 * properties to the created object.
 *
 * @private
 * @param {Object} proto The object to inherit from.
 * @returns {Object} Returns the new object.
 */
var background_baseCreate = (function() {
  function object() {}
  return function(proto) {
    if (!background_lodash_es_isObject(proto)) {
      return {};
    }
    if (background_objectCreate) {
      return background_objectCreate(proto);
    }
    object.prototype = proto;
    var result = new object;
    object.prototype = undefined;
    return result;
  };
}());

/* harmony default export */ const pages_background_baseCreate = (background_baseCreate);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_initCloneObject.js




/**
 * Initializes an object clone.
 *
 * @private
 * @param {Object} object The object to clone.
 * @returns {Object} Returns the initialized clone.
 */
function background_initCloneObject(object) {
  return (typeof object.constructor == 'function' && !pages_background_isPrototype(object))
    ? pages_background_baseCreate(pages_background_getPrototype(object))
    : {};
}

/* harmony default export */ const pages_background_initCloneObject = (background_initCloneObject);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsMap.js



/** `Object#toString` result references. */
var background_baseIsMap_mapTag = '[object Map]';

/**
 * The base implementation of `_.isMap` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
 */
function background_baseIsMap(value) {
  return background_lodash_es_isObjectLike(value) && pages_background_getTag(value) == background_baseIsMap_mapTag;
}

/* harmony default export */ const pages_background_baseIsMap = (background_baseIsMap);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isMap.js




/* Node.js helper references. */
var background_nodeIsMap = pages_background_nodeUtil && pages_background_nodeUtil.isMap;

/**
 * Checks if `value` is classified as a `Map` object.
 *
 * @static
 * @memberOf _
 * @since 4.3.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
 * @example
 *
 * _.isMap(new Map);
 * // => true
 *
 * _.isMap(new WeakMap);
 * // => false
 */
var background_isMap_isMap = background_nodeIsMap ? pages_background_baseUnary(background_nodeIsMap) : pages_background_baseIsMap;

/* harmony default export */ const background_lodash_es_isMap = (background_isMap_isMap);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsSet.js



/** `Object#toString` result references. */
var background_baseIsSet_setTag = '[object Set]';

/**
 * The base implementation of `_.isSet` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
 */
function background_baseIsSet(value) {
  return background_lodash_es_isObjectLike(value) && pages_background_getTag(value) == background_baseIsSet_setTag;
}

/* harmony default export */ const pages_background_baseIsSet = (background_baseIsSet);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isSet.js




/* Node.js helper references. */
var background_nodeIsSet = pages_background_nodeUtil && pages_background_nodeUtil.isSet;

/**
 * Checks if `value` is classified as a `Set` object.
 *
 * @static
 * @memberOf _
 * @since 4.3.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
 * @example
 *
 * _.isSet(new Set);
 * // => true
 *
 * _.isSet(new WeakSet);
 * // => false
 */
var background_isSet_isSet = background_nodeIsSet ? pages_background_baseUnary(background_nodeIsSet) : pages_background_baseIsSet;

/* harmony default export */ const background_lodash_es_isSet = (background_isSet_isSet);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseClone.js























/** Used to compose bitmasks for cloning. */
var background_CLONE_DEEP_FLAG = 1,
    background_CLONE_FLAT_FLAG = 2,
    background_CLONE_SYMBOLS_FLAG = 4;

/** `Object#toString` result references. */
var background_baseClone_argsTag = '[object Arguments]',
    background_baseClone_arrayTag = '[object Array]',
    background_baseClone_boolTag = '[object Boolean]',
    background_baseClone_dateTag = '[object Date]',
    background_baseClone_errorTag = '[object Error]',
    background_baseClone_funcTag = '[object Function]',
    background_baseClone_genTag = '[object GeneratorFunction]',
    background_baseClone_mapTag = '[object Map]',
    background_baseClone_numberTag = '[object Number]',
    background_baseClone_objectTag = '[object Object]',
    background_baseClone_regexpTag = '[object RegExp]',
    background_baseClone_setTag = '[object Set]',
    background_baseClone_stringTag = '[object String]',
    background_baseClone_symbolTag = '[object Symbol]',
    background_baseClone_weakMapTag = '[object WeakMap]';

var background_baseClone_arrayBufferTag = '[object ArrayBuffer]',
    background_baseClone_dataViewTag = '[object DataView]',
    background_baseClone_float32Tag = '[object Float32Array]',
    background_baseClone_float64Tag = '[object Float64Array]',
    background_baseClone_int8Tag = '[object Int8Array]',
    background_baseClone_int16Tag = '[object Int16Array]',
    background_baseClone_int32Tag = '[object Int32Array]',
    background_baseClone_uint8Tag = '[object Uint8Array]',
    background_baseClone_uint8ClampedTag = '[object Uint8ClampedArray]',
    background_baseClone_uint16Tag = '[object Uint16Array]',
    background_baseClone_uint32Tag = '[object Uint32Array]';

/** Used to identify `toStringTag` values supported by `_.clone`. */
var background_cloneableTags = {};
background_cloneableTags[background_baseClone_argsTag] = background_cloneableTags[background_baseClone_arrayTag] =
background_cloneableTags[background_baseClone_arrayBufferTag] = background_cloneableTags[background_baseClone_dataViewTag] =
background_cloneableTags[background_baseClone_boolTag] = background_cloneableTags[background_baseClone_dateTag] =
background_cloneableTags[background_baseClone_float32Tag] = background_cloneableTags[background_baseClone_float64Tag] =
background_cloneableTags[background_baseClone_int8Tag] = background_cloneableTags[background_baseClone_int16Tag] =
background_cloneableTags[background_baseClone_int32Tag] = background_cloneableTags[background_baseClone_mapTag] =
background_cloneableTags[background_baseClone_numberTag] = background_cloneableTags[background_baseClone_objectTag] =
background_cloneableTags[background_baseClone_regexpTag] = background_cloneableTags[background_baseClone_setTag] =
background_cloneableTags[background_baseClone_stringTag] = background_cloneableTags[background_baseClone_symbolTag] =
background_cloneableTags[background_baseClone_uint8Tag] = background_cloneableTags[background_baseClone_uint8ClampedTag] =
background_cloneableTags[background_baseClone_uint16Tag] = background_cloneableTags[background_baseClone_uint32Tag] = true;
background_cloneableTags[background_baseClone_errorTag] = background_cloneableTags[background_baseClone_funcTag] =
background_cloneableTags[background_baseClone_weakMapTag] = false;

/**
 * The base implementation of `_.clone` and `_.cloneDeep` which tracks
 * traversed objects.
 *
 * @private
 * @param {*} value The value to clone.
 * @param {boolean} bitmask The bitmask flags.
 *  1 - Deep clone
 *  2 - Flatten inherited properties
 *  4 - Clone symbols
 * @param {Function} [customizer] The function to customize cloning.
 * @param {string} [key] The key of `value`.
 * @param {Object} [object] The parent object of `value`.
 * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
 * @returns {*} Returns the cloned value.
 */
function background_baseClone(value, bitmask, customizer, key, object, stack) {
  var result,
      isDeep = bitmask & background_CLONE_DEEP_FLAG,
      isFlat = bitmask & background_CLONE_FLAT_FLAG,
      isFull = bitmask & background_CLONE_SYMBOLS_FLAG;

  if (customizer) {
    result = object ? customizer(value, key, object, stack) : customizer(value);
  }
  if (result !== undefined) {
    return result;
  }
  if (!background_lodash_es_isObject(value)) {
    return value;
  }
  var isArr = background_lodash_es_isArray(value);
  if (isArr) {
    result = pages_background_initCloneArray(value);
    if (!isDeep) {
      return pages_background_copyArray(value, result);
    }
  } else {
    var tag = pages_background_getTag(value),
        isFunc = tag == background_baseClone_funcTag || tag == background_baseClone_genTag;

    if (background_lodash_es_isBuffer(value)) {
      return pages_background_cloneBuffer(value, isDeep);
    }
    if (tag == background_baseClone_objectTag || tag == background_baseClone_argsTag || (isFunc && !object)) {
      result = (isFlat || isFunc) ? {} : pages_background_initCloneObject(value);
      if (!isDeep) {
        return isFlat
          ? pages_background_copySymbolsIn(value, pages_background_baseAssignIn(result, value))
          : pages_background_copySymbols(value, pages_background_baseAssign(result, value));
      }
    } else {
      if (!background_cloneableTags[tag]) {
        return object ? value : {};
      }
      result = pages_background_initCloneByTag(value, tag, isDeep);
    }
  }
  // Check for circular references and return its corresponding clone.
  stack || (stack = new pages_background_Stack);
  var stacked = stack.get(value);
  if (stacked) {
    return stacked;
  }
  stack.set(value, result);

  if (background_lodash_es_isSet(value)) {
    value.forEach(function(subValue) {
      result.add(background_baseClone(subValue, bitmask, customizer, subValue, value, stack));
    });
  } else if (background_lodash_es_isMap(value)) {
    value.forEach(function(subValue, key) {
      result.set(key, background_baseClone(subValue, bitmask, customizer, key, value, stack));
    });
  }

  var keysFunc = isFull
    ? (isFlat ? pages_background_getAllKeysIn : pages_background_getAllKeys)
    : (isFlat ? background_lodash_es_keysIn : background_lodash_es_keys);

  var props = isArr ? undefined : keysFunc(value);
  pages_background_arrayEach(props || value, function(subValue, key) {
    if (props) {
      key = subValue;
      subValue = value[key];
    }
    // Recursively populate clone (susceptible to call stack limits).
    pages_background_assignValue(result, key, background_baseClone(subValue, bitmask, customizer, key, value, stack));
  });
  return result;
}

/* harmony default export */ const pages_background_baseClone = (background_baseClone);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/cloneDeep.js


/** Used to compose bitmasks for cloning. */
var background_cloneDeep_CLONE_DEEP_FLAG = 1,
    background_cloneDeep_CLONE_SYMBOLS_FLAG = 4;

/**
 * This method is like `_.clone` except that it recursively clones `value`.
 *
 * @static
 * @memberOf _
 * @since 1.0.0
 * @category Lang
 * @param {*} value The value to recursively clone.
 * @returns {*} Returns the deep cloned value.
 * @see _.clone
 * @example
 *
 * var objects = [{ 'a': 1 }, { 'b': 2 }];
 *
 * var deep = _.cloneDeep(objects);
 * console.log(deep[0] === objects[0]);
 * // => false
 */
function background_cloneDeep(value) {
  return pages_background_baseClone(value, background_cloneDeep_CLONE_DEEP_FLAG | background_cloneDeep_CLONE_SYMBOLS_FLAG);
}

/* harmony default export */ const background_lodash_es_cloneDeep = (background_cloneDeep);

// EXTERNAL MODULE: ./node_modules/.pnpm/@adguard+tsurlfilter@3.3.3_@adguard+re2-wasm@1.2.0/node_modules/@adguard/tsurlfilter/dist/es/request-type.js
var background_request_type = __webpack_require__(55712);
;// ./node_modules/.pnpm/@adguard+tswebextension@3.1.0-alpha.3_@adguard+re2-wasm@1.2.0/node_modules/@adguard/tswebextension/dist/common/message-constants.js
/**
 * @file
 * This file contains constants for communication between background and content scripts.
 * This constants are separated from message.ts to reduce bundle size,
 * because rollup cannot tree-shake tswebextension library code.
 */
/**
 * Name of the message handler.
 * It is needed for determining specific tswebextension message from other messages.
 */
const background_MESSAGE_HANDLER_NAME = 'tsWebExtension';
/**
 * Message types for communication between background and content scripts.
 */
var background_message_constants_MessageType;
(function (MessageType) {
    MessageType["ProcessShouldCollapse"] = "processShouldCollapse";
    MessageType["GetCosmeticData"] = "getCosmeticData";
    MessageType["GetCookieRules"] = "getCookieRules";
    MessageType["SaveCookieLogEvent"] = "saveCookieLogEvent";
    MessageType["InitAssistant"] = "initAssistant";
    MessageType["CloseAssistant"] = "closeAssistant";
    MessageType["AssistantCreateRule"] = "assistantCreateRule";
    MessageType["SaveCssHitsStats"] = "saveCssHitsStats";
})(background_message_constants_MessageType || (background_message_constants_MessageType = {}));



;// ./node_modules/.pnpm/nanoid@5.1.5/node_modules/nanoid/non-secure/index.js
/* @ts-self-types="./index.d.ts" */
let background_urlAlphabet =
  'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
let background_non_secure_customAlphabet = (alphabet, defaultSize = 21) => {
  return (size = defaultSize) => {
    let id = ''
    let i = size | 0
    while (i--) {
      id += alphabet[(Math.random() * alphabet.length) | 0]
    }
    return id
  }
}
let background_non_secure_nanoid = (size = 21) => {
  let id = ''
  let i = size | 0
  while (i--) {
    id += background_urlAlphabet[(Math.random() * 64) | 0]
  }
  return id
}

;// ./node_modules/.pnpm/@adguard+tswebextension@3.1.0-alpha.3_@adguard+re2-wasm@1.2.0/node_modules/@adguard/tswebextension/dist/common/trackers-min.js
const background_rawCompaniesDb = {
    "timeUpdated": "2025-05-19T10:05:12.099Z",
    "categories": {
        "0": "audio_video_player",
        "1": "comments",
        "2": "customer_interaction",
        "3": "pornvertising",
        "4": "advertising",
        "5": "essential",
        "6": "site_analytics",
        "7": "social_media",
        "8": "misc",
        "9": "cdn",
        "10": "hosting",
        "11": "unknown",
        "12": "extensions",
        "13": "email",
        "14": "consent",
        "15": "telemetry",
        "101": "mobile_analytics"
    },
    "trackerDomains": {
        "mmtro.com": 6,
        "creative-serving.com": 4,
        "p161.net": 4,
        "analytics.163.com": 4,
        "1822direkt.de": 8,
        "1dmp.io": 4,
        "opecloud.com": 6,
        "1sponsor.com": 4,
        "tm.dentsu.de": 6,
        "1and1.com": 8,
        "1und1.de": 8,
        "uicdn.com": 8,
        "website-start.de": 8,
        "24-ads.com": 4,
        "247-inc.net": 2,
        "d1af033869koo7.cloudfront.net": 2,
        "counter.24log.ru": 6,
        "24smi.net": 8,
        "24smi.org": 8,
        "2leep.com": 4,
        "33across.com": 4,
        "3dstats.com": 6,
        "3gpp.org": 5,
        "3gppnetwork.org": 5,
        "4cdn.org": 8,
        "4finance.com": 2,
        "4wnet.com": 4,
        "d3aa0ztdn3oibi.cloudfront.net": 2,
        "51.la": 6,
        "5min.com": 0,
        "d1lm7kd3bd3yo9.cloudfront.net": 6,
        "grepdata.com": 6,
        "77tracking.com": 6,
        "swm.digital": 0,
        "7tv.de": 0,
        "888media.net": 4,
        "hit.8digits.com": 6,
        "94j7afz2nr.xyz": 12,
        "statsanalytics.com": 6,
        "a3cloud.net": 11,
        "a8.net": 4,
        "aaxads.com": 4,
        "abtasty.com": 6,
        "d1447tq2m68ekg.cloudfront.net": 6,
        "ab.co": 8,
        "abc-cdn.net.au": 8,
        "abc-host.net": 8,
        "abc-host.net.au": 8,
        "abc-prod.net.au": 8,
        "abc-stage.net.au": 8,
        "abc-test.net.au": 8,
        "abc.net.au": 8,
        "abcaustralia.net.au": 8,
        "abcradio.net.au": 8,
        "ablida.de": 4,
        "ablida.net": 4,
        "durasite.net": 4,
        "accengage.net": 4,
        "ax.xrea.com": 6,
        "accesstrade.net": 4,
        "agcdn.com": 4,
        "accmgr.com": 4,
        "p-td.com": 4,
        "acestream.net": 12,
        "acint.net": 6,
        "acloudimages.com": 4,
        "acpm.fr": 6,
        "acquia.com": 6,
        "ziyu.net": 7,
        "actionpay.ru": 4,
        "adnwb.ru": 4,
        "adonweb.ru": 4,
        "active-agent.com": 4,
        "trackcmp.net": 6,
        "active-srv02.de": 4,
        "active-tracking.de": 4,
        "activeconversion.com": 4,
        "a-cast.jp": 6,
        "activemeter.com": 4,
        "go.activengage.com": 2,
        "actonsoftware.com": 4,
        "acuityplatform.com": 4,
        "acxiom-online.com": 4,
        "acxiom.com": 4,
        "ad-blocker.org": 11,
        "ads.ad-center.com": 6,
        "ad-delivery.net": 11,
        "ad-sys.com": 4,
        "adagionet.com": 4,
        "ad2click.go2cloud.org": 4,
        "ad2games.com": 4,
        "ad360.vn": 4,
        "ads.ad4game.com": 4,
        "ad4mat.ar": 4,
        "ad4mat.at": 4,
        "ad4mat.be": 4,
        "ad4mat.bg": 4,
        "ad4mat.br": 4,
        "ad4mat.ch": 4,
        "ad4mat.co.uk": 4,
        "ad4mat.cz": 4,
        "ad4mat.de": 4,
        "ad4mat.dk": 4,
        "ad4mat.es": 4,
        "ad4mat.fi": 4,
        "ad4mat.fr": 4,
        "ad4mat.gr": 4,
        "ad4mat.hu": 4,
        "ad4mat.it": 4,
        "ad4mat.mx": 4,
        "ad4mat.net": 4,
        "ad4mat.nl": 4,
        "ad4mat.no": 4,
        "ad4mat.pl": 4,
        "ad4mat.ro": 4,
        "ad4mat.ru": 4,
        "ad4mat.se": 4,
        "ad4mat.tr": 4,
        "ad6.fr": 4,
        "ad6media.co.uk": 4,
        "ad6media.com": 4,
        "ad6media.es": 4,
        "ad6media.fr": 4,
        "a2dfp.net": 4,
        "addynamo.net": 4,
        "ebis.ne.jp": 4,
        "adlightning.com": 4,
        "admagnet.net": 4,
        "amimg.net": 4,
        "adspirit.de": 4,
        "adspirit.net": 4,
        "adac.de": 8,
        "adacado.com": 4,
        "ozonemedia.com": 4,
        "adrtx.net": 4,
        "adalliance.io": 4,
        "adalyser.com": 6,
        "adaos-ads.net": 4,
        "adap.tv": 4,
        "smrtlnks.com": 2,
        "yieldoptimizer.com": 4,
        "adnetwork.adasiaholdings.com": 4,
        "adbetclickin.pink": 4,
        "adbetnet.com": 4,
        "adblade.com": 4,
        "adbooth.com": 4,
        "adbooth.net": 4,
        "adbox.lv": 4,
        "adbrn.com": 6,
        "adbrite.com": 4,
        "adbull.com": 4,
        "adbutler.com": 4,
        "adc-serv.net": 4,
        "adc-srv.net": 4,
        "adcash.com": 4,
        "vuroll.in": 6,
        "acs86.com": 4,
        "csbew.com": 4,
        "irs09.com": 4,
        "adcito.com": 4,
        "adcitomedia.com": 4,
        "adclear.net": 4,
        "swift.adclerks.com": 4,
        "adclickmedia.com": 4,
        "adclickzone.go2cloud.org": 4,
        "ad-cloud.jp": 4,
        "admarvel.s3.amazonaws.com": 4,
        "ads.admarvel.com": 4,
        "adcolony.com": 4,
        "adrdgt.com": 4,
        "amgdgt.com": 4,
        "adcrowd.com": 4,
        "shop2market.com": 4,
        "addtocalendar.com": 2,
        "dpmsrv.com": 4,
        "yagiay.com": 4,
        "addfreestats.com": 6,
        "addinto.com": 2,
        "addshoppers.com": 7,
        "shop.pe": 7,
        "addthis.com": 4,
        "addthiscdn.com": 4,
        "addthisedge.com": 4,
        "b2btracking.addvalue.de": 6,
        "addyon.com": 4,
        "adeasy.ru": 4,
        "ipredictive.com": 6,
        "adengage.com": 4,
        "adespresso.com": 4,
        "adexcite.com": 4,
        "adextent.com": 4,
        "adf.ly": 4,
        "adfalcon.com": 4,
        "adfoc.us": 4,
        "js.adforgames.com": 4,
        "adform.net": 4,
        "adformdsp.net": 4,
        "seadform.net": 4,
        "adfox.ru": 4,
        "adwolf.ru": 4,
        "adfreestyle.pl": 4,
        "adfront.org": 4,
        "adfrontiers.com": 4,
        "adgebra.co.in": 4,
        "adgenie.co.uk": 4,
        "ad.adgile.com": 4,
        "ad.antventure.com": 4,
        "adglare.net": 4,
        "adsafety.net": 4,
        "smartadcheck.de": 4,
        "smartredirect.de": 4,
        "adgorithms.com": 4,
        "adgoto.com": 4,
        "adguard.com": 8,
        "adguard.app": 8,
        "adguard.info": 8,
        "adguard.io": 8,
        "adguard.org": 8,
        "adtidy.org": 8,
        "agrd.io": 8,
        "agrd.eu": 8,
        "adguard-dns.com": 8,
        "adguard-dns.io": 8,
        "adguard-vpn.com": 8,
        "adguard-vpn.online": 8,
        "adguardvpn.com": 8,
        "adhands.ru": 4,
        "adhese.be": 4,
        "adhese.com": 4,
        "adhese.net": 4,
        "adhitzads.com": 4,
        "adhood.com": 4,
        "afy11.net": 4,
        "cdn.adikteev.com": 4,
        "adimpact.com": 4,
        "adinch.com": 4,
        "adition.com": 4,
        "adjal.com": 4,
        "cdn.adjs.net": 4,
        "adjug.com": 4,
        "adjust.com": 101,
        "adj.st": 101,
        "adjust.io": 101,
        "adjust.net.in": 101,
        "adjust.world": 101,
        "apptrace.com": 101,
        "adk2.com": 4,
        "cdn.adsrvmedia.com": 4,
        "cdn.cdnrl.com": 4,
        "adklip.com": 4,
        "adkengage.com": 4,
        "adknowledge.com": 4,
        "bidsystem.com": 4,
        "blogads.com": 4,
        "cubics.com": 4,
        "yarpp.org": 4,
        "adsearch.adkontekst.pl": 4,
        "netsprint.eu": 4,
        "adlabs.ru": 4,
        "clickiocdn.com": 4,
        "luxup.ru": 4,
        "mixmarket.biz": 4,
        "ad-serverparc.nl": 4,
        "adimg.net": 4,
        "adlantis.jp": 4,
        "cdn.adless.io": 4,
        "api.publishers.adlive.io": 4,
        "adlooxtracking.com": 4,
        "adx1.com": 4,
        "adman.gr": 4,
        "adman.in.gr": 4,
        "admanmedia.com": 4,
        "admantx.com": 4,
        "admaster.net": 4,
        "cdnmaster.com": 4,
        "admaster.com.cn": 4,
        "admasterapi.com": 4,
        "admatic.com.tr": 4,
        "ads5.admatic.com.tr": 4,
        "cdn2.admatic.com.tr": 4,
        "lib-3pas.admatrix.jp": 4,
        "admaxserver.com": 4,
        "admaxim.com": 4,
        "admaya.in": 4,
        "admedia.com": 4,
        "adizio.com": 4,
        "admedo.com": 4,
        "admeira.ch": 4,
        "admeld.com": 4,
        "admeo.ru": 4,
        "admaym.com": 4,
        "atemda.com": 4,
        "admicro.vn": 4,
        "vcmedia.vn": 4,
        "admitad.com": 4,
        "admixer.net": 4,
        "admixer.com": 4,
        "admized.com": 8,
        "admo.tv": 4,
        "a.admob.com": 4,
        "mm.admob.com": 4,
        "mmv.admob.com": 4,
        "p.admob.com": 4,
        "run.admost.com": 4,
        "dmmotion.com": 4,
        "nspmotion.com": 4,
        "admulti.com": 4,
        "adnegah.net": 4,
        "adnet.vn": 4,
        "adnet.biz": 4,
        "adnet.de": 4,
        "adclick.lt": 4,
        "adnet.lt": 4,
        "ad.adnetwork.net": 4,
        "adnetworkperformance.com": 11,
        "adserver.adnexio.com": 4,
        "adnium.com": 4,
        "heias.com": 4,
        "smaclick.com": 4,
        "st-n.ads3-adnow.com": 4,
        "adnymics.com": 4,
        "adobe.com": 4,
        "demdex.net": 4,
        "everestjs.net": 4,
        "everesttech.net": 4,
        "adobe.io": 8,
        "scene7.com": 4,
        "adobedtm.com": 5,
        "2o7.net": 6,
        "du8783wkf05yr.cloudfront.net": 6,
        "hitbox.com": 6,
        "imageg.net": 6,
        "nedstat.com": 6,
        "omtrdc.net": 6,
        "sitestat.com": 6,
        "adobedc.net": 6,
        "adobelogin.com": 2,
        "adobetag.com": 4,
        "typekit.com": 5,
        "typekit.net": 5,
        "adocean.pl": 4,
        "dmtry.com": 4,
        "adomik.com": 4,
        "adcde.com": 4,
        "addlvr.com": 4,
        "adfeedstrk.com": 4,
        "adtrgt.com": 4,
        "bannertgt.com": 4,
        "cptgt.com": 4,
        "cpvfeed.com": 4,
        "cpvtgt.com": 4,
        "mygeek.com": 4,
        "popcde.com": 4,
        "sdfje.com": 4,
        "urtbk.com": 4,
        "adonion.com": 4,
        "t.adonly.com": 4,
        "adoperator.com": 4,
        "adoric.com": 6,
        "adorika.com": 4,
        "adorika.net": 4,
        "adosia.com": 4,
        "adotmob.com": 4,
        "adotube.com": 4,
        "adparlor.com": 4,
        "adparlour.com": 4,
        "a4p.adpartner.pro": 4,
        "adpeepshosted.com": 4,
        "adperfect.com": 4,
        "adperium.com": 4,
        "adpilot.at": 4,
        "erne.co": 4,
        "adplan-ds.com": 4,
        "advg.jp": 4,
        "c.p-advg.com": 4,
        "adplus.co.id": 4,
        "adprofex.com": 4,
        "ads2.bid": 4,
        "adframesrc.com": 4,
        "adserve.adpulse.ir": 4,
        "ads.adpv.com": 4,
        "adreactor.com": 4,
        "adrecord.com": 4,
        "adrecover.com": 4,
        "ad.vcm.jp": 4,
        "adresult.jp": 4,
        "adriver.ru": 4,
        "adroll.com": 4,
        "adrom.net": 4,
        "txt.eu": 4,
        "adru.net": 4,
        "adrunnr.com": 4,
        "adsame.com": 4,
        "adsbookie.com": 4,
        "adscale.de": 4,
        "adscience.nl": 4,
        "adsco.re": 4,
        "adsensecamp.com": 4,
        "adserverpub.com": 4,
        "online.adservicemedia.dk": 4,
        "adsfactor.net": 4,
        "ads.doclix.com": 4,
        "adskeeper.co.uk": 4,
        "ssp.adskom.com": 4,
        "adslot.com": 4,
        "adsnative.com": 4,
        "adsniper.ru": 4,
        "adspeed.com": 4,
        "adspeed.net": 4,
        "o333o.com": 4,
        "adstage-analytics.herokuapp.com": 4,
        "code.adstanding.com": 4,
        "adstars.co.id": 4,
        "ad-stir.com": 4,
        "4dsply.com": 4,
        "cdn.engine.adsupply.com": 4,
        "trklnks.com": 4,
        "adswizz.com": 4,
        "adtaily.com": 4,
        "adtaily.pl": 4,
        "adtarget.me": 4,
        "adtech.de": 6,
        "adtechus.com": 6,
        "adtegrity.net": 4,
        "adtpix.com": 4,
        "adtelligence.de": 4,
        "adentifi.com": 4,
        "adthink.com": 4,
        "advertstream.com": 4,
        "audienceinsights.net": 4,
        "adtiger.de": 4,
        "adtimaserver.vn": 4,
        "adtng.com": 3,
        "adtoma.com": 4,
        "adtomafusion.com": 4,
        "adtr02.com": 11,
        "track.adtraction.com": 4,
        "adtraxx.de": 4,
        "adtriba.com": 6,
        "adtrue.com": 4,
        "adtrustmedia.com": 4,
        "ad.adtube.ir": 4,
        "awempire.com": 3,
        "dditscdn.com": 3,
        "livejasmin.com": 3,
        "adultadworld.com": 3,
        "adworldmedia.com": 3,
        "adup-tech.com": 4,
        "advaction.ru": 4,
        "aucourant.info": 4,
        "schetu.net": 4,
        "dqfw2hlp4tfww.cloudfront.net": 4,
        "ahcdn.com": 9,
        "pix-cdn.org": 9,
        "s3.advarkads.com": 4,
        "adventori.com": 8,
        "adnext.fr": 4,
        "adverline.com": 4,
        "surinter.net": 4,
        "adversaldisplay.com": 4,
        "adversalservers.com": 4,
        "go.adversal.com": 4,
        "adverserve.net": 4,
        "ad.adverteerdirect.nl": 4,
        "adverticum.net": 4,
        "advertise.com": 4,
        "advertisespace.com": 4,
        "adsdk.com": 4,
        "advertising.com": 4,
        "aol.com": 4,
        "atwola.com": 4,
        "pictela.net": 4,
        "verizonmedia.com": 4,
        "advertlets.com": 4,
        "advertserve.com": 4,
        "advidi.com": 4,
        "am10.ru": 4,
        "am15.net": 4,
        "advolution.de": 4,
        "adwebster.com": 4,
        "ads.adwitserver.com": 4,
        "adworx.at": 4,
        "adworxs.net": 4,
        "adxion.com": 4,
        "adxpansion.com": 3,
        "ads.adxpose.com": 4,
        "event.adxpose.com": 4,
        "servedby.adxpose.com": 4,
        "adxprtz.com": 4,
        "adyoulike.com": 4,
        "omnitagjs.com": 4,
        "adzerk.net": 4,
        "adzly.com": 4,
        "aemediatraffic.com": 6,
        "hprofits.com": 6,
        "amxdt.com": 4,
        "aerisapi.com": 2,
        "aerisweather.com": 2,
        "affectv.com": 4,
        "go.affec.tv": 4,
        "hybridtheory.com": 4,
        "affilbox.com": 4,
        "affilbox.cz": 4,
        "track.affiliate-b.com": 4,
        "affiliate4you.nl": 4,
        "ads.affbuzzads.com": 4,
        "affiliatefuture.com": 4,
        "affiliatelounge.com": 4,
        "affiliation-france.com": 4,
        "affiliator.com": 4,
        "affiliaweb.fr": 4,
        "banner-rotation.com": 4,
        "webmasterplan.com": 4,
        "affimax.de": 4,
        "affinity.com": 4,
        "countby.com": 4,
        "affiz.net": 4,
        "pml.afftrack.com": 6,
        "afgr2.com": 3,
        "v2.afilio.com.br": 6,
        "afsanalytics.com": 6,
        "ads.aftonbladet.se": 4,
        "aftv-serving.bid": 4,
        "agkn.com": 4,
        "agilone.com": 6,
        "adview.pl": 4,
        "pingagenow.com": 7,
        "aimediagroup.com": 4,
        "advombat.ru": 4,
        "aidata.io": 4,
        "aim4media.com": 4,
        "muscache.com": 6,
        "musthird.com": 6,
        "airbrake.io": 4,
        "airpr.com": 6,
        "ab.airpush.com": 4,
        "abmr.net": 9,
        "akamai.net": 9,
        "akamaihd.net": 9,
        "akamaized.net": 9,
        "akstat.io": 9,
        "edgekey.net": 9,
        "edgesuite.net": 9,
        "imiclk.com": 9,
        "akadns.net": 9,
        "akamaiedge.net": 9,
        "akaquill.net": 9,
        "akamoihd.net": 12,
        "adn-d.sp.gmossp-sp.jp": 4,
        "akanoo.com": 6,
        "akavita.com": 4,
        "ads.albawaba.com": 4,
        "serve.albacross.com": 4,
        "aldi-international.com": 8,
        "alenty.com": 4,
        "alephd.com": 4,
        "alexametrics.com": 6,
        "d31qbv1cthcecs.cloudfront.net": 6,
        "d5nxst8fruw4z.cloudfront.net": 6,
        "alexa.com": 4,
        "algolia.com": 4,
        "algolia.net": 4,
        "algovid.com": 11,
        "alibaba.com": 8,
        "alicdn.com": 8,
        "aliapp.org": 8,
        "alibabachengdun.com": 8,
        "alibabausercontent.com": 8,
        "aliexpress.com": 8,
        "alikunlun.com": 8,
        "aliyuncs.com": 8,
        "alibabacloud.com": 10,
        "alibabadns.com": 10,
        "aliyun.com": 10,
        "ucweb.com": 8,
        "alipay.com": 2,
        "alipayobjects.com": 2,
        "websitealive.com": 2,
        "allegroimg.com": 8,
        "allegrostatic.com": 8,
        "allegrostatic.pl": 8,
        "ngacm.com": 8,
        "ngastatic.com": 8,
        "i.btg360.com.br": 6,
        "allo-pages.fr": 2,
        "allotraffic.com": 4,
        "edge.alluremedia.com.au": 4,
        "allyes.com": 4,
        "inputs.alooma.com": 4,
        "arena.altitude-arena.com": 4,
        "amadesa.com": 4,
        "amap.com": 2,
        "amazon.ca": 8,
        "amazon.co.jp": 8,
        "amazon.co.uk": 8,
        "amazon.com": 8,
        "amazon.de": 8,
        "amazon.es": 8,
        "amazon.fr": 8,
        "amazon.it": 8,
        "d3io1k5o0zdpqr.cloudfront.net": 8,
        "a2z.com": 8,
        "aamazoncognito.com": 8,
        "amazon-corp.com": 8,
        "amazon-dss.com": 8,
        "amazon.com.au": 8,
        "amazon.com.mx": 8,
        "amazon.dev": 8,
        "amazon.in": 8,
        "amazon.nl": 8,
        "amazon.sa": 8,
        "amazonbrowserapp.co.uk": 8,
        "amazonbrowserapp.es": 8,
        "amazoncrl.com": 8,
        "firetvcaptiveportal.com": 8,
        "ntp-fireos.com": 8,
        "amazon-adsystem.com": 4,
        "serving-sys.com": 4,
        "sizmek.com": 4,
        "assoc-amazon.ca": 4,
        "assoc-amazon.co.uk": 4,
        "assoc-amazon.com": 4,
        "assoc-amazon.de": 4,
        "assoc-amazon.fr": 4,
        "assoc-amazon.jp": 4,
        "images-amazon.com": 9,
        "media-amazon.com": 9,
        "ssl-images-amazon.com": 9,
        "amazontrust.com": 9,
        "associates-amazon.com": 9,
        "cloudfront.net": 10,
        "ota-cloudfront.net": 10,
        "axx-eu.amazon-adsystem.com": 4,
        "amazonpay.com": 2,
        "payments-amazon.com": 2,
        "amazonpay.in": 2,
        "aiv-cdn.net": 0,
        "aiv-delivery.net": 0,
        "amazonvideo.com": 0,
        "pv-cdn.net": 0,
        "primevideo.com": 0,
        "amazonaws.com": 10,
        "amazonwebservices.com": 10,
        "awsstatic.com": 10,
        "adnetwork.net.vn": 4,
        "adnetwork.vn": 4,
        "ambientplatform.vn": 4,
        "amgload.net": 11,
        "amoad.com": 4,
        "ad.amgdgt.com": 4,
        "ads.amgdgt.com": 4,
        "amobee.com": 4,
        "collective-media.net": 4,
        "amplitude.com": 6,
        "d24n15hnbwhuhn.cloudfront.net": 6,
        "ampproject.org": 8,
        "anametrix.net": 6,
        "ancestrycdn.com": 9,
        "ancoraplatform.com": 6,
        "android.com": 101,
        "anetwork.ir": 4,
        "aniview.com": 4,
        "a-ads.com": 4,
        "anormal-tracker.de": 6,
        "answerscloud.com": 1,
        "anthill.vn": 7,
        "ants.vn": 7,
        "rt.analytics.anvato.net": 0,
        "tkx2-prod.anvato.net": 0,
        "w3.cdn.anvato.net": 0,
        "player.anyclip.com": 0,
        "video-loader.com": 4,
        "aolcdn.com": 6,
        "isp.netscape.com": 6,
        "apa.at": 8,
        "apester.com": 4,
        "apicit.net": 4,
        "carrierzone.com": 6,
        "appcenter.ms": 5,
        "appcues.com": 2,
        "appdynamics.com": 6,
        "de8of677fyt0b.cloudfront.net": 6,
        "eum-appdynamics.com": 6,
        "jscdn.appier.net": 4,
        "apple.com": 8,
        "aaplimg.com": 8,
        "apple-cloudkit.com": 8,
        "apple-dns.net": 8,
        "apple-livephotoskit.com": 8,
        "apple-mapkit.com": 8,
        "apple.news": 8,
        "apzones.com": 8,
        "cdn-apple.com": 8,
        "icloud-content.com": 8,
        "icloud.com": 8,
        "icons.axm-usercontent-apple.com": 8,
        "itunes.com": 8,
        "me.com": 8,
        "mzstatic.com": 8,
        "safebrowsing.apple": 8,
        "safebrowsing.g.applimg.com": 8,
        "iadsdk.apple.com": 4,
        "applifier.com": 4,
        "assets.applovin.com": 4,
        "applovin.com": 4,
        "applvn.com": 4,
        "appmetrx.com": 4,
        "adnxs.com": 4,
        "adnxs.net": 4,
        "appsflyer.com": 101,
        "appsflyersdk.com": 101,
        "adne.tv": 4,
        "readserver.net": 4,
        "www.apture.com": 2,
        "arcpublishing.com": 6,
        "ard.de": 0,
        "areyouahuman.com": 6,
        "arkoselabs.com": 6,
        "art19.com": 4,
        "banners.advsnx.net": 4,
        "artlebedev.ru": 8,
        "ammadv.it": 4,
        "arubamediamarketing.it": 4,
        "cya2.net": 6,
        "asambeauty.com": 8,
        "ask.com": 7,
        "aspnetcdn.com": 9,
        "ads.assemblyexchange.com": 4,
        "cdn.astronomer.io": 6,
        "ati-host.net": 6,
        "aticdn.net": 6,
        "xiti.com": 6,
        "atedra.com": 4,
        "oadts.com": 4,
        "as00.estara.com": 4,
        "atgsvcs.com": 4,
        "adbureau.net": 4,
        "atdmt.com": 4,
        "atlassbx.com": 4,
        "track.roiservice.com": 4,
        "atl-paas.net": 2,
        "atlassian.com": 2,
        "atlassian.net": 2,
        "d12ramskps3070.cloudfront.net": 2,
        "bitbucket.org": 2,
        "jira.com": 2,
        "ss-inf.net": 2,
        "d1xfq2052q7thw.cloudfront.net": 9,
        "marketplace.atlassian.com": 9,
        "atomz.com": 2,
        "atsfi.de": 11,
        "cdn.attracta.com": 4,
        "locayta.com": 6,
        "ads.audience2media.com": 4,
        "qwobl.net": 4,
        "revsci.net": 4,
        "wunderloop.net": 4,
        "12mlbe.com": 4,
        "audiencesquare.com": 4,
        "ad.gt": 4,
        "audigent.com": 4,
        "hadronid.net": 4,
        "auditude.com": 0,
        "audtd.com": 4,
        "cdn.augur.io": 6,
        "aumago.com": 4,
        "clicktracks.com": 4,
        "ausgezeichnet.org": 2,
        "advertising.gov.au": 4,
        "auth0.com": 6,
        "ai.autoid.com": 6,
        "optimost.com": 4,
        "oc-track.autonomycloud.com": 4,
        "track.yieldsoftware.com": 4,
        "api.autopilothq.com": 4,
        "autoscout24.com": 8,
        "autoscout24.net": 8,
        "avail.net": 4,
        "analytics.avanser.com.au": 2,
        "avmws.com": 6,
        "avantlink.com": 4,
        "ads.avazu.net": 4,
        "avenseo.com": 4,
        "adspdbl.com": 0,
        "avocet.io": 8,
        "aweber.com": 4,
        "awin.com": 4,
        "awin1.com": 4,
        "perfb.com": 4,
        "ad.globe7.com": 4,
        "azadify.com": 4,
        "azure.com": 10,
        "azure.net": 10,
        "azurefd.net": 10,
        "trafficmanager.net": 10,
        "blob.core.windows.net": 8,
        "azureedge.net": 9,
        "b2bcontext.ru": 4,
        "b2bvideo.ru": 4,
        "babator.com": 6,
        "backbeatmedia.com": 4,
        "widgets.backtype.com": 4,
        "bahn.de": 8,
        "img-bahn.de": 8,
        "baidu.com": 4,
        "baidustatic.com": 4,
        "bdimg.com": 8,
        "bdstatic.com": 8,
        "baletingo.com": 11,
        "bangdom.com": 3,
        "widgets.bankrate.com": 4,
        "bannerconnect.net": 4,
        "bannerflow.com": 4,
        "bannerplay.com": 4,
        "cdn.bannersnack.com": 4,
        "dn3y71tq7jf07.cloudfront.net": 4,
        "getbarometer.s3.amazonaws.com": 2,
        "basilic.io": 6,
        "batanga.com": 4,
        "t4ft.de": 4,
        "bauernative.com": 4,
        "baur.de": 8,
        "baynote.net": 4,
        "bazaarvoice.com": 2,
        "bbci.co.uk": 10,
        "tracking.bd4travel.com": 4,
        "beopinion.com": 2,
        "bfmio.com": 4,
        "beaconads.com": 4,
        "beampulse.com": 4,
        "beanstalkdata.com": 4,
        "bebi.com": 4,
        "beeketing.com": 4,
        "beeline.ru": 4,
        "bidr.io": 4,
        "tracker.beezup.com": 4,
        "begun.ru": 4,
        "behavioralengine.com": 4,
        "belboon.de": 8,
        "cdn.belco.io": 2,
        "belstat.be": 6,
        "belstat.com": 6,
        "belstat.de": 6,
        "belstat.fr": 6,
        "belstat.nl": 6,
        "bemobile.ua": 10,
        "tag.benchplatform.com": 4,
        "betterttv.net": 7,
        "betweendigital.com": 4,
        "intencysrv.com": 4,
        "bid.run": 4,
        "bidgear.com": 6,
        "bidswitch.net": 4,
        "exe.bid": 4,
        "bttrack.com": 4,
        "bidtheatre.com": 4,
        "bidvertiser.com": 4,
        "bigmobileads.com": 4,
        "bigcommerce.com": 6,
        "bigmir.net": 6,
        "bigpoint-payment.com": 8,
        "bigpoint.com": 8,
        "bigpoint.net": 8,
        "bpcdn.net": 8,
        "bpsecure.com": 8,
        "bildstatic.de": 8,
        "ad-cdn.bilgin.pro": 4,
        "pixel.bilinmedia.net": 4,
        "bat.r.msn.com": 4,
        "bing.com": 4,
        "bing.net": 4,
        "virtualearth.net": 2,
        "binge.com.au": 0,
        "view.binlayer.com": 4,
        "widgets.binotel.com": 4,
        "esendra.fi": 4,
        "bitcoinplus.com": 2,
        "bit.ly": 6,
        "bitrix.de": 4,
        "bitrix.info": 4,
        "bitrix.ru": 4,
        "bitrix24.com": 4,
        "bitrix24.com.br": 4,
        "bitwarden.com": 8,
        "traffic.adxprts.com": 4,
        "jssr.jd.com": 4,
        "blau.de": 8,
        "bnmla.com": 4,
        "blismedia.com": 6,
        "blogad.com.tw": 4,
        "blogbang.com": 4,
        "www.blogcatalog.com": 2,
        "track.blogcounter.de": 6,
        "blogfoster.com": 8,
        "bloggerads.net": 4,
        "blogher.com": 4,
        "blogherads.com": 4,
        "blogimg.jp": 9,
        "blogsmithmedia.com": 8,
        "blogblog.com": 8,
        "blogger.com": 8,
        "blogspot.com": 8,
        "brcdn.com": 4,
        "brsrvr.com": 4,
        "brtstats.com": 4,
        "offerpoint.net": 4,
        "blueserving.com": 4,
        "blueconic.net": 6,
        "bluecore.com": 4,
        "triggeredmail.appspot.com": 4,
        "bkrtx.com": 4,
        "bluekai.com": 4,
        "adrevolver.com": 4,
        "bluelithium.com": 4,
        "bmmetrix.com": 4,
        "japanmetrix.jp": 4,
        "bluenewsupdate.info": 11,
        "bluestreak.com": 4,
        "bluetriangletech.com": 6,
        "btttag.com": 6,
        "bodelen.com": 4,
        "tracking.bol.com": 4,
        "qb.boldapps.net": 4,
        "secure.apps.shappify.com": 4,
        "boldchat.com": 2,
        "boltdns.net": 11,
        "bom.gov.au": 9,
        "ml314.com": 6,
        "bongacams.com": 3,
        "bonial.com": 2,
        "bonialconnect.com": 2,
        "bonialserviceswidget.de": 2,
        "boo-box.com": 4,
        "booking.com": 8,
        "bstatic.com": 8,
        "boostbox.com.br": 6,
        "boostervideo.ru": 0,
        "bootstrapcdn.com": 9,
        "borrango.com": 11,
        "scan.botscanner.com": 6,
        "boudja.com": 11,
        "bounceexchange.com": 4,
        "bouncex.com": 4,
        "bouncex.net": 4,
        "j.clickdensity.com": 6,
        "boxever.com": 4,
        "brainient.com": 4,
        "brainsins.com": 4,
        "d2xkqxdy6ewr93.cloudfront.net": 4,
        "mobileapptracking.com": 101,
        "app.link": 4,
        "branch.io": 4,
        "brandaffinity.net": 4,
        "go.cpmadvisors.com": 4,
        "optorb.com": 4,
        "brandmetrics.com": 4,
        "brandreachsys.com": 4,
        "rtbidder.net": 4,
        "brandwire.tv": 4,
        "branica.com": 4,
        "appboycdn.com": 6,
        "braze.com": 6,
        "brealtime.com": 4,
        "bridgetrack.com": 4,
        "brightcove.com": 0,
        "brightcove.net": 0,
        "analytics.brightedge.com": 4,
        "munchkin.brightfunnel.com": 6,
        "brightonclick.com": 4,
        "btrll.com": 4,
        "p.brilig.com": 4,
        "brillen.de": 8,
        "broadstreetads.com": 4,
        "bm23.com": 4,
        "brow.si": 4,
        "browser-statistik.de": 6,
        "browser-update.org": 2,
        "btncdn.com": 9,
        "in.bubblestat.com": 4,
        "brighteroption.com": 7,
        "bufferapp.com": 7,
        "bugherd.com": 2,
        "bugsnag.com": 6,
        "d2wy8f7a9ursnm.cloudfront.net": 6,
        "bulkhentai.com": 3,
        "bumlam.com": 11,
        "bunchbox.co": 6,
        "bf-ad.net": 4,
        "bf-tools.net": 4,
        "bstatic.de": 4,
        "burstbeacon.com": 4,
        "burstnet.com": 4,
        "burt.io": 4,
        "d3q6px0y2suh5n.cloudfront.net": 4,
        "rich-agent.s3.amazonaws.com": 4,
        "richmetrics.com": 4,
        "stats.businessol.com": 6,
        "bttn.io": 4,
        "buysellads.com": 4,
        "servedby-buysellads.com": 4,
        "buzzadexchange.com": 4,
        "buzzador.com": 7,
        "buzzfed.com": 2,
        "bwbx.io": 9,
        "bypass.jp": 4,
        "c1exchange.com": 4,
        "c3metrics.com": 6,
        "c3tag.com": 6,
        "c8.net.ua": 4,
        "cackle.me": 3,
        "d1cerpgff739r9.cloudfront.net": 4,
        "d1qpxk1wfeh8v1.cloudfront.net": 4,
        "callpage.io": 2,
        "callbackhunter.com": 2,
        "callmeasurement.com": 2,
        "callibri.ru": 4,
        "callrail.com": 2,
        "calltracking.ru": 2,
        "caltat.com": 2,
        "cam-content.com": 3,
        "camakaroda.com": 11,
        "s.edkay.com": 6,
        "canddi.com": 6,
        "canonical.com": 8,
        "canvas.net": 2,
        "canvasnetwork.com": 2,
        "du11hjcvx0uqb.cloudfront.net": 2,
        "kdata.fr": 6,
        "captora.com": 4,
        "edge.capturemedia.network": 4,
        "cdn.capturly.com": 6,
        "route.carambo.la": 4,
        "carbonads.com": 4,
        "carbonads.net": 4,
        "fusionads.net": 4,
        "cardinalcommerce.com": 6,
        "cardlytics.com": 6,
        "cdn.carrotquest.io": 6,
        "api.cartstack.com": 2,
        "caspion.com": 6,
        "t.castle.io": 2,
        "3gl.net": 6,
        "cbox.ws": 2,
        "adlog.com.com": 0,
        "cbsinteractive.com": 0,
        "dw.com.com": 0,
        "ccmbg.com": 4,
        "admission.net": 4,
        "cdn-net.com": 11,
        "cdn13.com": 8,
        "cdn77.com": 9,
        "cdn77.org": 9,
        "cdnetworks.com": 9,
        "cdnetworks.net": 9,
        "cdnnetwok.xyz": 12,
        "cdnondemand.org": 11,
        "cdnsure.com": 11,
        "cdnvideo.com": 9,
        "cdnwidget.com": 9,
        "cedexis-radar.net": 6,
        "cedexis-test.com": 6,
        "cedexis.com": 6,
        "cedexis.fastlylb.net": 6,
        "cedexis.net": 6,
        "celebrus.com": 6,
        "celtra.com": 0,
        "cendyn.adtrack.calls.net": 4,
        "centraltag.com": 4,
        "brand-server.com": 4,
        "speed-trap.nl": 6,
        "link.ixs1.net": 4,
        "hits.e.cl": 4,
        "certona.net": 4,
        "res-x.com": 4,
        "gsn.chameleon.ad": 4,
        "chango.ca": 4,
        "chango.com": 4,
        "channelintelligence.com": 4,
        "cptrack.de": 6,
        "channeladvisor.com": 4,
        "searchmarketing.com": 4,
        "channelfinder.net": 4,
        "chaordicsystems.com": 4,
        "chartbeat.com": 6,
        "chartbeat.net": 6,
        "chartboost.com": 4,
        "chaser.ru": 2,
        "cloud.chatbeacon.io": 2,
        "chatango.com": 2,
        "call.chatra.io": 2,
        "chaturbate.com": 3,
        "chatwing.com": 2,
        "checkmystats.com.au": 4,
        "chefkoch-cdn.de": 8,
        "chefkoch.de": 8,
        "tracker.chinmedia.vn": 4,
        "chinesean.com": 4,
        "chitika.net": 4,
        "choicestream.com": 4,
        "api.getchute.com": 5,
        "media.chute.io": 5,
        "iqcontentplatform.de": 6,
        "data.circulate.com": 6,
        "p.cityspark.com": 4,
        "cityads.ru": 4,
        "gameleads.ru": 4,
        "ciuvo.com": 12,
        "widget.civey.com": 2,
        "civicscience.com": 6,
        "ciweb.ciwebgroup.com": 4,
        "clcknads.pro": 3,
        "pulseradius.com": 4,
        "clearbit.com": 6,
        "clearsale.com.br": 4,
        "tag.clrstm.com": 4,
        "api.clerk.io": 4,
        "cleverpush.com": 6,
        "wzrkt.com": 6,
        "cleversite.ru": 2,
        "script.click360.io": 6,
        "clickandchat.com": 2,
        "software.clickback.com": 4,
        "hit.clickaider.com": 4,
        "clickaine.com": 4,
        "clickbank.net": 4,
        "cbproads.com": 4,
        "adtoll.com": 4,
        "clickbooth.com": 4,
        "clickboothlnk.com": 4,
        "clickcease.com": 2,
        "clickcertain.com": 4,
        "remarketstats.com": 4,
        "clickdesk.com": 2,
        "analytics.clickdimensions.com": 4,
        "clickequations.net": 4,
        "clickexperts.net": 4,
        "doublemax.net": 4,
        "clickinc.com": 4,
        "clickintext.net": 4,
        "clickky.biz": 4,
        "9nl.be": 4,
        "9nl.com": 4,
        "9nl.eu": 4,
        "9nl.it": 4,
        "9nl.me": 4,
        "clickmeter.com": 4,
        "clickonometrics.pl": 4,
        "clickpoint.com": 4,
        "clickpoint.it": 4,
        "clickprotector.com": 6,
        "clickreport.com": 6,
        "doogleonduty.com": 6,
        "ctn.go2cloud.org": 4,
        "clicksor.com": 4,
        "hatid.com": 4,
        "lzjl.com": 4,
        "myroitracking.com": 4,
        "clicktale.com": 6,
        "clicktale.net": 6,
        "clicktale.pantherssl.com": 6,
        "clicktalecdn.sslcs.cdngc.net": 6,
        "clicktripz.com": 4,
        "clickwinks.com": 4,
        "getclicky.com": 6,
        "staticstuff.net": 6,
        "clickyab.com": 4,
        "clicmanager.fr": 4,
        "eplayer.clipsyndicate.com": 4,
        "www.is1.clixgalore.com": 4,
        "clixmetrix.com": 4,
        "clixsense.com": 4,
        "cloud-media.fr": 4,
        "cloudflare.com": 9,
        "cloudflare.net": 9,
        "cloudflare-dm-cmpimg.com": 9,
        "cloudflare-dns.com": 9,
        "cloudflare-ipfs.com": 9,
        "cloudflare-quic.com": 9,
        "cloudflare-terms-of-service-abuse.com": 9,
        "cloudflare.tv": 9,
        "cloudflareaccess.com": 9,
        "cloudflareclient.com": 9,
        "cloudflareinsights.com": 9,
        "cloudflareok.com": 9,
        "cloudflareportal.com": 9,
        "cloudflareresolve.com": 9,
        "cloudflaressl.com": 9,
        "cloudflarestatus.com": 9,
        "cloudflarestream.com": 9,
        "pacloudflare.com": 9,
        "sn-cloudflare.com": 9,
        "videodelivery.net": 9,
        "cloudimg.io": 9,
        "cloudinary.com": 9,
        "clovenetwork.com": 4,
        "clustrmaps.com": 4,
        "cnbc.com": 8,
        "cnetcontent.com": 8,
        "cnstats.ru": 6,
        "cnzz.com": 6,
        "umeng.com": 6,
        "acc-hd.de": 4,
        "client.cobrowser.net": 2,
        "codeonclick.com": 11,
        "cogocast.net": 4,
        "coin-have.com": 4,
        "appsha1.cointraffic.io": 2,
        "authedmine.com": 8,
        "coin-hive.com": 8,
        "coinhive.com": 8,
        "coinurl.com": 4,
        "coll1onf.com": 11,
        "coll2onf.com": 11,
        "service.collarity.com": 4,
        "static.clmbtech.com": 4,
        "combotag.com": 4,
        "pdk.theplatform.com": 0,
        "theplatform.com": 0,
        "comm100.cn": 2,
        "comm100.com": 2,
        "cdn-cs.com": 4,
        "cdn.mercent.com": 4,
        "link.mercent.com": 4,
        "commercialvalue.org": 11,
        "afcyhf.com": 4,
        "anrdoezrs.net": 4,
        "apmebf.com": 4,
        "awltovhc.com": 4,
        "emjcd.com": 4,
        "ftjcfx.com": 4,
        "lduhtrp.net": 4,
        "qksz.net": 4,
        "tkqlhce.com": 4,
        "tqlkg.com": 4,
        "yceml.net": 4,
        "communicatorcorp.com": 4,
        "wowanalytics.co.uk": 6,
        "c-col.com": 6,
        "c.compete.com": 6,
        "complex.com": 4,
        "complexmedianetwork.com": 4,
        "comprigo.com": 12,
        "comscore.com": 6,
        "zqtk.net": 6,
        "conative.de": 4,
        "condenast.com": 8,
        "conduit-banners.com": 4,
        "conduit-data.com": 4,
        "conduit.com": 4,
        "confirmit.com": 4,
        "congstar.de": 4,
        "connatix.com": 4,
        "connected-by.connectad.io": 4,
        "cdn.connecto.io": 6,
        "connexity.net": 4,
        "cxt.ms": 4,
        "connextra.com": 4,
        "rs6.net": 4,
        "serverbid.com": 4,
        "contactatonce.com": 2,
        "adrolays.de": 4,
        "c-i.as": 4,
        "df-srv.de": 4,
        "d1uwd25yvxu96k.cloudfront.net": 4,
        "static.contactme.com": 4,
        "contaxe.com": 5,
        "content.ad": 4,
        "ingestion.contentinsights.com": 6,
        "contentexchange.me": 6,
        "ctfassets.net": 9,
        "contentpass.de": 6,
        "contentpass.net": 6,
        "contentsquare.net": 4,
        "d1aug3dv5magti.cloudfront.net": 6,
        "d39se0h2uvfakd.cloudfront.net": 6,
        "c-on-text.com": 4,
        "intext.contextad.pl": 4,
        "continum.net": 10,
        "s2.contribusourcesyndication.com": 4,
        "hits.convergetrack.com": 6,
        "fastclick.net": 4,
        "mediaplex.com": 4,
        "mplxtms.com": 4,
        "cm-commerce.com": 6,
        "media.conversio.com": 6,
        "c.conversionlogic.net": 6,
        "conversionruler.com": 4,
        "conversionsbox.com": 7,
        "conversionsondemand.com": 5,
        "ant.conversive.nl": 4,
        "convertexperiments.com": 6,
        "d3sjgucddk68ji.cloudfront.net": 2,
        "convertro.com": 4,
        "d1ivexoxmp59q7.cloudfront.net": 4,
        "conviva.com": 6,
        "cookieconsent.silktide.com": 5,
        "cookie-script.com": 5,
        "cookiebot.com": 5,
        "cookieq.com": 5,
        "lite.piclens.com": 2,
        "copacet.com": 4,
        "raasnet.com": 4,
        "coremotives.com": 4,
        "coull.com": 4,
        "cpmrocket.com": 4,
        "cpmprofit.com": 4,
        "cpmstar.com": 4,
        "captifymedia.com": 4,
        "cpx.to": 4,
        "cqcounter.com": 6,
        "cqq5id8n.com": 11,
        "cquotient.com": 6,
        "craftkeys.com": 4,
        "ads.crakmedia.com": 4,
        "craktraffic.com": 4,
        "crankyads.com": 4,
        "crashlytics.com": 101,
        "cetrk.com": 6,
        "crazyegg.com": 6,
        "dnn506yrbagrg.cloudfront.net": 6,
        "creafi-online-media.com": 4,
        "createjs.com": 9,
        "creativecommons.org": 8,
        "brandwatch.com": 6,
        "crimsonhexagon.com": 6,
        "hexagon-analytics.com": 6,
        "ctnsnet.com": 4,
        "crisp.chat": 2,
        "crisp.im": 2,
        "criteo.com": 4,
        "criteo.net": 4,
        "p.crm4d.com": 6,
        "crossengage.io": 6,
        "crosspixel.net": 4,
        "crsspxl.com": 4,
        "crosssell.info": 4,
        "crossss.com": 4,
        "widget.crowdignite.com": 4,
        "static.crowdscience.com": 4,
        "ss.crowdprocess.com": 2,
        "our.glossip.nl": 7,
        "widget.breakingburner.com": 7,
        "widget.crowdynews.com": 7,
        "searchg2.crownpeak.net": 5,
        "snippet.omm.crownpeak.com": 5,
        "cryptoloot.pro": 4,
        "ctnetwork.hu": 4,
        "adzhub.com": 4,
        "data.withcubed.com": 6,
        "cuelinks.com": 4,
        "cdn.cupinteractive.com": 4,
        "curse.com": 8,
        "cursecdn.com": 9,
        "assets.customer.io": 2,
        "widget.customerly.io": 2,
        "cxense.com": 4,
        "cxo.name": 6,
        "cyberwing.co.jp": 4,
        "cybersource.com": 6,
        "cygnus.com": 4,
        "da-ads.com": 4,
        "dailymail.co.uk": 8,
        "dailymotion.com": 8,
        "dailymotionbus.com": 8,
        "dm-event.net": 8,
        "dmcdn.net": 8,
        "dmxleo.com": 4,
        "ds1.nl": 4,
        "dantrack.net": 4,
        "dmclick.cn": 4,
        "tags.dashboardad.net": 4,
        "datacaciques.com": 6,
        "datacoral.com": 4,
        "abandonaid.com": 6,
        "datacrushers.com": 6,
        "datadome.co": 6,
        "optimahub.com": 6,
        "supert.ag": 5,
        "inextaction.net": 4,
        "nexac.com": 4,
        "datamind.ru": 4,
        "datatables.net": 2,
        "adunits.datawrkz.com": 4,
        "dataxpand.script.ag": 4,
        "tc.dataxpand.com": 4,
        "w55c.net": 4,
        "datds.net": 12,
        "pro-market.net": 4,
        "displaymarketplace.com": 4,
        "davebestdeals.com": 12,
        "dawandastatic.com": 8,
        "dc-storm.com": 4,
        "h4k5.com": 4,
        "stormcontainertag.com": 4,
        "stormiq.com": 4,
        "dcbap.com": 12,
        "dcmn.com": 4,
        "statslogger.rocket.persgroep.cloud": 4,
        "deadlinefunnel.com": 6,
        "cc2.dealer.com": 6,
        "d9lq0o81skkdj.cloudfront.net": 6,
        "esm1.net": 6,
        "static.dealer.com": 6,
        "decibelinsight.net": 6,
        "ads.dedicatedmedia.com": 4,
        "api.deep.bi": 6,
        "deepintent.com": 4,
        "defpush.com": 11,
        "deichmann.com": 4,
        "vxml4.delacon.com.au": 6,
        "tracking.percentmobile.com": 6,
        "adaction.se": 4,
        "de17a.com": 4,
        "deluxe.script.ag": 6,
        "delvenetworks.com": 7,
        "company-target.com": 4,
        "demandbase.com": 4,
        "dmd53.com": 4,
        "dmtracker.com": 4,
        "deqwas.net": 6,
        "devatics.com": 2,
        "developermedia.com": 4,
        "dapxl.com": 8,
        "deviantart.net": 8,
        "my.blueadvertise.com": 4,
        "dgm-au.com": 4,
        "s2d6.com": 4,
        "d31y97ze264gaa.cloudfront.net": 6,
        "d3von6il1wr7wo.cloudfront.net": 4,
        "dianomi.com": 4,
        "dianomioffers.co.uk": 4,
        "tag.didit.com": 4,
        "track.did-it.com": 4,
        "privacy-center.org": 5,
        "digg.com": 2,
        "digicert.com": 5,
        "phicdn.net": 5,
        "digidip.net": 4,
        "digiglitzmarketing.go2cloud.org": 6,
        "wtp101.com": 4,
        "digioh.com": 4,
        "lightboxcdn.com": 4,
        "digitalgov.gov": 6,
        "cookiereports.com": 5,
        "adtag.cc": 4,
        "adready.com": 4,
        "adreadytractions.com": 4,
        "cpxinteractive.com": 4,
        "directtrack.com": 4,
        "onenetworkdirect.net": 4,
        "track.digitalriver.com": 4,
        "dwin1.com": 4,
        "digiteka.net": 4,
        "ultimedia.com": 4,
        "digitru.st": 4,
        "widget.dihitt.com.br": 7,
        "dimml.io": 8,
        "keywordsconnect.com": 4,
        "directadvert.ru": 4,
        "directrev.com": 4,
        "discordapp.com": 2,
        "disneyplus.com": 0,
        "bamgrid.com": 0,
        "dssedge.com": 0,
        "dssott.com": 0,
        "d81mfvml8p5ml.cloudfront.net": 4,
        "disqus.com": 1,
        "disquscdn.com": 1,
        "disqusads.com": 4,
        "distiltag.com": 5,
        "districtm.ca": 4,
        "districtm.io": 4,
        "jsrdn.com": 6,
        "div.show": 12,
        "stats.vertriebsassistent.de": 6,
        "tag.divvit.com": 6,
        "d-msquared.com": 4,
        "and.co.uk": 8,
        "dmm.co.jp": 3,
        "ctret.de": 8,
        "toolbar.dockvine.com": 2,
        "awecr.com": 0,
        "fwbntw.com": 0,
        "s.dogannet.tv": 4,
        "domain.glass": 8,
        "www.domodomain.com": 6,
        "donation-tools.org": 12,
        "doofinder.com": 2,
        "embed.doorbell.io": 5,
        "dotandad.com": 4,
        "trackedlink.net": 2,
        "dotmetrics.net": 6,
        "dotomi.com": 4,
        "dtmc.com": 4,
        "dtmpub.com": 4,
        "double.net": 4,
        "2mdn.net": 4,
        "doublepimp.com": 3,
        "doublepimpssl.com": 3,
        "redcourtside.com": 3,
        "xeontopa.com": 3,
        "zerezas.com": 3,
        "doubleverify.com": 4,
        "wrating.com": 6,
        "adsymptotic.com": 4,
        "dreame.tech": 8,
        "dreametech.com": 8,
        "dreamlab.pl": 4,
        "drift.com": 2,
        "js.driftt.com": 2,
        "getdrip.com": 2,
        "dropbox.com": 2,
        "dropboxstatic.com": 2,
        "z5x.net": 4,
        "dsp-rambler.ru": 4,
        "m6d.com": 4,
        "media6degrees.com": 4,
        "dtscout.com": 4,
        "dd-cdn.multiscreensite.com": 4,
        "px.multiscreensite.com": 4,
        "cdn-0.d41.co": 6,
        "cn01.dwstat.cn": 6,
        "dynad.net": 4,
        "dyntrk.com": 4,
        "dyntracker.de": 8,
        "media01.eu": 8,
        "content.dl-rms.com": 4,
        "dlqm.net": 4,
        "questionmarket.com": 4,
        "dynamicyield.com": 5,
        "beacons.hottraffic.nl": 4,
        "dynatrace.com": 6,
        "dyncdn.me": 11,
        "e-planning.net": 4,
        "eadv.it": 4,
        "eanalyzer.de": 11,
        "early-birds.fr": 4,
        "cdn.earnify.com": 4,
        "earnify.com": 6,
        "easyads.bg": 4,
        "easylist.club": 11,
        "classistatic.de": 4,
        "ebay-us.com": 4,
        "ebay.com": 4,
        "ebay.de": 4,
        "ebayclassifiedsgroup.com": 4,
        "ebaycommercenetwork.com": 4,
        "ebaydesc.com": 4,
        "ebayimg.com": 4,
        "ebayrtm.com": 4,
        "ebaystatic.com": 4,
        "ad.about.co.kr": 4,
        "adcheck.about.co.kr": 4,
        "adn.ebay.com": 4,
        "beead.co.uk": 4,
        "beead.fr": 4,
        "beead.net": 4,
        "ebuzzing.com": 4,
        "ebz.io": 4,
        "echoenabled.com": 4,
        "eclick.vn": 4,
        "econda-monitor.de": 6,
        "eco-tag.jp": 4,
        "alphacdn.net": 9,
        "edg.io": 9,
        "edgecast.com": 9,
        "edgecastcdn.net": 9,
        "edgecastdns.net": 9,
        "sigmacdn.net": 9,
        "ecustomeropinions.com": 4,
        "effectivemeasure.net": 4,
        "effiliation.com": 4,
        "egain.net": 2,
        "cloud-emea.analytics-egain.com": 6,
        "ehi-siegel.de": 2,
        "ekmpinpoint.com": 6,
        "ekomi.de": 1,
        "elasticad.net": 4,
        "elasticbeanstalk.com": 6,
        "cloudcell.com": 2,
        "ea.com": 2,
        "eamobile.com": 2,
        "element.io": 7,
        "riot.im": 7,
        "elicitapp.com": 4,
        "eloqua.com": 4,
        "en25.com": 4,
        "eluxer.net": 12,
        "tracker.emailaptitude.com": 4,
        "tag.email-attitude.com": 4,
        "app.emarketeer.com": 4,
        "embed.ly": 6,
        "embedly.com": 6,
        "emediate.dk": 4,
        "emediate.eu": 4,
        "emediate.se": 4,
        "emetriq.de": 4,
        "e2ma.net": 4,
        "adinsight.co.kr": 4,
        "colbenson.es": 4,
        "emsmobile.de": 8,
        "sitecompass.com": 4,
        "enectoanalytics.com": 6,
        "trk.enecto.com": 6,
        "track.engagesciences.com": 6,
        "widget.engageya.com": 4,
        "engagio.com": 6,
        "engineseeker.com": 4,
        "enquisite.com": 4,
        "adtlgc.com": 4,
        "ats.tumri.net": 4,
        "ensighten.com": 5,
        "envolve.com": 2,
        "cdn.callbackkiller.com": 2,
        "email-reflex.com": 4,
        "epicgameads.com": 4,
        "trafficmp.com": 4,
        "adshost1.com": 4,
        "adshost2.com": 4,
        "epom.com": 4,
        "epoq.de": 2,
        "banzaiadv.it": 4,
        "eproof.com": 6,
        "equitystory.com": 6,
        "eqads.com": 4,
        "ero-advertising.com": 3,
        "eroadvertising.com": 3,
        "d15qhc0lu1ghnk.cloudfront.net": 6,
        "errorception.com": 6,
        "eshopcomp.com": 12,
        "espncdn.com": 9,
        "esprit.de": 8,
        "cybermonitor.com": 6,
        "estat.com": 6,
        "teste-s3-maycon.s3.amazonaws.com": 4,
        "etahub.com": 11,
        "etargetnet.com": 4,
        "ethn.io": 4,
        "pages.etology.com": 4,
        "sa.etp-prod.com": 6,
        "etracker.com": 6,
        "etracker.de": 6,
        "sedotracker.com": 6,
        "etrigue.com": 4,
        "etsystatic.com": 9,
        "eulerian.net": 6,
        "eultech.fnac.com": 6,
        "ew3.io": 6,
        "euroads.dk": 4,
        "euroads.fi": 4,
        "euroads.no": 4,
        "newpromo.europacash.com": 4,
        "tracker.euroweb.net": 4,
        "apptegic.com": 2,
        "evergage.com": 2,
        "listener.everstring.com": 6,
        "waterfrontmedia.com": 7,
        "betrad.com": 5,
        "evidon.com": 5,
        "evisitanalyst.com": 4,
        "evisitcs.com": 4,
        "websiteperform.com": 4,
        "ads.exactdrive.com": 4,
        "exactag.com": 6,
        "exelator.com": 4,
        "dynamicoxygen.com": 4,
        "exitjunction.com": 4,
        "exdynsrv.com": 3,
        "exoclick.com": 3,
        "exosrv.com": 3,
        "exoticads.com": 3,
        "expedia.com": 8,
        "trvl-px.com": 8,
        "eccmp.com": 8,
        "audienceiq.com": 4,
        "techlightenment.com": 4,
        "expo-max.com": 4,
        "server.exposebox.com": 4,
        "sf.exposebox.com": 2,
        "express.co.uk": 8,
        "d1lp05q4sghme9.cloudfront.net": 2,
        "extreme-dm.com": 6,
        "eyenewton.ru": 2,
        "eyeota.net": 4,
        "eyereturn.com": 4,
        "eyeviewads.com": 4,
        "ezakus.net": 4,
        "f11-ads.com": 4,
        "facebook.com": 4,
        "facebook.net": 4,
        "graph.facebook.com": 4,
        "fbcdn.net": 9,
        "fbsbx.com": 9,
        "facetz.net": 4,
        "adsfac.eu": 4,
        "adsfac.net": 4,
        "adsfac.sg": 4,
        "adsfac.us": 4,
        "faktor.io": 6,
        "thefancy.com": 7,
        "d1q7pknmpq2wkm.cloudfront.net": 4,
        "fap.to": 8,
        "farlightgames.com": 8,
        "fastly-insights.com": 6,
        "fastly.net": 9,
        "fastlylb.net": 9,
        "fastly-edge.com": 9,
        "fastly-masque.net": 9,
        "fastpic.ru": 10,
        "fmpub.net": 4,
        "fby.s3.amazonaws.com": 2,
        "feedbackify.com": 2,
        "feedburner.com": 4,
        "feedify.de": 7,
        "feedjit.com": 4,
        "log.feedjit.com": 4,
        "tracking.feedperfect.com": 4,
        "feedsportal.com": 4,
        "feefo.com": 2,
        "fidelity-media.com": 4,
        "fiksu.com": 4,
        "filamentapp.s3.amazonaws.com": 4,
        "fileserve.xyz": 10,
        "tools.financeads.net": 4,
        "tracker.financialcontent.com": 4,
        "findizer.fr": 8,
        "findologic.com": 2,
        "app-measurement.com": 101,
        "fcm.googleapis.com": 101,
        "firebase.com": 101,
        "firebase.google.com": 101,
        "firebase.googleapis.com": 101,
        "firebaseapp.com": 101,
        "firebaseappcheck.googleapis.com": 101,
        "firebasedynamiclinks-ipv4.googleapis.com": 101,
        "firebasedynamiclinks-ipv6.googleapis.com": 101,
        "firebasedynamiclinks.googleapis.com": 101,
        "firebaseinappmessaging.googleapis.com": 101,
        "firebaseinstallations.googleapis.com": 101,
        "firebaselogging-pa.googleapis.com": 101,
        "firebaselogging.googleapis.com": 101,
        "firebaseperusertopics-pa.googleapis.com": 101,
        "firebaseremoteconfig.googleapis.com": 101,
        "firebaseio.com": 8,
        "firstimpression.io": 4,
        "fitanalytics.com": 6,
        "fivetran.com": 6,
        "flagads.net": 4,
        "flagcounter.com": 4,
        "flashnews.com.au": 0,
        "flashtalking.com": 4,
        "flattr.com": 7,
        "flexlinks.com": 4,
        "linkoffers.net": 4,
        "flickr.com": 7,
        "staticflickr.com": 7,
        "lflipboard.com": 6,
        "flipboard.com": 6,
        "flite.com": 4,
        "flixcdn.com": 9,
        "flix360.com": 8,
        "flixcar.com": 8,
        "flocktory.com": 6,
        "flowplayer.org": 4,
        "adingo.jp": 4,
        "clicken.us": 4,
        "strcst.net": 4,
        "fluidads.co": 4,
        "fluidsurveys.com": 2,
        "cdn.flurry.com": 101,
        "data.flurry.com": 101,
        "flurry.com": 101,
        "flx1.com": 4,
        "flxpxl.com": 4,
        "api.flyertown.ca": 6,
        "adservinghost.com": 4,
        "adservinginternational.com": 4,
        "special.matchtv.ru": 6,
        "kavijaseuranta.fi": 2,
        "fontawesome.com": 9,
        "foodieblogroll.com": 7,
        "footprintlive.com": 4,
        "footprintdns.com": 11,
        "forcetrac.com": 2,
        "fqsecure.com": 4,
        "fqtag.com": 4,
        "securepaths.com": 4,
        "4seeresults.com": 5,
        "foresee.com": 5,
        "cdn-static.formisimo.com": 4,
        "forter.com": 4,
        "fortlachanhecksof.info": 11,
        "platform.foursquare.com": 4,
        "fout.jp": 4,
        "fimserve.com": 4,
        "foxsports.com.au": 0,
        "fncstatic.com": 9,
        "cdn.foxpush.net": 4,
        "foxpush.com": 4,
        "foxtel.com.au": 0,
        "foxtelgroupcdn.net.au": 0,
        "foxydeal.com": 12,
        "yabidos.com": 4,
        "besucherstatistiken.com": 6,
        "compteurdevisite.com": 6,
        "contadorvisitasgratis.com": 6,
        "contatoreaccessi.com": 6,
        "freecounterstat.com": 6,
        "statcounterfree.com": 6,
        "webcontadores.com": 6,
        "fastonlineusers.com": 6,
        "fastwebcounter.com": 6,
        "freeonlineusers.com": 6,
        "atoomic.com": 6,
        "free-pagerank.com": 6,
        "freedom.com": 6,
        "freegeoip.net": 6,
        "freenet.de": 4,
        "freent.de": 4,
        "freeview.com": 0,
        "freeview.com.au": 0,
        "freeviewaustralia.tv": 0,
        "fwmrm.net": 4,
        "heimdall.fresh8.co": 6,
        "d36mpcpuzc4ztk.cloudfront.net": 2,
        "freshdesk.com": 2,
        "freshplum.com": 4,
        "friendbuy.com": 6,
        "friendfeed.com": 7,
        "adultfriendfinder.com": 3,
        "amigos.com": 3,
        "board-books.com": 3,
        "cams.com": 3,
        "facebookofsex.com": 3,
        "getiton.com": 3,
        "nostringsattached.com": 3,
        "pop6.com": 3,
        "streamray.com": 3,
        "inpref.com": 4,
        "inpref.s3-external-3.amazonaws.com": 4,
        "inpref.s3.amazonaws.com": 4,
        "adflan.com": 4,
        "fruitflan.com": 4,
        "fstrk.net": 6,
        "cookie.fuel451.com": 4,
        "fullstory.com": 6,
        "track.funnelytics.io": 6,
        "angsrvr.com": 4,
        "fyber.com": 4,
        "game-advertising-online.com": 4,
        "gameanalytics.com": 101,
        "gamedistribution.com": 8,
        "gamerdna.com": 7,
        "gannett-cdn.com": 0,
        "gaug.es": 6,
        "gpm-digital.com": 0,
        "js.gb-world.net": 7,
        "gdeslon.ru": 4,
        "gdmdigital.com": 4,
        "gntm.geeen.co.jp": 6,
        "lpomax.net": 6,
        "gemius.pl": 4,
        "generaltracking.de": 11,
        "genesismedia.com": 4,
        "gssprt.jp": 4,
        "rsvpgenius.com": 6,
        "genoo.com": 4,
        "js.geoads.com": 4,
        "geolify.com": 4,
        "geoplugin.net": 6,
        "geotrust.com": 5,
        "geovisite.com": 6,
        "gestionpub.com": 4,
        "app.getresponse.com": 2,
        "getsitecontrol.com": 4,
        "getconversion.net": 2,
        "widgets.getglue.com": 0,
        "adhigh.net": 4,
        "static.getkudos.me": 1,
        "yottos.com": 4,
        "gsfn.us": 1,
        "gettyimages.com": 8,
        "sensic.net": 4,
        "gfycat.com": 7,
        "a.giantrealm.com": 4,
        "videostat.com": 4,
        "gigaonclick.com": 4,
        "analytics.gigyahosting1.com": 6,
        "gigcount.com": 6,
        "gigya.com": 6,
        "service.giosg.com": 6,
        "giphy.com": 7,
        "giraff.io": 4,
        "github.com": 2,
        "githubassets.com": 2,
        "githubusercontent.com": 2,
        "ghcr.io": 2,
        "github.blog": 2,
        "github.dev": 2,
        "octocaptcha.com": 2,
        "githubapp.com": 2,
        "github.io": 10,
        "aff3.gittigidiyor.com": 4,
        "gittip.com": 2,
        "sitest.jp": 6,
        "glganltcs.space": 12,
        "globalwebindex.net": 6,
        "globalnotifier.com": 11,
        "globalsign.com": 8,
        "ad.globaltakeoff.net": 4,
        "glomex.cloud": 0,
        "glomex.com": 0,
        "glotgrx.com": 11,
        "a.gmdelivery.com": 4,
        "gmail.com": 13,
        "ad.atown.jp": 4,
        "gmx.net": 8,
        "gmxpro.net": 8,
        "go.com": 8,
        "affiliate.godaddy.com": 4,
        "trafficfacts.com": 6,
        "seal.godaddy.com": 5,
        "tracking.godatafeed.com": 6,
        "counter.goingup.com": 6,
        "axf8.net": 6,
        "goodadvert.ru": 4,
        "google.at": 4,
        "google.be": 4,
        "google.ca": 4,
        "google.ch": 4,
        "google.co.id": 4,
        "google.co.in": 4,
        "google.co.jp": 4,
        "google.co.ma": 4,
        "google.co.th": 4,
        "google.co.uk": 4,
        "google.com": 4,
        "google.com.ar": 4,
        "google.com.au": 4,
        "google.com.br": 4,
        "google.com.mx": 4,
        "google.com.tr": 4,
        "google.com.tw": 4,
        "google.com.ua": 4,
        "google.cz": 4,
        "google.de": 4,
        "google.dk": 4,
        "google.dz": 4,
        "google.es": 4,
        "google.fi": 4,
        "google.fr": 4,
        "google.gr": 4,
        "google.hu": 4,
        "google.ie": 4,
        "google.it": 4,
        "google.nl": 4,
        "google.no": 4,
        "google.pl": 4,
        "google.pt": 4,
        "google.ro": 4,
        "google.rs": 4,
        "google.ru": 4,
        "google.se": 4,
        "google.tn": 4,
        "1e100.net": 4,
        "agnss.goog": 4,
        "channel.status.request.url": 4,
        "g.cn": 4,
        "g.co": 4,
        "google.ad": 4,
        "google.ae": 4,
        "google.al": 4,
        "google.am": 4,
        "google.as": 4,
        "google.az": 4,
        "google.ba": 4,
        "google.bf": 4,
        "google.bg": 4,
        "google.bi": 4,
        "google.bj": 4,
        "google.bs": 4,
        "google.bt": 4,
        "google.by": 4,
        "google.cat": 4,
        "google.cd": 4,
        "google.cf": 4,
        "google.cg": 4,
        "google.ci": 4,
        "google.cl": 4,
        "google.cm": 4,
        "google.cn": 4,
        "google.co.ao": 4,
        "google.co.bw": 4,
        "google.co.ck": 4,
        "google.co.cr": 4,
        "google.co.il": 4,
        "google.co.ke": 4,
        "google.co.kr": 4,
        "google.co.ls": 4,
        "google.co.mz": 4,
        "google.co.nz": 4,
        "google.co.tz": 4,
        "google.co.ug": 4,
        "google.co.uz": 4,
        "google.co.ve": 4,
        "google.co.vi": 4,
        "google.co.za": 4,
        "google.co.zm": 4,
        "google.co.zw": 4,
        "google.com.af": 4,
        "google.com.ag": 4,
        "google.com.ai": 4,
        "google.com.bd": 4,
        "google.com.bh": 4,
        "google.com.bn": 4,
        "google.com.bo": 4,
        "google.com.bz": 4,
        "google.com.co": 4,
        "google.com.cu": 4,
        "google.com.cy": 4,
        "google.com.ec": 4,
        "google.com.eg": 4,
        "google.com.et": 4,
        "google.com.fj": 4,
        "google.com.gh": 4,
        "google.com.gi": 4,
        "google.com.gt": 4,
        "google.com.hk": 4,
        "google.com.jm": 4,
        "google.com.kh": 4,
        "google.com.kw": 4,
        "google.com.lb": 4,
        "google.com.my": 4,
        "google.com.na": 4,
        "google.com.nf": 4,
        "google.com.ng": 4,
        "google.com.ni": 4,
        "google.com.np": 4,
        "google.com.om": 4,
        "google.com.pa": 4,
        "google.com.pe": 4,
        "google.com.pg": 4,
        "google.com.ph": 4,
        "google.com.pk": 4,
        "google.com.pr": 4,
        "google.com.py": 4,
        "google.com.qa": 4,
        "google.com.sa": 4,
        "google.com.sb": 4,
        "google.com.sg": 4,
        "google.com.sl": 4,
        "google.com.sv": 4,
        "google.com.tj": 4,
        "google.com.uy": 4,
        "google.com.vc": 4,
        "google.com.vn": 4,
        "google.cv": 4,
        "google.dj": 4,
        "google.dm": 4,
        "google.ee": 4,
        "google.fm": 4,
        "google.ga": 4,
        "google.ge": 4,
        "google.gg": 4,
        "google.gl": 4,
        "google.gm": 4,
        "google.gp": 4,
        "google.gy": 4,
        "google.hn": 4,
        "google.hr": 4,
        "google.ht": 4,
        "google.im": 4,
        "google.in": 4,
        "google.iq": 4,
        "google.is": 4,
        "google.je": 4,
        "google.jo": 4,
        "google.kg": 4,
        "google.ki": 4,
        "google.kz": 4,
        "google.la": 4,
        "google.li": 4,
        "google.lk": 4,
        "google.lt": 4,
        "google.lu": 4,
        "google.lv": 4,
        "google.md": 4,
        "google.me": 4,
        "google.mg": 4,
        "google.mk": 4,
        "google.ml": 4,
        "google.mn": 4,
        "google.ms": 4,
        "google.mu": 4,
        "google.mv": 4,
        "google.mw": 4,
        "google.ne": 4,
        "google.net": 4,
        "google.nr": 4,
        "google.nu": 4,
        "google.org": 4,
        "google.pn": 4,
        "google.ps": 4,
        "google.rw": 4,
        "google.sc": 4,
        "google.sh": 4,
        "google.si": 4,
        "google.sk": 4,
        "google.sm": 4,
        "google.sn": 4,
        "google.so": 4,
        "google.sr": 4,
        "google.st": 4,
        "google.td": 4,
        "google.tg": 4,
        "google.tk": 4,
        "google.tl": 4,
        "google.tm": 4,
        "google.to": 4,
        "google.tt": 4,
        "google.us": 4,
        "google.vg": 4,
        "google.vu": 4,
        "google.ws": 4,
        "googleapis.cn": 4,
        "googlecode.com": 4,
        "googledownloads.cn": 4,
        "googleoptimize.com": 4,
        "googleweblight.in": 4,
        "googlezip.net": 4,
        "gstatic.cn": 4,
        "news.google.com": 4,
        "oo.gl": 4,
        "withgoogle.com": 4,
        "googleadservices.com": 4,
        "google-analytics.com": 6,
        "app-analytics-services.com": 6,
        "ssl-google-analytics.l.google.com": 6,
        "www-googletagmanager.l.google.com": 6,
        "appspot.com": 10,
        "googlehosted.com": 10,
        "accounts.google.com": 2,
        "myaccount.google.com": 2,
        "oauth2.googleapis.com": 2,
        "ogs.google.com": 2,
        "securetoken.googleapis.com": 2,
        "beacons-google.com": 6,
        "alt1-mtalk.google.com": 7,
        "alt2-mtalk.google.com": 7,
        "alt3-mtalk.google.com": 7,
        "alt4-mtalk.google.com": 7,
        "alt5-mtalk.google.com": 7,
        "alt6-mtalk.google.com": 7,
        "alt7-mtalk.google.com": 7,
        "alt8-mtalk.google.com": 7,
        "chat.google.com": 7,
        "mobile-gtalk.l.google.com": 7,
        "mobile-gtalk4.l.google.com": 7,
        "mtalk.google.com": 7,
        "mtalk4.google.com": 7,
        "talk.google.com": 7,
        "talk.l.google.com": 7,
        "talkx.l.google.com": 7,
        "cloud.google.com": 10,
        "gcp.gvt2.com": 10,
        "storage.googleapis.com": 10,
        "adsensecustomsearchads.com": 4,
        "dns.google": 10,
        "dns.google.com": 10,
        "google-public-dns-a.google.com": 10,
        "google-public-dns-b.google.com": 10,
        "domains.google": 10,
        "googledomains.com": 10,
        "nic.google": 10,
        "registry.google": 10,
        "edge.google.com": 9,
        "mail-ads.google.com": 13,
        "fonts.googleapis.com": 9,
        "cloudfunctions.net": 10,
        "ghs.googlehosted.com": 10,
        "ghs4.googlehosted.com": 10,
        "ghs46.googlehosted.com": 10,
        "ghs6.googlehosted.com": 10,
        "googlehosted.l.googleusercontent.com": 10,
        "run.app": 10,
        "supl.google.com": 8,
        "earth.app.goo.gl": 2,
        "geo0.ggpht.com": 2,
        "geo1.ggpht.com": 2,
        "geo2.ggpht.com": 2,
        "geo3.ggpht.com": 2,
        "kh.google.com": 2,
        "maps.app.goo.gl": 2,
        "maps.google.ca": 2,
        "maps.google.ch": 2,
        "maps.google.co.jp": 2,
        "maps.google.co.uk": 2,
        "maps.google.com": 2,
        "maps.google.com.mx": 2,
        "maps.google.es": 2,
        "maps.google.se": 2,
        "maps.gstatic.com": 2,
        "doubleclick.net": 4,
        "invitemedia.com": 4,
        "adsense.google.com": 4,
        "adservice.google.ca": 4,
        "adservice.google.co.in": 4,
        "adservice.google.co.kr": 4,
        "adservice.google.co.uk": 4,
        "adservice.google.co.za": 4,
        "adservice.google.com": 4,
        "adservice.google.com.ar": 4,
        "adservice.google.com.au": 4,
        "adservice.google.com.br": 4,
        "adservice.google.com.co": 4,
        "adservice.google.com.gt": 4,
        "adservice.google.com.mx": 4,
        "adservice.google.com.pe": 4,
        "adservice.google.com.ph": 4,
        "adservice.google.com.pk": 4,
        "adservice.google.com.tr": 4,
        "adservice.google.com.tw": 4,
        "adservice.google.com.vn": 4,
        "adservice.google.de": 4,
        "adservice.google.dk": 4,
        "adservice.google.es": 4,
        "adservice.google.fr": 4,
        "adservice.google.nl": 4,
        "adservice.google.no": 4,
        "adservice.google.pl": 4,
        "adservice.google.ru": 4,
        "adservice.google.vg": 4,
        "adtrafficquality.google": 4,
        "dai.google.com": 4,
        "doubleclick.com": 4,
        "doubleclickbygoogle.com": 4,
        "googlesyndication-cn.com": 4,
        "duo.google.com": 2,
        "hangouts.clients6.google.com": 2,
        "hangouts.google.com": 2,
        "hangouts.googleapis.com": 2,
        "meet.google.com": 2,
        "meetings.googleapis.com": 2,
        "stun.l.google.com": 2,
        "stun1.l.google.com": 2,
        "ggpht.com": 9,
        "play-fe.googleapis.com": 8,
        "play-lh.googleusercontent.com": 8,
        "play.google.com": 8,
        "play.googleapis.com": 8,
        "1e100cdn.net": 8,
        "gvt1.com": 8,
        "gvt2.com": 8,
        "gvt3.com": 8,
        "googlesyndication.com": 4,
        "googletagmanager.com": 5,
        "googletagservices.com": 5,
        "translate.google.com": 2,
        "googletraveladservices.com": 4,
        "pki.goog": 5,
        "googlecommerce.com": 6,
        "googleusercontent.com": 9,
        "telephony.goog": 2,
        "voice.google.com": 2,
        "gmodules.com": 2,
        "calendar.google.com": 2,
        "contacts.google.com": 2,
        "currents.google.com": 2,
        "docs.google.com": 2,
        "drive.google.com": 2,
        "forms.google.com": 2,
        "gsuite.google.com": 2,
        "jamboard.google.com": 2,
        "keep.google.com": 2,
        "plus.google.com": 2,
        "sheets.google.com": 2,
        "slides.google.com": 2,
        "spreadsheets.google.com": 2,
        "googleapis.com": 9,
        "gooal.herokuapp.com": 6,
        "gooo.al": 6,
        "cdn.triggertag.gorillanation.com": 4,
        "evolvemediametrics.com": 4,
        "d1l6p2sc9645hc.cloudfront.net": 6,
        "gosquared.com": 6,
        "gostats.com": 6,
        "govmetric.com": 6,
        "servmetric.com": 6,
        "b.grabo.bg": 4,
        "trw12.com": 4,
        "tuberewards.com": 4,
        "d2bw638ufki166.cloudfront.net": 6,
        "granify.com": 6,
        "grapeshot.co.uk": 4,
        "gscontxt.net": 4,
        "graphcomment.com": 5,
        "gravatar.com": 7,
        "cdn.gravitec.net": 6,
        "gravity.com": 6,
        "grvcdn.com": 6,
        "greatviews.de": 4,
        "gandrad.org": 4,
        "green-red.com": 4,
        "co2stats.com": 2,
        "greenstory.ca": 6,
        "greentube.com": 7,
        "gt-cdn.net": 7,
        "greystripe.com": 4,
        "groovehq.com": 2,
        "groovinads.com": 4,
        "bidagent.xad.com": 4,
        "gmads.net": 4,
        "grmtech.net": 4,
        "media.gsimedia.net": 4,
        "gstatic.com": 9,
        "fx.gtop.ro": 6,
        "fx.gtopstats.com": 6,
        "gubagootracking.com": 4,
        "guj.de": 4,
        "emsservice.de": 4,
        "gumgum.com": 4,
        "gumroad.com": 7,
        "gunggo.com": 4,
        "h12-media.com": 4,
        "h12-media.net": 4,
        "hnbutton.appspot.com": 7,
        "haendlerbund.de": 2,
        "halogennetwork.com": 7,
        "d1l7z5ofrj6ab8.cloudfront.net": 2,
        "ad.harrenmedianetwork.com": 4,
        "ads.networkhm.com": 4,
        "app.hatchbuck.com": 6,
        "hhcdn.ru": 6,
        "healte.de": 11,
        "d36lvucg9kzous.cloudfront.net": 6,
        "heapanalytics.com": 6,
        "heatmap.it": 6,
        "weltsport.net": 8,
        "hellobar.com": 7,
        "hellosociety.com": 6,
        "here.com": 8,
        "herokuapp.com": 10,
        "heureka.cz": 4,
        "heybubble.com": 2,
        "heyos.com": 4,
        "adlink.net": 4,
        "comclick.com": 4,
        "hi-mediaserver.com": 4,
        "himediads.com": 4,
        "himediadx.com": 4,
        "hiconversion.com": 4,
        "highwebmedia.com": 3,
        "hwcdn.net": 6,
        "hiiir.com": 4,
        "hiro.tv": 4,
        "histats.com": 4,
        "hit-parade.com": 4,
        "hit.ua": 4,
        "hitslink.com": 4,
        "hitsprocessor.com": 4,
        "hitsniffer.com": 4,
        "hittail.com": 4,
        "hivedx.com": 4,
        "ads.thehiveworks.com": 4,
        "hockeyapp.net": 101,
        "hoholikik.club": 12,
        "h-cdn.com": 0,
        "homeaway.com": 8,
        "honeybadger.io": 6,
        "hlserve.com": 4,
        "apiae.hopscore.com": 4,
        "hotdogsandads.com": 11,
        "hotjar.com": 6,
        "hotkeys.com": 4,
        "hotlog.ru": 4,
        "hotwords.com": 4,
        "hotwords.es": 4,
        "howtank.com": 7,
        "hqentertainmentnetwork.com": 4,
        "justservingfiles.net": 4,
        "hsoub.com": 4,
        "hstrck.com": 8,
        "httpool.com": 4,
        "toboads.com": 4,
        "hubrus.com": 4,
        "hs-analytics.net": 6,
        "hs-scripts.com": 6,
        "hsleadflows.net": 6,
        "hubapi.com": 6,
        "hubspot.com": 6,
        "forms.hubspot.com": 2,
        "hubvisor.io": 4,
        "files.hucksterbot.com": 4,
        "hupso.com": 7,
        "hurra.com": 4,
        "hybrid.ai": 4,
        "targetix.net": 4,
        "hypeads.org": 4,
        "hypercomments.com": 1,
        "hyves.nl": 4,
        "hyvyd.com": 8,
        "ib-ibi.com": 4,
        "i-mobile.co.jp": 4,
        "r.i.ua": 4,
        "i10c.net": 11,
        "i2i.jp": 6,
        "i2idata.com": 6,
        "consensu.org": 5,
        "iadvize.com": 2,
        "cmcore.com": 6,
        "coremetrics.com": 6,
        "coremetrics.eu": 6,
        "tracker.icerocket.com": 7,
        "nsimg.net": 2,
        "optimix.asia": 4,
        "ic-live.com": 4,
        "icstats.nl": 6,
        "icuazeczpeoohx.com": 11,
        "id-news.net": 4,
        "idcdn.de": 4,
        "eu-1-id5-sync.com": 4,
        "id5-sync.com": 4,
        "id5.io": 4,
        "cdn.id.services": 6,
        "e-generator.com": 4,
        "idealo.com": 4,
        "identrust.com": 5,
        "ideoclick.com": 4,
        "s.idio.co": 4,
        "ie8eamus.com": 11,
        "600z.com": 4,
        "api.iflychat.com": 2,
        "ignitionone.com": 6,
        "knotice.net": 6,
        "igodigital.com": 2,
        "ad.wsod.com": 6,
        "collserve.com": 6,
        "ihvmcqojoj.com": 11,
        "iias.eu": 3,
        "ijento.com": 6,
        "adv.imadrep.co.kr": 4,
        "worthathousandwords.com": 4,
        "picadmedia.com": 4,
        "imgix.net": 9,
        "imgur.com": 8,
        "vidigital.ru": 4,
        "immanalytics.com": 2,
        "immobilienscout24.de": 8,
        "static-immobilienscout24.de": 8,
        "imonomy.com": 6,
        "7eer.net": 5,
        "d3cxv97fi8q177.cloudfront.net": 5,
        "evyy.net": 5,
        "impactradius-event.com": 5,
        "impactradius-tag.com": 5,
        "impactradius.com": 5,
        "ojrq.net": 5,
        "r7ls.net": 5,
        "impresionesweb.com": 4,
        "360yield.com": 4,
        "iljmp.com": 6,
        "inbenta.com": 6,
        "inboxsdk.com": 8,
        "indeed.com": 4,
        "casalemedia.com": 4,
        "indexww.com": 4,
        "indieclick.com": 4,
        "industrybrains.com": 4,
        "impdesk.com": 4,
        "impressiondesk.com": 4,
        "zachysprod.infiniteanalytics.com": 6,
        "infinity-tracking.net": 6,
        "engine.influads.com": 4,
        "infolinks.com": 4,
        "intextscript.com": 4,
        "ioam.de": 6,
        "iocnt.net": 6,
        "ivwbox.de": 6,
        "informer.com": 6,
        "infusionsoft.com": 4,
        "keap.com": 4,
        "innity.com": 4,
        "innity.net": 4,
        "innogames.com": 8,
        "innogames.de": 8,
        "innogamescdn.com": 8,
        "innovid.com": 4,
        "inside-graph.com": 7,
        "useinsider.com": 6,
        "insightexpressai.com": 6,
        "inskinad.com": 4,
        "inskinmedia.com": 4,
        "inspectlet.com": 6,
        "inspsearchapi.com": 4,
        "cdninstagram.com": 8,
        "instagram.com": 8,
        "tcgtrkr.com": 2,
        "sdad.guru": 4,
        "insticator.com": 4,
        "load.instinctiveads.com": 4,
        "intango.com": 4,
        "adsafeprotected.com": 4,
        "iasds01.com": 4,
        "integral-marketing.com": 4,
        "intelliad.com": 6,
        "intelliad.de": 6,
        "saas.intelligencefocus.com": 6,
        "ist-track.com": 4,
        "intensedebate.com": 2,
        "intentiq.com": 4,
        "intentmedia.net": 4,
        "intercom.com": 2,
        "intercom.io": 2,
        "intercomassets.com": 2,
        "intercomcdn.com": 2,
        "interedy.info": 11,
        "ads.intergi.com": 4,
        "intermarkets.net": 4,
        "intermundomedia.com": 4,
        "bbelements.com": 4,
        "goadservices.com": 4,
        "ibillboard.com": 4,
        "mediainter.net": 4,
        "voice2page.com": 0,
        "ibpxl.com": 7,
        "ibsrv.net": 7,
        "interpolls.com": 4,
        "ps7894.com": 4,
        "intilery-analytics.com": 6,
        "im-apps.net": 6,
        "investingchannel.com": 8,
        "inviziads.com": 4,
        "js12.invoca.net": 4,
        "ringrevenue.com": 4,
        "invodo.com": 6,
        "ionicframework.com": 8,
        "dsp.io": 4,
        "iesnare.com": 5,
        "iovation.com": 5,
        "ip-label.net": 6,
        "eltoro.com": 6,
        "iptargeting.com": 6,
        "ip-tracker.org": 6,
        "iptrack.io": 6,
        "iperceptions.com": 2,
        "dust.ipfingerprint.com": 6,
        "mbww.com": 4,
        "ipify.org": 8,
        "ipinfo.io": 2,
        "iplogger.ru": 6,
        "centraliprom.com": 4,
        "iprom.net": 4,
        "ipromote.com": 4,
        "clickmanage.com": 4,
        "iq.com": 0,
        "iqiyi.com": 0,
        "qy.net": 0,
        "addelive.com": 4,
        "afdads.com": 4,
        "delivery47.com": 4,
        "ironsrc.com": 4,
        "ironsrc.net": 4,
        "is.com": 4,
        "soom.la": 4,
        "supersonicads.com": 4,
        "tapjoy.com": 4,
        "adsbyisocket.com": 4,
        "isocket.com": 4,
        "isolarcloud.com": 6,
        "isolarcloud.com.a.lahuashanbx.com": 6,
        "isolarcloud.com.w.cdngslb.com": 6,
        "isolarcloud.com.w.kunlunsl.com": 6,
        "ispot.tv": 4,
        "itineraire.info": 2,
        "autolinkmaker.itunes.apple.com": 4,
        "ity.im": 4,
        "iubenda.com": 5,
        "ivcbrasil.org.br": 6,
        "ivitrack.com": 4,
        "iwiw.hu": 2,
        "ixiaa.com": 4,
        "ixquick.com": 8,
        "cdn.izooto.com": 6,
        "jlist.com": 4,
        "getjaco.com": 6,
        "janrainbackplane.com": 6,
        "rpxnow.com": 6,
        "jeeng.com": 4,
        "api.jeeng.com": 4,
        "phone-analytics.com": 6,
        "grazie.ai": 8,
        "intellij.net": 8,
        "jb.gg": 8,
        "jetbrains.ai": 8,
        "jetbrains.com": 8,
        "jetbrains.com.cn": 8,
        "jetbrains.dev": 8,
        "jetbrains.net": 8,
        "jetbrains.org": 8,
        "jetbrains.ru": 8,
        "jetbrains.space": 8,
        "kotl.in": 8,
        "kotlinconf.com": 8,
        "kotlinlang.org": 8,
        "myjetbrains.com": 8,
        "talkingkotlin.com": 8,
        "jetlore.com": 6,
        "pixel.wp.com": 6,
        "stats.wp.com": 6,
        "jetpackdigital.com": 6,
        "jimcdn.com": 10,
        "jimdo.com": 10,
        "jimstatic.com": 10,
        "ads.jinkads.com": 4,
        "jirafe.com": 6,
        "jivosite.com": 2,
        "jivox.com": 4,
        "jobs2careers.com": 4,
        "joinhoney.com": 8,
        "create.leadid.com": 6,
        "d1tprjo2w7krrh.cloudfront.net": 6,
        "cdnjquery.com": 9,
        "jquery.com": 9,
        "cjmooter.xcache.kinxcdn.com": 4,
        "jsdelivr.net": 9,
        "jsecoin.com": 4,
        "jsuol.com.br": 4,
        "contentabc.com": 3,
        "mofos.com": 3,
        "juiceadv.com": 4,
        "juicyads.com": 3,
        "cdn.jumplead.com": 6,
        "jumpstarttaggingsolutions.com": 6,
        "jumptap.com": 4,
        "jump-time.net": 6,
        "jumptime.com": 6,
        "components.justanswer.com": 2,
        "justpremium.com": 4,
        "justpremium.nl": 4,
        "justrelevant.com": 4,
        "jvc.gg": 9,
        "d21rhj7n383afu.cloudfront.net": 0,
        "jwpcdn.com": 0,
        "jwplatform.com": 0,
        "jwplayer.com": 0,
        "jwpltx.com": 0,
        "jwpsrv.com": 0,
        "ltassrv.com": 4,
        "kaeufersiegel.de": 2,
        "kairion.de": 4,
        "kctag.net": 4,
        "kaloo.ga": 4,
        "kaltura.com": 0,
        "kameleoon.com": 6,
        "kameleoon.eu": 6,
        "kampyle.com": 2,
        "kanoodle.com": 4,
        "kmi-us.com": 4,
        "tnsinternet.be": 4,
        "karambasecurity.com": 8,
        "kargo.com": 4,
        "kaspersky-labs.com": 12,
        "kataweb.it": 4,
        "cen.katchup.fr": 4,
        "kau.li": 4,
        "kavanga.ru": 4,
        "kayosports.com.au": 0,
        "dc8na2hxrj29i.cloudfront.net": 6,
        "keen.io": 6,
        "widget.kelkoo.com": 4,
        "xg4ken.com": 6,
        "keymetric.net": 6,
        "lb.keytiles.com": 6,
        "keywee.co": 6,
        "keywordmax.com": 4,
        "massrelevance.com": 7,
        "tweetriver.com": 7,
        "khzbeucrltin.com": 11,
        "ping.kickfactory.com": 4,
        "sa-as.com": 4,
        "sniff.visistat.com": 4,
        "stats.visistat.com": 4,
        "apikik.com": 7,
        "kik-gateway-use1.meetme.com": 7,
        "kik-live.com": 7,
        "kik-stream.meetme.com": 7,
        "kik.com": 7,
        "king.com": 4,
        "midasplayer.com": 8,
        "kinja-img.com": 6,
        "kinja-static.com": 6,
        "kinja.com": 6,
        "kiosked.com": 4,
        "doug1izaerwt3.cloudfront.net": 6,
        "kissmetrics.com": 6,
        "ad.103092804.com": 4,
        "kmdisplay.com": 4,
        "kixer.com": 4,
        "klarna.com": 2,
        "a.klaviyo.com": 6,
        "klaviyo.com": 6,
        "klikki.com": 4,
        "scr.kliksaya.com": 4,
        "mediapeo2.com": 4,
        "knoopstat.nl": 6,
        "knotch.it": 2,
        "komoona.com": 4,
        "kona.kontera.com": 4,
        "ktxtr.com": 4,
        "kontextua.com": 4,
        "cleanrm.net": 4,
        "korrelate.net": 4,
        "trackit.ktxlytics.io": 6,
        "kaptcha.com": 6,
        "krxd.net": 4,
        "d31bfnnwekbny6.cloudfront.net": 4,
        "kpcustomer.de": 4,
        "q-sis.de": 4,
        "kxcdn.com": 9,
        "cdn.kyto.com": 6,
        "cd-ladsp-com.s3.amazonaws.com": 4,
        "ladmp.com": 4,
        "ladsp.com": 4,
        "lanistaads.com": 4,
        "latimes.com": 8,
        "events.launchdarkly.com": 5,
        "launchdarkly.com": 5,
        "launchbit.com": 4,
        "launchpad.net": 8,
        "launchpadcontent.net": 8,
        "layer-ad.org": 4,
        "ph-live.slatic.net": 4,
        "slatic.net": 4,
        "lcxdigital.com": 4,
        "lemde.fr": 8,
        "t1.llanalytics.com": 6,
        "leadback.ru": 6,
        "leaddyno.com": 4,
        "123-tracker.com": 4,
        "55-trk-srv.com": 4,
        "business-path-55.com": 4,
        "click-to-trace.com": 4,
        "cloud-exploration.com": 4,
        "cloud-journey.com": 4,
        "cloud-trail.com": 4,
        "cloudpath82.com": 4,
        "cloudtracer101.com": 4,
        "discover-path.com": 4,
        "discovertrail.net": 4,
        "domainanalytics.net": 4,
        "dthvdr9.com": 4,
        "explore-123.com": 4,
        "finger-info.net": 4,
        "forensics1000.com": 4,
        "ip-route.net": 4,
        "ipadd-path.com": 4,
        "iproute66.com": 4,
        "lead-123.com": 4,
        "lead-analytics-1000.com": 4,
        "lead-watcher.com": 4,
        "leadforensics.com": 4,
        "ledradn.com": 4,
        "letterbox-path.com": 4,
        "letterboxtrail.com": 4,
        "network-handle.com": 4,
        "path-follower.com": 4,
        "path-trail.com": 4,
        "scan-trail.com": 4,
        "site-research.net": 4,
        "srv1010elan.com": 4,
        "the-lead-tracker.com": 4,
        "trace-2000.com": 4,
        "track-web.net": 4,
        "trackdiscovery.net": 4,
        "trackercloud.net": 4,
        "trackinvestigate.net": 4,
        "trail-viewer.com": 4,
        "trail-web.com": 4,
        "trailbox.net": 4,
        "trailinvestigator.com": 4,
        "web-path.com": 4,
        "webforensics.co.uk": 4,
        "websiteexploration.com": 4,
        "www-path.com": 4,
        "gate.leadgenic.com": 4,
        "leadhit.ru": 2,
        "js.leadin.com": 6,
        "io.leadingreports.de": 4,
        "js.leadinspector.de": 6,
        "formalyzer.com": 6,
        "trackalyzer.com": 6,
        "analytics.leadlifesolutions.net": 2,
        "my.leadpages.net": 6,
        "leadplace.fr": 6,
        "scorecard.wspisp.net": 4,
        "www.leadscoreapp.dk": 2,
        "tracker.leadsius.com": 4,
        "leady.com": 4,
        "leady.cz": 4,
        "leiki.com": 4,
        "lengow.com": 4,
        "lenmit.com": 11,
        "lentainform.com": 8,
        "lenua.de": 4,
        "letreach.com": 2,
        "lencr.org": 5,
        "letsencrypt.org": 5,
        "js.letvcdn.com": 6,
        "footprint.net": 8,
        "alphonso.tv": 4,
        "lgads.tv": 4,
        "lg.com": 8,
        "lge.com": 8,
        "lgsmartad.com": 8,
        "lgtvcommon.com": 8,
        "lgtvsdp.com": 8,
        "licensebuttons.net": 9,
        "lfstmedia.com": 4,
        "content-recommendation.net": 4,
        "ligadx.com": 4,
        "ligatus.com": 4,
        "ligatus.de": 4,
        "veeseo.com": 4,
        "limk.com": 4,
        "line-apps.com": 6,
        "line-scdn.net": 6,
        "line.me": 6,
        "tongji.linezing.com": 4,
        "linkbucks.com": 4,
        "linkconnector.com": 4,
        "bizo.com": 8,
        "licdn.com": 8,
        "linkedin.com": 8,
        "lynda.com": 8,
        "ads.linkedin.com": 4,
        "snap.licdn.com": 6,
        "bizographics.com": 4,
        "platform.linkedin.com": 7,
        "linker.hr": 4,
        "linkprice.com": 4,
        "lp4.io": 6,
        "linksalpha.com": 7,
        "erovinmo.com": 4,
        "linksmart.com": 4,
        "linkstorm.net": 2,
        "linksynergy.com": 4,
        "linkup.com": 6,
        "linkwi.se": 4,
        "linkwithin.com": 7,
        "lqm.io": 4,
        "lqmcdn.com": 4,
        "liqwid.net": 4,
        "list.ru": 7,
        "listrakbi.com": 2,
        "live2support.com": 2,
        "live800.com": 2,
        "ladesk.com": 2,
        "livehelpnow.net": 2,
        "liadm.com": 6,
        "l-stat.livejournal.net": 6,
        "liveadexchanger.com": 11,
        "livechat.s3.amazonaws.com": 2,
        "livechatinc.com": 2,
        "livechatinc.net": 2,
        "livechatnow.com": 2,
        "livechatnow.net": 2,
        "liveclicker.net": 2,
        "livecounter.dk": 6,
        "fyre.co": 1,
        "livefyre.com": 1,
        "yadro.ru": 1,
        "liveperson.net": 2,
        "lpsnmedia.net": 2,
        "pippio.com": 4,
        "rapleaf.com": 4,
        "rlcdn.com": 4,
        "livere.co.kr": 7,
        "livere.co.kr.cizion.ixcloud.net": 7,
        "livesportmedia.eu": 8,
        "analytics.livestream.com": 0,
        "livetex.ru": 2,
        "lkqd.net": 4,
        "loadbee.com": 4,
        "loadercdn.com": 11,
        "loadsource.org": 11,
        "web.localytics.com": 101,
        "localytics.com": 101,
        "cdn2.lockerdome.com": 7,
        "addtoany.com": 7,
        "pixel.loganmedia.mobi": 6,
        "ping.answerbook.com": 4,
        "loggly.com": 6,
        "logly.co.jp": 6,
        "logsss.com": 11,
        "lomadee.com": 4,
        "assets.loomia.com": 4,
        "loop11.com": 6,
        "lfov.net": 4,
        "crwdcntrl.net": 4,
        "vidcpm.com": 11,
        "tracker.samplicio.us": 4,
        "lucidmedia.com": 4,
        "lead.adsender.us": 4,
        "livestatserver.com": 6,
        "luckyorange.com": 6,
        "luckyorange.net": 6,
        "luckypushh.com": 11,
        "adelixir.com": 4,
        "lypn.com": 4,
        "lypn.net": 4,
        "lytics.io": 6,
        "lyuoaxruaqdo.com": 11,
        "m-pathy.com": 4,
        "mpnrs.com": 4,
        "m4n.nl": 4,
        "madadsmedia.com": 4,
        "madeleine.de": 4,
        "dinclinx.com": 4,
        "madisonlogic.com": 4,
        "madnet.ru": 4,
        "eu2.madsone.com": 4,
        "magna.ru": 4,
        "d3ezl4ajpp2zy8.cloudfront.net": 4,
        "domdex.com": 4,
        "domdex.net": 4,
        "magnetisemedia.com": 4,
        "magnify360.com": 6,
        "magnuum.com": 11,
        "ad.mail.ru": 4,
        "imgsmail.ru": 7,
        "mail.ru": 7,
        "mradx.net": 7,
        "odnoklassniki.ru": 7,
        "ok.ru": 7,
        "chimpstatic.com": 4,
        "list-manage.com": 4,
        "mailchimp.com": 4,
        "mailerlite.com": 10,
        "mailtrack.io": 4,
        "mainadv.com": 4,
        "makazi.com": 4,
        "makeappdev.xyz": 12,
        "makesource.cool": 11,
        "widgets.mango-office.ru": 4,
        "manycontacts.com": 4,
        "mapandroute.de": 2,
        "mapbox.com": 2,
        "www.maploco.com": 4,
        "px.marchex.io": 4,
        "voicestar.com": 4,
        "mmadsgadget.com": 4,
        "qadabra.com": 4,
        "qadserve.com": 4,
        "qadservice.com": 4,
        "marinsm.com": 4,
        "markandmini.com": 4,
        "ak-cdn.placelocal.com": 4,
        "dt00.net": 4,
        "dt07.net": 4,
        "marketgid.com": 4,
        "mgid.com": 4,
        "marketingautomation.si": 4,
        "marketo.com": 4,
        "marketo.net": 4,
        "mktoresp.com": 4,
        "caanalytics.com": 4,
        "mmstat.com": 4,
        "markmonitor.com": 4,
        "netscope.data.marktest.pt": 4,
        "marshadow.io": 4,
        "martiniadnetwork.com": 4,
        "edigitalsurvey.com": 2,
        "marvellousmachine.net": 6,
        "mbn.com.ua": 4,
        "mastertarget.ru": 4,
        "rns.matelso.de": 6,
        "matheranalytics.com": 6,
        "mathjax.org": 9,
        "nzaza.com": 6,
        "matomo.cloud": 6,
        "matomo.org": 6,
        "piwik.org": 6,
        "adsmarket.com": 4,
        "m2pub.com": 4,
        "matrix.org": 5,
        "mb01.com": 5,
        "maxcdn.com": 9,
        "netdna-cdn.com": 9,
        "netdna-ssl.com": 9,
        "maxlab.ru": 4,
        "maxmind.com": 4,
        "maxonclick.com": 11,
        "mxptint.net": 4,
        "maxymiser.hs.llnwd.net": 4,
        "maxymiser.net": 4,
        "m6r.eu": 4,
        "pixel.adbuyer.com": 4,
        "mcabi.mcloudglobal.com": 4,
        "scanalert.com": 5,
        "ywxi.net": 5,
        "mconet.biz": 4,
        "mdotlabs.com": 4,
        "media-clic.com": 4,
        "media-imdb.com": 9,
        "media.net": 4,
        "mediaimpact.de": 4,
        "mookie1.com": 4,
        "idntfy.ru": 4,
        "s1.mediaad.org": 4,
        "mlnadvertising.com": 4,
        "fhserve.com": 4,
        "media-lab.ai": 8,
        "medialab.la": 8,
        "adnet.ru": 4,
        "medialand.ru": 4,
        "medialead.de": 4,
        "mathads.com": 4,
        "mathtag.com": 4,
        "mediametrics.ru": 7,
        "audit.median.hu": 4,
        "mediapass.com": 4,
        "mt.mediapostcommunication.net": 6,
        "mediarithmics.com": 4,
        "tns-counter.ru": 6,
        "ad.media-servers.net": 4,
        "adsvc1107131.net": 4,
        "mediator.media": 6,
        "mediav.com": 4,
        "adnetinteractive.com": 4,
        "adnetinteractive.net": 4,
        "mediego.com": 4,
        "medleyads.com": 4,
        "adnet.com.tr": 4,
        "e-kolay.net": 4,
        "medyanetads.com": 4,
        "cim.meebo.com": 7,
        "meetrics.net": 4,
        "mxcdn.net": 4,
        "research.de.com": 4,
        "counter.megaindex.ru": 4,
        "mega.co.nz": 8,
        "mega.io": 8,
        "mega.nz": 8,
        "mein-bmi.com": 12,
        "webvisitor.melissadata.net": 6,
        "meltdsp.com": 4,
        "mlt01.com": 4,
        "mentad.com": 4,
        "mercadoclics.com": 4,
        "mercadolivre.com.br": 4,
        "mlstatic.com": 4,
        "merchantadvantage.com": 4,
        "merchenta.com": 4,
        "roia.biz": 4,
        "cdn.merklesearch.com": 6,
        "rkdms.com": 6,
        "messenger.com": 7,
        "ad.metanetwork.com": 7,
        "metaffiliation.com": 4,
        "netaffiliation.com": 4,
        "metalyzer.com": 4,
        "mlsat02.de": 4,
        "metrigo.com": 4,
        "metriweb.be": 4,
        "miaozhen.com": 4,
        "microad.co.jp": 4,
        "microad.jp": 4,
        "microad.net": 4,
        "microadinc.com": 4,
        "azurewebsites.net": 8,
        "cloudapp.net": 8,
        "gfx.ms": 8,
        "microsoft.com": 8,
        "microsoftonline-p.com": 8,
        "microsoftonline.com": 8,
        "microsofttranslator.com": 8,
        "msecnd.net": 8,
        "msedge.net": 8,
        "msocdn.com": 8,
        "onestore.ms": 8,
        "s-microsoft.com": 8,
        "trouter.io": 8,
        "windows.net": 8,
        "aka.ms": 8,
        "microsoftazuread-sso.com": 8,
        "bingapis.com": 8,
        "msauth.net": 8,
        "msauthimages.net": 8,
        "msftauth.net": 8,
        "msftstatic.com": 8,
        "msidentity.com": 8,
        "nelreports.net": 8,
        "windowscentral.com": 8,
        "analytics.live.com": 4,
        "a.clarity.ms": 6,
        "b.clarity.ms": 6,
        "c.clarity.ms": 6,
        "d.clarity.ms": 6,
        "e.clarity.ms": 6,
        "f.clarity.ms": 6,
        "g.clarity.ms": 6,
        "h.clarity.ms": 6,
        "i.clarity.ms": 6,
        "j.clarity.ms": 6,
        "log.clarity.ms": 6,
        "www.clarity.ms": 6,
        "mmismm.com": 4,
        "imgfarm.com": 6,
        "mindspark.com": 6,
        "staticimgfarm.com": 6,
        "mvtracker.com": 4,
        "minewhat.com": 4,
        "mintsapp.io": 2,
        "snackly.co": 0,
        "snippet.minute.ly": 0,
        "apv.configuration.minute.ly": 0,
        "get.mirando.de": 4,
        "mirtesen.ru": 7,
        "misterbell.com": 4,
        "mixi.jp": 7,
        "mixpanel.com": 6,
        "mxpnl.com": 6,
        "mxpnl.net": 6,
        "swf.mixpo.com": 4,
        "app.mluvii.com": 2,
        "mncdn.com": 9,
        "moatads.com": 4,
        "moatpixel.com": 4,
        "mobicow.com": 4,
        "a.mobify.com": 4,
        "mobtrks.com": 11,
        "ads.mocean.mobi": 4,
        "ads.moceanads.com": 4,
        "chat.mochapp.com": 2,
        "intelligentpixel.modernimpact.com": 4,
        "teljari.is": 6,
        "modulepush.com": 4,
        "mogointeractive.com": 4,
        "mokonocdn.com": 4,
        "devappgrant.space": 8,
        "monetate.net": 6,
        "monetize-me.com": 4,
        "ads.themoneytizer.com": 4,
        "mongoosemetrics.com": 4,
        "track.monitis.com": 6,
        "monitus.net": 6,
        "fonts.net": 9,
        "fonts.com": 2,
        "cdn.monsido.com": 6,
        "monster.com": 4,
        "mooxar.com": 4,
        "mopinion.com": 2,
        "mopub.com": 4,
        "ad.ad-arata.com": 4,
        "moras.jp": 4,
        "nedstatbasic.net": 7,
        "webstats.motigo.com": 7,
        "analytics.convertlanguage.com": 6,
        "mouseflow.com": 6,
        "mousestats.com": 4,
        "s.mousetrace.com": 6,
        "movad.de": 8,
        "movad.net": 8,
        "micpn.com": 2,
        "mvb.me": 4,
        "moz.com": 8,
        "firefox.com": 8,
        "mozaws.net": 8,
        "mozgcp.net": 8,
        "mozilla.com": 8,
        "mozilla.net": 8,
        "mozilla.org": 8,
        "storage.mozoo.com": 4,
        "tracker.mrpfd.com": 4,
        "mrpdata.com": 6,
        "mrpdata.net": 6,
        "mrskincash.com": 3,
        "a-msedge.net": 8,
        "b-msedge.net": 8,
        "dual-s-msedge.net": 8,
        "e-msedge.net": 8,
        "k-msedge.net": 8,
        "l-msedge.net": 8,
        "s-msedge.net": 8,
        "spo-msedge.net": 8,
        "t-msedge.net": 8,
        "wac-msedge.net": 8,
        "msn.com": 8,
        "s-msn.com": 8,
        "musculahq.appspot.com": 4,
        "litix.io": 0,
        "mybloglog.com": 7,
        "t.p.mybuys.com": 4,
        "mycdn.me": 9,
        "mycliplister.com": 2,
        "mycounter.com.ua": 6,
        "mycounter.ua": 6,
        "myfonts.net": 6,
        "mypagerank.net": 6,
        "stat.mystat.hu": 7,
        "mythings.com": 4,
        "mystat-in.net": 7,
        "nab.com": 8,
        "nab.com.au": 8,
        "nab.net": 8,
        "nabgroup.com": 8,
        "national.com.au": 8,
        "nationalaustraliabank.com.au": 8,
        "nationalbank.com.au": 8,
        "nakanohito.jp": 4,
        "namogoo.coom": 4,
        "nanigans.com": 4,
        "audiencemanager.de": 4,
        "nanorep.com": 2,
        "narando.com": 0,
        "static.bam-x.com": 4,
        "narrative.io": 6,
        "p1.ntvk1.ru": 4,
        "nativeads.com": 4,
        "cdn01.nativeroll.tv": 0,
        "ntv.io": 4,
        "postrelease.com": 4,
        "navdmp.com": 6,
        "naver.com": 4,
        "naver.net": 4,
        "s-nbcnews.com": 8,
        "richmedia247.com": 4,
        "needle.com": 2,
        "nekudo.com": 2,
        "neodatagroup.com": 4,
        "ad-srv.net": 4,
        "contentspread.net": 4,
        "neory-tm.com": 4,
        "simptrack.com": 4,
        "nerfherdersolo.com": 8,
        "wemfbox.ch": 6,
        "cdnma.com": 4,
        "nr7.us": 4,
        "netavenir.com": 4,
        "netcommunities.com": 4,
        "visibility-stats.com": 4,
        "netbiscuits.net": 6,
        "bbtrack.net": 4,
        "netbooster.com": 4,
        "netflix.com": 0,
        "nflxext.com": 0,
        "nflximg.net": 0,
        "nflxso.net": 0,
        "nflxvideo.net": 0,
        "flxvpn.net": 0,
        "netflix.ca": 0,
        "netflix.com.au": 0,
        "netflix.net": 0,
        "netflixdnstest1.com": 0,
        "netflixdnstest10.com": 0,
        "netflixdnstest2.com": 0,
        "netflixdnstest3.com": 0,
        "netflixdnstest4.com": 0,
        "netflixdnstest5.com": 0,
        "netflixdnstest6.com": 0,
        "netflixdnstest7.com": 0,
        "netflixdnstest8.com": 0,
        "netflixdnstest9.com": 0,
        "netflixinvestor.com": 0,
        "netflixstudios.com": 0,
        "netflixtechblog.com": 0,
        "nflximg.com": 0,
        "netify.ai": 8,
        "netzathleten-media.de": 4,
        "netminers.dk": 6,
        "netmining.com": 4,
        "netmng.com": 4,
        "stat.netmonitor.fi": 6,
        "glanceguide.com": 4,
        "imrworldwide.com": 4,
        "vizu.com": 4,
        "netrk.net": 6,
        "netseer.com": 4,
        "netshelter.net": 4,
        "nsaudience.pl": 6,
        "nwidget.networkedblogs.com": 7,
        "adadvisor.net": 4,
        "d1ros97qkrwjf5.cloudfront.net": 6,
        "newrelic.com": 6,
        "nr-data.net": 6,
        "codestream.com": 6,
        "newscgp.com": 4,
        "nmcdn.us": 4,
        "newstogram.com": 4,
        "newsupdatedir.info": 11,
        "newsupdatewe.info": 12,
        "ads.newtention.net": 4,
        "ads.newtentionassets.net": 4,
        "nexage.com": 4,
        "nexeps.com": 4,
        "nxtck.com": 4,
        "track.nextuser.com": 4,
        "imgsrv.nextag.com": 4,
        "nextclick.pl": 4,
        "nextstat.com": 6,
        "d1d8vn0fpluuz7.cloudfront.net": 6,
        "ads.ngageinc.com": 6,
        "nice264.com": 0,
        "nimblecommerce.com": 4,
        "nineanalytics.io": 4,
        "cho-chin.com": 6,
        "donburako.com": 6,
        "hishaku.com": 6,
        "shinobi.jp": 6,
        "static.nirror.com": 6,
        "nitropay.com": 4,
        "nk.pl": 4,
        "noaa.gov": 8,
        "track.noddus.com": 4,
        "contextbar.ru": 4,
        "nonli.com": 4,
        "non.li": 4,
        "trkme.net": 4,
        "noop.style": 11,
        "nosto.com": 6,
        "adleadevent.com": 4,
        "notifyfox.com": 6,
        "notion.so": 8,
        "nowinteract.com": 6,
        "npario-inc.net": 6,
        "nplexmedia.com": 4,
        "nrelate.com": 2,
        "ns8.com": 4,
        "nt.vc": 8,
        "featurelink.com": 4,
        "ntp.org": 5,
        "ntppool.org": 5,
        "tracer.jp": 6,
        "nuffnang.com": 4,
        "nuggad.net": 4,
        "rotator.adjuggler.com": 4,
        "numbers.md": 6,
        "channeliq.com": 5,
        "nyacampwk.com": 11,
        "nyetm2mkch.com": 11,
        "nyt.com": 8,
        "nytimes.com": 8,
        "o12zs3u2n.com": 11,
        "o2.pl": 8,
        "o2online.de": 8,
        "oath.com": 8,
        "observerapp.com": 4,
        "ocioso.com.br": 7,
        "oclasrv.com": 11,
        "octapi.net": 11,
        "service.octavius.rocks": 4,
        "office.com": 8,
        "office.net": 8,
        "office365.com": 8,
        "oghub.io": 11,
        "ohmystats.com": 6,
        "adohana.com": 4,
        "photorank.me": 4,
        "olark.com": 2,
        "olx-st.com": 8,
        "onap.io": 8,
        "omarsys.com": 4,
        "ometria.com": 4,
        "omgpm.com": 7,
        "omniconvert.com": 4,
        "omnidsp.com": 4,
        "oms.eu": 4,
        "omsnative.de": 4,
        "onaudience.com": 4,
        "btc-echode.api.oneall.com": 7,
        "tracking.onefeed.co.uk": 6,
        "onesignal.com": 5,
        "os.tc": 5,
        "stat.onestat.com": 6,
        "ocdn.eu": 8,
        "onet.pl": 8,
        "onetag.com": 4,
        "s-onetag.com": 4,
        "onetrust.com": 5,
        "fogl1onf.com": 4,
        "onfocus.io": 4,
        "onlinewebstat.com": 6,
        "onlinewebstats.com": 6,
        "onswipe.com": 4,
        "onthe.io": 6,
        "moon-ray.com": 4,
        "moonraymarketing.com": 4,
        "ooyala.com": 0,
        "openadex.dk": 4,
        "247realmedia.com": 4,
        "oaserve.com": 4,
        "realmedia.com": 4,
        "realmediadigital.com": 4,
        "opensharecount.com": 4,
        "chatgpt.com": 8,
        "oaistatic.com": 8,
        "oaiusercontent.com": 8,
        "openai.com": 8,
        "oloadcdn.net": 9,
        "openload.co": 9,
        "openstat.net": 6,
        "spylog.com": 6,
        "spylog.ru": 6,
        "opentracker.net": 6,
        "openwebanalytics.com": 6,
        "odnxs.net": 4,
        "openx.net": 4,
        "openx.org": 4,
        "openxenterprise.com": 4,
        "servedbyopenx.com": 4,
        "adsummos.net": 4,
        "opinary.com": 2,
        "opinionbar.com": 2,
        "emagazines.com": 6,
        "allawnos.com": 101,
        "allawntech.com": 101,
        "heytapdl.com": 101,
        "heytapmobi.com": 101,
        "heytapmobile.com": 101,
        "oppomobile.com": 101,
        "opta.net": 6,
        "optaim.com": 4,
        "cookielaw.org": 5,
        "service.optify.net": 4,
        "optimatic.com": 0,
        "optmd.com": 4,
        "optimicdn.com": 9,
        "optimizely.com": 6,
        "episerver.net": 6,
        "optimonk.com": 6,
        "mstrlytcs.com": 2,
        "optmnstr.com": 2,
        "optmstr.com": 2,
        "optnmstr.com": 2,
        "optincollect.com": 4,
        "volvelle.tech": 4,
        "ora.tv": 4,
        "oracleinfinity.io": 6,
        "instantservice.com": 2,
        "ts.istrack.com": 2,
        "rightnowtech.com": 8,
        "rnengage.com": 8,
        "orange.fr": 4,
        "orangeads.fr": 4,
        "ads.orange142.com": 4,
        "wanadoo.fr": 8,
        "otracking.com": 4,
        "emxdgt.com": 4,
        "static.ordergroove.com": 4,
        "orelsite.ru": 2,
        "otclick-adv.ru": 4,
        "othersearch.info": 8,
        "otm-r.com": 4,
        "otto.de": 8,
        "ottogroup.media": 8,
        "outbrain.com": 4,
        "outbrainimg.com": 4,
        "live.com": 13,
        "cloud.microsoft": 13,
        "hotmail.com": 13,
        "outlook.com": 13,
        "svc.ms": 13,
        "overheat.it": 6,
        "oewabox.at": 6,
        "owneriq.net": 4,
        "ownpage.fr": 2,
        "owox.com": 6,
        "adconnexa.com": 2,
        "adsbwm.com": 2,
        "oxomi.com": 4,
        "oztam.com.au": 8,
        "pageanalytics.space": 11,
        "blockmetrics.com": 2,
        "pagefair.com": 2,
        "pagefair.net": 2,
        "btloader.com": 2,
        "ghmedia.com": 4,
        "777seo.com": 4,
        "paid-to-promote.net": 4,
        "ptp22.com": 4,
        "ptp33.com": 4,
        "paperg.com": 4,
        "pardot.com": 6,
        "d1z2jf7jlzjs58.cloudfront.net": 6,
        "parsely.com": 6,
        "partner-ads.com": 4,
        "passionfruitads.com": 4,
        "pathful.com": 6,
        "pay-hit.com": 4,
        "payclick.it": 4,
        "app.paykickstart.com": 6,
        "paypal.com": 2,
        "paypalobjects.com": 2,
        "pcvark.com": 11,
        "peer39.com": 4,
        "peer39.net": 4,
        "peer5.com": 9,
        "peerius.com": 2,
        "pendo.io": 6,
        "pepper.com": 4,
        "gopjn.com": 4,
        "pjatr.com": 4,
        "pjtra.com": 4,
        "pntra.com": 4,
        "pntrac.com": 4,
        "pntrs.com": 4,
        "player.pepsia.com": 6,
        "perfdrive.com": 11,
        "perfectaudience.com": 4,
        "prfct.co": 4,
        "perfectmarket.com": 4,
        "perfops.io": 6,
        "performgroup.com": 5,
        "analytics.performable.com": 6,
        "performancing.com": 6,
        "performax.cz": 4,
        "perimeterx.net": 6,
        "permutive.com": 4,
        "persgroep.net": 4,
        "persianstat.com": 6,
        "code.pers.io": 4,
        "counter.personyze.com": 2,
        "petametrics.com": 2,
        "ads.pheedo.com": 4,
        "app.phonalytics.com": 2,
        "d2bgg7rjywcwsy.cloudfront.net": 4,
        "piguiqproxy.com": 11,
        "trgt.eu": 6,
        "pingdom.net": 6,
        "pinimg.com": 7,
        "pinterest.com": 7,
        "app.pipz.io": 4,
        "disabled.invalid": 6,
        "piwik.pro": 6,
        "adrta.com": 4,
        "app.pixelpop.co": 4,
        "pixfuture.net": 4,
        "vast1.pixfuture.com": 4,
        "piximedia.com": 4,
        "pizzaandads.com": 11,
        "ads.placester.net": 4,
        "d3uemyw1e5n0jw.cloudfront.net": 4,
        "pladform.com": 4,
        "tag.bi.serviceplan.com": 6,
        "pfrm.co": 4,
        "impact-ad.jp": 4,
        "loveadvert.ru": 4,
        "playbuzz.com": 2,
        "pof.com": 6,
        "plex.bz": 0,
        "plex.direct": 0,
        "plex.tv": 0,
        "analytics.plex.tv": 6,
        "metrics.plex.tv": 6,
        "plista.com": 4,
        "plugrush.com": 4,
        "pluso.ru": 7,
        "plutusads.com": 4,
        "pmddby.com": 12,
        "pnamic.com": 12,
        "po.st": 7,
        "widgets.getpocket.com": 6,
        "pocketcents.com": 4,
        "pointificsecure.com": 6,
        "pointroll.com": 4,
        "poirreleast.club": 11,
        "mediavoice.com": 4,
        "polar.me": 4,
        "polarmobile.com": 4,
        "polldaddy.com": 2,
        "polyad.net": 4,
        "polyfill.io": 8,
        "popads.net": 4,
        "popadscdn.net": 4,
        "popcash.net": 4,
        "popcashjs.b-cdn.net": 4,
        "desv383oqqc0.cloudfront.net": 6,
        "popin.cc": 7,
        "cdn.popmyads.com": 4,
        "poponclick.com": 4,
        "populis.com": 4,
        "populisengage.com": 4,
        "phncdn.com": 3,
        "pornhub.com": 3,
        "prscripts.com": 3,
        "prstatics.com": 3,
        "prwidgets.com": 3,
        "barra.brasil.gov.br": 4,
        "postaffiliatepro.com": 4,
        "powerlinks.com": 4,
        "powerreviews.com": 2,
        "powr.io": 6,
        "api.pozvonim.com": 4,
        "prebid.org": 4,
        "precisionclick.com": 4,
        "adserver.com.br": 4,
        "predicta.net": 4,
        "prnx.net": 4,
        "ppjol.com": 4,
        "ppjol.net": 4,
        "api.pressly.com": 4,
        "pricegrabber.com": 4,
        "cdn.pricespider.com": 4,
        "pmdrecrute.com": 4,
        "prismamediadigital.com": 4,
        "privy.com": 2,
        "pswec.com": 4,
        "prodperfect.com": 6,
        "lib.productsup.io": 4,
        "proadsnet.com": 6,
        "profitshare.ro": 6,
        "tracking.proformics.com": 6,
        "programattik.com": 4,
        "projectwonderful.com": 4,
        "propelmarketing.com": 4,
        "oclaserver.com": 4,
        "onclasrv.com": 4,
        "onclickads.net": 4,
        "onclkds.com": 4,
        "propellerads.com": 4,
        "propellerpops.com": 4,
        "proper.io": 4,
        "st-a.props.id": 4,
        "propvideo.net": 11,
        "tr.prospecteye.com": 4,
        "prosperent.com": 4,
        "prostor-lite.ru": 4,
        "reports.proton.me": 2,
        "providesupport.com": 2,
        "proximic.com": 4,
        "proxistore.com": 4,
        "pscp.tv": 7,
        "pstatic.net": 9,
        "psyma.com": 4,
        "ptengine.jp": 6,
        "pub-fit.com": 4,
        "pub.network": 4,
        "learnpipe.com": 2,
        "pubble.co": 2,
        "pubdirecte.com": 4,
        "pubgears.com": 4,
        "publicidees.com": 4,
        "publicidad.net": 4,
        "intgr.net": 4,
        "pubmatic.com": 4,
        "pubnub.com": 8,
        "puboclic.com": 4,
        "pulpix.com": 4,
        "tentaculos.net": 4,
        "pulse360.com": 4,
        "pulseinsights.com": 6,
        "contextweb.com": 4,
        "pulsepoint.com": 4,
        "punchtab.com": 4,
        "purch.com": 4,
        "servebom.com": 4,
        "purechat.com": 2,
        "cdn.pprl.io": 6,
        "oopt.fr": 4,
        "puserving.com": 11,
        "push.world": 2,
        "pushengage.com": 2,
        "pushame.com": 11,
        "zebra.pushbullet.com": 2,
        "pushcrew.com": 2,
        "pusher.com": 6,
        "pusherapp.com": 6,
        "pushnative.com": 11,
        "cdn.pushnews.eu": 4,
        "pushno.com": 11,
        "pushwhy.com": 11,
        "pushwoosh.com": 2,
        "pvclouds.com": 11,
        "ads.q1media.com": 4,
        "q1mediahydraplatform.com": 4,
        "q-divisioncdn.de": 4,
        "qbaka.net": 6,
        "track.qcri.org": 6,
        "collect.qeado.com": 6,
        "s.lianmeng.360.cn": 6,
        "qq.com": 2,
        "qrius.me": 7,
        "qualaroo.com": 6,
        "qualcomm.com": 8,
        "gpsonextra.net": 15,
        "izatcloud.net": 15,
        "xtracloud.net": 15,
        "bluecava.com": 4,
        "qualtrics.com": 6,
        "quantcast.com": 4,
        "quantserve.com": 4,
        "quantcount.com": 6,
        "quantummetric.com": 6,
        "quartic.pl": 6,
        "quarticon.com": 6,
        "d3c3cq33003psk.cloudfront.net": 6,
        "qubit.com": 6,
        "easyresearch.se": 2,
        "queue-it.net": 6,
        "quick-counter.net": 6,
        "adsonar.com": 4,
        "qnsr.com": 4,
        "quinstreet.com": 4,
        "thecounter.com": 4,
        "quintelligence.com": 6,
        "qservz.com": 4,
        "quisma.com": 4,
        "quora.com": 7,
        "ads-digitalkeys.com": 4,
        "rackcdn.com": 9,
        "radarurl.com": 6,
        "dsa.csdata1.com": 4,
        "gwallet.com": 4,
        "r1-cdn.net": 4,
        "widget.raisenow.com": 6,
        "mediaforge.com": 4,
        "rmtag.com": 4,
        "rakuten.co.jp": 4,
        "trafficgate.net": 4,
        "mtwidget04.affiliate.rakuten.co.jp": 4,
        "xml.affilliate.rakuten.co.jp": 4,
        "rambler.ru": 6,
        "top100.ru": 6,
        "rapidspike.com": 6,
        "ravelin.com": 6,
        "rawgit.com": 9,
        "raygun.io": 4,
        "count.rbc.ru": 6,
        "rcs.it": 4,
        "rcsmediagroup.it": 4,
        "d335luupugsy2.cloudfront.net": 6,
        "rea-group.com": 4,
        "reagroupdata.com.au": 4,
        "reastatic.net": 4,
        "d12ulf131zb0yj.cloudfront.net": 6,
        "reachforce.com": 6,
        "reachjunction.com": 4,
        "cdn.rlets.com": 4,
        "reachlocal.com": 4,
        "reachlocallivechat.com": 4,
        "rlcdn.net": 4,
        "plugin.reactful.com": 4,
        "reactivpub.fr": 6,
        "skinected.com": 4,
        "readrboard.com": 7,
        "readme.com": 6,
        "readme.io": 6,
        "readspeaker.com": 2,
        "realclick.co.kr": 4,
        "realestate.com.au": 4,
        "realperson.de": 2,
        "powermarketing.com": 2,
        "realtime.co": 2,
        "webspectator.com": 2,
        "dcniko1cv0rz.cloudfront.net": 6,
        "realytics.io": 6,
        "static.rbl.ms": 6,
        "recaptcha.net": 8,
        "recettes.net": 8,
        "static.recopick.com": 4,
        "recreativ.ru": 4,
        "analytics.recruitics.com": 6,
        "analytics.cohesionapps.com": 6,
        "cdn.cohesionapps.com": 6,
        "redblue.de": 6,
        "atendesoftware.pl": 9,
        "redd.it": 7,
        "reddit-image.s3.amazonaws.com": 7,
        "reddit.com": 7,
        "redditmedia.com": 7,
        "redditstatic.com": 7,
        "redhelper.ru": 2,
        "pixelinteractivemedia.com": 4,
        "triggit.com": 4,
        "grt01.com": 4,
        "grt02.com": 4,
        "redtram.com": 4,
        "rdtcdn.com": 9,
        "redtube.com": 9,
        "reduxmedia.com": 4,
        "reduxmediagroup.com": 4,
        "reedbusiness.net": 6,
        "reembed.com": 0,
        "reevoo.com": 4,
        "refericon.pl": 4,
        "ads.referlocal.com": 4,
        "refersion.com": 4,
        "refinedads.com": 4,
        "product.reflektion.com": 4,
        "reformal.ru": 2,
        "reinvigorate.net": 6,
        "convertglobal.com": 4,
        "convertglobal.s3.amazonaws.com": 4,
        "dnhgz729v27ca.cloudfront.net": 4,
        "reklamstore.com": 4,
        "ad.reklamport.com": 4,
        "delivery.reklamz.com": 4,
        "adimg.rekmob.com": 4,
        "relap.io": 4,
        "svtrd.com": 5,
        "synovite-scripts.com": 5,
        "tdn.r42tag.com": 5,
        "relestar.com": 6,
        "relevant4.com": 8,
        "remintrex.com": 4,
        "remove.video": 12,
        "rp-api.com": 4,
        "republer.com": 4,
        "resmeter.respublica.al": 6,
        "researchnow.com": 4,
        "reson8.com": 4,
        "respondhq.com": 4,
        "adinsight.com": 4,
        "adinsight.eu": 4,
        "responsetap.com": 4,
        "data.resultlinks.com": 4,
        "sli-system.com": 6,
        "retailrocket.net": 4,
        "retailrocket.ru": 4,
        "shopify.retargetapp.com": 4,
        "retargeter.com": 4,
        "retargeting.cl": 4,
        "d1stxfv94hrhia.cloudfront.net": 4,
        "waves.retentionscience.com": 4,
        "reutersmedia.net": 9,
        "revcontent.com": 4,
        "socialtwist.com": 4,
        "revenue.com": 4,
        "clkads.com": 4,
        "clkmon.com": 4,
        "clkrev.com": 4,
        "clksite.com": 4,
        "eclkspbn.com": 4,
        "imageshack.host": 4,
        "revenuemantra.com": 4,
        "revive-adserver.com": 4,
        "revolvermaps.com": 6,
        "cts.tradepub.com": 4,
        "revresponse.com": 4,
        "incontext.pl": 4,
        "pl-engine.intextad.net": 4,
        "addesktop.com": 4,
        "1rx.io": 4,
        "ria.ru": 8,
        "rmbn.ru": 4,
        "ics0.com": 2,
        "richrelevance.com": 2,
        "ringier.ch": 6,
        "meteorsolutions.com": 7,
        "riskified.com": 2,
        "rncdn3.com": 9,
        "ro2.biz": 4,
        "rbxcdn.com": 8,
        "getrockerbox.com": 6,
        "rocket.la": 4,
        "trk.sodoit.com": 4,
        "collector.roistat.com": 6,
        "rollad.ru": 4,
        "d37gvrvc0wt4s1.cloudfront.net": 6,
        "get.roost.me": 6,
        "getrooster.com": 6,
        "rqtrk.eu": 4,
        "rotaban.ru": 4,
        "routenplaner-karten.com": 2,
        "rovion.com": 4,
        "rsspump.com": 2,
        "creativecdn.com": 4,
        "rvty.net": 4,
        "rtbsuperhub.com": 4,
        "rtl.de": 8,
        "static-fra.de": 8,
        "technical-service.net": 8,
        "rtmark.net": 4,
        "dpclk.com": 4,
        "mobsmith.com": 4,
        "nearbyad.com": 4,
        "rubiconproject.com": 4,
        "tracker.ruhrgebiet-onlineservices.de": 4,
        "click.rummycircle.com": 4,
        "runadtag.com": 4,
        "rundsp.com": 4,
        "un-syndicate.com": 4,
        "cdn.secretrune.com": 6,
        "runmewivel.com": 10,
        "rhythmxchange.com": 0,
        "s24.com": 4,
        "s3xified.com": 11,
        "camp.sabavision.com": 4,
        "sageanalyst.net": 4,
        "sail-horizon.com": 4,
        "sail-personalize.com": 4,
        "sailthru.com": 4,
        "d16fk4ms6rqz1v.cloudfront.net": 4,
        "salecycle.com": 4,
        "api.salesfeed.com": 4,
        "salesmanago.com": 6,
        "salesmanago.pl": 6,
        "force.com": 4,
        "salesforce.com": 4,
        "liveagentforsalesforce.com": 2,
        "salesforceliveagent.com": 2,
        "msgapp.com": 4,
        "salespidermedia.com": 4,
        "salesviewer.com": 6,
        "samba.tv": 4,
        "game-mode.net": 8,
        "gos-gsp.io": 8,
        "lldns.net": 8,
        "pavv.co.kr": 8,
        "remotesamsung.com": 8,
        "samsung-gamelauncher.com": 8,
        "samsung.co.kr": 8,
        "samsung.com": 8,
        "samsung.com.cn": 8,
        "samsungcloud.com": 8,
        "samsungcloudcdn.com": 8,
        "samsungcloudprint.com": 8,
        "samsungcloudsolution.com": 8,
        "samsungcloudsolution.net": 8,
        "samsungelectronics.com": 8,
        "samsunghealth.com": 8,
        "samsungiotcloud.com": 8,
        "samsungknox.com": 8,
        "samsungnyc.com": 8,
        "samsungosp.com": 8,
        "samsungotn.net": 8,
        "samsungpositioning.com": 8,
        "samsungqbe.com": 8,
        "samsungrm.net": 8,
        "samsungrs.com": 8,
        "samsungsemi.com": 8,
        "samsungsetup.com": 8,
        "samsungusa.com": 8,
        "secb2b.com": 8,
        "smartthings.com": 8,
        "adgear.com": 4,
        "adgrx.com": 4,
        "samsungacr.com": 4,
        "samsungadhub.com": 4,
        "samsungads.com": 4,
        "samsungtifa.com": 4,
        "aibixby.com": 101,
        "findmymobile.samsung.com": 101,
        "samsapps.cust.lldns.net": 101,
        "samsung-omc.com": 101,
        "samsungapps.com": 101,
        "samsungdiroute.net": 101,
        "samsungdive.com": 101,
        "samsungdm.com": 101,
        "samsungdmroute.com": 101,
        "samsungmdec.com": 101,
        "samsungvisioncloud.com": 101,
        "sbixby.com": 101,
        "ospserver.net": 101,
        "samsungdms.net": 101,
        "samsungmax.com": 101,
        "samsungmobile.com": 101,
        "secmobilesvc.com": 101,
        "push.samsungosp.com": 8,
        "pushmessage.samsung.com": 8,
        "scs.samsungqbe.com": 8,
        "ssp.samsung.com": 8,
        "samsungsds.com": 10,
        "internetat.tv": 15,
        "samsungcloud.tv": 15,
        "tizenservice.com": 15,
        "ilsemedia.nl": 4,
        "sanoma.fi": 4,
        "d13im3ek7neeqp.cloudfront.net": 6,
        "d28ethi6slcjbm.cloudfront.net": 6,
        "d2uevgmgh16uk4.cloudfront.net": 6,
        "d3m83gvgzupli.cloudfront.net": 6,
        "saas.seewhy.com": 6,
        "leadforce1.com": 2,
        "vlog.leadformix.com": 2,
        "sap-xm.org": 4,
        "sape.ru": 6,
        "js.sl.pt": 4,
        "aimatch.com": 6,
        "sas.com": 6,
        "say.ac": 4,
        "ads.saymedia.com": 4,
        "srv.sayyac.net": 6,
        "scarabresearch.com": 4,
        "schibsted.com": 8,
        "schibsted.io": 8,
        "schneevonmorgen.com": 0,
        "svonm.com": 0,
        "rockabox.co": 4,
        "scorecardresearch.com": 6,
        "scoreresearch.com": 6,
        "scrsrch.com": 6,
        "securestudies.com": 6,
        "scout.scoutanalytics.net": 4,
        "scribblelive.com": 8,
        "scribol.com": 4,
        "analytics.snidigital.com": 6,
        "scroll.com": 5,
        "scupio.com": 4,
        "search123.uk.com": 4,
        "searchforce.net": 4,
        "searchignite.com": 4,
        "srtk.net": 4,
        "tacticalrepublic.com": 4,
        "sectigo.com": 5,
        "securedtouch.com": 6,
        "securedvisit.com": 4,
        "bacontent.de": 4,
        "nativendo.de": 4,
        "seedtag.com": 4,
        "svlu.net": 6,
        "d2dq2ahtl5zl1z.cloudfront.net": 6,
        "d47xnnr8b1rki.cloudfront.net": 6,
        "segment.com": 6,
        "segment.io": 6,
        "rutarget.ru": 4,
        "segmint.net": 6,
        "sekindo.com": 4,
        "sellpoint.net": 4,
        "sellpoints.com": 4,
        "semantiqo.com": 4,
        "semasio.net": 4,
        "semilo.com": 4,
        "semknox.com": 5,
        "sibautomation.com": 4,
        "sendpulse.com": 3,
        "sendsay.ru": 2,
        "track.sensedigital.in": 6,
        "static.sensorsdata.cn": 6,
        "sentifi.com": 6,
        "d3nslu0hdya83q.cloudfront.net": 6,
        "getsentry.com": 6,
        "ravenjs.com": 6,
        "sentry.io": 6,
        "sepyra.com": 4,
        "d2oh4tlt9mrke9.cloudfront.net": 6,
        "sessioncam.com": 6,
        "sessionly.io": 2,
        "71i.de": 4,
        "sexad.net": 3,
        "ads.sexinyourcity.com": 3,
        "sextracker.com": 3,
        "sexypartners.net": 3,
        "im.cz": 6,
        "imedia.cz": 6,
        "szn.cz": 6,
        "dtym7iokkjlif.cloudfront.net": 6,
        "shareaholic.com": 6,
        "shareasale.com": 4,
        "quintrics.nl": 2,
        "sharecompany.nl": 2,
        "sharepointonline.com": 8,
        "onmicrosoft.com": 8,
        "sharepoint.com": 8,
        "sharethis.com": 4,
        "shareth.ru": 4,
        "sharethrough.com": 4,
        "marketingautomation.services": 6,
        "sharpspring.com": 6,
        "sheego.de": 8,
        "services.sheerid.com": 4,
        "shinystat.com": 6,
        "shinystat.it": 6,
        "app.shoptarget.com.br": 4,
        "retargeter.com.br": 4,
        "shopauskunft.de": 2,
        "shopgate.com": 2,
        "shopify.com": 2,
        "shopifycdn.com": 2,
        "cdn.shopify.com": 2,
        "myshopify.com": 2,
        "shop.app": 2,
        "shopify.co.za": 2,
        "shopify.com.au": 2,
        "shopify.com.mx": 2,
        "shopify.dev": 2,
        "shopifyapps.com": 2,
        "shopifycdn.net": 2,
        "shopifynetwork.com": 2,
        "shopifypreview.com": 2,
        "shopifysvc.com": 6,
        "stats.shopify.com": 6,
        "v.shopify.com": 6,
        "shopifycloud.com": 2,
        "shopperapproved.com": 2,
        "shoppingshadow.com": 4,
        "tracking.shopping-flux.com": 6,
        "shoprunner.com": 2,
        "shopsocially.com": 2,
        "shopzilla.com": 4,
        "shortnews.de": 8,
        "showrss.info": 8,
        "shink.in": 2,
        "shutterstock.com": 8,
        "siblesectiveal.club": 11,
        "d3v27wwd40f0xu.cloudfront.net": 6,
        "getsidecar.com": 6,
        "dtlilztwypawv.cloudfront.net": 6,
        "siftscience.com": 6,
        "btstatic.com": 5,
        "signal.co": 5,
        "thebrighttag.com": 5,
        "cdn-scripts.signifyd.com": 6,
        "signifyd.com": 6,
        "gw-services.vtrenz.net": 2,
        "mkt51.net": 2,
        "mkt912.com": 2,
        "mkt922.com": 2,
        "mkt941.com": 2,
        "pages01.net": 2,
        "pages02.net": 2,
        "pages04.net": 2,
        "pages05.net": 2,
        "similardeals.net": 8,
        "similarweb.com": 6,
        "similarweb.io": 6,
        "d8rk54i4mohrb.cloudfront.net": 6,
        "simplereach.com": 6,
        "simpli.fi": 4,
        "sina.com.cn": 6,
        "sinaimg.cn": 9,
        "reporting.singlefeed.com": 4,
        "sddan.com": 6,
        "site24x7rum.com": 6,
        "site24x7rum.eu": 6,
        "sitebooster-fjfmworld-production.azureedge.net": 7,
        "a5.ogt.jp": 4,
        "siteapps.com": 2,
        "sitebro.com": 6,
        "sitebro.com.tw": 6,
        "sitebro.net": 6,
        "sitebro.tw": 6,
        "siteheart.com": 2,
        "siteimprove.com": 6,
        "siteimproveanalytics.com": 6,
        "sitelabweb.com": 11,
        "sitemeter.com": 6,
        "pixel.ad": 4,
        "sitescout.com": 4,
        "ad.sitemaji.com": 2,
        "sitetag.us": 2,
        "analytics.sitewit.com": 4,
        "ads.sixapart.com": 4,
        "sixt-neuwagen.de": 8,
        "skadtec.com": 6,
        "redirectingat.com": 4,
        "skimlinks.com": 4,
        "skimresources.com": 4,
        "analytics.skroutz.gr": 6,
        "skyglue.com": 6,
        "skype.com": 2,
        "skypeassets.com": 2,
        "skysa.com": 2,
        "skyscnr.com": 9,
        "slack-edge.com": 8,
        "slack-imgs.com": 8,
        "slack.com": 8,
        "slackb.com": 8,
        "slashdot.org": 2,
        "sleeknotestaticcontent.sleeknote.com": 2,
        "resultspage.com": 2,
        "builder.extensionfactory.com": 2,
        "freeskreen.com": 6,
        "slingpic.com": 4,
        "smaato.net": 4,
        "smart4ads.com": 4,
        "sascdn.com": 4,
        "smartadserver.com": 4,
        "styria-digital.com": 4,
        "yoc-adserver.com": 4,
        "smartcall.kz": 2,
        "getsmartcontent.com": 4,
        "smartdevicemedia.com": 4,
        "x.cnt.my": 4,
        "tracking.smartselling.cz": 2,
        "bepolite.eu": 4,
        "smartbn.ru": 4,
        "smartclick.net": 4,
        "smartclip.net": 4,
        "smartcontext.pl": 4,
        "d1n00d49gkbray.cloudfront.net": 4,
        "dhxtx5wtu812h.cloudfront.net": 4,
        "smartertravel.com": 4,
        "travelsmarter.net": 4,
        "smct.co": 4,
        "smartertrack.com": 4,
        "smartlink.cool": 11,
        "getsmartlook.com": 2,
        "smartlook.com": 2,
        "smartstream.tv": 4,
        "smartsuppchat.com": 2,
        "smi2.net": 6,
        "smi2.ru": 6,
        "stat.media": 6,
        "cdn.smooch.io": 2,
        "smowtion.com": 4,
        "smxindia.in": 6,
        "smyte.com": 6,
        "snacktv.de": 6,
        "snap.com": 2,
        "addlive.io": 2,
        "feelinsonice.com": 2,
        "sc-cdn.net": 2,
        "sc-corp.net": 2,
        "sc-gw.com": 2,
        "sc-jpl.com": 2,
        "sc-prod.net": 2,
        "snap-dev.net": 2,
        "snapads.com": 2,
        "snapkit.com": 2,
        "snapengage.com": 2,
        "sc-static.net": 4,
        "snapchat.com": 4,
        "snapcraft.io": 8,
        "snapcraftcontent.com": 8,
        "h-bid.com": 4,
        "eu2.snoobi.eu": 6,
        "snoobi.com": 6,
        "d346whrrklhco7.cloudfront.net": 6,
        "d78fikflryjgj.cloudfront.net": 6,
        "dc8xl0ndzn2cb.cloudfront.net": 6,
        "playwire.com": 6,
        "snplow.net": 6,
        "go-mpulse.net": 6,
        "mpstat.us": 6,
        "tiaa-cref.org": 6,
        "sociablelabs.com": 4,
        "socialamp.com": 4,
        "socialannex.com": 4,
        "soclminer.com.br": 7,
        "duu8lzqdm8tsz.cloudfront.net": 4,
        "ratevoice.com": 7,
        "sociaplus.com": 6,
        "sociomantic.com": 4,
        "images.sohu.com": 7,
        "sojern.com": 4,
        "sokrati.com": 4,
        "solads.media": 4,
        "solaredge.com": 8,
        "solidopinion.com": 2,
        "pixel.solvemedia.com": 4,
        "soma2.de": 4,
        "mobileadtrading.com": 4,
        "sonobi.com": 4,
        "sonos.com": 8,
        "sophus3.com": 4,
        "deployads.com": 4,
        "sndcdn.com": 0,
        "soundcloud.com": 0,
        "provenpixel.com": 4,
        "decenthat.com": 4,
        "summerhamster.com": 4,
        "d3pkae9owd2lcf.cloudfront.net": 4,
        "lijit.com": 4,
        "onscroll.com": 4,
        "rts.sparkstudios.com": 0,
        "sparkasse.de": 8,
        "speakpipe.com": 2,
        "adviva.net": 4,
        "specificclick.net": 4,
        "specificmedia.com": 4,
        "spectate.com": 6,
        "speedshiftmedia.com": 4,
        "speedcurve.com": 6,
        "admarket.entireweb.com": 4,
        "affiliate.entireweb.com": 4,
        "sa.entireweb.com": 4,
        "speee-ad.akamaized.net": 4,
        "sphere.com": 4,
        "surphace.com": 4,
        "api.spheremall.com": 6,
        "zdwidget3-bs.sphereup.com": 2,
        "static.sspicy.ru": 4,
        "spider.ad": 4,
        "metrics.spiderads.eu": 4,
        "spn.ee": 6,
        "embed.spokenlayer.com": 0,
        "spongecell.com": 4,
        "sponsorads.de": 4,
        "sportsbetaffiliates.com.au": 4,
        "spot.im": 7,
        "spoteffects.net": 6,
        "scdn.co": 0,
        "spotify.com": 0,
        "pscdn.co": 0,
        "spotifycdn.com": 0,
        "spotifycdn.net": 0,
        "spotilocal.com": 0,
        "embed.spotify.com": 0,
        "spotscenered.info": 11,
        "spotx.tv": 4,
        "spotxcdn.com": 4,
        "spotxchange.com": 4,
        "spoutable.com": 4,
        "cdn.springboardplatform.com": 4,
        "springserve.com": 4,
        "pixel.sprinklr.com": 4,
        "stat.sputnik.ru": 6,
        "email-match.com": 4,
        "squarespace.com": 6,
        "srvtrck.com": 12,
        "srvvtrk.com": 11,
        "sstatic.net": 9,
        "hatena.ne.jp": 7,
        "st-hatena.com": 7,
        "stackadapt.com": 4,
        "stackpathdns.com": 9,
        "stailamedia.com": 4,
        "stalluva.pro": 11,
        "startappservice.com": 4,
        "hit.stat24.com": 6,
        "adstat.4u.pl": 6,
        "stat.4u.pl": 6,
        "statcounter.com": 6,
        "stathat.com": 6,
        "statisfy.net": 6,
        "statsy.net": 11,
        "statuscake.com": 6,
        "statuspage.io": 2,
        "stspg-customer.com": 2,
        "stayfriends.de": 8,
        "steelhousemedia.com": 4,
        "steepto.com": 4,
        "stepstone.com": 8,
        "4stats.de": 6,
        "stetic.com": 6,
        "stickyadstv.com": 4,
        "stocktwits.com": 2,
        "storify.com": 4,
        "storygize.net": 4,
        "bizsolutions.strands.com": 4,
        "strava.com": 6,
        "mailfoogae.appspot.com": 2,
        "streamotion.com.au": 0,
        "streamrail.com": 4,
        "streamrail.net": 4,
        "stridespark.com": 6,
        "stripcdn.com": 3,
        "stripchat.com": 3,
        "stripe.com": 2,
        "stripe.network": 2,
        "stripst.com": 3,
        "interactivemedia.net": 4,
        "stroeerdigitalgroup.de": 4,
        "stroeerdigitalmedia.de": 4,
        "stroeerdp.de": 4,
        "stroeermediabrands.de": 4,
        "spklw.com": 4,
        "sprinklecontent.com": 4,
        "strossle.it": 4,
        "struq.com": 4,
        "stumble-upon.com": 7,
        "stumbleupon.com": 7,
        "su.pr": 7,
        "sub2tech.com": 4,
        "ayads.co": 4,
        "suggest.io": 4,
        "sumologic.com": 6,
        "sumo.com": 6,
        "sumome.com": 6,
        "sundaysky.com": 4,
        "supercell.com": 2,
        "supercellsupport.com": 2,
        "supercounters.com": 6,
        "superfastcdn.com": 11,
        "socdm.com": 4,
        "supplyframe.com": 4,
        "surfingbird.ru": 2,
        "px.surveywall-api.survata.com": 4,
        "cdn.sweettooth.io": 2,
        "swiftypecdn.com": 9,
        "swisscom.ch": 8,
        "myswitchads.com": 4,
        "switchadhub.com": 4,
        "switchads.com": 4,
        "switchafrica.com": 4,
        "switch.tv": 8,
        "shopximity.com": 4,
        "swoop.com": 4,
        "analytics-cdn.sykescottages.co.uk": 6,
        "norton.com": 5,
        "seal.verisign.com": 5,
        "symantec.com": 5,
        "d.hodes.com": 2,
        "technorati.com": 4,
        "technoratimedia.com": 4,
        "cn.clickable.net": 4,
        "synergy-e.com": 4,
        "sdp-campaign.de": 8,
        "t-online.de": 8,
        "telekom-dienste.de": 8,
        "telekom.com": 8,
        "telekom.de": 8,
        "toi.de": 8,
        "t8cdn.com": 11,
        "tableteducation.com": 11,
        "basebanner.com": 4,
        "taboola.com": 4,
        "taboolasyndication.com": 4,
        "tacoda.net": 4,
        "commander1.com": 5,
        "tagcommander.com": 5,
        "tags.tagcade.com": 4,
        "taggify.net": 4,
        "taggyad.jp": 4,
        "levexis.com": 5,
        "tailtarget.com": 6,
        "tailsweep.com": 4,
        "tamedia.ch": 4,
        "tanx.com": 4,
        "alipcsec.com": 4,
        "taobao.com": 4,
        "tapad.com": 4,
        "theblogfrog.com": 4,
        "tarafdari.com": 4,
        "target2sell.com": 4,
        "trackmytarget.com": 6,
        "cdn.targetfuel.com": 6,
        "tawk.to": 2,
        "tbn.ru": 4,
        "tchibo-content.de": 8,
        "tchibo.de": 8,
        "tdsrmbl.net": 8,
        "teads.tv": 4,
        "tealeaf.ibmcloud.com": 6,
        "tealium.com": 5,
        "tealium.hs.llnwd.net": 5,
        "tealiumiq.com": 5,
        "tiqcdn.com": 5,
        "teaser.cc": 4,
        "emailretargeting.com": 4,
        "tracking.dsmmadvantage.com": 4,
        "telstra.com": 8,
        "telstra.com.au": 8,
        "tenderapp.com": 2,
        "tensitionschoo.club": 11,
        "watch.teroti.com": 4,
        "webterren.com": 4,
        "teufel.de": 8,
        "theadex.com": 4,
        "connect.decknetwork.net": 4,
        "gu-web.net": 8,
        "guardianapps.co.uk": 8,
        "guim.co.uk": 8,
        "deepthought.online": 4,
        "reachgroup.com": 4,
        "redintelligence.net": 4,
        "thesearchagency.net": 4,
        "thesun.co.uk": 8,
        "w-x.co": 4,
        "weather.com": 4,
        "wfxtriggers.com": 4,
        "tmdb.org": 8,
        "thinglink.com": 4,
        "online-metrix.net": 6,
        "tidbit.co.in": 2,
        "code.tidio.co": 2,
        "widget-v4.tidiochat.com": 2,
        "analytics.tiktok.com": 6,
        "optimized.by.tiller.co": 4,
        "vip.timezonedb.com": 4,
        "npttech.com": 5,
        "tinypass.com": 5,
        "tisoomi-services.com": 4,
        "ad.tlvmedia.com": 4,
        "ads.tlvmedia.com": 4,
        "tag.tlvmedia.com": 4,
        "research-int.se": 6,
        "sesamestats.com": 6,
        "spring-tns.net": 6,
        "statistik-gallup.net": 6,
        "tns-cs.net": 6,
        "tns-gallup.dk": 6,
        "tomnewsupdate.info": 12,
        "tfag.de": 4,
        "srv.clickfuse.com": 4,
        "toplist.cz": 11,
        "toponclick.com": 11,
        "topsy.com": 4,
        "insight.torbit.com": 6,
        "toro-tags.com": 4,
        "toroadvertising.com": 4,
        "toroadvertisingmedia.com": 4,
        "tororango.com": 11,
        "i.total-media.net": 4,
        "inq.com": 2,
        "tovarro.com": 4,
        "rialpay.com": 4,
        "tp-cdn.com": 4,
        "kiwe.io": 6,
        "tracc.it": 6,
        "ipnoid.com": 4,
        "tracemyip.org": 4,
        "d2gfdmu30u15x7.cloudfront.net": 6,
        "tracelytics.com": 6,
        "cdn.trackduck.com": 6,
        "d2zah9y47r7bi2.cloudfront.net": 6,
        "dl1d2m8ri9v3j.cloudfront.net": 6,
        "trackjs.com": 6,
        "conversionlab.trackset.com": 4,
        "trackuity.com": 2,
        "adsrvr.org": 4,
        "tradedoubler.com": 4,
        "tradelab.fr": 4,
        "tradetracker.net": 4,
        "cdntrf.com": 4,
        "traffective.com": 4,
        "my.trafficfuel.com": 4,
        "trafficrevenue.net": 4,
        "trafficstars.com": 3,
        "tsyndicate.com": 3,
        "trafficbroker.com": 4,
        "trafficfabrik.com": 3,
        "trafficfactory.biz": 4,
        "trafficforce.com": 4,
        "traffichaus.com": 3,
        "trafficjunky.net": 3,
        "traffiliate.com": 4,
        "storage.trafic.ro": 6,
        "trafmag.com": 4,
        "api.transcend.io": 14,
        "cdn.transcend.io": 14,
        "sync-transcend-cdn.com": 14,
        "transcend-cdn.com": 14,
        "transcend.io": 14,
        "telemetry.transcend.io": 6,
        "backoffice.transmatico.com": 6,
        "travelaudience.com": 6,
        "trbo.com": 4,
        "treasuredata.com": 6,
        "scanscout.com": 0,
        "tremorhub.com": 0,
        "tremormedia.com": 0,
        "tremorvideo.com": 0,
        "videohub.tv": 0,
        "s.tcimg.com": 6,
        "tcimg.com": 6,
        "trendemon.com": 6,
        "exponential.com": 4,
        "tribalfusion.com": 4,
        "tribl.io": 6,
        "api.temails.com": 4,
        "t.myvisitors.se": 2,
        "jscache.com": 8,
        "tacdn.com": 8,
        "tamgrt.com": 8,
        "tripadvisor.co.uk": 8,
        "tripadvisor.com": 8,
        "tripadvisor.de": 8,
        "3lift.com": 4,
        "d3iwjrnl4m67rd.cloudfront.net": 4,
        "triplelift.com": 4,
        "static.triptease.io": 2,
        "andomedia.com": 0,
        "tritondigital.com": 0,
        "revelations.trovus.co.uk": 4,
        "trsv3.com": 11,
        "truefitcorp.com": 4,
        "tru.am": 4,
        "adlegend.com": 4,
        "addoer.com": 6,
        "truehits.in.th": 6,
        "truehits.net": 6,
        "trumba.com": 4,
        "truoptik.com": 6,
        "trustarc.com": 5,
        "truste.com": 5,
        "consent.truste.com": 5,
        "choices-or.truste.com": 5,
        "choices.truste.com": 5,
        "privacy-policy.truste.com": 5,
        "trustedshops.com": 5,
        "trustev.com": 6,
        "secure.comodo.net": 5,
        "trustlogo.com": 5,
        "usertrust.com": 5,
        "trustpilot.com": 2,
        "trustwave.com": 8,
        "tubecorporate.com": 3,
        "tubecup.org": 3,
        "tubemogul.com": 4,
        "sre-perim.com": 6,
        "txmblr.com": 6,
        "platform.tumblr.com": 7,
        "lib.tunein.com": 0,
        "adagio.turboadv.com": 4,
        "turn.com": 4,
        "ngtv.io": 6,
        "turner.com": 6,
        "warnermedia.com": 6,
        "turnsocial.com": 7,
        "turnto.com": 2,
        "tvsquared.com": 4,
        "tweetboard.com": 7,
        "tweetmeme.com": 7,
        "c4tw.net": 4,
        "twiago.com": 4,
        "twinedigital.go2cloud.org": 6,
        "ext-twitch.tv": 0,
        "twitch.tv": 0,
        "jtvnw.net": 0,
        "ttvnw.net": 0,
        "twitchcdn.net": 0,
        "twitchsvc.net": 0,
        "t.co": 7,
        "twimg.com": 7,
        "twitter.com": 7,
        "twttr.com": 7,
        "x.com": 7,
        "ads-twitter.com": 4,
        "analytics.twitter.com": 6,
        "tellapart.com": 4,
        "syndication.twitter.com": 7,
        "twittercounter.com": 6,
        "twyn.com": 4,
        "txxx.com": 8,
        "tynt.com": 4,
        "typeform.com": 2,
        "typepad.com": 6,
        "typography.com": 9,
        "tyroodirect.com": 7,
        "tyroodr.com": 7,
        "tzetze.it": 2,
        "ubersetzung-app.com": 12,
        "ubuntu.com": 8,
        "ubuntucompanyservices.co.za": 8,
        "aralego.net": 4,
        "ucfunnel.com": 4,
        "at.ua": 6,
        "do.am": 6,
        "ucoz.net": 6,
        "ad-api-v01.uliza.jp": 4,
        "api.umbel.com": 6,
        "umebiggestern.club": 11,
        "unanimis.co.uk": 4,
        "d3pkntwtp2ukl5.cloudfront.net": 6,
        "t.unbounce.com": 6,
        "d21gpk1vhmjuf5.cloudfront.net": 6,
        "tracker.unbxdapi.com": 6,
        "under-box.com": 12,
        "undercomputer.com": 11,
        "udmserve.net": 4,
        "undertone.com": 4,
        "roitesting.com": 2,
        "unica.com": 2,
        "unister-adservices.com": 6,
        "unister-gmbh.de": 6,
        "uadx.com": 4,
        "nonstoppartner.net": 4,
        "tifbs.net": 4,
        "ui-portal.de": 4,
        "uimserv.net": 4,
        "unity.com": 8,
        "unity3d.com": 8,
        "unity3dusercontent.com": 8,
        "unityads.unity3d.com": 4,
        "univide.com": 4,
        "unpkg.com": 9,
        "unrulymedia.com": 4,
        "src.kitcode.net": 6,
        "s.clickability.com": 4,
        "uppr.de": 4,
        "upravel.com": 11,
        "upsellit.com": 2,
        "kontagent.net": 6,
        "app.uptain.de": 6,
        "uptolike.com": 7,
        "uptrends.com": 6,
        "urban-media.com": 4,
        "urbanairship.com": 6,
        "mobile.usabilitytools.com": 6,
        "usabilla.com": 2,
        "usemax.de": 4,
        "usemaxserver.de": 4,
        "usemessages.com": 11,
        "api.usercycle.com": 6,
        "userdive.com": 6,
        "userecho.com": 2,
        "dq4irj27fs462.cloudfront.net": 2,
        "userlike-cdn-widgets.s3-eu-west-1.amazonaws.com": 2,
        "userlike.com": 2,
        "contactusplus.com": 2,
        "user-pulse.appspot.com": 2,
        "userpulse.com": 2,
        "userreplay.net": 6,
        "sdsbucket.s3.amazonaws.com": 2,
        "userreport.com": 2,
        "dtkm4pd19nw6z.cloudfront.net": 2,
        "api.usersnap.com": 2,
        "d3mvnvhjmkxpjz.cloudfront.net": 2,
        "uservoice.com": 2,
        "userzoom.com": 2,
        "usocial.pro": 7,
        "utarget.ru": 4,
        "uuidksinc.net": 11,
        "v12group.com": 6,
        "vacaneedasap.com": 11,
        "ads.brand.net": 4,
        "vdrn.redplum.com": 4,
        "api.searchlinks.com": 4,
        "js.searchlinks.com": 4,
        "vinsight.de": 4,
        "valueclick.net": 4,
        "valuecommerce.com": 4,
        "valuedopinions.co.uk": 4,
        "buzzparadise.com": 4,
        "vmmpxl.com": 4,
        "vcita.com": 6,
        "tracking.vcommission.com": 4,
        "vdopia.com": 4,
        "veinteractive.com": 4,
        "vee24.com": 0,
        "velocecdn.com": 11,
        "mdcn.mobi": 4,
        "velti.com": 4,
        "vendemore.com": 1,
        "venturead.com": 11,
        "api.venyoo.ru": 2,
        "veoxa.com": 4,
        "vergic.com": 1,
        "d3qxef4rp70elm.cloudfront.net": 4,
        "getvero.com": 4,
        "verticalacuity.com": 4,
        "roi.vertical-leap.co.uk": 4,
        "cts.vresp.com": 4,
        "verticalscope.com": 4,
        "ads.vertoz.com": 4,
        "banner.vrtzads.com": 4,
        "veruta.com": 4,
        "vrvm.com": 4,
        "vgwort.de": 6,
        "digitaltarget.ru": 4,
        "btg.mtvnservices.com": 4,
        "viafoura.com": 4,
        "viafoura.net": 4,
        "intellitxt.com": 4,
        "vicomi.com": 6,
        "vidazoo.com": 4,
        "module-videodesk.com": 0,
        "vidtok.ru": 0,
        "videoadex.com": 4,
        "tidaltv.com": 4,
        "videonow.ru": 4,
        "videoplayerhub.com": 11,
        "videoplaza.tv": 4,
        "kweb.videostep.com": 4,
        "content.vidgyor.com": 0,
        "vidible.tv": 4,
        "assets.vidora.com": 0,
        "vietad.vn": 4,
        "viglink.com": 4,
        "vigo.one": 6,
        "vigo.ru": 6,
        "vimeo.com": 0,
        "vimeocdn.com": 0,
        "vindicosuite.com": 4,
        "vinted.net": 8,
        "viraladnetwork.net": 4,
        "app.viral-loops.com": 2,
        "viralgains.com": 4,
        "viralmint.com": 7,
        "virgul.com": 4,
        "ssp.virool.com": 4,
        "virtusize.com": 5,
        "viewablemedia.net": 4,
        "visiblemeasures.com": 4,
        "visioncriticalpanels.com": 6,
        "visitstreamer.com": 6,
        "visitortracklog.com": 4,
        "visitorville.com": 6,
        "d2hkbi3gan6yg6.cloudfront.net": 4,
        "myvisualiq.net": 6,
        "visualrevenue.com": 6,
        "d5phz18u4wuww.cloudfront.net": 6,
        "visualwebsiteoptimizer.com": 6,
        "wingify.com": 6,
        "vdna-assets.com": 4,
        "visualdna.com": 4,
        "visualstudio.com": 8,
        "id-visitors.com": 6,
        "vi-tag.net": 4,
        "vivistats.com": 6,
        "vizury.com": 4,
        "vizzit.se": 4,
        "cdn-vk.com": 7,
        "vk-analytics.com": 7,
        "vkuservideo.net": 7,
        "userapi.com": 7,
        "vk.com": 7,
        "vkontakte.ru": 7,
        "vntsm.com": 4,
        "vodafone.de": 8,
        "voicefive.com": 6,
        "volusion.com": 2,
        "cwkuki.com": 4,
        "volumtrk.com": 4,
        "voluumtrk3.com": 4,
        "vooxe.com": 8,
        "vorwerk.de": 8,
        "vox-cdn.com": 2,
        "embed.voxus.tv": 4,
        "voxus-targeting-voxusmidia.netdna-ssl.com": 4,
        "c-dsp.vpadn.com": 4,
        "tools.vpscash.nl": 4,
        "vsassets.io": 8,
        "exp-tas.com": 8,
        "v0cdn.net": 8,
        "vscode-cdn.net": 8,
        "vscode-unpkg.net": 8,
        "vtracy.de": 11,
        "liftoff.io": 4,
        "vungle.com": 4,
        "vuukle.com": 6,
        "view.vzaar.com": 0,
        "w3counter.com": 6,
        "w3roi.com": 6,
        "contentwidgets.net": 2,
        "wahoha.com": 2,
        "walkme.com": 2,
        "wsod.com": 4,
        "walmart.com": 8,
        "wamcash.com": 3,
        "cdn-saveit.wanelo.com": 2,
        "static.warp.ly": 6,
        "way2traffic.com": 4,
        "wayfair.com": 8,
        "wdr.de": 8,
        "web-stat.com": 6,
        "web.de": 8,
        "webde.de": 8,
        "webstat.net": 6,
        "ssl.webserviceaward.com": 6,
        "webtraxs.com": 6,
        "wipe.de": 6,
        "webads.nl": 4,
        "tr.webantenna.info": 6,
        "webclicks24.com": 11,
        "webclose.net": 12,
        "webcollage.net": 2,
        "goutee.top": 4,
        "mediaathay.org.uk": 4,
        "wbdx.fr": 4,
        "webeffective.keynote.com": 6,
        "widgets.webengage.com": 2,
        "webgains.com": 8,
        "webgozar.com": 6,
        "webgozar.ir": 6,
        "webhelpje.be": 2,
        "webhelpje.nl": 2,
        "webleads-tracker.com": 6,
        "automation.webmecanik.com": 6,
        "adrcdn.com": 4,
        "adrcntr.com": 4,
        "weborama.com": 4,
        "weborama.fr": 4,
        "webprospector.de": 6,
        "webstat.com": 6,
        "webstat.se": 6,
        "stat.webtrack.biz": 6,
        "webtraffic.no": 6,
        "webtraffic.se": 6,
        "d1r27qvpjiaqj3.cloudfront.net": 6,
        "mateti.net": 6,
        "wbtrk.net": 6,
        "wcfbc.net": 6,
        "webtrekk-asia.net": 6,
        "webtrekk.com": 6,
        "webtrekk.de": 6,
        "webtrekk.net": 6,
        "wt-eu02.net": 6,
        "wt-safetag.com": 6,
        "webtrends.com": 6,
        "webtrendslive.com": 6,
        "rd.clickshift.com": 4,
        "web-visor.com": 6,
        "weebly.com": 4,
        "widget.weibo.com": 4,
        "westlotto.com": 8,
        "wetter.com": 8,
        "wettercomassets.com": 8,
        "whatsbroadcast.com": 2,
        "whatsapp.com": 8,
        "whatsapp.net": 8,
        "whisper.onelink.me": 7,
        "whisper.sh": 7,
        "amung.us": 6,
        "whoson.com": 6,
        "api.wibbitz.com": 0,
        "cdn4.wibbitz.com": 0,
        "cdn.wibiya.com": 7,
        "predictad.com": 2,
        "widerplanet.com": 4,
        "widespace.com": 4,
        "widgetserver.com": 2,
        "3c45d848d99.se": 4,
        "wigetmedia.com": 4,
        "tracker.wigzopush.com": 4,
        "wikia-services.com": 8,
        "wikia-beacon.com": 6,
        "nocookie.net": 9,
        "wikimedia.org": 9,
        "wikipedia.org": 9,
        "wikiquote.org": 9,
        "tracking.winaffiliates.com": 6,
        "maps.windows.com": 8,
        "client.wns.windows.com": 8,
        "time.windows.com": 8,
        "windowsupdate.com": 9,
        "api.wipmania.com": 6,
        "col1.wiqhit.com": 6,
        "wirecard.com": 2,
        "wirecard.de": 2,
        "leadlab.click": 6,
        "wiredminds.com": 6,
        "wiredminds.de": 6,
        "adtotal.pl": 4,
        "wisepops.com": 4,
        "cdn.wishpond.net": 2,
        "wistia.com": 6,
        "wistia.net": 6,
        "parastorage.com": 8,
        "wix.com": 8,
        "public.wixab-cloud.com": 6,
        "wixmp.com": 9,
        "wnzmauurgol.com": 11,
        "wonderpush.com": 2,
        "woopic.com": 8,
        "woopra.com": 6,
        "pubmine.com": 4,
        "w.org": 6,
        "wordpress.com": 6,
        "wp.com": 6,
        "tracker.wordstream.com": 6,
        "worldnaturenet.xyz": 12,
        "wp.pl": 4,
        "wpimg.pl": 4,
        "wpengine.com": 5,
        "clickanalyzer.jp": 6,
        "wurfl.io": 6,
        "wwwpromoter.com": 4,
        "imgwykop.pl": 7,
        "wykop.pl": 7,
        "wysistat.com": 6,
        "wysistat.net": 6,
        "wywy.com": 4,
        "wywyuserservice.com": 4,
        "cdn.x-lift.jp": 4,
        "xapads.com": 4,
        "xen-media.com": 11,
        "xfreeservice.com": 11,
        "xhamster.com": 3,
        "xhamsterlive.com": 3,
        "xhamsterpremium.com": 3,
        "xhcdn.com": 3,
        "huami.com": 8,
        "mi-img.com": 8,
        "mi.com": 8,
        "miui.com": 8,
        "xiaomi.com": 8,
        "xiaomi.net": 8,
        "xiaomiyoupin.com": 8,
        "xing-share.com": 6,
        "xing.com": 6,
        "xmediaclicks.com": 3,
        "xnxx-cdn.com": 9,
        "xplosion.de": 4,
        "xtendmedia.com": 4,
        "xvideos-cdn.com": 8,
        "xvideos.com": 8,
        "xxxlshop.de": 8,
        "xxxlutz.de": 8,
        "adx.com.ru": 4,
        "yabbi.me": 4,
        "yabuka.com": 4,
        "tumblr.com": 6,
        "yahoo.com": 6,
        "yahooapis.com": 6,
        "yimg.com": 6,
        "oath.cloud": 6,
        "yahoo.net": 6,
        "yahooinc.com": 6,
        "yahoodns.net": 6,
        "yads.yahoo.com": 4,
        "yieldmanager.com": 4,
        "pr-bh.ybp.yahoo.com": 4,
        "ads.yahoo.com": 4,
        "adtech.yahooinc.com": 4,
        "analytics.yahoo.com": 6,
        "np.lexity.com": 4,
        "storage-yahoo.jp": 4,
        "yahoo.co.jp": 4,
        "yahooapis.jp": 4,
        "yimg.jp": 4,
        "yjtag.jp": 4,
        "ov.yahoo.co.jp": 4,
        "overture.com": 4,
        "search.yahooinc.com": 4,
        "luminate.com": 4,
        "pixazza.com": 4,
        "awaps.yandex.ru": 4,
        "d31j93rd8oukbv.cloudfront.net": 4,
        "webvisor.org": 4,
        "yandex.net": 4,
        "yandex.ru": 4,
        "yastatic.net": 4,
        "ya.ru": 4,
        "yandex.by": 4,
        "yandex.com": 4,
        "yandex.com.tr": 4,
        "yandex.fr": 4,
        "yandex.kz": 4,
        "yandex.st": 2,
        "yandexadexchange.net": 4,
        "metabar.ru": 12,
        "appmetrica.yandex.com": 101,
        "an.webvisor.org": 6,
        "an.yandex.ru": 6,
        "bs.yandex.ru": 6,
        "mc.yandex.ru": 6,
        "passport.yandex.ru": 2,
        "yapfiles.ru": 8,
        "yashi.com": 4,
        "ad.adserverplus.com": 4,
        "player.sambaads.com": 0,
        "cdn.yektanet.com": 4,
        "fetch.yektanet.com": 4,
        "yengo.com": 4,
        "yengointernational.com": 4,
        "link.p0.com": 4,
        "adsrevenue.net": 4,
        "infinityads.com": 4,
        "momentsharing.com": 4,
        "multipops.com": 4,
        "onlineadultadvertising.com": 4,
        "paypopup.com": 4,
        "popupxxx.com": 4,
        "xtargeting.com": 4,
        "xxxwebtraffic.com": 4,
        "app.yesware.com": 2,
        "yldbt.com": 6,
        "yieldify.com": 4,
        "yieldlab.net": 4,
        "yieldlove-ad-serving.net": 4,
        "yieldlove.com": 4,
        "yieldmo.com": 4,
        "254a.com": 4,
        "collect.yldr.io": 6,
        "yieldsquare.com": 4,
        "analytics-sdk.yle.fi": 6,
        "yllix.com": 4,
        "ymetrica1.com": 11,
        "ymzrrizntbhde.com": 11,
        "yoapp.s3.amazonaws.com": 2,
        "natpal.com": 4,
        "analytics.yola.net": 6,
        "pixel.yola.net": 6,
        "delivery.yomedia.vn": 4,
        "yoochoose.net": 4,
        "yotpo.com": 1,
        "yottaa.net": 6,
        "yottlyscript.com": 4,
        "api.youcanbook.me": 2,
        "youcanbook.me": 2,
        "player.youku.com": 0,
        "youporn.com": 3,
        "ypncdn.com": 3,
        "googlevideo.com": 0,
        "youtube-nocookie.com": 0,
        "youtube.com": 0,
        "ytimg.com": 0,
        "c.ypcdn.com": 4,
        "i1.ypcdn.com": 4,
        "yellowpages.com": 4,
        "prod-js.aws.y-track.com": 4,
        "y-track.com": 4,
        "yume.com": 4,
        "yumenetworks.com": 4,
        "gravityrd-services.com": 6,
        "api.zadarma.com": 2,
        "zalan.do": 8,
        "zalando.de": 8,
        "ztat.net": 8,
        "zaloapp.com": 2,
        "zanox-affiliate.de": 4,
        "zanox.com": 4,
        "zanox.ws": 4,
        "zaparena.com": 4,
        "zapunited.com": 4,
        "track.zappos.com": 4,
        "zdassets.com": 8,
        "zebestof.com": 4,
        "zedo.com": 4,
        "zemanta.com": 2,
        "zencdn.net": 0,
        "zendesk.com": 2,
        "zergnet.com": 2,
        "zero.kz": 6,
        "app.insightgrit.com": 2,
        "app.ubertags.com": 2,
        "cdn.boomtrain.com": 2,
        "events.api.boomtrain.com": 2,
        "rfihub.com": 2,
        "rfihub.net": 2,
        "ru4.com": 2,
        "xplusone.com": 2,
        "zeusclicks.com": 4,
        "webtest.net": 4,
        "zdbb.net": 4,
        "ziffdavis.com": 4,
        "ziffdavisinternational.com": 4,
        "ziffprod.com": 4,
        "ziffstatic.com": 4,
        "analytics.ziftsolutions.com": 6,
        "zimbio.com": 8,
        "api.zippyshare.com": 2,
        "zmags.com": 6,
        "zmctrack.net": 11,
        "zog.link": 11,
        "js.zohostatic.eu": 6,
        "zononi.com": 3,
        "zopim.com": 2,
        "zukxd6fkxqn.com": 11,
        "zwaar.net": 4,
        "zwaar.org": 4,
        "extend.tv": 4
    }
};



;// ./node_modules/.pnpm/@adguard+tswebextension@3.1.0-alpha.3_@adguard+re2-wasm@1.2.0/node_modules/@adguard/tswebextension/dist/common/configuration.js














/**
 * Simple pub-sub implementation.
 */
class background_EventChannel {
    listeners = [];
    /**
     * Dispatch event.
     *
     * @param data Event data.
     */
    dispatch(data) {
        this.listeners.forEach((listener) => listener(data));
    }
    /**
     * Subscribe to events channel.
     *
     * @param listener Callback to be called on event.
     */
    subscribe(listener) {
        this.listeners.push(listener);
    }
    /**
     * Unsubscribe from events channel.
     *
     * @param listener Callback to be removed from listeners.
     */
    unsubscribe(listener) {
        const index = this.listeners.indexOf(listener);
        if (index !== -1) {
            this.listeners.splice(index, 1);
        }
    }
}

// TODO: Add 'is' prefix to cssRule, scriptRule and contentRule properties.
/**
 * Types of filtering events that can occur during request processing.
 */
var background_FilteringEventType;
(function (FilteringEventType) {
    FilteringEventType["SendRequest"] = "sendRequest";
    FilteringEventType["TabReload"] = "tabReload";
    FilteringEventType["ApplyBasicRule"] = "applyBasicRule";
    FilteringEventType["ApplyCosmeticRule"] = "applyCosmeticRule";
    FilteringEventType["ApplyCspRule"] = "applyCspRule";
    FilteringEventType["ApplyPermissionsRule"] = "applyPermissionsRule";
    FilteringEventType["ReceiveResponse"] = "receiveResponse";
    FilteringEventType["Cookie"] = "cookie";
    FilteringEventType["RemoveHeader"] = "removeHeader";
    FilteringEventType["RemoveParam"] = "removeParam";
    FilteringEventType["ReplaceRuleApply"] = "replaceRuleApply";
    FilteringEventType["ContentFilteringStart"] = "contentFilteringStart";
    FilteringEventType["ContentFilteringFinish"] = "contentFilteringFinish";
    FilteringEventType["StealthAction"] = "stealthAction";
    FilteringEventType["StealthAllowlistAction"] = "stealthAllowlistAction";
    FilteringEventType["JsInject"] = "jsInject";
    FilteringEventType["CspReportBlocked"] = "cspReportBlocked";
    /**
     * Used only in unpacked MV3.
     */
    FilteringEventType["MatchedDeclarativeRule"] = "matchedDeclarativeRule";
})(background_FilteringEventType || (background_FilteringEventType = {}));
/**
 * {@link FilteringLogInterface} Default implementation.
 */
class background_FilteringLog {
    onLogEvent = new background_EventChannel();
    channels = [];
    /**
     * Registers listener for specified {@link FilteringLogEvent}.
     *
     * @param type Filtering log type.
     * @param listener Filtering log listener.
     */
    addEventListener(type, listener) {
        const channel = { type, listener };
        this.channels.push(channel);
    }
    /**
     * Publishes event to attached listeners.
     *
     * @param event Filtering log event.
     */
    publishEvent(event) {
        const listeners = this.channels
            .filter(({ type }) => type === event.type)
            .map(({ listener }) => listener);
        for (const listener of listeners) {
            listener(event);
        }
        this.onLogEvent.dispatch(event);
    }
}
/**
 * Shared {@link FilteringLog} instance.
 */
const background_defaultFilteringLog = new background_FilteringLog();

/**
 * The allowlist is used to exclude certain websites from filtering.
 * Blocking rules are not applied to the sites in the list.
 * The allow list can also be inverted.
 * In inverted mode, the application will unblock ads everywhere except for the
 * sites added to this list.
 */
let background_Allowlist$1 = class Allowlist {
    /**
     * Indicates whether the allowlist is enabled.
     */
    enabled = false;
    /**
     * If true, ads will be blocked only on sites listed in the allowlist,
     * like "blocklist" mode.
     */
    inverted = false;
    /**
     * List of domains which are allowed (by default)
     * or blocked (if the allowlist is inverted).
     */
    domains = [];
    /**
     * Configures allowlist state based on app configuration.
     *
     * @param configuration App configuration.
     */
    configure(configuration) {
        const { allowlist, settings, } = configuration;
        const { allowlistEnabled, allowlistInverted, } = settings;
        this.enabled = allowlistEnabled;
        this.inverted = allowlistInverted;
        this.domains = allowlist.map((hostname) => {
            return hostname.startsWith('www.') ? hostname.substring(4).trim() : hostname.trim();
        });
    }
    /**
     * Returns a list of rules to be loaded into the engine based on allowlist state.
     *
     * @returns List of allowlist rules or null.
     */
    getAllowlistRules() {
        if (!this.enabled || this.inverted) {
            return null;
        }
        return (0,background_es/* createAllowlistRuleList */.kn)(background_ALLOWLIST_FILTER_ID, this.domains);
    }
    /**
     * Creates an allowlist rule for a domain which will be passed to our engine
     * to unblock requests. In MV3 we will pass this rule to TsUrlFilter engine,
     * because it do work with cosmetic rules.
     *
     * @param domain Domain name.
     *
     * @returns Allowlist rule or null.
     */
    static createAllowlistRule(domain) {
        if (!domain) {
            return null;
        }
        return background_es/* RuleFactory */.Vf.createAllowlistRule(domain, background_ALLOWLIST_FILTER_ID);
    }
};

/**
 * Checks if url is http request.
 *
 * @param url Request url.
 *
 * @returns True if url starts with http{s?}.
 */
function background_isHttpRequest(url) {
    return typeof url === 'string' && !!url && url.startsWith('http');
}
/**
 * Checks if url is http or websocket.
 *
 * @param url Request url.
 *
 * @returns True if url starts with http{s?} or ws.
 */
function background_isHttpOrWsRequest(url) {
    return !!url && (url.startsWith('http') || url.startsWith('ws'));
}
/**
 * Extract host from url.
 *
 * @param url Url.
 *
 * @returns Host of the url or null.
 */
function background_getHost(url) {
    let firstIdx = url.indexOf('//');
    if (firstIdx === -1) {
        /**
         * It's non-hierarchical structured URL (stun: or turn:).
         *
         * @see {@link https://tools.ietf.org/html/rfc4395#section-2.2}
         * @see {@link https://tools.ietf.org/html/draft-nandakumar-rtcweb-stun-uri-08#appendix-B}
         */
        firstIdx = url.indexOf(':');
        if (firstIdx === -1) {
            return null;
        }
        firstIdx -= 1;
    }
    const nextSlashIdx = url.indexOf('/', firstIdx + 2);
    const startParamsIdx = url.indexOf('?', firstIdx + 2);
    let lastIdx = nextSlashIdx;
    if (startParamsIdx > 0 && (startParamsIdx < nextSlashIdx || nextSlashIdx < 0)) {
        lastIdx = startParamsIdx;
    }
    let host = lastIdx === -1 ? url.substring(firstIdx + 2) : url.substring(firstIdx + 2, lastIdx);
    const portIndex = host.indexOf(':');
    host = portIndex === -1 ? host : host.substring(0, portIndex);
    const lastChar = host.charAt(host.length - 1);
    if (lastChar === '.') {
        host = host.slice(0, -1);
    }
    return host;
}
/**
 * Extracts domain name from url.
 *
 * @param url Url.
 *
 * @returns Domain name or null.
 */
function background_getDomain(url) {
    const host = background_getHost(url);
    if (!host) {
        return null;
    }
    return host.startsWith('www.') ? host.substring(4) : host;
}
/**
 * If referrer of request contains full url of extension, then this request is considered as extension's own request.
 * Example: request for filter downloading.
 * Related issue: @see {@link https://github.com/AdguardTeam/AdguardBrowserExtension/issues/1437}.
 *
 * @param url Request url.
 *
 * @returns True if request is extension's own.
 */
function background_isExtensionUrl(url) {
    return url.indexOf(background_browser_polyfill.runtime.getURL('')) === 0;
}
/**
 * Checks third party relation.
 *
 * @param requestUrl Request url.
 * @param referrer Referrer url.
 *
 * @returns True if request is third-party.
 */
function background_isThirdPartyRequest(requestUrl, referrer) {
    const tldResult = (0,background_es6/* parse */.qg)(requestUrl);
    const sourceTldResult = (0,background_es6/* parse */.qg)(referrer);
    return tldResult.domain !== sourceTldResult.domain;
}
/**
 * Extracts upper level domain from domain.
 *
 * @param domain Domain.
 *
 * @returns Upper level domain.
 *
 * @example
 * ```
 * getUpperLevelDomain('www.example.com') => `example.com`
 * getUpperLevelDomain('test.pages.dev') => `pages.dev`
 * getUpperLevelDomain('allowlist.test.pages.dev') => `test.pages.dev`
 * ```
 */
function background_getUpperLevelDomain(domain) {
    const parts = domain.split('.');
    parts.shift();
    return parts.join('.');
}

/**
 * Wrapper around a map for frames.
 */
class background_Frames {
    /**
     * A map where the key is the frame ID and the value is the frame object.
     */
    framesMap = new Map();
    /**
     * Sets frame by id.
     *
     * @param frameId Frame id.
     * @param frame Frame to save.
     */
    set(frameId, frame) {
        this.framesMap.set(frameId, frame);
    }
    /**
     * Returns frame by id.
     *
     * @param frameId Frame id.
     *
     * @returns Frame or undefined if frame not found.
     */
    get(frameId) {
        return this.framesMap.get(frameId);
    }
    /**
     * Clears all frames.
     */
    clear() {
        this.framesMap.clear();
    }
    /**
     * Deletes frame by id.
     *
     * @param frameId Frame id.
     */
    delete(frameId) {
        this.framesMap.delete(frameId);
    }
    /**
     * Returns all frames.
     *
     * @returns Array of frames.
     */
    values() {
        return [...this.framesMap.values()];
    }
}

/**
 * Tab context common class.
 */
class background_TabContextCommon {
    info;
    filteringLog;
    /**
     * Frames context.
     *
     * NOTE: this is temporary storage for frames data.
     * Each frame context is deleted after navigation is complete.
     * Storage is cleared on tab reload.
     * Do not use it as a data source out of request or navigation processing.
     */
    frames = new background_Frames();
    /**
     * Document IDs map.
     * Used to get frame context by document ID.
     */
    documentIdsMap = new Map();
    /**
     * Blocked request count.
     */
    blockedRequestCount = 0;
    /**
     * Document level rule, applied to the tab.
     */
    mainFrameRule = null;
    // TODO: remove later.
    /**
     * @deprecated
     * This field is used in the extension, and mv2 version uses it,
     * but it is not used anymore in mv3, so it is deprecated here.
     *
     * We mark these tabs as synthetic because they may not actually exist.
     */
    isSyntheticTab = false;
    /**
     * Timestamp of the assistant initialization.
     *
     * Needed to avoid cosmetic rules injection into the assistant frame.
     *
     * @see {@link https://github.com/AdguardTeam/AdguardBrowserExtension/issues/1848}
     */
    assistantInitTimestamp = null;
    /**
     * Tab creation timestamp in milliseconds.
     */
    createdAtMs;
    /**
     * Tab context constructor.
     *
     * @param info Tab info.
     * @param filteringLog Filtering log.
     */
    constructor(info, filteringLog = background_defaultFilteringLog) {
        this.info = info;
        this.filteringLog = filteringLog;
        this.createdAtMs = Date.now();
    }
    /**
     * Updates tab info.
     *
     * @param tabInfo Tab info.
     */
    updateTabInfo(tabInfo) {
        this.info = tabInfo;
    }
    /**
     * Updates main frame data.
     *
     * Note: this method will be called on tab reload before the first {@link browser.tabs.onUpdated} event
     * and {@link handleTabUpdate} calls.
     *
     * @param tabId Tab ID.
     * @param url Url.
     */
    updateMainFrameData(tabId, url) {
        this.info.url = url;
        this.info.id = tabId;
    }
    /**
     * Increments blocked requests count.
     */
    incrementBlockedRequestCount() {
        this.blockedRequestCount += 1;
    }
    /**
     * Resets blocked requests count.
     */
    resetBlockedRequestsCount() {
        this.blockedRequestCount = 0;
    }
    /**
     * Checks if passed {@link Tabs.Tab} details represent a browser tab.
     *
     * @see https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/Tab#type
     * @see https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/TAB_ID_NONE
     *
     * @param tab Tab details.
     *
     * @returns True if the tab is a browser tab, otherwise returns false.
     */
    static isBrowserTab(tab) {
        return typeof tab.id === 'number' && tab.id !== background_browser_polyfill.tabs.TAB_ID_NONE;
    }
    /**
     * Get frame context.
     *
     * @param frameId Frame id.
     *
     * @returns Frame context.
     */
    getFrameContext(frameId) {
        return this.frames.get(frameId);
    }
    /**
     * Set frame context.
     *
     * @param frameId Frame id.
     * @param frameContext Frame context.
     */
    setFrameContext(frameId, frameContext) {
        this.frames.set(frameId, frameContext);
    }
    /**
     * Set document id.
     *
     * @param documentId Unique identifier of the frame.
     * @param frameId Frame id.
     */
    setDocumentId(documentId, frameId) {
        this.documentIdsMap.set(documentId, frameId);
    }
    /**
     * Get frame context by document id.
     *
     * @param documentId Unique identifier of the frame.
     *
     * @returns Frame context.
     */
    getFrameContextByDocumentId(documentId) {
        const frameId = this.documentIdsMap.get(documentId);
        // frameId might be 0, do not use falsy check
        if (frameId !== undefined) {
            return this.frames.get(frameId);
        }
        return undefined;
    }
    /**
     * Deletes the frame context.
     *
     * @param frameId The ID of the frame to delete.
     * @param maxFrameAgeMs The maximum allowed frame age in milliseconds.
     */
    deleteFrameContext(frameId, maxFrameAgeMs) {
        // The main frame should only be deleted when the tab is closed,
        // as it may be needed for sub frames created during the page's lifetime
        // or for retrieving the main frame rule.
        if (frameId === background_MAIN_FRAME_ID) {
            return;
        }
        const frame = this.frames.get(frameId);
        if (!frame) {
            return;
        }
        // Do not delete frames that are not stale, as they may still be needed.
        if (frame.timeStamp && frame.timeStamp > Date.now() - maxFrameAgeMs) {
            return;
        }
        // Clear the document ID map if the frame has a document ID.
        if (frame.documentId) {
            this.documentIdsMap.delete(frame.documentId);
        }
        this.frames.delete(frameId);
    }
    /**
     * Since document frames are not removed, but rather updated, document IDs can become stale.
     * This method clears stale document IDs.
     */
    clearStaleDocumentIds() {
        const documentIdsLeft = this.frames.values()
            .map((frame) => frame.documentId)
            .filter(background_lodash_es_identity);
        const documentIdsLeftSet = new Set(documentIdsLeft);
        const documentIds = [...this.documentIdsMap.keys()];
        for (const documentId of documentIds) {
            if (!documentIdsLeftSet.has(documentId)) {
                this.documentIdsMap.delete(documentId);
            }
        }
    }
    /**
     * Clears stale frames.
     *
     * @param maxFrameAgeMs The maximum allowed frame age in milliseconds.
     */
    clearStaleFrames(maxFrameAgeMs) {
        const values = this.frames.values();
        for (const value of values) {
            this.deleteFrameContext(value.frameId, maxFrameAgeMs);
        }
        this.clearStaleDocumentIds();
    }
}

/**
 * Tabs API common class.
 */
class background_TabsApiCommon {
    documentApi;
    context = new Map();
    onCreate = new background_EventChannel();
    onUpdate = new background_EventChannel();
    onDelete = new background_EventChannel();
    onActivate = new background_EventChannel();
    onReplace = new background_EventChannel();
    /**
     * Tabs API constructor.
     *
     * @param documentApi Optional, Document API instance. Needed for MV2.
     */
    constructor(documentApi) {
        this.documentApi = documentApi;
        this.handleTabCreate = this.handleTabCreate.bind(this);
        this.handleTabUpdate = this.handleTabUpdate.bind(this);
        this.handleTabActivate = this.handleTabActivate.bind(this);
        this.handleTabReplace = this.handleTabReplace.bind(this);
        this.handleTabDelete = this.handleTabDelete.bind(this);
        this.onWindowFocusChanged = this.onWindowFocusChanged.bind(this);
        this.getTabContext = this.getTabContext.bind(this);
        this.getTabFrameRule = this.getTabFrameRule.bind(this);
        this.getTabFrame = this.getTabFrame.bind(this);
        this.getTabMainFrame = this.getTabMainFrame.bind(this);
        this.getMainFrameUrl = this.getMainFrameUrl.bind(this);
    }
    /**
     * Starts recording the main frame URLs for the tabs.
     */
    async start() {
        background_browser_polyfill.tabs.onCreated.addListener(this.handleTabCreate);
        background_browser_polyfill.tabs.onRemoved.addListener(this.handleTabDelete);
        background_browser_polyfill.tabs.onUpdated.addListener(this.handleTabUpdate);
        background_browser_polyfill.tabs.onActivated.addListener(this.handleTabActivate);
        background_browser_polyfill.tabs.onReplaced.addListener(this.handleTabReplace);
        // Firefox for android doesn't support windows API
        // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/windows#browser_compatibility
        if (background_browser_polyfill.windows) {
            background_browser_polyfill.windows.onFocusChanged.addListener(this.onWindowFocusChanged);
        }
    }
    /**
     * Stops recording the main frame URLs for the tabs.
     */
    stop() {
        background_browser_polyfill.tabs.onCreated.removeListener(this.handleTabCreate);
        background_browser_polyfill.tabs.onRemoved.removeListener(this.handleTabDelete);
        background_browser_polyfill.tabs.onUpdated.removeListener(this.handleTabUpdate);
        background_browser_polyfill.tabs.onActivated.removeListener(this.handleTabActivate);
        background_browser_polyfill.tabs.onReplaced.removeListener(this.handleTabReplace);
        // Firefox for android doesn't support windows API
        if (background_browser_polyfill.windows) {
            background_browser_polyfill.windows.onFocusChanged.removeListener(this.onWindowFocusChanged);
        }
        this.context.clear();
    }
    /**
     * Updates tab context data on tab update.
     *
     * If the tab context is not found, creates a new tab context.
     *
     * If the tab context is not found, creates a new tab context.
     *
     * @param tabId Tab ID.
     * @param changeInfo Tab change info.
     * @param tabInfo Tab info.
     */
    handleTabUpdate(tabId, changeInfo, tabInfo) {
        if (!background_TabContextCommon.isBrowserTab(tabInfo)) {
            return;
        }
        // Skip updates for non-http requests.
        if (changeInfo.url && !background_isHttpRequest(changeInfo.url)) {
            return;
        }
        // TODO: we can ignore some events (favicon url update etc.)
        const tabContext = this.context.get(tabId);
        if (!tabContext) {
            return;
        }
        tabContext.updateTabInfo(tabInfo);
        this.onUpdate.dispatch(tabContext);
    }
    /**
     * Dispatches tab on activated event.
     *
     * @param tab Tab info.
     */
    handleTabActivate(tab) {
        const tabContext = this.context.get(tab.tabId);
        if (!tabContext) {
            return;
        }
        this.onActivate.dispatch(tabContext);
    }
    /**
     * The browser tab may be replaced by another when the discarded tab wakes up.
     * We handle this case on {@link browser.tabs.onReplaced} event.
     * It fires before the tab details are updated,
     * so we just move the existing tab context to the new key.
     *
     * @param addedTabId Id of the new tab context moved to.
     * @param removedTabId Id of removed tab.
     */
    handleTabReplace(addedTabId, removedTabId) {
        const tabContext = this.context.get(removedTabId);
        if (!tabContext) {
            return;
        }
        this.context.delete(removedTabId);
        this.context.set(addedTabId, tabContext);
        this.onReplace.dispatch(tabContext);
    }
    /**
     * Removes tab context by tab ID.
     *
     * @param tabId Tab ID.
     */
    handleTabDelete(tabId) {
        const tabContext = this.context.get(tabId);
        if (!tabContext) {
            return;
        }
        this.context.delete(tabId);
        this.onDelete.dispatch(tabContext);
    }
    /**
     * Called when focus state of window changed.
     *
     * @param windowId Window ID.
     */
    async onWindowFocusChanged(windowId) {
        // If all browser windows have lost focus.
        if (windowId === background_browser_polyfill.windows.WINDOW_ID_NONE) {
            return;
        }
        const [activeTab] = await background_browser_polyfill.tabs.query({
            active: true,
            windowId,
        });
        if (!activeTab || !activeTab.id) {
            return;
        }
        const tabContext = this.context.get(activeTab.id);
        if (!tabContext) {
            return;
        }
        this.onActivate.dispatch(tabContext);
    }
    /**
     * Retrieves tab context by tab ID.
     *
     * @param tabId Tab ID.
     *
     * @returns Tab context or undefined if not found.
     */
    getTabContext(tabId) {
        return this.context.get(tabId);
    }
    /**
     * Retrieves frame rule for the tab context.
     *
     * @param tabId Tab ID.
     *
     * @returns Frame rule or null if not found.
     */
    getTabFrameRule(tabId) {
        const tabContext = this.context.get(tabId);
        if (!tabContext) {
            return null;
        }
        return tabContext.mainFrameRule;
    }
    /**
     * Retrieves frame data for the frame in the tab context.
     *
     * @param tabId Tab ID.
     * @param frameId Frame ID.
     *
     * @returns Frame data or null if not found.
     */
    getTabFrame(tabId, frameId) {
        const tabContext = this.context.get(tabId);
        if (!tabContext) {
            return null;
        }
        const frame = tabContext.frames.get(frameId);
        if (!frame) {
            return null;
        }
        return frame;
    }
    /**
     * Retrieves main frame data for the tab context.
     *
     * @param tabId Tab ID.
     *
     * @returns Frame data or null if not found.
     */
    getTabMainFrame(tabId) {
        return this.getTabFrame(tabId, background_MAIN_FRAME_ID);
    }
    /**
     * Returns main frame URL for provided tab ID.
     *
     * @param tabId Tab ID.
     *
     * @returns Main frame URL for provided tab ID.
     */
    getMainFrameUrl(tabId) {
        return this.getTabMainFrame(tabId)?.url;
    }
    /**
     * Checks if the frame is a document-level frame by checking its parent frame ID.
     *
     * @param parentFrameId Parent frame ID.
     *
     * @returns True if the parent frame is a document-level frame.
     */
    static isDocumentLevelFrame(parentFrameId) {
        return parentFrameId === background_NO_PARENT_FRAME_ID;
    }
    /**
     * Checks whether the tab with the specified ID is open
     * in incognito mode or not.
     *
     * @param tabId Tab ID.
     *
     * @returns True if the tab is open in incognito mode, false otherwise.
     */
    isIncognitoTab(tabId) {
        const tabContext = this.getTabContext(tabId);
        if (!tabContext) {
            return false;
        }
        return tabContext.info.incognito;
    }
    /**
     * Increments tab context blocked request count.
     *
     * @param tabId Tab ID.
     * @param referrerUrl Request initiator url.
     */
    incrementTabBlockedRequestCount(tabId, referrerUrl) {
        const tabContext = this.context.get(tabId);
        if (!tabContext) {
            return;
        }
        const tabUrl = tabContext.info?.url;
        /**
         * Only increment count for requests that are initiated from the same domain as the tab.
         *
         * This prevents count 'leaks' when moving between main frames due to async nature of
         * {@link browser.webRequest.onBeforeRequest} and {@link browser.tabs.onUpdated} events.
         */
        if (!tabUrl
            || !referrerUrl
            || background_getDomain(tabUrl) !== background_getDomain(referrerUrl)) {
            return;
        }
        tabContext.incrementBlockedRequestCount();
    }
    /**
     * Resets blocked requests count for the tab.
     *
     * @param tabId Tab ID.
     */
    resetBlockedRequestsCount(tabId) {
        const tabContext = this.getTabContext(tabId);
        if (!tabContext) {
            return;
        }
        tabContext.resetBlockedRequestsCount();
    }
    /**
     * Sets a current timestamp as `assistantInitTimestamp` of the tab context.
     *
     * Needed to determine later if a newly created frame is an assistant frame.
     *
     * @param tabId Tab id.
     */
    setAssistantInitTimestamp(tabId) {
        const tabContext = this.context.get(tabId);
        if (!tabContext) {
            return;
        }
        tabContext.assistantInitTimestamp = Date.now();
    }
    /**
     * Resets tab context's `assistantInitTimestamp` to null.
     *
     * @param tabId Tab id.
     */
    resetAssistantInitTimestamp(tabId) {
        const tabContext = this.context.get(tabId);
        if (!tabContext) {
            return;
        }
        tabContext.assistantInitTimestamp = null;
    }
    /**
     * Sets frame context.
     *
     * @param tabId Tab ID.
     * @param frameId Frame ID.
     * @param frameContext Frame context.
     *
     * @throws Error if the tab context is not found, as this should not occur at this point.
     */
    setFrameContext(tabId, frameId, frameContext) {
        const tabContext = this.getTabContext(tabId);
        if (!tabContext) {
            background_common_logger_logger.debug('At this point tab context should already exist');
            return;
        }
        tabContext.setFrameContext(frameId, frameContext);
    }
    /**
     * Returns frame context by tabId and frameId.
     *
     * @param tabId Tab ID.
     * @param frameId Frame ID.
     *
     * @returns Frame context.
     */
    getFrameContext(tabId, frameId) {
        const tabContext = this.getTabContext(tabId);
        const frameContext = tabContext?.getFrameContext(frameId);
        return frameContext;
    }
    /**
     * Updates the frame context with additional data.
     *
     * @param tabId The ID of the tab.
     * @param frameId The ID of the frame.
     * @param partialFrameContext The details to be added to the frame context.
     *
     * @throws Error if the tab context or frame context is not found, as this should not occur at this point.
     */
    updateFrameContext(tabId, frameId, partialFrameContext) {
        const tabContext = this.getTabContext(tabId);
        if (!tabContext) {
            background_common_logger_logger.debug('At this point tab context should already exist');
            return;
        }
        const frameContext = tabContext?.getFrameContext(frameId);
        if (!frameContext) {
            background_common_logger_logger.debug('At this point frame context should already exist');
            return;
        }
        Object.assign(frameContext, partialFrameContext);
        if (frameContext.documentId) {
            tabContext.setDocumentId(frameContext.documentId, frameId);
        }
    }
    /**
     * Deletes the frame context.
     * Also clears frames older than the specified maxFrameAgeMs.
     *
     * @param tabId The ID of the tab.
     * @param frameId The ID of the frame.
     * @param maxFrameAgeMs The maximum allowed age for frames, in milliseconds.
     */
    deleteFrameContext(tabId, frameId, maxFrameAgeMs) {
        const tabContext = this.getTabContext(tabId);
        if (!tabContext) {
            return;
        }
        tabContext.deleteFrameContext(frameId, maxFrameAgeMs);
        tabContext.clearStaleFrames(maxFrameAgeMs);
    }
    /**
     * Returns frame context by documentId.
     *
     * @param tabId Tab ID.
     * @param documentId Unique identifier assigned to the frame on onCommitted event.
     *
     * @returns Frame context.
     */
    getByDocumentId(tabId, documentId) {
        const tabContext = this.getTabContext(tabId);
        return tabContext?.getFrameContextByDocumentId(documentId);
    }
    /**
     * Sets main frame rule for the tab context and for the frame context.
     *
     * @param tabId Tab ID.
     * @param frameId Frame ID.
     * @param frameRule Frame rule.
     */
    setMainFrameRule(tabId, frameId, frameRule) {
        const tabContext = this.getTabContext(tabId);
        if (tabContext && frameId === background_MAIN_FRAME_ID) {
            tabContext.mainFrameRule = frameRule;
        }
        if (frameRule) {
            this.updateFrameContext(tabId, frameId, { frameRule });
        }
        else {
            this.updateFrameContext(tabId, frameId, { frameRule: undefined });
        }
    }
}

/**
 * Frame context data.
 *
 * We store {@link MatchingResult} and {@link CosmeticResult} in the frame context
 * to apply rules that cannot be handled during request processing.
 * The frame data is deleted after the {@link browser.webNavigation.onCompleted} event.
 *
 * @see {@link WebRequestApi.deleteFrameContext}
 *
 * The class is abstract because FrameMV2 and FrameMV3 extend it.
 */
class background_FrameCommon {
    /**
     * Frame url.
     */
    url;
    /**
     * Main frame url.
     */
    mainFrameUrl;
    /**
     * Tab id.
     */
    tabId;
    /**
     * Frame id.
     */
    frameId;
    /**
     * Parent frame id.
     */
    parentFrameId;
    /**
     * Frame creation time.
     */
    timeStamp;
    /**
     * Frame rule. Needed in the case of allowlist rules for the tab.
     */
    frameRule;
    /**
     * Parent document id.
     */
    parentDocumentId;
    /**
     * The cosmetic result for the frame.
     *
     * This data is stored in the frame because it is required for logging script and scriptlet rules.
     */
    cosmeticResult;
    /**
     * Matching result for the frame.
     *
     * This data is saved in frame, because we need for access it for script rules injection
     * after deleting request context data.
     */
    matchingResult;
    /**
     * Unique identifier for the frame.
     */
    documentId;
    /**
     * Creates frame instance.
     *
     * @param props Frame constructor properties.
     */
    constructor(props) {
        const { url, tabId, parentFrameId, frameId, timeStamp, parentDocumentId, documentId, } = props;
        this.url = url;
        this.tabId = tabId;
        this.frameId = frameId;
        this.parentFrameId = parentFrameId;
        this.timeStamp = timeStamp;
        this.parentDocumentId = parentDocumentId;
        this.documentId = documentId;
    }
}

/**
 * @file
 * This file contains validation schemas and inferred types for message data.
 */
/**
 * Message DTO validation schema.
 */
const background_messageValidator = background_zod_lib.z.object({
    handlerName: background_zod_lib.z.literal(background_MESSAGE_HANDLER_NAME),
    type: background_zod_lib.z.nativeEnum(background_message_constants_MessageType),
    payload: background_zod_lib.z.unknown(),
}).strict();
/**
 * {@link MessageType.ProcessShouldCollapse} Message payload validation schema.
 */
const background_processShouldCollapsePayloadValidator = background_zod_lib.z.object({
    elementUrl: background_zod_lib.z.string(),
    documentUrl: background_zod_lib.z.string(),
    requestType: background_zod_lib.z.nativeEnum(background_request_type/* RequestType */.Y),
}).strict();
/**
 * {@link MessageType.GetCosmeticData} Message payload validation schema.
 */
const background_getExtendedCssPayloadValidator = background_zod_lib.z.object({
    documentUrl: background_zod_lib.z.string(),
}).strict();
/**
 * {@link MessageType.GetCosmeticData} Message payload validation schema.
 */
const background_getCosmeticDataPayloadValidator = background_zod_lib.z.object({
    documentUrl: background_zod_lib.z.string(),
}).strict();
/**
 * {@link MessageType.GetCookieRules} Message payload validation schema.
 */
const background_getCookieRulesPayloadValidator = background_zod_lib.z.object({
    documentUrl: background_zod_lib.z.string(),
}).strict();
/**
 * {@link MessageType.SaveCookieLogEvent} Message payload validation schema.
 */
const background_getSaveCookieLogEventPayloadValidator = background_zod_lib.z.object({
    cookieName: background_zod_lib.z.string(),
    cookieDomain: background_zod_lib.z.string(),
    cookieValue: background_zod_lib.z.string(),
    filterId: background_zod_lib.z.number(),
    ruleIndex: background_zod_lib.z.number(),
    thirdParty: background_zod_lib.z.boolean(),
    isAllowlist: background_zod_lib.z.boolean(),
    isImportant: background_zod_lib.z.boolean(),
    isDocumentLevel: background_zod_lib.z.boolean(),
    isCsp: background_zod_lib.z.boolean(),
    isCookie: background_zod_lib.z.boolean(),
    advancedModifier: background_zod_lib.z.string().nullable(),
}).strict();
/**
 * {@link MessageType.InitAssistant} Message payload validation schema.
 */
const background_getAssistantCreateRulePayloadValidator = background_zod_lib.z.object({
    ruleText: background_zod_lib.z.string(),
}).strict();

/**
 * Request content type.
 *
 * NOTE: Do not use `const enum`,
 * because this enum is imported in extension frontend writing in js.
 */
var background_ContentType;
(function (ContentType) {
    ContentType["Document"] = "document";
    ContentType["Subdocument"] = "subdocument";
    ContentType["Script"] = "script";
    ContentType["Stylesheet"] = "stylesheet";
    ContentType["Object"] = "object";
    ContentType["Image"] = "image";
    ContentType["XmlHttpRequest"] = "xmlHttpRequest";
    ContentType["Media"] = "media";
    ContentType["Font"] = "font";
    ContentType["Websocket"] = "websocket";
    ContentType["WebRtc"] = "webRtc";
    ContentType["Other"] = "other";
    ContentType["Csp"] = "csp";
    ContentType["PermissionsPolicy"] = "permissionsPolicy";
    ContentType["Cookie"] = "cookie";
    ContentType["Ping"] = "ping";
    ContentType["CspReport"] = "cspReport";
})(background_ContentType || (background_ContentType = {}));
/**
 * Returns request type and content type by resource type.
 *
 * @param resourceType Resource type.
 *
 * @returns Request type and content type.
 */
function background_getRequestType(resourceType) {
    switch (resourceType) {
        case 'main_frame':
            return {
                contentType: background_ContentType.Document,
                requestType: background_request_type/* RequestType */.Y.Document,
            };
        case 'sub_frame':
            return {
                contentType: background_ContentType.Subdocument,
                requestType: background_request_type/* RequestType */.Y.SubDocument,
            };
        case 'stylesheet':
            return {
                contentType: background_ContentType.Stylesheet,
                requestType: background_request_type/* RequestType */.Y.Stylesheet,
            };
        case 'script':
            return {
                contentType: background_ContentType.Script,
                requestType: background_request_type/* RequestType */.Y.Script,
            };
        case 'image':
        case 'imageset':
            return {
                contentType: background_ContentType.Image,
                requestType: background_request_type/* RequestType */.Y.Image,
            };
        case 'object':
            return {
                contentType: background_ContentType.Object,
                requestType: background_request_type/* RequestType */.Y.Object,
            };
        case 'xmlhttprequest':
            return {
                contentType: background_ContentType.XmlHttpRequest,
                requestType: background_request_type/* RequestType */.Y.XmlHttpRequest,
            };
        case 'ping':
        case 'beacon':
            return {
                contentType: background_ContentType.Ping,
                requestType: background_request_type/* RequestType */.Y.Ping,
            };
        case 'font':
            return {
                contentType: background_ContentType.Font,
                requestType: background_request_type/* RequestType */.Y.Font,
            };
        case 'media':
            return {
                contentType: background_ContentType.Media,
                requestType: background_request_type/* RequestType */.Y.Media,
            };
        case 'websocket':
            return {
                contentType: background_ContentType.Websocket,
                requestType: background_request_type/* RequestType */.Y.WebSocket,
            };
        case 'csp_report':
            return {
                contentType: background_ContentType.CspReport,
                requestType: background_request_type/* RequestType */.Y.CspReport,
            };
        default:
            return {
                contentType: background_ContentType.Other,
                requestType: background_request_type/* RequestType */.Y.Other,
            };
    }
}

/**
 * @file
 * In the content script, we need access to @adguard/assistant only when
 * the user clicks 'block ad manually'.
 * Therefore, we exclude @adguard/assistant from the bundled content-script code
 * and load it on-demand. We also added a required field to the configuration
 * object to ensure the assistant is bundled inside the final extension,
 * allowing tswebextension to load it on-demand.
 *
 * Schema:
 * - Buildtime:
 *  -- [tswebext]  Script to inject assistant from the URL provided by the extension.
 *  -- [tswebext]  Assistant controller script for interacting with the assistant. <--- current file.
 *  -- [tswebext]  Assistant messages listener on the content-script side.
 *  -- [extension] Entry point script for injecting the assistant
 * - Runtime:
 *  -- [tswebext] Content script injects into every new tab without the assistant.
 *  -- [tswebext] On-demand content script dynamically injects the assistant.
 *  -- [tswebext] After injection, the content script interacts with the assistant.
 *
 * Reference code: ASSISTANT_INJECT.
 */
/**
 * Abstract assistant class is the handler of messages and events related
 * to AdGuard assistant.
 * Should be extended by the specific assistant implementation for executing
 * script for injecting assistant.
 */
class background_CommonAssistant {
    /**
     * Maximum time delay in milliseconds between the assistant frame creation and the assistant initialization.
     */
    static FRAME_CREATION_LIMIT_MS = 200;
    /**
     * Assistant frame URL.
     */
    static FRAME_URL = 'about:blank';
    /**
     * Fires when a rule has been created from the AdGuard assistant.
     */
    static onCreateRule = new background_EventChannel();
    /**
     * Path to assembled @adguard/assistant module. Necessary for lazy on-demand
     * loading of the assistant.
     */
    static assistantUrl = '';
    /**
     * Sets assistant url to the static variable. This method needs because we
     * currently use extended assistant class in both MV2 and MV3 and via directly set
     * CommonAssistant.assistantUrl it will not set filed inside super class itself.
     *
     * @param url Path to assistant, see {@link CommonAssistant.assistantUrl}.
     */
    static setAssistantUrl(url) {
        background_CommonAssistant.assistantUrl = url;
    }
    /**
     * Dynamically inject AdGuard assistant to the tab and after it opens it.
     *
     * @param tabId The ID of the tab where is needed to inject and open
     * the AdGuard assistant.
     */
    async openAssistant(tabId) {
        if (!background_CommonAssistant.assistantUrl) {
            throw new Error('Path to bundled assistant-inject file is not set up.');
        }
        // Inject assistant to the frame, before accessing it.
        await this.injectAssistant(tabId, background_CommonAssistant.assistantUrl);
        // After injection we can request opening it.
        await background_browser_polyfill.tabs.sendMessage(tabId, {
            type: background_message_constants_MessageType.InitAssistant,
        });
    }
    /**
     * Closes the AdGuard Assistant frame in the specified tab.
     *
     * @param tabId The ID of the tab where is needed to close
     * the AdGuard assistant.
     */
    static async closeAssistant(tabId) {
        await background_browser_polyfill.tabs.sendMessage(tabId, {
            type: background_message_constants_MessageType.CloseAssistant,
        });
    }
    /**
     * Checks whether the frame is an assistant frame. Two conditions must be met:
     * 1. The frame was created less than {@link CommonAssistant.FRAME_CREATION_LIMIT_MS}
     *    after the assistant initialization.
     * 2. The frame is a child of the main frame.
     *
     * @see {@link https://github.com/AdguardTeam/AdguardBrowserExtension/issues/1848}
     *
     * @param details Frame details of the onDomContentLoaded event.
     * @param tabContext Tab context.
     *
     * @returns True if the frame is an assistant frame, false otherwise.
     */
    static isAssistantFrame(details, tabContext) {
        if (!tabContext || !tabContext.assistantInitTimestamp) {
            return false;
        }
        const { frameId, url, timeStamp, } = details;
        const frameContext = tabContext.getFrameContext(frameId);
        if (!frameContext) {
            return false;
        }
        const timeSinceFrameCreatedMs = timeStamp - tabContext.assistantInitTimestamp;
        return timeSinceFrameCreatedMs < background_CommonAssistant.FRAME_CREATION_LIMIT_MS
            && frameContext.parentFrameId === background_MAIN_FRAME_ID
            && url === background_CommonAssistant.FRAME_URL;
    }
}

/**
 * CosmeticApiCommon contains common logic about building css for hiding elements.
 */
class background_CosmeticApiCommon {
    static LINE_BREAK = '\r\n';
    /**
     * Number of selectors in grouped selector list.
     */
    static CSS_SELECTORS_PER_LINE = 50;
    /**
     * Element hiding CSS style beginning.
     */
    static ELEMHIDE_HIT_START = " { display: none !important; content: 'adguard";
    /**
     * CSS style declaration for hit stats.
     */
    static INJECT_HIT_START = " content: 'adguard";
    /**
     * Separator for hit stats.
     */
    static HIT_SEP = encodeURIComponent(background_SEMICOLON);
    /**
     * Element hiding CSS style ending.
     */
    static HIT_END = "' !important; }";
    /**
     * Regular expression to find content attribute in css rule.
     */
    static CONTENT_ATTR_RE = /[{;"(]\s*content\s*:/gi;
    /**
     * Builds stylesheets from rules.
     * If `groupElemhideSelectors` is set,
     * element hiding selector are to be combined into selector lists of {@link CosmeticApi.CSS_SELECTORS_PER_LINE}.
     *
     * @param elemhideRules List of elemhide rules.
     * @param injectRules List of inject css rules.
     * @param groupElemhideSelectors Flag for elemhide selectors grouping.
     *
     * @returns List of stylesheet expressions.
     */
    static buildStyleSheets(elemhideRules, injectRules, groupElemhideSelectors) {
        const styles = [];
        const elemHideStyles = background_CosmeticApiCommon.buildElemhideStyles(elemhideRules, groupElemhideSelectors);
        if (elemHideStyles.length > 0) {
            if (groupElemhideSelectors) {
                styles.push(elemHideStyles.join(background_CosmeticApiCommon.LINE_BREAK));
            }
            else {
                styles.push(...elemHideStyles);
            }
        }
        const cssStyles = injectRules.map((x) => x.getContent());
        if (cssStyles.length > 0) {
            if (groupElemhideSelectors) {
                styles.push(cssStyles.join(background_CosmeticApiCommon.LINE_BREAK));
            }
            else {
                styles.push(...cssStyles);
            }
        }
        return styles;
    }
    /**
     * Builds element hiding stylesheet from rules.
     * If `groupElemhideSelectors` is set,
     * selector are to be combined into selector lists of {@link CosmeticApi.CSS_SELECTORS_PER_LINE}.
     *
     * @param elemhideRules List of elemhide rules.
     * @param groupElemhideSelectors Flag for elemhide selectors grouping.
     *
     * @returns Array of styles.
     */
    static buildElemhideStyles(elemhideRules, groupElemhideSelectors) {
        // TODO: refactor constants as ELEMHIDE_CSS_STYLE and ELEMHIDE_HIT_START are duplicates partly
        const ELEMHIDE_CSS_STYLE = ' { display: none !important; }';
        const elemhideSelectors = [];
        for (const selector of elemhideRules) {
            elemhideSelectors.push(selector.getContent());
        }
        // if selector should not be grouped,
        // add element hiding style to each of them
        if (!groupElemhideSelectors) {
            return elemhideSelectors.map((selector) => {
                return `${selector}${ELEMHIDE_CSS_STYLE}`;
            });
        }
        // otherwise selectors should be grouped into selector lists
        const elemhideStyles = [];
        for (let i = 0; i < elemhideSelectors.length; i += background_CosmeticApiCommon.CSS_SELECTORS_PER_LINE) {
            const selectorList = elemhideSelectors
                .slice(i, i + background_CosmeticApiCommon.CSS_SELECTORS_PER_LINE)
                .join(', ');
            elemhideStyles.push(`${selectorList}${ELEMHIDE_CSS_STYLE}`);
        }
        return elemhideStyles;
    }
    /**
     * Patches rule selector adding adguard mark rule info in the content attribute.
     *
     * @param rule Elemhide cosmetic rule.
     *
     * @returns Rule with modified stylesheet, containing content marker.
     *
     * @example
     * `.selector` -> `.selector { content: 'adguard{filterId};{ruleText} !important;}`
     */
    static addMarkerToElemhideRule(rule) {
        const result = [];
        result.push(rule.getContent());
        result.push(background_CosmeticApiCommon.ELEMHIDE_HIT_START);
        result.push(String(rule.getFilterListId()));
        result.push(background_CosmeticApiCommon.HIT_SEP);
        result.push(String(rule.getIndex()));
        result.push(background_CosmeticApiCommon.HIT_END);
        return result.join('');
    }
    /**
     * Patches rule selector adding adguard mark and rule info in the content style attribute.
     * Example:
     * .selector { color: red } -> .selector { color: red, content: 'adguard{filterId};{ruleText} !important;}.
     *
     * @param rule Inject cosmetic rule.
     *
     * @returns Modified rule with injected content marker into stylesheet.
     */
    static addMarkerToInjectRule(rule) {
        const result = [];
        const ruleContent = rule.getContent();
        // if rule text has content attribute we don't add rule marker
        if (background_CosmeticApiCommon.CONTENT_ATTR_RE.test(ruleContent)) {
            return ruleContent;
        }
        // remove closing brace
        const ruleTextWithoutCloseBrace = ruleContent.slice(0, -1).trim();
        // check semicolon
        const ruleTextWithSemicolon = ruleTextWithoutCloseBrace.endsWith(background_SEMICOLON)
            ? ruleTextWithoutCloseBrace
            : `${ruleTextWithoutCloseBrace}${background_SEMICOLON}`;
        result.push(ruleTextWithSemicolon);
        result.push(background_CosmeticApiCommon.INJECT_HIT_START);
        result.push(String(rule.getFilterListId()));
        result.push(background_CosmeticApiCommon.HIT_SEP);
        result.push(String(rule.getIndex()));
        result.push(background_CosmeticApiCommon.HIT_END);
        return result.join('');
    }
    /**
     * Builds stylesheets with css-hits marker.
     *
     * @param elemhideRules Elemhide css rules.
     * @param injectRules Inject css rules.
     *
     * @returns List of stylesheet expressions.
     */
    static buildStyleSheetsWithHits(elemhideRules, injectRules) {
        const elemhideStyles = elemhideRules.map((x) => background_CosmeticApiCommon.addMarkerToElemhideRule(x));
        const injectStyles = injectRules.map((x) => background_CosmeticApiCommon.addMarkerToInjectRule(x));
        return [...elemhideStyles, ...injectStyles];
    }
    /**
     * Builds extended css rules from cosmetic result.
     *
     * @param cosmeticResult Cosmetic result.
     * @param collectingCosmeticRulesHits Flag to collect cosmetic rules hits.
     *
     * @returns Array of extended css rules or null.
     */
    static getExtCssRules(cosmeticResult, collectingCosmeticRulesHits = false) {
        const { elementHiding, CSS } = cosmeticResult;
        const elemhideExtCss = elementHiding.genericExtCss.concat(elementHiding.specificExtCss);
        const injectExtCss = CSS.genericExtCss.concat(CSS.specificExtCss);
        let extCssRules;
        if (collectingCosmeticRulesHits) {
            extCssRules = background_CosmeticApiCommon.buildStyleSheetsWithHits(elemhideExtCss, injectExtCss);
        }
        else {
            extCssRules = background_CosmeticApiCommon.buildStyleSheets(elemhideExtCss, injectExtCss, false);
        }
        return extCssRules.length > 0
            ? extCssRules
            : null;
    }
    /**
     * Retrieves CSS styles from the cosmetic result.
     *
     * @param cosmeticResult Cosmetic result.
     * @param collectingCosmeticRulesHits Flag to collect cosmetic rules hits.
     *
     * @returns Css styles as string, or `undefined` if no styles found.
     */
    static getCssText(cosmeticResult, collectingCosmeticRulesHits = false) {
        const { elementHiding, CSS } = cosmeticResult;
        const elemhideCss = elementHiding.generic.concat(elementHiding.specific);
        const injectCss = CSS.generic.concat(CSS.specific);
        let styles;
        if (collectingCosmeticRulesHits) {
            styles = background_CosmeticApiCommon.buildStyleSheetsWithHits(elemhideCss, injectCss);
        }
        else {
            styles = background_CosmeticApiCommon.buildStyleSheets(elemhideCss, injectCss, true);
        }
        if (styles.length > 0) {
            return styles.join(background_CosmeticApiCommon.LINE_BREAK);
        }
        return undefined;
    }
    /**
     * Wraps the given JavaScript code in a self-invoking function for safe execution
     * and appends a source URL comment for debugging purposes.
     *
     * @param scriptText The JavaScript code to wrap.
     *
     * @returns The wrapped script code, or an empty string if the input is falsy.
     */
    static wrapScriptText(scriptText) {
        if (!scriptText) {
            return '';
        }
        // The "//# sourceURL=ag-scripts.js" line is necessary to ensure the script always has the same URL,
        // making it possible to debug consistently.
        return `
        (function () {
            try {
                ${scriptText}
            } catch (ex) {
                console.error('Error executing AG js: ' + ex);
            }
        })();
        //# sourceURL=ag-scripts.js
        `;
    }
    /**
     * Combines unique script strings into a single script text.
     *
     * Script string is being trimmed and a semicolon is added if it is missing.
     *
     * @param uniqueScriptStrings Set of unique script strings to combine.
     *
     * @returns Combined script string.
     */
    static combineScripts(uniqueScriptStrings) {
        let scriptText = '';
        uniqueScriptStrings.forEach((rawScriptStr) => {
            const script = rawScriptStr.trim();
            scriptText += script.endsWith(background_SEMICOLON)
                ? `${script}${background_constants_LF}`
                : `${script}${background_SEMICOLON}${background_constants_LF}`;
        });
        return scriptText;
    }
    /**
     * Logs js rules applied to a specific frame.
     *
     * @param params Data for js rule logging.
     * @param predicate Function to filter script rules before logging, e.g. check if the script rule is local.
     */
    static logScriptRules(params, predicate) {
        const { tabId, cosmeticResult, url, contentType, timestamp, } = params;
        const scriptRules = cosmeticResult.getScriptRules().filter(predicate);
        for (const scriptRule of scriptRules) {
            if (scriptRule.isGeneric()) {
                continue;
            }
            const ruleType = scriptRule.getType();
            background_defaultFilteringLog.publishEvent({
                type: background_FilteringEventType.JsInject,
                data: {
                    script: true,
                    tabId,
                    // for proper filtering log request info rule displaying
                    // event id should be unique for each event, not copied from request
                    // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2341
                    eventId: background_non_secure_nanoid(),
                    requestUrl: url,
                    frameUrl: url,
                    frameDomain: background_getDomain(url),
                    requestType: contentType,
                    timestamp,
                    filterId: scriptRule.getFilterListId(),
                    ruleIndex: scriptRule.getIndex(),
                    cssRule: ruleType === background_nodes/* CosmeticRuleType */.k9.ElementHidingRule
                        || ruleType === background_nodes/* CosmeticRuleType */.k9.CssInjectionRule,
                    scriptRule: ruleType === background_nodes/* CosmeticRuleType */.k9.ScriptletInjectionRule
                        || ruleType === background_nodes/* CosmeticRuleType */.k9.JsInjectionRule,
                    contentRule: ruleType === background_nodes/* CosmeticRuleType */.k9.HtmlFilteringRule,
                },
            });
        }
    }
}

/**
 * Check if the frame URL is about:blank or about:srcdoc.
 *
 * @param frameUrl Frame URL.
 *
 * @returns True if frame URL is about:blank or about:srcdoc, otherwise false.
 */
const background_isEmptySrcFrame = (frameUrl) => {
    return frameUrl === 'about:blank'
        || frameUrl === 'about:srcdoc';
};

/**
 * Checks if iframe has same source as main frame or if src is about:blank, javascript:, etc.
 * We don't include frames with 'src=data:' because Chrome and Firefox
 * do not allow data to be injected into frames with this type of src,
 * this bug is reported here https://bugs.chromium.org/p/chromium/issues/detail?id=55084.
 *
 * @param frameUrl Frame url.
 * @param frameId Unique id of frame in the tab.
 * @param mainFrameUrl Url of tab where iframe exists.
 *
 * @returns True if frame without src, else returns false.
 */
function background_isLocalFrame(frameUrl, frameId, mainFrameUrl) {
    return frameId !== background_MAIN_FRAME_ID
        && (frameUrl === mainFrameUrl
            || background_isEmptySrcFrame(frameUrl)
            // eslint-disable-next-line no-script-url
            || frameUrl.indexOf('javascript:') > -1);
}

/**
 * Creates match query for frame based on content script data and background tab context.
 * Used in {@link CosmeticApi} and {@link CookieFiltering} to match rules for content scripts.
 *
 * @param frameUrl Frame url. Received from content script.
 * @param frameId Frame id. Received from content script.
 * @param tabContext Tab context. Received from background script.
 *
 * @returns Match query for {@link EngineApi}.
 *
 * @throws Error if tab context url is not defined.
 */
function background_createFrameMatchQuery(frameUrl, frameId, tabContext) {
    const { info } = tabContext;
    if (!info.url) {
        throw new Error('Tab url is required');
    }
    const mainFrameUrl = info.url;
    const isLocal = background_isLocalFrame(frameUrl, frameId, mainFrameUrl);
    const requestUrl = isLocal ? mainFrameUrl : frameUrl;
    let requestType;
    // if frame is Local, then apply main frame rules.
    if (isLocal) {
        requestType = background_request_type/* RequestType */.Y.Document;
    }
    else if (frameId === background_MAIN_FRAME_ID) {
        requestType = background_request_type/* RequestType */.Y.Document;
    }
    else {
        requestType = background_request_type/* RequestType */.Y.SubDocument;
    }
    return {
        requestUrl,
        frameUrl: requestUrl,
        requestType,
        frameRule: tabContext.mainFrameRule,
    };
}

/**
 * Wrapper for StorageArea with dev-friendly interface.
 *
 * @template Data The type of the value stored in the storage.
 */
class background_configuration_BrowserStorage {
    storage;
    /**
     * Constructs an instance of the BrowserStorage class.
     *
     * @param storage The storage area to use.
     */
    constructor(storage) {
        this.storage = storage;
    }
    /**
     * Sets data to storage.
     *
     * @param key Storage key.
     * @param value Storage value.
     */
    async set(key, value) {
        await this.storage.set({ [key]: value });
    }
    /**
     * Returns data from storage.
     *
     * @param key Storage key.
     *
     * @returns Storage value.
     */
    async get(key) {
        return this.storage.get(key).then((data) => data[key]);
    }
    /**
     * Removes data from storage.
     *
     * @param key Storage key.
     */
    async remove(key) {
        await this.storage.remove(key);
    }
    /**
     * Sets multiple key-value pairs in the storage.
     *
     * @param data The key-value pairs to set.
     *
     * @returns True if all operations were successful, false otherwise.
     *
     * @example
     * ```ts
     * const storage = new Storage();
     * await storage.setMultiple({
     *    key1: 'value1',
     *    key2: 'value2',
     * });
     * ```
     */
    // TODO: Implement some kind of transaction to ensure atomicity, if possible
    // Note: We only use this method for Firefox if "Never Remember History" is enabled
    async setMultiple(data) {
        try {
            await this.storage.set(data);
            return true;
        }
        catch (e) {
            return false;
        }
    }
    /**
     * Removes multiple key-value pairs from the storage.
     *
     * @param keys The keys to remove.
     *
     * @returns True if all operations were successful, false otherwise.
     */
    async removeMultiple(keys) {
        await this.storage.remove(keys);
        return true;
    }
    /**
     * Get the entire contents of the storage.
     *
     * @returns Promise that resolves with the entire contents of the storage.
     */
    async entries() {
        return this.storage.get(null);
    }
    /**
     * Get all keys from the storage.
     *
     * @returns Promise that resolves with all keys from the storage.
     */
    async keys() {
        return Object.keys(await this.entries());
    }
    /**
     * Checks if the storage has a key.
     *
     * @param key The key to check.
     *
     * @returns True if the key exists, false otherwise.
     */
    async has(key) {
        return this.storage.get(key).then((data) => key in data);
    }
    /**
     * Clears the storage.
     */
    async clear() {
        await this.storage.clear();
    }
}

/**
 * @file Memory storage implementation with async operations.
 */
/**
 * Provides a simple in-memory storage implementation.
 * This class implements the ExtendedStorageInterface with asynchronous methods.
 *
 * @template Data The type of the value stored in the storage.
 */
class background_MemoryStorage {
    /**
     * Internal map to hold the key-value pairs.
     */
    store;
    /**
     * Constructs an instance of the MemoryStorage class.
     */
    constructor() {
        this.store = new Map();
    }
    /**
     * Retrieves a value by key from the storage.
     *
     * @param key The key of the value to retrieve.
     *
     * @returns A promise that resolves with the value associated with the key.
     */
    async get(key) {
        return Promise.resolve(this.store.get(key));
    }
    /**
     * Sets a value in the storage with the specified key.
     *
     * @param key The key under which to store the value.
     * @param value The value to store.
     *
     * @returns A promise that resolves when the operation is complete.
     */
    async set(key, value) {
        this.store.set(key, background_lodash_es_cloneDeep(value));
        return Promise.resolve();
    }
    /**
     * Removes a value from the storage by key.
     *
     * @param key The key of the value to remove.
     *
     * @returns A promise that resolves when the operation is complete.
     */
    async remove(key) {
        this.store.delete(key);
        return Promise.resolve();
    }
    /**
     * Sets multiple key-value pairs in the storage.
     *
     * @param data The key-value pairs to set.
     *
     * @returns A promise that resolves with true if all operations were successful.
     */
    async setMultiple(data) {
        try {
            // Create a deep copy of each value
            const clonedData = background_lodash_es_cloneDeep(data);
            // Set each key-value pair into the store using Object.assign
            Object.assign(this.store, Object.entries(clonedData).reduce((acc, [key, value]) => {
                acc[key] = value;
                return acc;
            }, {}));
            return await Promise.resolve(true);
        }
        catch (error) {
            background_common_logger_logger.error('Error in setMultiple:', error);
            return Promise.resolve(false);
        }
    }
    /**
     * Removes multiple key-value pairs from the storage.
     *
     * @param keys The keys to remove.
     *
     * @returns A promise that resolves with true if all operations were successful.
     */
    async removeMultiple(keys) {
        try {
            keys.forEach((key) => this.store.delete(key));
            return await Promise.resolve(true);
        }
        catch (error) {
            background_common_logger_logger.error('Error in removeMultiple:', error);
            return Promise.resolve(false);
        }
    }
    /**
     * Retrieves all entries in the storage.
     *
     * @returns A promise that resolves with an object containing all key-value pairs in the storage.
     */
    async entries() {
        return Promise.resolve(Object.fromEntries(this.store.entries()));
    }
    /**
     * Retrieves all keys in the storage.
     *
     * @returns A promise that resolves with an array of all keys in the storage.
     */
    async keys() {
        return Promise.resolve(Array.from(this.store.keys()));
    }
    /**
     * Checks if a key exists in the storage.
     *
     * @param key The key to check.
     *
     * @returns A promise that resolves with true if the key exists, false otherwise.
     */
    async has(key) {
        return Promise.resolve(this.store.has(key));
    }
    /**
     * Clears the storage.
     *
     * @returns A promise that resolves when the storage is cleared.
     */
    async clear() {
        this.store.clear();
        return Promise.resolve();
    }
}

/**
 * API to store a persistent value with debounced synchronization to the specified storage key.
 *
 * After the container is created, we initialize it asynchronously to get the actual value from the storage.
 * The Init method is guarded against multiple initializations to avoid unnecessary reads from the memory.
 * Get/set methods are protected from uninitialized storage to ensure that actual data is used.
 *
 * We declare the sync get/set methods to update the cached value. This allows us to use containers in accessors.
 *
 * Set method updates the cached value and schedules the save operation to the storage via a debounce function to
 * avoid unnecessary writes to the storage.
 *
 * This container saves the data to storage using the specified key to avoid collisions with other instances.
 * It helps to avoid reading the data from the storage that is not related to the current instance.
 */
class background_PersistentValueContainer {
    static #IS_BACKGROUND_PERSISTENT = background_PersistentValueContainer.#isBackgroundPersistent();
    #storage; // Using the async StorageInterface
    #key;
    #value;
    #save;
    #isInitialized = false;
    /**
     * Creates {@link PersistentValueContainer} instance.
     *
     * @param key The key to use for storing the data.
     * @param storage The storage interface implementation.
     * @param debounceMs The debounce time in milliseconds to save the data to the storage.
     * Optional. Default is 300ms.
     */
    constructor(key, storage, // Accepts a StorageInterface implementation
    debounceMs = 300) {
        this.#key = key;
        this.#storage = storage;
        // Configure the #save method to decide dynamically between debounce or direct call
        this.#save = background_PersistentValueContainer.#IS_BACKGROUND_PERSISTENT
            ? () => {
                this.#storage.set(this.#key, this.#value); // Save directly
            }
            : background_lodash_es_debounce(() => {
                this.#storage.set(this.#key, this.#value); // Save using debounce
            }, debounceMs);
    }
    /**
     * Initializes the value.
     *
     * @param value The initial value.
     *
     * @returns Promise that resolves when the value is initialized.
     *
     * @throws Error, if storage already initialized.
     */
    async init(value) {
        if (this.#isInitialized) {
            throw new Error('Storage already initialized');
        }
        if (background_PersistentValueContainer.#IS_BACKGROUND_PERSISTENT) {
            this.#value = value;
        }
        else {
            const storedValue = await this.#storage.get(this.#key);
            this.#value = storedValue !== undefined ? storedValue : value; // Use stored value or fallback to default
        }
        this.#isInitialized = true;
    }
    /**
     * Gets the value.
     *
     * @returns The value stored by the specified key.
     *
     * @throws Error, if storage not initialized.
     */
    get() {
        this.#checkIsInitialized();
        return this.#value;
    }
    /**
     * Sets the value.
     *
     * @param value Value to be stored in the specified key.
     *
     * @throws Error, if storage not initialized.
     */
    set(value) {
        this.#checkIsInitialized();
        this.#value = value;
        this.#save();
    }
    /**
     * Checks if the storage is initialized.
     *
     * @throws Error, if storage not initialized.
     */
    #checkIsInitialized() {
        if (!this.#isInitialized) {
            throw new Error('Storage not initialized');
        }
    }
    /**
     * TODO: remove this method after the migration to event-driven background.
     * Checks if the background script is persistent.
     *
     * @returns True if the background script is persistent.
     */
    static #isBackgroundPersistent() {
        const manifest = background_browser_polyfill.runtime.getManifest();
        if (manifest.manifest_version === 3) {
            return false;
        }
        if (!manifest.background) {
            return true;
        }
        const background = manifest.background;
        return background.persistent ?? true;
    }
}

/**
 * API for storing persistent key-value data with debounced sync using a specified storage key.
 * Storage synchronization is described in the {@link PersistentValueContainer} class.
 */
class background_ExtensionStorage {
    /**
     * API for storing persistent value with debounced sync using the specified storage key.
     */
    #container;
    /**
     * Creates {@link ExtensionStorage} instance.
     *
     * @param key The key to use for storing the data.
     * @param storage Storage interface implementation (replacing WebExtension API storage).
     */
    constructor(key, storage) {
        this.#container = new background_PersistentValueContainer(key, storage);
    }
    /**
     * Initializes the storage.
     *
     * @param data The initial data.
     *
     * @returns Promise that resolves when the storage is initialized.
     *
     * @throws Error, if storage already initialized.
     */
    init(data) {
        return this.#container.init(data);
    }
    /**
     * Gets the value by the specified key.
     *
     * @param key The key to retrieve the value.
     *
     * @returns The data stored by the specified key.
     *
     * @throws Error, if storage not initialized.
     */
    get(key) {
        return this.#container.get()[key];
    }
    /**
     * Sets the value by the specified key.
     *
     * @param key The key for the value to be stored.
     * @param value The new value.
     *
     * @throws Error, if storage not initialized.
     */
    set(key, value) {
        const data = this.#container.get();
        data[key] = value;
        this.#container.set(data);
    }
    /**
     * Deletes the value by the specified key.
     *
     * @param key The key for the value to be deleted.
     *
     * @throws Error, if storage not initialized.
     */
    delete(key) {
        const data = this.#container.get();
        delete data[key];
        this.#container.set(data);
    }
}

/**
 * Creates accessor decorator for the specified storage.
 *
 * @see https://github.com/tc39/proposal-decorators
 *
 * @param storage The extension storage API to use.
 *
 * @returns Accessor decorator for the specified storage.
 */
function background_createExtensionStorageDecorator(storage) {
    const fields = new Set();
    /**
     * Creates accessor decorator for the specified storage field.
     *
     * NOTE: You should not set the initial value to the accessor via assignment,
     * because the decorator overwrites accessor methods and doesn't use a private property, created on initialization.
     * Use Non-null assertion operator instead.
     *
     * @param field Storage field name.
     *
     * @returns Decorator for access to specified storage {@link field}.
     *
     * @throws Error if the decorator is already registered for {@link field}
     * or the decorator is applied to a class member other than an accessor.
     *
     * @example `@storage('foo') accessor bar!: string`;
     */
    return function createFieldDecorator(field) {
        // Prevent the use of multiple decorators on a single storage field
        if (fields.has(field)) {
            throw new Error(`Decorator for ${String(field)} field is already registered`);
        }
        fields.add(field);
        return function fieldDecorator(_target, context) {
            // Ensure the class member is an accessor
            if (context.kind !== 'accessor') {
                throw new Error('Class member is not an accessor');
            }
            // Provide getter and setter using the ExtensionStorage methods
            return {
                get() {
                    return storage.get(field);
                },
                set(value) {
                    storage.set(field, value);
                },
            };
        };
    };
}

/**
 * Service for working with companies database.
 */
class background_CompaniesDbService {
    /**
     * Category name for unknown domains.
     *
     * @see {@link https://github.com/AdguardTeam/companiesdb/blob/6a8fbfc3bff4fdffc4c8bae30756530afc2635bd/dist/trackers.json#L15}
     */
    static UNKNOWN_CATEGORY_NAME = 'unknown';
    /**
     * Dot symbol.
     */
    static DOT = '.';
    /**
     * Companies database.
     */
    companiesDb = background_rawCompaniesDb;
    /**
     * Returns categories from the companiesdb data where
     * - key — numeric category id
     * - value — category name.
     *
     * @returns Categories from the companiesdb data.
     *
     * @throws Error if companies database is not loaded.
     */
    getCompaniesDbCategories() {
        if (!this.companiesDb) {
            throw new Error('[CompaniesDbService] Companies database is not loaded');
        }
        return this.companiesDb.categories;
    }
    /**
     * Recursively tries to match a company category id for a `domainToCheck`.
     *
     * If the category is not found for an input `domainToCheck`,
     * slices the first subdomain and tries to check a category for a new domain,
     * e.g. `test1.sub.example.com` -> `sub.example.com` -> `example.com`,
     * and returns the category if found.
     *
     * @param domainToCheck Domain to check.
     * @param rootDomain Root domain.
     *
     * @returns Matched company category id or `null` if not found.
     */
    matchCompanyCategoryId(domainToCheck, rootDomain) {
        if (!domainToCheck || !rootDomain) {
            return null;
        }
        if (domainToCheck === rootDomain) {
            return this.companiesDb.trackerDomains[rootDomain] || null;
        }
        const categoryId = this.companiesDb.trackerDomains[domainToCheck];
        if (!categoryId) {
            const firstDotIndex = domainToCheck.indexOf(background_CompaniesDbService.DOT);
            const nextDomainToCheck = domainToCheck.slice(firstDotIndex + 1);
            return this.matchCompanyCategoryId(nextDomainToCheck, rootDomain);
        }
        return categoryId;
    }
    /**
     * Matches a URL to a tracker category id.
     *
     * List of categories ids can be found in {@link companiesDb.categories}.
     *
     * @param url Request URL to match.
     *
     * @returns Matched company category name,
     * or {@link CompaniesDbService.UNKNOWN_CATEGORY_NAME} if the category is unknown.
     */
    match(url) {
        if (!this.companiesDb || !this.companiesDb.trackerDomains) {
            return background_CompaniesDbService.UNKNOWN_CATEGORY_NAME;
        }
        const companyCategoryId = this.matchCompanyCategoryId((0,background_es6/* getHostname */.EW)(url), 
        // getDomain with no allowPrivateDomains flag set returns root domain,
        // e.g. 'test-public.s3.amazonaws.com' -> 'amazonaws.com'
        (0,background_es6/* getDomain */.FB)(url));
        if (!companyCategoryId) {
            return background_CompaniesDbService.UNKNOWN_CATEGORY_NAME;
        }
        const companyCategoryName = this.companiesDb.categories[companyCategoryId];
        if (!companyCategoryName) {
            return background_CompaniesDbService.UNKNOWN_CATEGORY_NAME;
        }
        return companyCategoryName;
    }
}
const background_companiesDbService = new background_CompaniesDbService();

/**
 * Synthetic Cookie-like object parsed from headers.
 */
class background_ParsedCookie {
    /**
     * The request-URI to associate with the setting of the cookie.
     */
    url;
    /**
     * Defines the host to which the cookie will be sent.
     * Only the current domain can be set as the value, or a domain of a higher
     * order, unless it is a public suffix. Setting the domain will make
     * the cookie available to it, as well as to all its subdomains.
     *
     * Can be empty. And actually should be empty for `__Host-` cookies.
     *
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes}
     */
    domain;
    /**
     * The name of the cookie.
     */
    name;
    /**
     * The value of the cookie.
     */
    value;
    /**
     * The expiration date of the cookie.
     */
    expires;
    /**
     * The parsed max-age value in seconds.
     */
    maxAge;
    /**
     * True if the cookie is marked as Secure.
     */
    secure;
    /**
     * Whether the cookie should be marked as HttpOnly.
     */
    httpOnly;
    /**
     * Cookie's same-site status.
     */
    sameSite;
    /**
     * Cookies path. Defaults to the path portion of the url parameter.
     */
    path;
    /**
     * Priority chrome only specs.
     * Isn't affected. Let it be here just in case.
     *
     * @see {@link https://bugs.chromium.org/p/chromium/issues/detail?id=232693}
     */
    priority;
    /**
     * Cookie's third-party status.
     */
    thirdParty = false;
    /**
     * Constructor.
     *
     * @param name Cookie name.
     * @param value Cookie value.
     * @param url Url.
     */
    constructor(name, value, url) {
        this.name = name;
        this.value = value;
        this.url = url;
        this.path = new URL(url).pathname;
    }
    /**
     * Creates new {@link ParsedCookie} from provided {@link Cookies.Cookie}.
     *
     * @param cookie Item of {@link Cookies.Cookie}.
     * @param url String URL relative to this cookie.
     *
     * @returns New {@link ParsedCookie}.
     */
    static fromBrowserCookie(cookie, url) {
        const parsedCookie = new background_ParsedCookie(cookie.name, cookie.value, url);
        parsedCookie.thirdParty = !cookie.firstPartyDomain;
        parsedCookie.httpOnly = cookie.httpOnly;
        parsedCookie.secure = cookie.secure;
        parsedCookie.sameSite = cookie.sameSite;
        // For hostOnly cookie domain should be empty and path should be '/'.
        if (cookie.hostOnly) {
            parsedCookie.path = '/';
        }
        else {
            parsedCookie.domain = cookie.domain;
            parsedCookie.path = cookie.path;
        }
        if (cookie.expirationDate) {
            // cookie.expirationDate is a number of seconds that's why it should be multiplied
            parsedCookie.expires = new Date(cookie.expirationDate * 1000);
        }
        return parsedCookie;
    }
}

/**
 * Cookie Utils.
 */
let background_CookieUtils$1 = class CookieUtils {
    /**
     * RegExp to match field-content in RFC 7230 sec 3.2.
     *
     * Example:
     * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
     * field-vchar   = VCHAR / obs-text
     * obs-text      = %x80-FF.
     */
    // eslint-disable-next-line no-control-regex
    static FIELD_CONTENT_REGEX = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
    /**
     * Parses set-cookie header from http response header.
     *
     * @param header HTTP response header.
     * @param url Request URL.
     *
     * @returns Parsed cookie or null if it failed to parse the header.
     */
    static parseSetCookieHeader(header, url) {
        if (!header.name || header.name.toLowerCase() !== 'set-cookie') {
            return null;
        }
        if (!header.value) {
            return null;
        }
        return CookieUtils.parseSetCookie(header.value, url);
    }
    /**
     * Parses set-cookie headers for cookie objects.
     *
     * @param responseHeaders HTTP response headers.
     * @param url Request URL.
     *
     * @returns Array of parsed cookies.
     */
    static parseSetCookieHeaders(responseHeaders, url) {
        const result = [];
        let iResponseHeaders = responseHeaders.length;
        while (iResponseHeaders > 0) {
            iResponseHeaders -= 1;
            const header = responseHeaders[iResponseHeaders];
            const setCookie = CookieUtils.parseSetCookieHeader(header, url);
            if (setCookie) {
                result.push(setCookie);
            }
        }
        return result;
    }
    /**
     * Parse an HTTP Cookie header string and return an object with all cookie name-value pairs.
     *
     * @param cookieValue HTTP Cookie value.
     * @param url Request URL.
     *
     * @returns Array of cookie name-value pairs.
     */
    static parseCookies(cookieValue, url) {
        const cookies = [];
        // Split Cookie values
        const pairs = cookieValue.split(/; */);
        for (let i = 0; i < pairs.length; i += 1) {
            const pair = pairs[i];
            const eqIdx = pair.indexOf('=');
            // skip things that don't look like key=value
            if (eqIdx < 0) {
                continue;
            }
            const key = pair.substring(0, eqIdx).trim();
            const value = pair.substring(eqIdx + 1, pair.length).trim();
            const parsedCookie = new background_ParsedCookie(key, value, url);
            /**
             * Not obviously there are few special name prefixes.
             *
             * @see {@link https://developer.cdn.mozilla.net/pt-BR/docs/Web/HTTP/Headers/Set-Cookie}
             */
            if (key.startsWith('__Secure-') || key.startsWith('__Host-')) {
                parsedCookie.secure = true;
            }
            cookies.push(parsedCookie);
        }
        return cookies;
    }
    /**
     * Parses "Set-Cookie" header value and returns a cookie object with its properties.
     *
     * @param setCookieValue "Set-Cookie" header value to parse.
     * @param url Request URL.
     *
     * @returns Parsed cookie or null if it failed to parse the value.
     */
    static parseSetCookie(setCookieValue, url) {
        const parts = setCookieValue.split(';').filter((s) => !!s);
        const nameValuePart = parts.shift();
        if (!nameValuePart) {
            // eslint-disable-next-line max-len
            background_common_logger_logger.debug(`[tswebextension.parseSetCookie]: cannot shift first name-value pair from Set-Cookie header '${setCookieValue}'.`);
            return null;
        }
        const nameValue = nameValuePart.split('=');
        const name = nameValue.shift();
        if (!name) {
            // eslint-disable-next-line max-len
            background_common_logger_logger.debug(`[tswebextension.parseSetCookie]: cannot extract name from first name-value pair from Set-Cookie header '${setCookieValue}'.`);
            return null;
        }
        // Everything after the first =, joined by a "=" if there was more
        // than one part.
        const value = nameValue.join('=');
        const cookie = new background_ParsedCookie(name, value, url);
        parts.forEach((part) => {
            const sides = part.split('=');
            const key = sides
                .shift()
                .trimStart()
                .toLowerCase();
            const optionValue = sides.join('=');
            if (key === 'expires') {
                cookie.expires = new Date(optionValue);
            }
            else if (key === 'max-age') {
                cookie.maxAge = parseInt(optionValue, 10);
            }
            else if (key === 'secure') {
                cookie.secure = true;
            }
            else if (key === 'httponly') {
                cookie.httpOnly = true;
            }
            else if (key === 'samesite') {
                cookie.sameSite = optionValue;
            }
            else if (key === 'path') {
                cookie.path = optionValue;
            }
            else if (key === 'domain') {
                cookie.domain = optionValue;
            }
        });
        return cookie;
    }
    /**
     * Updates cookie maxAge value.
     *
     * @param cookie Cookie to modify.
     * @param maxAge New maxAge value.
     *
     * @returns True if cookie was modified.
     */
    static updateCookieMaxAge(cookie, maxAge) {
        const currentTimeSec = Date.now() / 1000;
        let cookieExpiresTimeSec = null;
        if (cookie.maxAge) {
            cookieExpiresTimeSec = currentTimeSec + cookie.maxAge;
        }
        else if (cookie.expires) {
            cookieExpiresTimeSec = cookie.expires.getTime() / 1000;
        }
        const newCookieExpiresTimeSec = currentTimeSec + maxAge;
        if (cookieExpiresTimeSec === null || cookieExpiresTimeSec > newCookieExpiresTimeSec) {
            // eslint-disable-next-line no-param-reassign
            cookie.expires = new Date(newCookieExpiresTimeSec * 1000);
            // eslint-disable-next-line no-param-reassign
            cookie.maxAge = maxAge;
            return true;
        }
        return false;
    }
    /**
     * Serializes cookie data into a string suitable for Set-Cookie header.
     *
     * @param cookie A cookie object.
     *
     * @returns Set-Cookie string or null if it failed to serialize object.
     *
     * @throws `TypeError` if input data is invalid.
     */
    static serializeCookieToResponseHeader(cookie) {
        if (!cookie) {
            throw new TypeError('empty cookie data');
        }
        // 1. Validate fields
        if (!CookieUtils.FIELD_CONTENT_REGEX.test(cookie.name)) {
            throw new TypeError(`Cookie name is invalid: ${cookie.name}`);
        }
        if (cookie.value && !CookieUtils.FIELD_CONTENT_REGEX.test(cookie.value)) {
            throw new TypeError(`Cookie value is invalid: ${cookie.value}`);
        }
        if (cookie.domain && !CookieUtils.FIELD_CONTENT_REGEX.test(cookie.domain)) {
            throw new TypeError(`Cookie domain is invalid: ${cookie.domain}`);
        }
        if (cookie.path && !CookieUtils.FIELD_CONTENT_REGEX.test(cookie.path)) {
            throw new TypeError(`Cookie path is invalid: ${cookie.path}`);
        }
        if (cookie.expires && typeof cookie.expires.toUTCString !== 'function') {
            throw new TypeError(`Cookie expires is invalid: ${cookie.expires}`);
        }
        // 2. Build Set-Cookie header value
        let setCookieValue = `${cookie.name}=${cookie.value}`;
        if (typeof cookie.maxAge === 'number' && !Number.isNaN(cookie.maxAge)) {
            setCookieValue += `; Max-Age=${Math.floor(cookie.maxAge)}`;
        }
        if (cookie.domain) {
            setCookieValue += `; Domain=${cookie.domain}`;
        }
        if (cookie.path) {
            setCookieValue += `; Path=${cookie.path}`;
        }
        if (cookie.expires) {
            setCookieValue += `; Expires=${cookie.expires.toUTCString()}`;
        }
        if (cookie.httpOnly) {
            setCookieValue += '; HttpOnly';
        }
        if (cookie.secure) {
            setCookieValue += '; Secure';
        }
        if (cookie.sameSite) {
            const sameSite = cookie.sameSite.toLowerCase();
            switch (sameSite) {
                case 'lax':
                    setCookieValue += '; SameSite=Lax';
                    break;
                case 'strict':
                    setCookieValue += '; SameSite=Strict';
                    break;
                case 'none':
                    setCookieValue += '; SameSite=None';
                    break;
                default:
                    throw new TypeError(`Cookie sameSite is invalid: ${cookie.sameSite}`);
            }
        }
        // Not affected. Let it be here just in case
        // https://bugs.chromium.org/p/chromium/issues/detail?id=232693
        if (cookie.priority) {
            setCookieValue += `; Priority=${cookie.priority}`;
        }
        return setCookieValue;
    }
    /**
     * Serializes cookie data into a string suitable for Cookie header.
     *
     * @param cookies Array with {@link ParsedCookie}.
     *
     * @returns Cookie string or null if it failed to serialize object.
     */
    static serializeCookieToRequestHeader(cookies) {
        return cookies
            .map((cookie) => `${cookie.name}=${cookie.value}`)
            .join('; ');
    }
};

/**
 * See {@link https://developer.chrome.com/docs/web-platform/prerender-pages#how_is_a_page_prerendered}.
 */
var background_DocumentLifecycle;
(function (DocumentLifecycle) {
    DocumentLifecycle["Prerender"] = "prerender";
    DocumentLifecycle["Active"] = "active";
    DocumentLifecycle["Cached"] = "cached";
    DocumentLifecycle["PendingDeletion"] = "pending_deletion";
})(background_DocumentLifecycle || (background_DocumentLifecycle = {}));

/**
 * Finds a header object by its name (case-insensitive).
 *
 * @param headers Headers collection.
 * @param headerName Name of the header.
 *
 * @returns The header object if found, or null otherwise.
 */
function background_findHeaderByName(headers, headerName) {
    const targetName = headerName.toLowerCase();
    return headers.find((header) => header.name.toLowerCase() === targetName) || null;
}
/**
 * Checks if a header with the given name exists in the headers collection (case-insensitive).
 *
 * @param headers Headers collection.
 * @param headerName Name of the header to search.
 *
 * @returns True if the header exists, false otherwise.
 */
function background_hasHeaderByName(headers, headerName) {
    return background_findHeaderByName(headers, headerName) !== null;
}
/**
 * Checks if a specific header (name and value) exists in the headers collection.
 *
 * @param headers Headers collection.
 * @param header The header object to match.
 *
 * @returns True if an exact match for the header exists, false otherwise.
 */
function background_hasHeader(headers, header) {
    const foundHeader = background_findHeaderByName(headers, header.name);
    return !!foundHeader && foundHeader.value === header.value;
}
/**
 * Removes a header by name from the headers collection (case-insensitive).
 *
 * @param headers Headers collection.
 * @param headerName Name of the header to remove.
 *
 * @returns True if any headers were removed, false otherwise.
 */
function background_removeHeader(headers, headerName) {
    const targetName = headerName.toLowerCase();
    return remove(headers, (header) => header.name.toLowerCase() === targetName).length > 0;
}

/**
 * Cookie rules manager class.
 */
class background_CookieRulesFinder {
    /**
     * Filters blocking rules.
     * Used in content scripts.
     *
     * @param url Request url.
     * @param rules List of rules.
     *
     * @returns Blocking rules.
     */
    static getBlockingRules(url, rules) {
        return rules.filter((rule) => !background_CookieRulesFinder.isModifyingRule(rule));
    }
    /**
     * Finds a rule that doesn't modify cookie:
     *  i.e.: this rule cancels cookie or if it's an allowlist rule.
     *
     * @param cookieName Cookie name.
     * @param rules List of network rules.
     * @param isThirdPartyCookie Flag that indicates if cookie is third-party.
     *
     * @returns Found rule or null.
     */
    static lookupNotModifyingRule(cookieName, rules, isThirdPartyCookie) {
        const blockingRules = [];
        const allowlistRules = [];
        for (let i = 0; i < rules.length; i += 1) {
            const rule = rules[i];
            if (!background_CookieRulesFinder.matchThirdParty(rule, isThirdPartyCookie)) {
                continue;
            }
            const cookieModifier = rule.getAdvancedModifier();
            if (cookieModifier.matches(cookieName) && !background_CookieRulesFinder.isModifyingRule(rule)) {
                if (rule.isAllowlist()) {
                    allowlistRules.push(rule);
                }
                else {
                    blockingRules.push(rule);
                }
            }
        }
        if (allowlistRules.length > 0) {
            return allowlistRules[0];
        }
        if (blockingRules.length > 0) {
            return blockingRules[0];
        }
        return null;
    }
    /**
     * Finds rules that modify cookie.
     *
     * @param cookieName Cookie name.
     * @param rules Matching rules.
     * @param isThirdPartyCookie Flag that indicates if cookie is third-party.
     *
     * @returns Modifying rules.
     */
    static lookupModifyingRules(cookieName, rules, isThirdPartyCookie) {
        const result = [];
        const allowlistRules = [];
        if (rules && rules.length > 0) {
            for (let i = 0; i < rules.length; i += 1) {
                const rule = rules[i];
                if (!background_CookieRulesFinder.matchThirdParty(rule, isThirdPartyCookie)) {
                    continue;
                }
                const cookieModifier = rule.getAdvancedModifier();
                if (!cookieModifier.matches(cookieName)) {
                    continue;
                }
                if (!rule.isAllowlist() && !background_CookieRulesFinder.isModifyingRule(rule)) {
                    return [];
                }
                if (rule.isAllowlist()) {
                    allowlistRules.push(rule);
                }
                else {
                    result.push(rule);
                }
            }
        }
        if (allowlistRules.length > 0) {
            return allowlistRules;
        }
        return result;
    }
    /**
     * Checks if rule and third party flag matches.
     *
     * @param rule Rule.
     * @param isThirdParty Flag that indicates if cookie is third-party.
     *
     * @returns True if rule and third party flag matches.
     */
    static matchThirdParty(rule, isThirdParty) {
        if (!rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.ThirdParty)) {
            return true;
        }
        return isThirdParty === rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.ThirdParty);
    }
    /**
     * Checks if $cookie rule is modifying.
     *
     * @param rule $cookie rule.
     *
     * @returns True if rule is modifying.
     */
    static isModifyingRule(rule) {
        const cookieModifier = rule.getAdvancedModifier();
        return cookieModifier.getSameSite() !== null
            || (cookieModifier.getMaxAge() !== null && cookieModifier.getMaxAge() > 0);
    }
}

/* eslint-disable class-methods-use-this */
/**
 * Cookie api implementation.
 */
class background_BrowserCookieApi {
    /**
     * Removes cookie.
     *
     * @param name Cookie name.
     * @param url Request url.
     *
     * @returns True if cookie was removed.
     */
    async removeCookie(name, url) {
        try {
            await background_browser_polyfill.cookies.remove({ name, url });
            return true;
        }
        catch (e) {
            background_common_logger_logger.error('[tswebextension.removeCookie]: error on removing cookie via browser.cookies.remove: ', e);
        }
        return false;
    }
    /**
     * Updates cookie.
     *
     * @param cookie Cookie for update.
     *
     * @returns Promise resolved with true if cookie was updated, false otherwise.
     */
    async modifyCookie(cookie) {
        try {
            const update = background_BrowserCookieApi.convertToSetDetailsType(cookie);
            await background_browser_polyfill.cookies.set(update);
            return true;
        }
        catch (e) {
            // If `domain` contains the `path` part, the cookie cannot be saved,
            // since `domain` can only contain hostname.
            if (cookie.domain?.includes('/')
                // if url is not matched with domain, cookie cannot be set
                // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2683
                || (cookie.domain && !background_BrowserCookieApi.doesDomainMatchUrl(cookie.domain, cookie.url))) {
                background_common_logger_logger.info('[tswebextension.modifyCookie]: error on modifying cookie via browser.cookies.set: ', e);
            }
            else {
                background_common_logger_logger.error('[tswebextension.modifyCookie]: error on modifying cookie via browser.cookies.set: ', e);
            }
        }
        return false;
    }
    /**
     * Search for cookies that match a given pattern.
     *
     * @param pattern Pattern of cookies to find.
     *
     * @returns List of found cookies.
     */
    async findCookies(pattern) {
        try {
            const found = await background_browser_polyfill.cookies.getAll(pattern);
            return found;
        }
        catch (e) {
            background_common_logger_logger.error('[tswebextension.findCookies]: error on finding cookies via browser.cookies.getAll: ', e);
        }
        return [];
    }
    /**
     * Checks whether the cookie domain matches the url.
     *
     * @param rawCookieDomain Cookie domain.
     * @param url Request url.
     *
     * @returns True if domain matches the url, false otherwise.
     */
    static doesDomainMatchUrl(rawCookieDomain, url) {
        let cookieDomain = rawCookieDomain;
        // cookie domain can be '.example.com'
        if (cookieDomain.startsWith('.')) {
            cookieDomain = cookieDomain.slice(1);
        }
        const urlDomain = (0,background_es6/* getDomain */.FB)(url);
        return !!urlDomain && cookieDomain.includes(urlDomain);
    }
    /**
     * Converts cookie to SetDetailsType.
     *
     * @param cookie Cookie for convert.
     *
     * @returns SetDetailsType.
     */
    static convertToSetDetailsType(cookie) {
        return {
            /**
             * The request-URI to associate with the setting of the cookie.
             * This value can affect the default domain and path values of the created cookie.
             * If host permissions for this URL are not specified in the manifest file, the API call will fail.
             */
            url: cookie.url,
            /**
             * The name of the cookie. Empty by default if omitted.
             */
            name: cookie.name,
            /**
             * The value of the cookie. Empty by default if omitted.
             */
            value: cookie.value,
            /**
             * The domain of the cookie. If omitted, the cookie becomes a host-only cookie.
             */
            domain: cookie.domain,
            /**
             * Whether the cookie should be marked as Secure. Defaults to false.
             */
            secure: cookie.secure,
            /**
             * Whether the cookie should be marked as HttpOnly. Defaults to false.
             */
            httpOnly: cookie.httpOnly,
            /**
             * The cookie's same-site status.
             */
            sameSite: background_BrowserCookieApi.getSameSiteStatus(cookie.sameSite),
            /**
             * The expiration date of the cookie as the number of seconds since the UNIX epoch.
             * If omitted, the cookie becomes a session cookie.
             */
            expirationDate: cookie.expires
                ? Math.floor(cookie.expires.getTime() / 1000)
                : undefined,
            /**
             * The path of the cookie. Defaults to the path portion of the url parameter.
             */
            path: cookie.path,
        };
    }
    /**
     * Returns same-site type.
     *
     * @param sameSite Same-site string.
     *
     * @returns Same-site status or undefined if same-site is not specified.
     */
    static getSameSiteStatus(sameSite) {
        if (sameSite) {
            if (sameSite.toLowerCase() === 'lax') {
                return 'lax';
            }
            if (sameSite.toLowerCase() === 'strict') {
                return 'strict';
            }
        }
        return undefined;
    }
}

/**
 * Checks if error has message.
 *
 * @param error Error object.
 *
 * @returns If param is error.
 */
function background_configuration_isErrorWithMessage(error) {
    return (typeof error === 'object'
        && error !== null
        && 'message' in error
        && typeof error.message === 'string');
}
/**
 * Converts error to the error with message.
 *
 * @param maybeError Possible error.
 *
 * @returns Error with message.
 */
function background_configuration_toErrorWithMessage(maybeError) {
    if (background_configuration_isErrorWithMessage(maybeError)) {
        return maybeError;
    }
    try {
        return new Error(JSON.stringify(maybeError));
    }
    catch {
        // fallback in case there's an error stringifying the maybeError
        // like with circular references for example.
        return new Error(String(maybeError));
    }
}
/**
 * Converts error object to error with message. This method might be helpful to handle thrown errors.
 *
 * @param error Error object.
 *
 * @returns Message of the error.
 */
function background_configuration_getErrorMessage(error) {
    return background_configuration_toErrorWithMessage(error).message;
}

/**
 * Stealth action bitwise masks used on the background page and on the filtering log page.
 */
var background_StealthActions;
(function (StealthActions) {
    StealthActions[StealthActions["None"] = 0] = "None";
    StealthActions[StealthActions["HideReferrer"] = 1] = "HideReferrer";
    StealthActions[StealthActions["HideSearchQueries"] = 2] = "HideSearchQueries";
    StealthActions[StealthActions["BlockChromeClientData"] = 4] = "BlockChromeClientData";
    StealthActions[StealthActions["SendDoNotTrack"] = 8] = "SendDoNotTrack";
    // TODO check where this enums are used, and add comments
    StealthActions[StealthActions["FirstPartyCookies"] = 16] = "FirstPartyCookies";
    StealthActions[StealthActions["ThirdPartyCookies"] = 32] = "ThirdPartyCookies";
})(background_StealthActions || (background_StealthActions = {}));

var background_version = "3.1.0-alpha.3";
var background_packageJson = {
	version: background_version};

/**
 * Re-export needed to print the library version on the extension About page.
 * NOTE: We are directly re-exporting `version` from `package.json` to prevent
 * environment runtime errors, like call `window.console`, which is not available
 * in the service worker in MV3. And also to avoid bundle size getting larger.
 */
const background_TSWEBEXTENSION_VERSION = background_packageJson.version;
/**
 * Stealth mode configuration schema.
 */
const background_configuration_stealthConfigValidator = background_zod_lib.z.object({
    /**
     * Should the application set a fixed lifetime from
     * {@link StealthConfig.selfDestructFirstPartyCookiesTime} for first-party
     * cookies.
     */
    selfDestructFirstPartyCookies: background_zod_lib.z.boolean(),
    /**
     * Time in minutes to delete first-party cookies.
     */
    selfDestructFirstPartyCookiesTime: background_zod_lib.z.number(),
    /**
     * Should the application set a fixed lifetime from
     * {@link StealthConfig.selfDestructThirdPartyCookiesTime} for third-party
     * cookies.
     */
    selfDestructThirdPartyCookies: background_zod_lib.z.boolean(),
    /**
     * Time in minutes to delete third-party cookies.
     */
    selfDestructThirdPartyCookiesTime: background_zod_lib.z.number(),
    /**
     * Should the application hide the origin referrer in third-party requests
     * by replacing the referrer url with the request url.
     */
    hideReferrer: background_zod_lib.z.boolean(),
    /**
     * Should the application hide the original referrer from the search page
     * containing the search query in third-party queries, replacing
     * the referrer url with the request url.
     */
    hideSearchQueries: background_zod_lib.z.boolean(),
    /**
     * For Google Chrome, it removes the 'X-Client-Data' header from
     * the requests, which contains information about the browser version
     * and modifications.
     */
    blockChromeClientData: background_zod_lib.z.boolean(),
    /**
     * Includes HTTP headers 'DNT' and 'Sec-GPC' in all requests.
     *
     * @see https://en.wikipedia.org/wiki/Do_Not_Track
     * @see https://globalprivacycontrol.org
     */
    sendDoNotTrack: background_zod_lib.z.boolean(),
    /**
     * Blocks the possibility of leaking your IP address through WebRTC, even if
     * you use a proxy server or VPN.
     */
    blockWebRTC: background_zod_lib.z.boolean(),
}).strict();
/**
 * Filter list configuration validator for MV2.
 */
const background_basicFilterValidator = background_zod_lib.z.object({
    /**
     * Filter list text content.
     */
    content: background_es/* filterListChunksValidator */.B8,
    /**
     * Source map.
     */
    sourceMap: background_es/* filterListSourceMapValidator */.kA.optional(),
});
/**
 * Settings configuration schema.
 */
const background_settingsConfigValidator = background_zod_lib.z.object({
    /**
     * If this flag is true, the application will work ONLY with domains
     * from the {@link Configuration.allowlist},
     * otherwise it will work everywhere EXCLUDING domains from the list.
     */
    allowlistInverted: background_zod_lib.z.boolean(),
    /**
     * Flag specifying {@link Configuration.allowlist} enable state.
     * We don't use allowlist array length condition for calculate enable state,
     * because it's not cover case with empty list in inverted mode.
     */
    allowlistEnabled: background_zod_lib.z.boolean(),
    /**
     * Enables css hits counter if true.
     */
    collectStats: background_zod_lib.z.boolean(),
    /**
     * Enables verbose scriptlets logging if true.
     */
    debugScriptlets: background_zod_lib.z.boolean().default(false),
    /**
     * Enables stealth mode if true.
     */
    stealthModeEnabled: background_zod_lib.z.boolean(),
    /**
     * Enables filtering if true.
     */
    filteringEnabled: background_zod_lib.z.boolean(),
    /**
     * Redirect url for $document rules.
     */
    documentBlockingPageUrl: background_zod_lib.z.string().optional(),
    /**
     * Path to the assembled @adguard/assistant module. Necessary for lazy
     * on-demand loading of the assistant.
     */
    assistantUrl: background_zod_lib.z.string(),
    /**
     * Stealth mode options.
     */
    stealth: background_configuration_stealthConfigValidator,
});
/**
 * Generic app configuration schema.
 */
const background_configurationValidator = background_zod_lib.z.object({
    /**
     * List of hostnames or domains of sites, which should be excluded
     * from blocking or which should be included in blocking
     * depending on the value of {@link SettingsConfig.allowlistInverted} setting value.
     */
    allowlist: background_zod_lib.z.string().array(),
    /**
     * List of rules added by user.
     */
    userrules: background_basicFilterValidator,
    /**
     * Flag responsible for logging.
     *
     * @deprecated  Will be removed in the next minor version.
     * Use {@link Configuration.logLevel} instead.
     */
    verbose: background_zod_lib.z.boolean().optional(),
    /**
     * Logging level.
     */
    logLevel: background_zod_lib.z.enum([
        background_LogLevel.Error,
        background_LogLevel.Warn,
        background_LogLevel.Info,
        background_LogLevel.Debug,
        background_LogLevel.Trace,
    ]).optional(),
    settings: background_settingsConfigValidator,
}).strict();



;// ./node_modules/.pnpm/@adguard+extended-css@2.1.1/node_modules/@adguard/extended-css/dist/version.esm.mjs
/**
 * @adguard/extended-css - v2.1.1 - Thu Dec 19 2024
 * https://github.com/AdguardTeam/ExtendedCss#homepage
 * Copyright (c) 2024 AdGuard. Licensed GPL-3.0
 */
var background_version_esm_version = "2.1.1";

/**
 * @file Extended CSS version.
 */
// Don't export version from package.json directly, because if you run
// `tsc` in the root directory, it will generate `dist/types/src/version.d.ts`
// with wrong relative path to `package.json`. So we need this little "hack"

const background_EXTENDED_CSS_VERSION = background_version_esm_version;



;// ./Extension/src/background/prefs.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_prefs_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}




/**
 * Extension global preferences.
 */ class background_Prefs {
}
background_prefs_define_property(background_Prefs, "id", (background_browser_polyfill_default()).runtime.id);
background_prefs_define_property(background_Prefs, "baseUrl", background_browser_polyfill_default().runtime.getURL(''));
background_prefs_define_property(background_Prefs, "version", background_browser_polyfill_default().runtime.getManifest().version);
background_prefs_define_property(background_Prefs, "language", background_browser_polyfill_default().i18n.getUILanguage());
background_prefs_define_property(background_Prefs, "libVersions", {
    tswebextension: background_TSWEBEXTENSION_VERSION,
    tsurlfilter: background_es/* TSURLFILTER_VERSION */.e_,
    scriptlets: background_scriptlets_dist/* SCRIPTLETS_VERSION */.t,
    extendedCss: background_EXTENDED_CSS_VERSION
});

;// ./Extension/src/common/api/extension/tabs.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 




/**
 * Helper class for browser.tabs API.
 */ class background_TabsApi {
    /**
     * Returns first matched tab for passed {@link Tabs.QueryQueryInfoType}.
     *
     * @param queryInfo Browser.tabs.query argument.
     *
     * @returns First matched tab or undefined.
     */ static async findOne(queryInfo) {
        const [tab] = await background_browser_polyfill_default().tabs.query(queryInfo);
        return tab;
    }
    /**
     * Activates an existing tab regardless of the browser window.
     *
     * @param tab {@link Tabs.Tab} Data.
     */ static async focus(tab) {
        const { id, windowId } = tab;
        await background_browser_polyfill_default().tabs.update(id, {
            active: true
        });
        if (windowId) {
            await background_browser_polyfill_default().windows.update(windowId, {
                focused: true
            });
        }
    }
    /**
     * Returns all opened tabs info.
     *
     * @returns Array of opened tabs.
     */ static async getAll() {
        return background_browser_polyfill_default().tabs.query({});
    }
    /**
     * Returns active tab in current window.
     *
     * @returns Active tab info or undefined.
     */ static async getActive() {
        return background_TabsApi.findOne({
            currentWindow: true,
            active: true
        });
    }
    /**
     * Check, if page in tab is extension page.
     *
     * @param tab {@link Tabs.Tab} Data.
     *
     * @returns True if it is extension page, else returns false.
     */ static isAdguardExtensionTab(tab) {
        const { url } = tab;
        if (!url) {
            return false;
        }
        try {
            const parsed = new URL(url);
            const { protocol, hostname } = parsed;
            const scheme = background_Prefs.baseUrl.split('://')[0];
            if (!scheme) {
                return false;
            }
            return protocol.indexOf(scheme) > -1 && hostname === background_Prefs.id;
        } catch (e) {
            return false;
        }
    }
    /**
     * Reloads a tab without cache by specified id.
     *
     * Clearing the cache on reload is necessary for correct application of the rules on pages with service workers.
     *
     * @param id Tab id.
     */ static async reload(id) {
        await background_browser_polyfill_default().tabs.reload(id, {
            bypassCache: true
        });
    }
}

;// ./Extension/src/common/api/extension/iconsCache.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

const background_cache = new Map();
/**
 * Downloads image and converts it to {@link ImageData}.
 * Since it uses new Image() it cannot be used in the mv3 extension.
 * {@link loadImageDataMv3} used in the mv3 extensions
 *
 * @param size Icon size in px.
 * @param url Icon url.
 *
 * @returns Image pixel data.
 */ function background_loadImageData(size, url) {
    return new Promise((resolve, reject)=>{
        const img = new Image();
        img.src = url;
        img.onload = ()=>{
            const canvas = document.createElement('canvas');
            document.documentElement.appendChild(canvas);
            canvas.width = size;
            canvas.height = size;
            const ctx = canvas.getContext('2d');
            if (!ctx) {
                reject(new Error('Cannot load image data'));
                return;
            }
            ctx.drawImage(img, 0, 0);
            const data = ctx.getImageData(0, 0, size, size);
            canvas.remove();
            resolve(data);
        };
        img.onerror = reject;
    });
}
/**
 * Downloads image and converts it to {@link ImageData}.
 * This function is used in MV3 with OffscreenCanvas.
 *
 * @param size Icon size in px.
 * @param url Icon url.
 *
 * @returns Image pixel data.
 *
 * @throws Error if image cannot be loaded.
 */ const background_loadImageDataMv3 = async (size, url)=>{
    try {
        const response = await fetch(url, {
            mode: 'cors'
        });
        if (!response.ok) {
            throw new Error(`Network response was not ok for url: ${url}`);
        }
        const blob = await response.blob();
        const bitmap = await createImageBitmap(blob);
        const offscreenCanvas = new OffscreenCanvas(size, size);
        const ctx = offscreenCanvas.getContext('2d');
        if (!ctx) {
            throw new Error('Cannot load image data');
        }
        ctx.drawImage(bitmap, 0, 0, size, size);
        const imageData = ctx.getImageData(0, 0, size, size);
        return imageData;
    } catch (error) {
        background_logger_logger.error('Failed to load image:', error);
        throw error;
    }
};
/**
 * Returns ImageData.
 *
 * @param size Icon size in px.
 * @param url Icon url.
 *
 * @returns Entry with image size and {@link ImageData}.
 */ async function background_getImageData(size, url) {
    // TODO create abstraction for separating modules for loadImageDataMv3 and loadImageData
    const loadImageDataFn =  true ? background_loadImageDataMv3 : 0;
    const imageData = background_cache.get(url);
    if (!imageData) {
        const data = await loadImageDataFn(Number(size), url);
        background_cache.set(url, data);
        return [
            size,
            data
        ];
    }
    return [
        size,
        imageData
    ];
}
/**
 * Matches urls from browserAction.setIcon 'path' property with cached ImageData values
 * and returns 'imageData' object for this action.
 *
 * @see https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/browserAction/setIcon
 *
 * @param path Browser.browserAction.setIcon 'path' property.
 *
 * @returns Browser.browserAction.setIcon 'imageData' property.
 */ async function background_getIconImageData(path) {
    const imageDataEntriesPromises = Object.entries(path).map(([size, url])=>background_getImageData(size, url));
    const imageDataEntries = await Promise.all(imageDataEntriesPromises);
    return Object.fromEntries(imageDataEntries);
}

;// ./Extension/src/common/api/extension/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 



;// ./Extension/src/background/utils/version.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ /**
 * Helper class for work with semver.
 *
 * Parsed semver string saves in {@link data} property.
 * We save first {@link Version.MAX_LENGTH} parts of parsed string.
 * If there are less than {@link Version.MAX_LENGTH} parts in the version, the missing ones are filled with zeros
 * For example, entry string `1.1` will be parsed as `[1, 1, 0, 0]`.
 *
 * @class
 *
 * @param version Semver string.
 *
 * @throws Error, if passed string cannot be parsed.
 */ function background_version_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}

class background_Version {
    /**
     * Compare current semver with passed.
     *
     * @param version Instance of {@link Version}.
     *
     * @returns Number, indicates the result of the comparison (1 greater, -1 less, 0 equals).
     *
     * @throws Error, if some version data is invalid.
     */ compare(version) {
        for(let i = 0; i < background_Version.MAX_LENGTH; i += 1){
            var _this_data, _this, _version_data;
            const leftPart = (_this = this) === null || _this === void 0 ? void 0 : (_this_data = _this.data) === null || _this_data === void 0 ? void 0 : _this_data[i];
            const rightPart = version === null || version === void 0 ? void 0 : (_version_data = version.data) === null || _version_data === void 0 ? void 0 : _version_data[i];
            if (typeof leftPart !== 'number' || typeof rightPart !== 'number') {
                throw new Error('Can not compare versions');
            }
            if (leftPart > rightPart) {
                return 1;
            }
            if (leftPart < rightPart) {
                return -1;
            }
        }
        return 0;
    }
    /**
     * Creates new object of {@link Version}.
     *
     * @param version Version in {@link https://semver.org/lang/ru/ Semantic Version}.
     */ constructor(version){
        // splitted semver
        background_version_define_property(this, "data", []);
        const parts = String(version || '').split('.', background_Version.MAX_LENGTH);
        for(let i = 0; i < background_Version.MAX_LENGTH; i += 1){
            if (parts[i] === '') {
                throw new Error(`Found empty part in string '${version}'`);
            }
            const part = parts[i] || '0';
            if (part.length > 1 && part.startsWith('0')) {
                throw new Error(`Can not parse ${version}. Leading zeros are not allowed in the version parts`);
            }
            if (Number.isNaN(Number.parseInt(part, 10))) {
                throw new Error(`Can not parse '${version}' string`);
            }
            this.data[i] = Math.max(Number(part), 0);
        }
    }
}
background_version_define_property(background_Version, "MAX_LENGTH", 4);

;// ./Extension/src/background/utils/browser-utils.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 





/**
 * Helper class for working with browser extension context.
 */ class background_BrowserUtils {
    /**
     * Returns extension specified query params.
     * This method called on app metadata, i18n metadata and thankyou page url calculation.
     *
     * @see NetworkSettings#filtersMetadataUrl
     * @see NetworkSettings#filtersI18nMetadataUrl
     * @see PagesApi.openThankYouPage
     *
     * @returns Extension specified query params array.
     *
     * @throws Error if client id is undefined.
     */ static getExtensionParams() {
        const persistedClientId = background_appContext.get(background_AppContextKey.ClientId);
        if (typeof persistedClientId !== 'string') {
            throw new Error('client id is not found');
        }
        const clientId = encodeURIComponent(persistedClientId);
        const locale = encodeURIComponent(background_Prefs.language);
        const version = encodeURIComponent(background_Prefs.version);
        const id = encodeURIComponent(background_Prefs.id);
        const params = [];
        params.push(`v=${version}`);
        params.push(`cid=${clientId}`);
        params.push(`lang=${locale}`);
        params.push(`id=${id}`);
        return params;
    }
    /**
     * Retrieves locales from navigator.
     *
     * @param limit Limit of returned locales.
     *
     * @returns Array of locales.
     */ static getNavigatorLanguages(limit) {
        let languages = [];
        // https://developer.mozilla.org/ru/docs/Web/API/NavigatorLanguage/languages
        if (Array.isArray(navigator.languages)) {
            // get all languages if 'limit' is not specified
            const langLimit = limit || navigator.languages.length;
            languages = navigator.languages.slice(0, langLimit);
        } else if (navigator.language) {
            languages.push(navigator.language); // .language is first in .languages
        }
        return languages;
    }
    /**
     * Checks if version can be parsed. Our format is different from
     * usual semver format, because it can handle 4 parts (1.1.1.1 usually filters use such
     * format) in version. To find out more details see {@link Version}.
     *
     * @param version Version string.
     *
     * @returns True, if string matches our versioning scheme, otherwise returns false.
     */ static isSemver(version) {
        try {
            // eslint-disable-next-line no-new
            new background_Version(version);
        } catch (e) {
            background_logger_logger.debug(`Can not parse version: "${version}", error: `, e);
            return false;
        }
        return true;
    }
    /**
     * Checks if left version is greater than the right version.
     *
     * @param leftVersion Semver string.
     * @param rightVersion Semver string.
     *
     * @returns True, if left version is greater than the right version, else returns false.
     */ static isGreaterVersion(leftVersion, rightVersion) {
        const left = new background_Version(leftVersion);
        const right = new background_Version(rightVersion);
        return left.compare(right) > 0;
    }
    /**
     * Checks if left version is greater than the right version or equals.
     *
     * @param leftVersion Semver string.
     * @param rightVersion Semver string.
     *
     * @returns True, if left version is greater than the right version or equals, else returns false.
     */ static isGreaterOrEqualsVersion(leftVersion, rightVersion) {
        const left = new background_Version(leftVersion);
        const right = new background_Version(rightVersion);
        return left.compare(right) >= 0;
    }
    /**
     * Returns major number of version.
     *
     * @param version Semver string.
     *
     * @returns Major part of semver.
     */ static getMajorVersionNumber(version) {
        const v = new background_Version(version);
        return String(v.data[0]);
    }
    /**
     * Returns minor number of version.
     *
     * @param version Semver string.
     *
     * @returns Minor part of semver.
     */ static getMinorVersionNumber(version) {
        const v = new background_Version(version);
        return String(v.data[1]);
    }
}

;// ./node_modules/.pnpm/punycode@2.3.0/node_modules/punycode/punycode.es6.js


/** Highest positive signed 32-bit float value */
const background_maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1

/** Bootstring parameters */
const background_base = 36;
const background_tMin = 1;
const background_tMax = 26;
const background_skew = 38;
const background_damp = 700;
const background_initialBias = 72;
const background_initialN = 128; // 0x80
const background_delimiter = '-'; // '\x2D'

/** Regular expressions */
const background_regexPunycode = /^xn--/;
const background_regexNonASCII = /[^\0-\x7F]/; // Note: U+007F DEL is excluded too.
const background_regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators

/** Error messages */
const background_errors = {
	'overflow': 'Overflow: input needs wider integers to process',
	'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
	'invalid-input': 'Invalid input'
};

/** Convenience shortcuts */
const background_baseMinusTMin = background_base - background_tMin;
const background_floor = Math.floor;
const background_stringFromCharCode = String.fromCharCode;

/*--------------------------------------------------------------------------*/

/**
 * A generic error utility function.
 * @private
 * @param {String} type The error type.
 * @returns {Error} Throws a `RangeError` with the applicable error message.
 */
function background_error(type) {
	throw new RangeError(background_errors[type]);
}

/**
 * A generic `Array#map` utility function.
 * @private
 * @param {Array} array The array to iterate over.
 * @param {Function} callback The function that gets called for every array
 * item.
 * @returns {Array} A new array of values returned by the callback function.
 */
function background_map(array, callback) {
	const result = [];
	let length = array.length;
	while (length--) {
		result[length] = callback(array[length]);
	}
	return result;
}

/**
 * A simple `Array#map`-like wrapper to work with domain name strings or email
 * addresses.
 * @private
 * @param {String} domain The domain name or email address.
 * @param {Function} callback The function that gets called for every
 * character.
 * @returns {String} A new string of characters returned by the callback
 * function.
 */
function background_mapDomain(domain, callback) {
	const parts = domain.split('@');
	let result = '';
	if (parts.length > 1) {
		// In email addresses, only the domain name should be punycoded. Leave
		// the local part (i.e. everything up to `@`) intact.
		result = parts[0] + '@';
		domain = parts[1];
	}
	// Avoid `split(regex)` for IE8 compatibility. See #17.
	domain = domain.replace(background_regexSeparators, '\x2E');
	const labels = domain.split('.');
	const encoded = background_map(labels, callback).join('.');
	return result + encoded;
}

/**
 * Creates an array containing the numeric code points of each Unicode
 * character in the string. While JavaScript uses UCS-2 internally,
 * this function will convert a pair of surrogate halves (each of which
 * UCS-2 exposes as separate characters) into a single code point,
 * matching UTF-16.
 * @see `punycode.ucs2.encode`
 * @see <https://mathiasbynens.be/notes/javascript-encoding>
 * @memberOf punycode.ucs2
 * @name decode
 * @param {String} string The Unicode input string (UCS-2).
 * @returns {Array} The new array of code points.
 */
function background_ucs2decode(string) {
	const output = [];
	let counter = 0;
	const length = string.length;
	while (counter < length) {
		const value = string.charCodeAt(counter++);
		if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
			// It's a high surrogate, and there is a next character.
			const extra = string.charCodeAt(counter++);
			if ((extra & 0xFC00) == 0xDC00) { // Low surrogate.
				output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
			} else {
				// It's an unmatched surrogate; only append this code unit, in case the
				// next code unit is the high surrogate of a surrogate pair.
				output.push(value);
				counter--;
			}
		} else {
			output.push(value);
		}
	}
	return output;
}

/**
 * Creates a string based on an array of numeric code points.
 * @see `punycode.ucs2.decode`
 * @memberOf punycode.ucs2
 * @name encode
 * @param {Array} codePoints The array of numeric code points.
 * @returns {String} The new Unicode string (UCS-2).
 */
const background_ucs2encode = codePoints => String.fromCodePoint(...codePoints);

/**
 * Converts a basic code point into a digit/integer.
 * @see `digitToBasic()`
 * @private
 * @param {Number} codePoint The basic numeric code point value.
 * @returns {Number} The numeric value of a basic code point (for use in
 * representing integers) in the range `0` to `base - 1`, or `base` if
 * the code point does not represent a value.
 */
const background_basicToDigit = function(codePoint) {
	if (codePoint >= 0x30 && codePoint < 0x3A) {
		return 26 + (codePoint - 0x30);
	}
	if (codePoint >= 0x41 && codePoint < 0x5B) {
		return codePoint - 0x41;
	}
	if (codePoint >= 0x61 && codePoint < 0x7B) {
		return codePoint - 0x61;
	}
	return background_base;
};

/**
 * Converts a digit/integer into a basic code point.
 * @see `basicToDigit()`
 * @private
 * @param {Number} digit The numeric value of a basic code point.
 * @returns {Number} The basic code point whose value (when used for
 * representing integers) is `digit`, which needs to be in the range
 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
 * used; else, the lowercase form is used. The behavior is undefined
 * if `flag` is non-zero and `digit` has no uppercase form.
 */
const background_digitToBasic = function(digit, flag) {
	//  0..25 map to ASCII a..z or A..Z
	// 26..35 map to ASCII 0..9
	return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
};

/**
 * Bias adaptation function as per section 3.4 of RFC 3492.
 * https://tools.ietf.org/html/rfc3492#section-3.4
 * @private
 */
const background_adapt = function(delta, numPoints, firstTime) {
	let k = 0;
	delta = firstTime ? background_floor(delta / background_damp) : delta >> 1;
	delta += background_floor(delta / numPoints);
	for (/* no initialization */; delta > background_baseMinusTMin * background_tMax >> 1; k += background_base) {
		delta = background_floor(delta / background_baseMinusTMin);
	}
	return background_floor(k + (background_baseMinusTMin + 1) * delta / (delta + background_skew));
};

/**
 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
 * symbols.
 * @memberOf punycode
 * @param {String} input The Punycode string of ASCII-only symbols.
 * @returns {String} The resulting string of Unicode symbols.
 */
const background_decode = function(input) {
	// Don't use UCS-2.
	const output = [];
	const inputLength = input.length;
	let i = 0;
	let n = background_initialN;
	let bias = background_initialBias;

	// Handle the basic code points: let `basic` be the number of input code
	// points before the last delimiter, or `0` if there is none, then copy
	// the first basic code points to the output.

	let basic = input.lastIndexOf(background_delimiter);
	if (basic < 0) {
		basic = 0;
	}

	for (let j = 0; j < basic; ++j) {
		// if it's not a basic code point
		if (input.charCodeAt(j) >= 0x80) {
			background_error('not-basic');
		}
		output.push(input.charCodeAt(j));
	}

	// Main decoding loop: start just after the last delimiter if any basic code
	// points were copied; start at the beginning otherwise.

	for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {

		// `index` is the index of the next character to be consumed.
		// Decode a generalized variable-length integer into `delta`,
		// which gets added to `i`. The overflow checking is easier
		// if we increase `i` as we go, then subtract off its starting
		// value at the end to obtain `delta`.
		const oldi = i;
		for (let w = 1, k = background_base; /* no condition */; k += background_base) {

			if (index >= inputLength) {
				background_error('invalid-input');
			}

			const digit = background_basicToDigit(input.charCodeAt(index++));

			if (digit >= background_base) {
				background_error('invalid-input');
			}
			if (digit > background_floor((background_maxInt - i) / w)) {
				background_error('overflow');
			}

			i += digit * w;
			const t = k <= bias ? background_tMin : (k >= bias + background_tMax ? background_tMax : k - bias);

			if (digit < t) {
				break;
			}

			const baseMinusT = background_base - t;
			if (w > background_floor(background_maxInt / baseMinusT)) {
				background_error('overflow');
			}

			w *= baseMinusT;

		}

		const out = output.length + 1;
		bias = background_adapt(i - oldi, out, oldi == 0);

		// `i` was supposed to wrap around from `out` to `0`,
		// incrementing `n` each time, so we'll fix that now:
		if (background_floor(i / out) > background_maxInt - n) {
			background_error('overflow');
		}

		n += background_floor(i / out);
		i %= out;

		// Insert `n` at position `i` of the output.
		output.splice(i++, 0, n);

	}

	return String.fromCodePoint(...output);
};

/**
 * Converts a string of Unicode symbols (e.g. a domain name label) to a
 * Punycode string of ASCII-only symbols.
 * @memberOf punycode
 * @param {String} input The string of Unicode symbols.
 * @returns {String} The resulting Punycode string of ASCII-only symbols.
 */
const background_encode = function(input) {
	const output = [];

	// Convert the input in UCS-2 to an array of Unicode code points.
	input = background_ucs2decode(input);

	// Cache the length.
	const inputLength = input.length;

	// Initialize the state.
	let n = background_initialN;
	let delta = 0;
	let bias = background_initialBias;

	// Handle the basic code points.
	for (const currentValue of input) {
		if (currentValue < 0x80) {
			output.push(background_stringFromCharCode(currentValue));
		}
	}

	const basicLength = output.length;
	let handledCPCount = basicLength;

	// `handledCPCount` is the number of code points that have been handled;
	// `basicLength` is the number of basic code points.

	// Finish the basic string with a delimiter unless it's empty.
	if (basicLength) {
		output.push(background_delimiter);
	}

	// Main encoding loop:
	while (handledCPCount < inputLength) {

		// All non-basic code points < n have been handled already. Find the next
		// larger one:
		let m = background_maxInt;
		for (const currentValue of input) {
			if (currentValue >= n && currentValue < m) {
				m = currentValue;
			}
		}

		// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
		// but guard against overflow.
		const handledCPCountPlusOne = handledCPCount + 1;
		if (m - n > background_floor((background_maxInt - delta) / handledCPCountPlusOne)) {
			background_error('overflow');
		}

		delta += (m - n) * handledCPCountPlusOne;
		n = m;

		for (const currentValue of input) {
			if (currentValue < n && ++delta > background_maxInt) {
				background_error('overflow');
			}
			if (currentValue === n) {
				// Represent delta as a generalized variable-length integer.
				let q = delta;
				for (let k = background_base; /* no condition */; k += background_base) {
					const t = k <= bias ? background_tMin : (k >= bias + background_tMax ? background_tMax : k - bias);
					if (q < t) {
						break;
					}
					const qMinusT = q - t;
					const baseMinusT = background_base - t;
					output.push(
						background_stringFromCharCode(background_digitToBasic(t + qMinusT % baseMinusT, 0))
					);
					q = background_floor(qMinusT / baseMinusT);
				}

				output.push(background_stringFromCharCode(background_digitToBasic(q, 0)));
				bias = background_adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength);
				delta = 0;
				++handledCPCount;
			}
		}

		++delta;
		++n;

	}
	return output.join('');
};

/**
 * Converts a Punycode string representing a domain name or an email address
 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
 * it doesn't matter if you call it on a string that has already been
 * converted to Unicode.
 * @memberOf punycode
 * @param {String} input The Punycoded domain name or email address to
 * convert to Unicode.
 * @returns {String} The Unicode representation of the given Punycode
 * string.
 */
const background_toUnicode = function(input) {
	return background_mapDomain(input, function(string) {
		return background_regexPunycode.test(string)
			? background_decode(string.slice(4).toLowerCase())
			: string;
	});
};

/**
 * Converts a Unicode string representing a domain name or an email address to
 * Punycode. Only the non-ASCII parts of the domain name will be converted,
 * i.e. it doesn't matter if you call it with a domain that's already in
 * ASCII.
 * @memberOf punycode
 * @param {String} input The domain name or email address to convert, as a
 * Unicode string.
 * @returns {String} The Punycode representation of the given domain name or
 * email address.
 */
const background_toASCII = function(input) {
	return background_mapDomain(input, function(string) {
		return background_regexNonASCII.test(string)
			? 'xn--' + background_encode(string)
			: string;
	});
};

/*--------------------------------------------------------------------------*/

/** Define the public API */
const background_punycode_es6_punycode = {
	/**
	 * A string representing the current Punycode.js version number.
	 * @memberOf punycode
	 * @type String
	 */
	'version': '2.1.0',
	/**
	 * An object of methods to convert from JavaScript's internal character
	 * representation (UCS-2) to Unicode code points, and back.
	 * @see <https://mathiasbynens.be/notes/javascript-encoding>
	 * @memberOf punycode
	 * @type Object
	 */
	'ucs2': {
		'decode': background_ucs2decode,
		'encode': background_ucs2encode
	},
	'decode': background_decode,
	'encode': background_encode,
	'toASCII': background_toASCII,
	'toUnicode': background_toUnicode
};


/* harmony default export */ const background_punycode_es6 = (background_punycode_es6_punycode);

;// ./Extension/src/background/utils/url.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_url_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}

/**
 * Helper class to work with URLs.
 */ class background_UrlUtils {
    /**
     * Converts provided Unicode string to {@link https://tools.ietf.org/html/rfc3492 Punycode}.
     *
     * @param domain Domain name.
     *
     * @returns Domain name in {@link https://tools.ietf.org/html/rfc3492 Punycode}.
     */ static toPunyCode(domain) {
        // eslint-disable-next-line no-control-regex
        if (/^[\x00-\x7F]+$/.test(domain)) {
            return domain;
        }
        return background_punycode_es6.toASCII(domain);
    }
    /**
     * Tries to extract host name from provided url and returns it, if found.
     *
     * @param url Url address.
     *
     * @returns Host name in case of successful extraction and null otherwise.
     */ static getHost(url) {
        let firstIdx = url.indexOf('//');
        if (firstIdx === -1) {
            /**
         * It's non hierarchical structured URL (e.g. Stun: or turn:)
         * https://tools.ietf.org/html/rfc4395#section-2.2
         * https://tools.ietf.org/html/draft-nandakumar-rtcweb-stun-uri-08#appendix-B.
         */ firstIdx = url.indexOf(':');
            if (firstIdx === -1) {
                return null;
            }
            firstIdx -= 1;
        }
        const nextSlashIdx = url.indexOf('/', firstIdx + 2);
        const startParamsIdx = url.indexOf('?', firstIdx + 2);
        let lastIdx = nextSlashIdx;
        if (startParamsIdx > 0 && (startParamsIdx < nextSlashIdx || nextSlashIdx < 0)) {
            lastIdx = startParamsIdx;
        }
        let host = lastIdx === -1 ? url.substring(firstIdx + 2) : url.substring(firstIdx + 2, lastIdx);
        const portIndex = host.indexOf(':');
        host = portIndex === -1 ? host : host.substring(0, portIndex);
        const lastChar = host.charAt(host.length - 1);
        if (lastChar === '.') {
            host = host.slice(0, -1);
        }
        return host;
    }
    /**
     * Tries to extract domain name from provided url and return it, if found.
     *
     * @param url Url address.
     *
     * @returns Domain name in case of successful extraction and null otherwise.
     */ static getDomainName(url) {
        const host = background_UrlUtils.getHost(url);
        if (!host) {
            return null;
        }
        return background_UrlUtils.getCroppedDomainName(host);
    }
    /**
     * Cuts the domain zone 'www.' and returns a string without it.
     *
     * @param host Any string.
     *
     * @returns String without 'www.' domain zone.
     */ static getCroppedDomainName(host) {
        return host.indexOf('www.') === 0 ? host.substring(4) : host;
    }
    /**
     * Checks that provided string is a IPv4.
     *
     * @param address IP address.
     *
     * @returns True if provided string is a IPv4.
     */ static isIpv4(address) {
        if (background_UrlUtils.RE_V4.test(address)) {
            return true;
        }
        if (background_UrlUtils.RE_V4_HEX.test(address)) {
            return true;
        }
        if (background_UrlUtils.RE_V4_NUMERIC.test(address)) {
            return true;
        }
        return false;
    }
    /**
     * Checks that provided string is a IPv6.
     *
     * @param address IP address.
     *
     * @returns True if provided string is a IPv6.
     */ static isIpv6(address) {
        var _address_match;
        let a4addon = 0;
        const address4 = (_address_match = address.match(background_UrlUtils.RE_V4_IN_V6)) === null || _address_match === void 0 ? void 0 : _address_match[0];
        if (address4) {
            const temp4 = address4.split('.');
            for(let i = 0; i < 4; i += 1){
                const part = temp4[i];
                if (part && /^0[0-9]+/.test(part)) {
                    return false;
                }
            }
            address = address.replace(background_UrlUtils.RE_V4_IN_V6, '');
            if (/[0-9]$/.test(address)) {
                return false;
            }
            address += temp4.join(':');
            a4addon = 2;
        }
        if (background_UrlUtils.RE_BAD_CHARACTERS.test(address)) {
            return false;
        }
        if (background_UrlUtils.RE_BAD_ADDRESS.test(address)) {
            return false;
        }
        const count = (string, substring)=>{
            return (string.length - string.replace(new RegExp(substring, 'g'), '').length) / substring.length;
        };
        const halves = count(address, '::');
        if (halves === 1 && count(address, ':') <= 6 + 2 + a4addon) {
            return true;
        }
        if (halves === 0 && count(address, ':') === 7 + a4addon) {
            return true;
        }
        return false;
    }
    /**
     * Cleanups file path of a custom filter.
     *
     * @param path Path to filter.
     *
     * @returns Cleaned path.
     */ static trimFilterFilepath(path) {
        if (path.indexOf('http') === 0) {
            return path;
        }
        const lastSlashIndex = path.lastIndexOf('/');
        const lastBackslashIndex = path.lastIndexOf('\\');
        if (lastSlashIndex === -1 && lastBackslashIndex === -1) {
            return path;
        }
        const lastSeparatorIndex = Math.max(lastSlashIndex, lastBackslashIndex);
        return path.substring(lastSeparatorIndex);
    }
    /**
     * Extracts upper level domain from domain.
     *
     * @param domain Domain.
     *
     * @returns Upper level domain.
     *
     * @example
     * ```
     * getUpperLevelDomain('www.example.com') => 'example.com'
     * getUpperLevelDomain('test.pages.dev') => 'pages.dev'
     * getUpperLevelDomain('allowlist.test.pages.dev') => 'test.pages.dev'
     * ```
     */ static getUpperLevelDomain(domain) {
        const parts = domain.split('.');
        parts.shift();
        return parts.join('.');
    }
}
// eslint-disable-next-line max-len
background_url_define_property(background_UrlUtils, "RE_V4", /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|0x[0-9a-f][0-9a-f]?|0[0-7]{3})\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|0x[0-9a-f][0-9a-f]?|0[0-7]{3})$/i);
background_url_define_property(background_UrlUtils, "RE_V4_HEX", /^0x([0-9a-f]{8})$/i);
background_url_define_property(background_UrlUtils, "RE_V4_NUMERIC", /^[0-9]+$/);
background_url_define_property(background_UrlUtils, "RE_V4_IN_V6", /(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/);
background_url_define_property(background_UrlUtils, "RE_BAD_CHARACTERS", /([^0-9a-f:])/i);
background_url_define_property(background_UrlUtils, "RE_BAD_ADDRESS", /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]$)/i);

;// ./Extension/src/background/utils/run-info.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 



/**
 * Gets data from storage by specified key.
 *
 * @param key Storage key.
 * @param fallback If true, try to get data from legacy destination.
 *
 * @returns Specified storage value.
 */ async function background_getData(key, fallback = true) {
    const data = await background_browserStorage.get(key);
    if (data) {
        return data;
    }
    // Before v4.2, app version and client id were stored in settings
    if (fallback) {
        const settings = await background_browserStorage.get(background_ADGUARD_SETTINGS_KEY);
        const result = background_lib/* default.record */.Ay.record(background_lib/* default.unknown */.Ay.unknown()).safeParse(settings);
        if (result.success && key in result.data) {
            return result.data[key];
        }
    }
    return null;
}
/**
 * Get client id from storage.
 *
 * @returns Client id or null.
 */ async function background_getClientId() {
    const clientId = await background_getData(background_CLIENT_ID_KEY);
    if (typeof clientId === 'string') {
        return clientId;
    }
    return null;
}
/**
 * Get app version from storage.
 *
 * @returns App version or null.
 */ async function background_getAppVersion() {
    const appVersion = await background_getData(background_APP_VERSION_KEY);
    if (typeof appVersion === 'string') {
        return appVersion;
    }
    return null;
}
/**
 * Get schema version from storage.
 *
 * @returns Schema version or 0.
 */ async function background_getSchemaVersion() {
    // don't search schema version in legacy source, because it was added in v4.2
    const schemaVersion = await background_getData(background_SCHEMA_VERSION_KEY, false);
    if (typeof schemaVersion === 'number') {
        return schemaVersion;
    }
    // If schema version is not exist, returns legacy v0
    return 0;
}
/**
 * Gets app running info from storage.
 *
 * @returns App running info.
 */ async function background_getRunInfo() {
    const currentAppVersion = background_Prefs.version;
    const currentSchemaVersion = background_APP_SCHEMA_VERSION;
    const previousAppVersion = await background_getAppVersion();
    const previousSchemaVersion = await background_getSchemaVersion();
    const clientId = await background_getClientId();
    return {
        previousAppVersion,
        currentAppVersion,
        currentSchemaVersion,
        previousSchemaVersion,
        clientId
    };
}

;// ./Extension/src/background/utils/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 







;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/throttle.js



/** Error message constants. */
var background_throttle_FUNC_ERROR_TEXT = 'Expected a function';

/**
 * Creates a throttled function that only invokes `func` at most once per
 * every `wait` milliseconds. The throttled function comes with a `cancel`
 * method to cancel delayed `func` invocations and a `flush` method to
 * immediately invoke them. Provide `options` to indicate whether `func`
 * should be invoked on the leading and/or trailing edge of the `wait`
 * timeout. The `func` is invoked with the last arguments provided to the
 * throttled function. Subsequent calls to the throttled function return the
 * result of the last `func` invocation.
 *
 * **Note:** If `leading` and `trailing` options are `true`, `func` is
 * invoked on the trailing edge of the timeout only if the throttled function
 * is invoked more than once during the `wait` timeout.
 *
 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
 * until to the next tick, similar to `setTimeout` with a timeout of `0`.
 *
 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
 * for details over the differences between `_.throttle` and `_.debounce`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to throttle.
 * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
 * @param {Object} [options={}] The options object.
 * @param {boolean} [options.leading=true]
 *  Specify invoking on the leading edge of the timeout.
 * @param {boolean} [options.trailing=true]
 *  Specify invoking on the trailing edge of the timeout.
 * @returns {Function} Returns the new throttled function.
 * @example
 *
 * // Avoid excessively updating the position while scrolling.
 * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
 *
 * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
 * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
 * jQuery(element).on('click', throttled);
 *
 * // Cancel the trailing throttled invocation.
 * jQuery(window).on('popstate', throttled.cancel);
 */
function background_throttle(func, wait, options) {
  var leading = true,
      trailing = true;

  if (typeof func != 'function') {
    throw new TypeError(background_throttle_FUNC_ERROR_TEXT);
  }
  if (background_lodash_es_isObject(options)) {
    leading = 'leading' in options ? !!options.leading : leading;
    trailing = 'trailing' in options ? !!options.trailing : trailing;
  }
  return background_lodash_es_debounce(func, wait, {
    'leading': leading,
    'maxWait': wait,
    'trailing': trailing
  });
}

/* harmony default export */ const background_lodash_es_throttle = (background_throttle);

;// ./node_modules/.pnpm/@adguard+tsurlfilter@3.3.3_@adguard+re2-wasm@1.2.0/node_modules/@adguard/tsurlfilter/dist/es/declarative-converter-utils.js
var background_declarative_converter_utils_ErrorStatusCodes;
(function (ErrorStatusCodes) {
    ErrorStatusCodes[ErrorStatusCodes["ComplexRegex"] = 1001] = "ComplexRegex";
    ErrorStatusCodes[ErrorStatusCodes["RuleLimit"] = 1002] = "RuleLimit";
    ErrorStatusCodes[ErrorStatusCodes["RegexpRuleLimit"] = 1003] = "RegexpRuleLimit";
    ErrorStatusCodes[ErrorStatusCodes["RemoveparamRegexpIsNotSupported"] = 1004] = "RemoveparamRegexpIsNotSupported";
    ErrorStatusCodes[ErrorStatusCodes["RemoveparamInversionIsNotSupported"] = 1005] = "RemoveparamInversionIsNotSupported";
})(background_declarative_converter_utils_ErrorStatusCodes || (background_declarative_converter_utils_ErrorStatusCodes = {}));
const background_declarative_converter_utils_EMPTY_STRING = '';
const background_RE_NUMBER = /^\d+$/;
/**
 * Prefix for ruleset name.
 */
const background_declarative_converter_utils_RULESET_NAME_PREFIX = 'ruleset_';

/**
 * Extension for ruleset file.
 */
const background_RULESET_FILE_EXT = '.json';
/**
 * Path separator.
 */
const background_PATH_SEPARATOR = '/';
/**
 * Helper method to get the rule set ID with the {@link RULESET_NAME_PREFIX} prefix.
 *
 * @param ruleSetId Rule set id. Can be a number or a string.
 *
 * @returns Rule set ID with the {@link RULESET_NAME_PREFIX} prefix.
 */
function background_declarative_converter_utils_getRuleSetId(ruleSetId) {
    let ruleSetIdStr = String(ruleSetId);
    if (!ruleSetIdStr.startsWith(background_declarative_converter_utils_RULESET_NAME_PREFIX)) {
        ruleSetIdStr = `${background_declarative_converter_utils_RULESET_NAME_PREFIX}${ruleSetIdStr}`;
    }
    return ruleSetIdStr;
}
/**
 * Helper method to get the path to the rule set file.
 *
 * @param ruleSetId Rule set id. Can be a number or a string.
 * @param baseDir Base directory.
 *
 * @returns Path to the rule set file.
 *
 * @note This is just a path, not a URL. To get a URL, use `browser.runtime.getURL`.
 * @note Rule set ID automatically gets a {@link RULESET_NAME_PREFIX} prefix if it doesn't have it,
 * e.g. `123` -> `ruleset_123` or `foo` -> `ruleset_foo`.
 */
function background_getRuleSetPath(ruleSetId, baseDir) {
    const ruleSetIdWithPrefix = background_declarative_converter_utils_getRuleSetId(ruleSetId);
    const resultPrefix = baseDir ? `${baseDir}${background_PATH_SEPARATOR}` : background_declarative_converter_utils_EMPTY_STRING;
    return `${resultPrefix}${ruleSetIdWithPrefix}${background_PATH_SEPARATOR}${ruleSetIdWithPrefix}${background_RULESET_FILE_EXT}`;
}
/**
 * Helper method to extract the rule set ID from the given string.
 *
 * This method processes a string that may represent a path or contain a prefix,
 * extracts the last part if it contains slashes, removes a defined prefix if present,
 * and validates whether the remaining part is a numeric string.
 *
 * @param ruleSetId The rule set ID or path to process.
 *
 * @returns The extracted rule set ID as a number, or `null` if the ID cannot be extracted.
 */
function background_extractRuleSetId(ruleSetId) {
    let ruleSetIdToParse = ruleSetId;
    // Extract the last part of the path if it contains '/'
    const lastSlashIndex = ruleSetIdToParse.lastIndexOf(background_PATH_SEPARATOR);
    if (lastSlashIndex !== -1) {
        ruleSetIdToParse = ruleSetIdToParse.slice(lastSlashIndex + background_PATH_SEPARATOR.length);
    }
    // Remove the prefix and file extension if present
    if (ruleSetIdToParse.startsWith(background_declarative_converter_utils_RULESET_NAME_PREFIX)) {
        ruleSetIdToParse = ruleSetIdToParse.slice(background_declarative_converter_utils_RULESET_NAME_PREFIX.length);
        if (ruleSetIdToParse.endsWith(background_RULESET_FILE_EXT)) {
            ruleSetIdToParse = ruleSetIdToParse.slice(0, -background_RULESET_FILE_EXT.length);
        }
    }
    // Validate and parse as a number
    if (!background_RE_NUMBER.test(ruleSetIdToParse)) {
        return null;
    }
    const possibleInt = parseInt(ruleSetIdToParse, 10);
    return Number.isNaN(possibleInt) ? null : possibleInt;
}



;// ./node_modules/.pnpm/tslib@2.5.3/node_modules/tslib/tslib.es6.mjs
/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */

var background_extendStatics = function(d, b) {
  background_extendStatics = Object.setPrototypeOf ||
      ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
      function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  return background_extendStatics(d, b);
};

function background_extends(d, b) {
  if (typeof b !== "function" && b !== null)
      throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  background_extendStatics(d, b);
  function __() { this.constructor = d; }
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

var background_assign = function() {
  background_assign = Object.assign || function __assign(t) {
      for (var s, i = 1, n = arguments.length; i < n; i++) {
          s = arguments[i];
          for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
      }
      return t;
  }
  return background_assign.apply(this, arguments);
}

function background_rest(s, e) {
  var t = {};
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
      t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
      for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
          if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
              t[p[i]] = s[p[i]];
      }
  return t;
}

function background_decorate(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
}

function background_param(paramIndex, decorator) {
  return function (target, key) { decorator(target, key, paramIndex); }
}

function background_esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
  function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
  var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
  var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
  var _, done = false;
  for (var i = decorators.length - 1; i >= 0; i--) {
      var context = {};
      for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
      for (var p in contextIn.access) context.access[p] = contextIn.access[p];
      context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
      var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
      if (kind === "accessor") {
          if (result === void 0) continue;
          if (result === null || typeof result !== "object") throw new TypeError("Object expected");
          if (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
      }
      else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
      }
  }
  if (target) Object.defineProperty(target, contextIn.name, descriptor);
  done = true;
};

function background_runInitializers(thisArg, initializers, value) {
  var useValue = arguments.length > 2;
  for (var i = 0; i < initializers.length; i++) {
      value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
  }
  return useValue ? value : void 0;
};

function background_propKey(x) {
  return typeof x === "symbol" ? x : "".concat(x);
};

function background_setFunctionName(f, name, prefix) {
  if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
  return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};

function background_metadata(metadataKey, metadataValue) {
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}

function background_awaiter(thisArg, _arguments, P, generator) {
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  return new (P || (P = Promise))(function (resolve, reject) {
      function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
      function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
      function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
      step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}

function background_generator(thisArg, body) {
  var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  function verb(n) { return function (v) { return step([n, v]); }; }
  function step(op) {
      if (f) throw new TypeError("Generator is already executing.");
      while (g && (g = 0, op[0] && (_ = 0)), _) try {
          if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
          if (y = 0, t) op = [op[0] & 2, t.value];
          switch (op[0]) {
              case 0: case 1: t = op; break;
              case 4: _.label++; return { value: op[1], done: false };
              case 5: _.label++; y = op[1]; op = [0]; continue;
              case 7: op = _.ops.pop(); _.trys.pop(); continue;
              default:
                  if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                  if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                  if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                  if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                  if (t[2]) _.ops.pop();
                  _.trys.pop(); continue;
          }
          op = body.call(thisArg, _);
      } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
      if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  }
}

var background_createBinding = Object.create ? (function(o, m, k, k2) {
  if (k2 === undefined) k2 = k;
  var desc = Object.getOwnPropertyDescriptor(m, k);
  if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
  }
  Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
  if (k2 === undefined) k2 = k;
  o[k2] = m[k];
});

function background_exportStar(m, o) {
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) background_createBinding(o, m, p);
}

function background_values(o) {
  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  if (m) return m.call(o);
  if (o && typeof o.length === "number") return {
      next: function () {
          if (o && i >= o.length) o = void 0;
          return { value: o && o[i++], done: !o };
      }
  };
  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}

function background_read(o, n) {
  var m = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m) return o;
  var i = m.call(o), r, ar = [], e;
  try {
      while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  }
  catch (error) { e = { error: error }; }
  finally {
      try {
          if (r && !r.done && (m = i["return"])) m.call(i);
      }
      finally { if (e) throw e.error; }
  }
  return ar;
}

/** @deprecated */
function background_spread() {
  for (var ar = [], i = 0; i < arguments.length; i++)
      ar = ar.concat(background_read(arguments[i]));
  return ar;
}

/** @deprecated */
function background_spreadArrays() {
  for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
  for (var r = Array(s), k = 0, i = 0; i < il; i++)
      for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
          r[k] = a[j];
  return r;
}

function background_spreadArray(to, from, pack) {
  if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
      if (ar || !(i in from)) {
          if (!ar) ar = Array.prototype.slice.call(from, 0, i);
          ar[i] = from[i];
      }
  }
  return to.concat(ar || Array.prototype.slice.call(from));
}

function background_await(v) {
  return this instanceof background_await ? (this.v = v, this) : new background_await(v);
}

function background_asyncGenerator(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var g = generator.apply(thisArg, _arguments || []), i, q = [];
  return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
  function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
  function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
  function step(r) { r.value instanceof background_await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
  function fulfill(value) { resume("next", value); }
  function reject(value) { resume("throw", value); }
  function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}

function background_asyncDelegator(o) {
  var i, p;
  return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
  function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: background_await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
}

function background_asyncValues(o) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var m = o[Symbol.asyncIterator], i;
  return m ? m.call(o) : (o = typeof background_values === "function" ? background_values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
  function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
  function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}

function background_makeTemplateObject(cooked, raw) {
  if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
  return cooked;
};

var background_setModuleDefault = Object.create ? (function(o, v) {
  Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
  o["default"] = v;
};

function background_importStar(mod) {
  if (mod && mod.__esModule) return mod;
  var result = {};
  if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) background_createBinding(result, mod, k);
  background_setModuleDefault(result, mod);
  return result;
}

function background_importDefault(mod) {
  return (mod && mod.__esModule) ? mod : { default: mod };
}

function background_classPrivateFieldGet(receiver, state, kind, f) {
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}

function background_classPrivateFieldSet(receiver, state, value, kind, f) {
  if (kind === "m") throw new TypeError("Private method is not writable");
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}

function background_classPrivateFieldIn(state, receiver) {
  if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
  return typeof state === "function" ? receiver === state : state.has(receiver);
}

/* harmony default export */ const background_tslib_es6 = ({
  __extends: background_extends,
  __assign: background_assign,
  __rest: background_rest,
  __decorate: background_decorate,
  __param: background_param,
  __metadata: background_metadata,
  __awaiter: background_awaiter,
  __generator: background_generator,
  __createBinding: background_createBinding,
  __exportStar: background_exportStar,
  __values: background_values,
  __read: background_read,
  __spread: background_spread,
  __spreadArrays: background_spreadArrays,
  __spreadArray: background_spreadArray,
  __await: background_await,
  __asyncGenerator: background_asyncGenerator,
  __asyncDelegator: background_asyncDelegator,
  __asyncValues: background_asyncValues,
  __makeTemplateObject: background_makeTemplateObject,
  __importStar: background_importStar,
  __importDefault: background_importDefault,
  __classPrivateFieldGet: background_classPrivateFieldGet,
  __classPrivateFieldSet: background_classPrivateFieldSet,
  __classPrivateFieldIn: background_classPrivateFieldIn,
});

;// ./node_modules/.pnpm/@adguard+tswebextension@3.1.0-alpha.3_@adguard+re2-wasm@1.2.0/node_modules/@adguard/tswebextension/dist/common/filters.js



/**
 * Singleton class for managing IndexedDB database.
 */
class background_IdbSingleton {
    /**
     * Database name.
     */
    static DB_NAME = 'tswebextensionIDB';
    /**
     * Active database connection (null when closed).
     */
    static db = null;
    /**
     * In‑flight promise used as a mutex to avoid races.
     */
    static dbGetterPromise = null;
    /**
     * Returns an opened database containing the requested store. The method
     * upgrades the database (and clears all existing stores) when the requested
     * store is missing.
     *
     * @param store Name of the object store that must be present.
     * @param onUpgrade Optional callback to be called when the database is upgraded.
     *
     * @returns Promise, resolved with opened database.
     */
    static async getOpenedDb(store, onUpgrade) {
        // Fast path when we already have an open DB containing the store.
        if (background_IdbSingleton.db?.objectStoreNames.contains(store)) {
            return background_IdbSingleton.db;
        }
        // If someone is already opening/upgrading, just wait for them.
        if (background_IdbSingleton.dbGetterPromise) {
            return background_IdbSingleton.dbGetterPromise;
        }
        background_IdbSingleton.dbGetterPromise = (async () => {
            try {
                if (background_IdbSingleton.db) {
                    background_IdbSingleton.db.close();
                    background_IdbSingleton.db = null;
                }
                // Probe: open with undefined version, which opens the current version.
                let db = await background_openDB(background_IdbSingleton.DB_NAME, undefined, {
                    upgrade(_database, oldVersion, newVersion) {
                        background_common_logger_logger.debug('Upgrade IDB version from', oldVersion, 'to', newVersion);
                    },
                    blocked() {
                        background_common_logger_logger.warn('IDB upgrade blocked');
                    },
                });
                if (!db.objectStoreNames.contains(store)) {
                    const currentVersion = db.version;
                    // Close the database before upgrading.
                    db.close();
                    // Upgrade: bump version by +1, clear stores, add missing store
                    db = await background_openDB(background_IdbSingleton.DB_NAME, currentVersion + 1, {
                        upgrade(database, oldVersion, newVersion, tx) {
                            onUpgrade?.(oldVersion, newVersion);
                            background_common_logger_logger.debug('Upgrade IDB version from', oldVersion, 'to', newVersion);
                            for (const name of Array.from(database.objectStoreNames)) {
                                tx.objectStore(name).clear();
                            }
                            if (!database.objectStoreNames.contains(store)) {
                                database.createObjectStore(store);
                            }
                        },
                        blocked() {
                            background_common_logger_logger.warn('IDB upgrade blocked');
                        },
                    });
                }
                background_IdbSingleton.db = db;
                return db;
            }
            finally {
                background_IdbSingleton.dbGetterPromise = null;
            }
        })();
        return background_IdbSingleton.dbGetterPromise;
    }
}

/**
 * Provides a "synchronized storage" for filter lists.
 * This storage is needed to synchronize data from JSON rulesets to IndexedDB
 * on every extension start (if needed).
 */
class background_filters_FiltersStorage {
    /**
     * Database store name.
     */
    static DB_STORE_NAME = 'filters';
    /**
     * Key combiner.
     */
    static KEY_COMBINER = '_';
    /**
     * Key prefix for byte serialized filter list.
     */
    static KEY_FILTER_LIST = 'filterList';
    /**
     * Key prefix for raw filter list.
     */
    static KEY_RAW_FILTER_LIST = 'rawFilterList';
    /**
     * Key prefix for conversion map.
     */
    static KEY_CONVERSION_MAP = 'conversionMap';
    /**
     * Key prefix for source map.
     */
    static KEY_SOURCE_MAP = 'sourceMap';
    /**
     * Key prefix for checksum.
     */
    static KEY_CHECKSUM = 'checksum';
    /**
     * Returns key with prefix.
     * Key format: <prefix>_<filterId>, e.g. `filterList_1`.
     *
     * @param keyPrefix Key prefix.
     * @param filterId Filter id.
     *
     * @returns Key with prefix.
     */
    static getKey(keyPrefix, filterId) {
        return `${keyPrefix}${background_filters_FiltersStorage.KEY_COMBINER}${filterId}`;
    }
    /**
     * Sets multiple filter lists to {@link filtersIdbStorage} in batch.
     *
     * @param filters Record with filter id as a key and filter rules strings as a value.
     *
     * @throws Error, if transaction failed.
     */
    static async setMultiple(filters) {
        const data = {};
        for (const [filterId, filter] of Object.entries(filters)) {
            for (const [key, value] of Object.entries(filter)) {
                data[background_filters_FiltersStorage.getKey(key, filterId)] = value;
            }
        }
        const db = await background_IdbSingleton.getOpenedDb(background_filters_FiltersStorage.DB_STORE_NAME);
        const tx = db.transaction(background_filters_FiltersStorage.DB_STORE_NAME, 'readwrite');
        try {
            for (const [key, value] of Object.entries(data)) {
                tx.store.put(value, key);
            }
            await tx.done;
        }
        catch (e) {
            background_common_logger_logger.error('Failed to set multiple filter data, got error:', e);
            tx.abort();
            throw e;
        }
    }
    /**
     * Checks if the filter list with the specified ID exists in the storage.
     *
     * @param filterId Filter id.
     *
     * @returns `true` if the filter list exists, `false` otherwise.
     */
    static async has(filterId) {
        const db = await background_IdbSingleton.getOpenedDb(background_filters_FiltersStorage.DB_STORE_NAME);
        const keys = await db.getAllKeys(background_filters_FiltersStorage.DB_STORE_NAME);
        const searchedKey = background_filters_FiltersStorage.getKey(background_filters_FiltersStorage.KEY_CHECKSUM, filterId);
        return keys
            .map(String)
            .some((key) => key === searchedKey);
    }
    /**
     * Returns specified filter list from cache or {@link filtersIdbStorage}.
     *
     * @param filterId Filter id.
     *
     * @returns Promise, resolved with filter rules strings.
     *
     * @throws Error, if DB operation failed or returned data is not valid.
     */
    static async get(filterId) {
        try {
            const data = await Promise.all([
                background_filters_FiltersStorage.getFilterList(filterId),
                background_filters_FiltersStorage.getRawFilterList(filterId),
                background_filters_FiltersStorage.getConversionMap(filterId),
                background_filters_FiltersStorage.getSourceMap(filterId),
                background_filters_FiltersStorage.getChecksum(filterId),
            ]);
            // eslint-disable-next-line prefer-const
            let [filterList, rawFilterList, conversionMap, sourceMap, checksum] = data;
            // If any of the data is missing, return undefined
            if (filterList === undefined || rawFilterList === undefined || checksum === undefined) {
                return undefined;
            }
            // If conversionMap or sourceMap is missing, set it to empty object
            if (conversionMap === undefined) {
                conversionMap = {};
            }
            if (sourceMap === undefined) {
                sourceMap = {};
            }
            return {
                filterList,
                rawFilterList,
                conversionMap,
                sourceMap,
                checksum,
            };
        }
        catch (e) {
            background_common_logger_logger.error(`Failed to get filter data for filter id ${filterId}, got error:`, e);
            throw e;
        }
    }
    /**
     * Removes multiple filter lists from {@link filtersIdbStorage} in batch.
     *
     * @param filterIds Filter ids.
     *
     * @throws Error, if transaction failed.
     */
    static async removeMultiple(filterIds) {
        const keys = filterIds.map((filterId) => {
            return [
                background_filters_FiltersStorage.getKey(background_filters_FiltersStorage.KEY_FILTER_LIST, filterId),
                background_filters_FiltersStorage.getKey(background_filters_FiltersStorage.KEY_RAW_FILTER_LIST, filterId),
                background_filters_FiltersStorage.getKey(background_filters_FiltersStorage.KEY_CONVERSION_MAP, filterId),
                background_filters_FiltersStorage.getKey(background_filters_FiltersStorage.KEY_SOURCE_MAP, filterId),
                background_filters_FiltersStorage.getKey(background_filters_FiltersStorage.KEY_CHECKSUM, filterId),
            ];
        }).flat();
        const db = await background_IdbSingleton.getOpenedDb(background_filters_FiltersStorage.DB_STORE_NAME);
        const tx = db.transaction(background_filters_FiltersStorage.DB_STORE_NAME, 'readwrite');
        try {
            await Promise.all(keys.map((key) => tx.store.delete(key)));
            await tx.done;
        }
        catch (e) {
            background_common_logger_logger.error('Failed to remove multiple filter data, got error:', e);
            tx.abort();
            throw e;
        }
    }
    /**
     * Gets the raw filter list for the specified filter ID.
     *
     * @param filterId Filter id.
     *
     * @returns Raw filter list or `undefined` if the filter list does not exist.
     */
    static async getRawFilterList(filterId) {
        const db = await background_IdbSingleton.getOpenedDb(background_filters_FiltersStorage.DB_STORE_NAME);
        return db.get(background_filters_FiltersStorage.DB_STORE_NAME, background_filters_FiltersStorage.getKey(background_filters_FiltersStorage.KEY_RAW_FILTER_LIST, filterId));
    }
    /**
     * Gets the byte array of the filter list for the specified filter ID.
     *
     * @param filterId Filter id.
     *
     * @returns Byte array of the filter list or `undefined` if the filter list does not exist.
     */
    static async getFilterList(filterId) {
        const db = await background_IdbSingleton.getOpenedDb(background_filters_FiltersStorage.DB_STORE_NAME);
        return db.get(background_filters_FiltersStorage.DB_STORE_NAME, background_filters_FiltersStorage.getKey(background_filters_FiltersStorage.KEY_FILTER_LIST, filterId));
    }
    /**
     * Gets the conversion map for the specified filter ID.
     *
     * @param filterId Filter id.
     *
     * @returns Conversion map or `undefined` if the filter list does not exist.
     */
    static async getConversionMap(filterId) {
        const db = await background_IdbSingleton.getOpenedDb(background_filters_FiltersStorage.DB_STORE_NAME);
        return db.get(background_filters_FiltersStorage.DB_STORE_NAME, background_filters_FiltersStorage.getKey(background_filters_FiltersStorage.KEY_CONVERSION_MAP, filterId));
    }
    /**
     * Gets the source map for the specified filter ID.
     *
     * @param filterId Filter id.
     *
     * @returns Source map or `undefined` if the filter list does not exist.
     */
    static async getSourceMap(filterId) {
        const db = await background_IdbSingleton.getOpenedDb(background_filters_FiltersStorage.DB_STORE_NAME);
        return db.get(background_filters_FiltersStorage.DB_STORE_NAME, background_filters_FiltersStorage.getKey(background_filters_FiltersStorage.KEY_SOURCE_MAP, filterId));
    }
    /**
     * Gets the checksum for the specified filter ID.
     *
     * @param filterId Filter id.
     *
     * @returns Promise, resolved with checksum or undefined if not found.
     */
    static async getChecksum(filterId) {
        const db = await background_IdbSingleton.getOpenedDb(background_filters_FiltersStorage.DB_STORE_NAME);
        return db.get(background_filters_FiltersStorage.DB_STORE_NAME, background_filters_FiltersStorage.getKey(background_filters_FiltersStorage.KEY_CHECKSUM, filterId));
    }
    /**
     * Returns all filter IDs from {@link filtersIdbStorage}.
     *
     * @returns Promise, resolved with filter ids.
     *
     * @throws Error, if DB operation failed.
     */
    static async getFilterIds() {
        try {
            const db = await background_IdbSingleton.getOpenedDb(background_filters_FiltersStorage.DB_STORE_NAME);
            const keys = await db.getAllKeys(background_filters_FiltersStorage.DB_STORE_NAME);
            return keys
                .map(String)
                .filter((key) => key.startsWith(background_filters_FiltersStorage.KEY_CHECKSUM))
                .map((key) => parseInt(key.split(background_filters_FiltersStorage.KEY_COMBINER)[1], 10));
        }
        catch (e) {
            background_common_logger_logger.error('Failed to get filter ids, got error:', e);
            throw e;
        }
    }
}



;// ./node_modules/.pnpm/@adguard+tswebextension@3.1.0-alpha.3_@adguard+re2-wasm@1.2.0/node_modules/@adguard/tswebextension/dist/index.mv3.js


























/**
 * The allowlist is used to exclude certain websites from filtering.
 * Blocking rules are not applied to the sites in the list.
 * The allow list can also be inverted.
 * In inverted mode, the application will unblock ads everywhere except for the
 * sites added to this list.
 */
class background_AllowlistApi extends background_Allowlist$1 {
    /**
     * Configures allowlist state based on app configuration.
     *
     * @param configuration App configuration.
     */
    configure(configuration) {
        /**
         * For MV3 we add "*." for each domain to make matching algorithm
         * same as in DNR engine: requestDomains and excludedRequestDomains in
         * DNR will match all subdomains of the domain by default.
         */
        const domainWithSubDomainsMask = configuration.allowlist.reduce((acc, domain) => {
            acc.push(domain);
            if (!domain.startsWith('*.')) {
                acc.push(`*.${domain}`);
            }
            return acc;
        }, []);
        super.configure({
            ...configuration,
            allowlist: domainWithSubDomainsMask,
        });
    }
    /**
     * Creates one allowlist rule for all allowlistRules. This one combined rule
     * will be passed to the DNR converter.
     *
     * NOTE: We use $to (_to domains_) modifier instead of $domain (_from domains_),
     * because it is needed to match frame request itself and all requests from
     * this frame.
     *
     * @see https://groups.google.com/a/chromium.org/g/chromium-extensions/c/S0TtE9Vk4N4/m/hPtSafzVAQAJ
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#to-modifier
     * @see https://adguard.com/kb/general/ad-filtering/create-own-filters/#domain-modifier
     *
     * @returns Combined rule in AG format.
     *
     * @example
     * ```
     * // configuration = { allowlist: 'example.com, example.org', enabled: true, inverted: false }
     * combineAllowListRules() -> '@@$document,to=example.com|example.org'
     *
     * // configuration = { allowlist: 'example.com, example.org', enabled: true, inverted: true }
     * combineAllowListRules() -> '@@$document,to=~example.com|~example.org'
     * ```
     */
    combineAllowListRulesForDNR() {
        const allDomains = this.domains.map((domain) => {
            // Map subdomain masks to upper domains records, because masks itself
            // will be ignored by DNR. Transforming masks to upper domains will
            // match all subdomains by default in DNR.
            // We added them for consistency between DNR engine and
            // our tsurlfilter (for cosmetic in MV3).
            const d = domain.startsWith('*.')
                ? background_getUpperLevelDomain(domain)
                : domain;
            return this.inverted ? `~${d}` : d;
        });
        const concatenatedUniqueDomains = Array.from(new Set(allDomains)).join('|');
        return allDomains.length > 0 ? `@@$document,to=${concatenatedUniqueDomains}` : '';
    }
}
const background_allowlistApi = new background_AllowlistApi();

const background_ASYNC_LOAD_CHINK_SIZE = 5000;
/**
 * EngineApi - TSUrlFilter engine wrapper which controls how to work with
 * cosmetic rules.
 */
class background_EngineApi {
    /**
     * Link to current Engine.
     */
    engine;
    // TODO: Make private
    /**
     * To prevent multiple calls to startEngine, saves the first call to
     * startEngine and waits for it.
     */
    waitingForEngine;
    /**
     * Starts the engine with the provided bunch of rules,
     * wrapped in filters or custom rules.
     *
     * @param config {@link EngineConfig} Which contains filters (static and
     * custom), custom rules, quick fixes rules and the verbose flag.
     */
    async startEngine(config) {
        const { filters, userrules, quickFixesRules, verbose, } = config;
        const lists = [];
        for (let i = 0; i < filters.length; i += 1) {
            try {
                const filter = filters[i];
                // eslint-disable-next-line no-await-in-loop
                const content = await filter.getContent();
                const trusted = filter.isTrusted();
                lists.push(new background_es/* BufferRuleList */.zV(filter.getId(), content.filterList, false, !trusted, !trusted, content.sourceMap));
            }
            catch (e) {
                const filterId = filters[i].getId();
                background_common_logger_logger.error(`Cannot create IRuleList for filter ${filterId} due to: ${background_configuration_getErrorMessage(e)}`);
            }
        }
        if (userrules.filterList.length > 0) {
            // Note: rules are already converted at the extension side
            lists.push(new background_es/* BufferRuleList */.zV(background_USER_FILTER_ID, userrules.filterList, false, false, false, userrules.sourceMap));
        }
        if (quickFixesRules.filterList.length > 0) {
            // Note: rules are already converted at the extension side
            lists.push(new background_es/* BufferRuleList */.zV(background_QUICK_FIXES_FILTER_ID, quickFixesRules.filterList, false, false, false, quickFixesRules.sourceMap));
        }
        const allowlistRulesList = background_allowlistApi.getAllowlistRules();
        if (allowlistRulesList) {
            lists.push(allowlistRulesList);
        }
        const ruleStorage = new background_es/* RuleStorage */._6(lists);
        /*
         * UI thread becomes blocked on the options page while request filter is
         * created that's why we create filter rules using chunks of
         * the specified length.
         * Request filter creation is rather slow operation so we should
         * use setTimeout calls to give UI thread some time.
        */
        const engine = new background_es/* Engine */.N$(ruleStorage, true);
        await engine.loadRulesAsync(background_ASYNC_LOAD_CHINK_SIZE);
        this.engine = engine;
        // Update configuration of engine.
        (0,background_es/* setConfiguration */.xN)({
            engine: 'extension',
            version: background_browser_polyfill.runtime.getManifest().version,
            verbose,
            compatibility: background_es/* CompatibilityTypes */.YD.Extension,
        });
    }
    /**
     * Stops filtering engine with cosmetic rules.
     */
    stopEngine() {
        this.engine = undefined;
    }
    /**
     * Matches current frame and returns document-level allowlist rule if found.
     *
     * @param frameUrl Url of current frame.
     *
     * @returns Document-level allowlist rule if found, otherwise null.
     */
    matchFrame(frameUrl) {
        if (!this.engine || !background_isHttpOrWsRequest(frameUrl)) {
            return null;
        }
        return this.engine.matchFrame(frameUrl);
    }
    /**
     * Gets cosmetic result for the specified url and cosmetic options if
     * engine is started.
     * Otherwise returns empty CosmeticResult.
     *
     * @param url Hostname to check.
     * @param option Mask of enabled cosmetic types.
     *
     * @returns Cosmetic result.
     */
    getCosmeticResult(url, option) {
        if (!this.engine) {
            return new background_es/* CosmeticResult */.jw();
        }
        const frameUrl = background_getHost(url);
        // Checks if an allowlist rule exists at the document level,
        // then discards all cosmetic rules.
        const allowlistFrameRule = background_DocumentApi.matchFrame(url);
        if (allowlistFrameRule) {
            return new background_es/* CosmeticResult */.jw();
        }
        const request = new background_es/* Request */.Kd(url, frameUrl, background_request_type/* RequestType */.Y.Document);
        return this.engine.getCosmeticResult(request, option);
    }
    /**
     * Gets current loaded rules in the filtering engine
     * (except declarative rules).
     *
     * @returns Number of loaded rules in the filtering engine.
     */
    getRulesCount() {
        return this.engine ? this.engine.getRulesCount() : 0;
    }
    /**
     * Searched for cosmetic rules by match query.
     *
     * @param matchQuery Query against which the request would be matched.
     *
     * @returns Cosmetic result.
     */
    matchCosmetic(matchQuery) {
        if (!this.engine || !background_isHttpRequest(matchQuery.frameUrl)) {
            return new background_es/* CosmeticResult */.jw();
        }
        const matchingResult = this.matchRequest(matchQuery);
        if (!matchingResult) {
            return new background_es/* CosmeticResult */.jw();
        }
        const cosmeticOption = matchingResult.getCosmeticOption();
        return this.getCosmeticResult(matchQuery.requestUrl, cosmeticOption);
    }
    /**
     * Matches the specified request against the filtering engine and returns the matching result.
     *
     * @param matchQuery Item of {@link MatchQuery}, contains request details.
     *
     * @returns Item of {@link MatchingResult} or null, if engine is not started.
     */
    matchRequest(matchQuery) {
        if (!this.engine) {
            return null;
        }
        const { requestUrl, frameUrl, requestType, frameRule, } = matchQuery;
        const request = new background_es/* Request */.Kd(requestUrl, frameUrl, requestType);
        return this.engine.matchRequest(request, frameRule);
    }
    /**
     * Retrieves a rule node by its filter list identifier and rule index.
     *
     * If there's no rule by that index or the rule structure is invalid, it will return null.
     *
     * @param filterId Filter list identifier.
     * @param ruleIndex Rule index.
     *
     * @returns Rule node or `null`.
     */
    retrieveRuleNode(filterId, ruleIndex) {
        if (!this.engine) {
            return null;
        }
        return this.engine.retrieveRuleNode(filterId, ruleIndex);
    }
}
const background_engineApi = new background_EngineApi();

/**
 * Matches rules from {@link EngineApi} based on current {@link Allowlist} state.
 */
class background_DocumentApi {
    /**
     * Match frame rule based on allowlist state.
     *
     * @param frameUrl Frame url.
     *
     * @returns Matched rule or null.
     */
    static matchFrame(frameUrl) {
        const { enabled, inverted } = background_allowlistApi;
        /**
         * If inverted allowlist enabled, use specific matching strategy.
         */
        if (enabled && inverted) {
            return background_DocumentApi.matchFrameInverted(frameUrl);
        }
        /**
         * If allowlist mode is default, request rule from engine.
         * If allowlist is enabled, rules have already loaded.
         */
        return background_engineApi.matchFrame(frameUrl);
    }
    /**
     * Creates allowlist rule for domains that are not in the inverted list.
     * In other cases returns engine matched rule.
     *
     * @param frameUrl Frame url.
     *
     * @returns Matched rule or null.
     */
    static matchFrameInverted(frameUrl) {
        const domain = background_getDomain(frameUrl);
        if (!domain) {
            return null;
        }
        const upperDomain = background_getUpperLevelDomain(domain);
        if (!background_allowlistApi.domains.includes(domain) && !background_allowlistApi.domains.includes(`*.${upperDomain}`)) {
            return background_AllowlistApi.createAllowlistRule(domain);
        }
        return background_engineApi.matchFrame(frameUrl);
    }
}

/**
 * Frame context data for MV3.
 *
 * @see {@link FrameCommon} description.
 */
class background_FrameMV3 extends background_FrameCommon {
    /**
     * Prepared cosmetic result for the frame in MV3.
     *
     * This data is saved in the frame because it is needed for injecting cosmetic rules into the frames.
     */
    preparedCosmeticResult;
}

/**
 * Tab context.
 */
class background_TabContext extends background_TabContextCommon {
    info;
    filteringLog;
    /**
     * Context constructor.
     *
     * @param info Webextension API tab data.
     * @param filteringLog Filtering Log API.
     */
    constructor(info, filteringLog = background_defaultFilteringLog) {
        super(info, filteringLog);
        this.info = info;
        this.filteringLog = filteringLog;
    }
    // TODO: consider moving to common class AG-39552.
    /**
     * Creates context for new tab.
     *
     * @param tab Webextension API tab data.
     *
     * @returns Tab context for new tab.
     */
    static createNewTabContext(tab) {
        const tabContext = new background_TabContext(tab);
        // In some cases, tab is created while browser navigation processing.
        // For example: when you navigate outside the browser or create new empty tab.
        // `pendingUrl` represent url navigated to. We check it first.
        // If server returns redirect, new main frame url will be processed in WebRequestApi.
        const url = tab.pendingUrl || tab.url;
        if (url && background_isHttpOrWsRequest(url)) {
            tabContext.mainFrameRule = background_DocumentApi.matchFrame(url);
            tabContext.frames.set(background_MAIN_FRAME_ID, new background_FrameMV3({
                tabId: tab.id,
                frameId: background_MAIN_FRAME_ID,
                parentFrameId: background_NO_PARENT_FRAME_ID,
                url,
                // timestamp is 0, so that it will be recalculated in the next event
                timeStamp: 0,
            }));
        }
        return tabContext;
    }
}

/**
 * TabsApi works with {@link browser.tabs} to record tabs' URLs - they are
 * needed for work domain-specific blocking/allowing cosmetic rules.
 */
class background_index_mv3_TabsApi extends background_TabsApiCommon {
    /**
     * @inheritdoc
     */
    handleTabCreate(tab) {
        if (!background_TabContext.isBrowserTab(tab)) {
            return null;
        }
        const tabContext = background_TabContext.createNewTabContext(tab);
        this.context.set(tab.id, tabContext);
        this.onCreate.dispatch(tabContext);
        return tabContext;
    }
    /**
     * Updates tab's main frame rule.
     *
     * @param tabId Tab ID.
     */
    updateTabMainFrameRule(tabId) {
        const tabContext = this.context.get(tabId);
        if (!tabContext?.info.url || !background_isHttpOrWsRequest(tabContext.info.url)) {
            return;
        }
        tabContext.mainFrameRule = background_DocumentApi.matchFrame(tabContext.info.url);
    }
    /**
     * Updates tab context data after filter engine load.
     */
    async updateCurrentTabsMainFrameRules() {
        const currentTabs = await background_browser_polyfill.tabs.query({});
        if (!Array.isArray(currentTabs)) {
            return;
        }
        for (const tab of currentTabs) {
            if (typeof tab.id === 'number') {
                this.updateTabMainFrameRule(tab.id);
            }
        }
    }
    /**
     * Checks if tab is a new tab.
     *
     * TODO: Change in AG-22715: if the lifetime of the tab is less than N
     * seconds (for example 5 seconds), then it is a popup and we close it. If
     * the opposite is true, then we block it with a stub.
     *
     * @param tabId Tab ID.
     *
     * @returns True if tab is a new tab.
     */
    isNewPopupTab(tabId) {
        const tab = this.context.get(tabId);
        if (!tab) {
            return false;
        }
        const url = tab.info?.url;
        return url === undefined
            || url === ''
            || url === 'about:blank';
    }
}
const background_tabsApi = new background_index_mv3_TabsApi();

/**
 * API for storing data described by {@link SessionStorageSchema} in the {@link browser.storage.session}.
 */
class background_ExtSessionStorage extends background_ExtensionStorage {
    static #DOMAIN = 'tswebextension';
    static #DEFAULT_DATA = {
        isAppStarted: false,
        configuration: undefined,
        startTimeMs: undefined,
        cosmeticsInjectedOnStartup: false,
    };
    /**
     * Creates {@link SessionStorage} instance.
     */
    constructor() {
        // Use memory storage as a fallback for old browsers and cases when the code
        // is launched outside the extension (case from partners)
        super(background_ExtSessionStorage.#DOMAIN, background_browser_polyfill.storage.session
            ? new background_configuration_BrowserStorage(background_browser_polyfill.storage.session)
            : new background_MemoryStorage());
    }
    /** @inheritdoc */
    init() {
        return super.init(background_ExtSessionStorage.#DEFAULT_DATA);
    }
}
const background_extSessionStorage = new background_ExtSessionStorage();
const background_sessionDecorator = background_createExtensionStorageDecorator(background_extSessionStorage);

/**
 * Top level app context storage.
 *
 * This context is needed to share data between other modules without cyclic dependencies.
 *
 * TODO (v.zhelvis) delete this context after DI is implemented.
 */
let background_index_mv3_AppContext = (() => {
    let _isAppStarted_decorators;
    let _isAppStarted_initializers = [];
    let _isAppStarted_extraInitializers = [];
    let _configuration_decorators;
    let _configuration_initializers = [];
    let _configuration_extraInitializers = [];
    let _startTimeMs_decorators;
    let _startTimeMs_initializers = [];
    let _startTimeMs_extraInitializers = [];
    let _cosmeticsInjectedOnStartup_decorators;
    let _cosmeticsInjectedOnStartup_initializers = [];
    let _cosmeticsInjectedOnStartup_extraInitializers = [];
    return class AppContext {
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
            _isAppStarted_decorators = [background_sessionDecorator("isAppStarted" /* SessionStorageKey.IsAppStarted */)];
            _configuration_decorators = [background_sessionDecorator("configuration" /* SessionStorageKey.Configuration */)];
            _startTimeMs_decorators = [background_sessionDecorator("startTimeMs" /* SessionStorageKey.StartTimeMs */)];
            _cosmeticsInjectedOnStartup_decorators = [background_sessionDecorator("cosmeticsInjectedOnStartup" /* SessionStorageKey.CosmeticsInjectedOnStartup */)];
            background_esDecorate(this, null, _isAppStarted_decorators, { kind: "accessor", name: "isAppStarted", static: false, private: false, access: { has: obj => "isAppStarted" in obj, get: obj => obj.isAppStarted, set: (obj, value) => { obj.isAppStarted = value; } }, metadata: _metadata }, _isAppStarted_initializers, _isAppStarted_extraInitializers);
            background_esDecorate(this, null, _configuration_decorators, { kind: "accessor", name: "configuration", static: false, private: false, access: { has: obj => "configuration" in obj, get: obj => obj.configuration, set: (obj, value) => { obj.configuration = value; } }, metadata: _metadata }, _configuration_initializers, _configuration_extraInitializers);
            background_esDecorate(this, null, _startTimeMs_decorators, { kind: "accessor", name: "startTimeMs", static: false, private: false, access: { has: obj => "startTimeMs" in obj, get: obj => obj.startTimeMs, set: (obj, value) => { obj.startTimeMs = value; } }, metadata: _metadata }, _startTimeMs_initializers, _startTimeMs_extraInitializers);
            background_esDecorate(this, null, _cosmeticsInjectedOnStartup_decorators, { kind: "accessor", name: "cosmeticsInjectedOnStartup", static: false, private: false, access: { has: obj => "cosmeticsInjectedOnStartup" in obj, get: obj => obj.cosmeticsInjectedOnStartup, set: (obj, value) => { obj.cosmeticsInjectedOnStartup = value; } }, metadata: _metadata }, _cosmeticsInjectedOnStartup_initializers, _cosmeticsInjectedOnStartup_extraInitializers);
            if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        /**
         * Is storage initialized.
         * This flag is used to prevent access to persistent storage data on
         * request from content script, before app is started.
         */
        isStorageInitialized = false;
        #isAppStarted_accessor_storage = background_runInitializers(this, _isAppStarted_initializers, void 0);
        /**
         * Is app started.
         */
        get isAppStarted() { return this.#isAppStarted_accessor_storage; }
        set isAppStarted(value) { this.#isAppStarted_accessor_storage = value; }
        #configuration_accessor_storage = (background_runInitializers(this, _isAppStarted_extraInitializers), background_runInitializers(this, _configuration_initializers, void 0));
        /**
         * MV3 ConfigurationMV3 excludes heavyweight fields with rules.
         */
        get configuration() { return this.#configuration_accessor_storage; }
        set configuration(value) { this.#configuration_accessor_storage = value; }
        #startTimeMs_accessor_storage = (background_runInitializers(this, _configuration_extraInitializers), background_runInitializers(this, _startTimeMs_initializers, void 0));
        /**
         * Start time of the app.
         */
        get startTimeMs() { return this.#startTimeMs_accessor_storage; }
        set startTimeMs(value) { this.#startTimeMs_accessor_storage = value; }
        #cosmeticsInjectedOnStartup_accessor_storage = (background_runInitializers(this, _startTimeMs_extraInitializers), background_runInitializers(this, _cosmeticsInjectedOnStartup_initializers, void 0));
        /**
         * Flag that indicates that cosmetics were injected on startup.
         */
        get cosmeticsInjectedOnStartup() { return this.#cosmeticsInjectedOnStartup_accessor_storage; }
        set cosmeticsInjectedOnStartup(value) { this.#cosmeticsInjectedOnStartup_accessor_storage = value; }
        constructor() {
            background_runInitializers(this, _cosmeticsInjectedOnStartup_extraInitializers);
        }
    };
})();
const background_index_mv3_appContext = new background_index_mv3_AppContext();

/**
 * This class is wrapping around chrome.scripting API.
 */
class background_ScriptingApi {
    /**
     * Injects CSS into a tab.
     *
     * @param params Parameters for applying CSS rules.
     * @param params.tabId Tab id.
     * @param params.frameId Frame id.
     * @param params.cssText CSS text.
     *
     * @returns Promise that resolves when the CSS is injected.
     */
    static async insertCSS({ tabId, frameId, cssText }) {
        if (tabId === background_constants_BACKGROUND_TAB_ID) {
            return;
        }
        await chrome.scripting.insertCSS({
            css: cssText,
            origin: 'USER',
            target: { tabId, frameIds: [frameId] },
        });
    }
    /**
     * Executes a scriptlet within the scope of the page.
     *
     * @param params Parameters for executing the scriptlet.
     * @param params.tabId The ID of the tab.
     * @param params.frameId The ID of the frame.
     * @param params.scriptletData The scriptlet data to be executed.
     * @param params.domainName The domain name of the frame. Used for debugging.
     *
     * @returns Promise that resolves when the script is executed.
     */
    static async executeScriptlet({ tabId, frameId, scriptletData, domainName, }) {
        // There is no reason to inject a script into the background page
        if (tabId === background_constants_BACKGROUND_TAB_ID) {
            return;
        }
        const params = {
            ...scriptletData.params,
            uniqueId: String(background_index_mv3_appContext.startTimeMs),
            verbose: background_index_mv3_appContext.configuration?.settings.debugScriptlets || false,
            domainName: domainName ?? undefined,
        };
        await chrome.scripting.executeScript({
            target: { tabId, frameIds: [frameId] },
            func: scriptletData.func,
            injectImmediately: true,
            world: 'MAIN',
            args: [params, scriptletData.params.args],
        });
    }
    /**
     * Executes a script within the scope of the page.
     *
     * @param params Parameters for executing the script.
     * @param params.tabId The ID of the tab.
     * @param params.frameId The ID of the frame.
     * @param params.scriptFunction The script function to be executed.
     *
     * @returns Promise that resolves when the script is executed.
     */
    static async executeScriptFunc({ tabId, frameId, scriptFunction, }) {
        // There is no reason to inject a script into the background page
        if (tabId === background_constants_BACKGROUND_TAB_ID) {
            return;
        }
        /**
         * It is possible to follow all places using this logic by searching JS_RULES_EXECUTION.
         *
         * This is STEP 4.2: Apply JS functions from pre-built filters — via chrome.scripting API.
         */
        await chrome.scripting.executeScript({
            target: { tabId, frameIds: [frameId] },
            func: scriptFunction,
            injectImmediately: true,
            world: 'MAIN',
        });
    }
}

/**
 * It is possible to follow all places using this logic by searching JS_RULES_EXECUTION.
 *
 * Due to Chrome Web Store policies, we cannot execute remotely hosted code.
 * Therefore, we use the following approach:
 *
 * 1. We bundle AdGuard’s JS rules into a local file included with the extension.
 * 2. At runtime, we verify each JS rule to see if it's included in our local bundle.
 *    If it is, we allow it to run; otherwise, we discard it.
 */
class background_LocalScriptRulesService {
    /**
     * When {@link setLocalScriptRules} is called, this holds a list of prebuilt JS rules
     * allowed to run. If it is never called, this remains undefined.
     */
    localScripts;
    /**
     * Stores prebuilt JS rules in memory for later use.
     *
     * @param localScriptRules A map of script text to their corresponding functions.
     */
    setLocalScriptRules(localScriptRules) {
        this.localScripts = localScriptRules;
    }
    /**
     * Checks if the given script text is included in our prebuilt local scripts.
     *
     * This helper method is primarily for transparency during the Chrome Web Store review process.
     *
     * @param scriptText The script rule to verify.
     *
     * @returns True if the script is part of our local collection, false otherwise.
     */
    isLocalScript(scriptText) {
        if (this.localScripts === undefined) {
            return false;
        }
        return this.localScripts[scriptText] !== undefined;
    }
    /**
     * Retrieves the function associated with the specified script text
     * from our local scripts collection.
     *
     * @param scriptText The script content to look up.
     *
     * @returns The corresponding function if found, or null otherwise.
     */
    getLocalScriptFunction(scriptText) {
        if (this.localScripts === undefined) {
            return null;
        }
        const scriptFunc = this.localScripts[scriptText];
        return scriptFunc !== undefined ? scriptFunc : null;
    }
}
const background_localScriptRulesService = new background_LocalScriptRulesService();

/**
 * Cosmetic api class.
 * Used to prepare and inject javascript and css into pages.
 */
class background_CosmeticApi extends background_CosmeticApiCommon {
    /**
     * It is possible to follow all places using this logic by searching JS_RULES_EXECUTION.
     *
     * This is STEP 3: All previously matched script rules are processed and filtered:
     * - JS and Scriptlet rules from pre-built filters (previously collected, pre-built and passed to the engine)
     *   are going to be executed as functions via chrome.scripting API.
     */
    /**
     * Generates data for scriptlets and local scripts:
     * - functions for scriptlets,
     * - script texts for JS rules from pre-built filters.
     *
     * @param cosmeticResult Object containing cosmetic rules.
     *
     * @returns An object with data for scriptlets and script texts.
     */
    static getScriptsAndScriptletsData(cosmeticResult) {
        const rules = cosmeticResult.getScriptRules();
        if (rules.length === 0) {
            return {
                scriptTexts: [],
                scriptletDataList: [],
            };
        }
        const uniqueScriptTexts = new Set();
        const scriptletDataList = [];
        for (let i = 0; i < rules.length; i += 1) {
            const rule = rules[i];
            if (rule.isScriptlet) {
                const scriptletData = rule.getScriptletData();
                if (scriptletData) {
                    scriptletDataList.push(scriptletData);
                }
            }
            else {
                // TODO: Optimize script injection by checking if common scripts (e.g., AG_)
                //  are actually used in the rules. If not, avoid injecting them to reduce overhead.
                const ruleScriptText = rule.getContent();
                if (ruleScriptText) {
                    uniqueScriptTexts.add(ruleScriptText);
                }
            }
        }
        return {
            scriptTexts: [...uniqueScriptTexts],
            scriptletDataList,
        };
    }
    /**
     * Returns content script data for applying cosmetic.
     *
     * @param frameUrl Frame url.
     * @param tabId Tab id.
     * @param frameId Frame id.
     *
     * @returns Content script data for applying cosmetic.
     */
    static getContentScriptData(frameUrl, tabId, frameId) {
        const { isStorageInitialized } = background_index_mv3_appContext;
        const data = {
            isAppStarted: false,
            areHitsStatsCollected: false,
            extCssRules: null,
        };
        // if storage is not initialized, then app is not ready yet.
        if (!isStorageInitialized) {
            return data;
        }
        const { isAppStarted, configuration } = background_index_mv3_appContext;
        const areHitsStatsCollected = configuration?.settings.collectStats || false;
        data.isAppStarted = isAppStarted;
        data.areHitsStatsCollected = areHitsStatsCollected;
        const tabContext = background_tabsApi.getTabContext(tabId);
        if (!tabContext?.info.url) {
            return data;
        }
        const matchQuery = background_createFrameMatchQuery(frameUrl, frameId, tabContext);
        const cosmeticResult = background_engineApi.matchCosmetic(matchQuery);
        data.extCssRules = background_CosmeticApi.getExtCssRules(cosmeticResult, areHitsStatsCollected);
        return data;
    }
    /**
     * Injects js to specified tab and frame.
     *
     * @param tabId Tab id.
     * @param frameId Frame id.
     */
    static async applyJsFuncsByTabAndFrame(tabId, frameId) {
        const frameContext = background_tabsApi.getFrameContext(tabId, frameId);
        if (!frameContext) {
            return;
        }
        const scriptTexts = frameContext.preparedCosmeticResult?.scriptTexts;
        if (!scriptTexts || scriptTexts.length === 0) {
            return;
        }
        try {
            await Promise.all(scriptTexts.map((scriptText) => {
                /**
                 * It is possible to follow all places using this logic by searching JS_RULES_EXECUTION.
                 *
                 * This is STEP 4.1: Selecting only local script functions which were pre-built into the extension.
                 */
                /**
                 * Here we check if the script text is local to guarantee that we do not execute remote code.
                 */
                const isLocalScript = background_localScriptRulesService.isLocalScript(scriptText);
                if (!isLocalScript) {
                    return;
                }
                /**
                 * Here we get the function associated with the script text.
                 */
                const localScriptFunction = background_localScriptRulesService.getLocalScriptFunction(scriptText);
                if (!localScriptFunction) {
                    return;
                }
                // eslint-disable-next-line consistent-return
                return background_ScriptingApi.executeScriptFunc({
                    tabId,
                    frameId,
                    scriptFunction: localScriptFunction,
                });
            }));
        }
        catch (e) {
            background_common_logger_logger.debug('[applyJsFuncsByTabAndFrame] error occurred during injection', background_configuration_getErrorMessage(e));
        }
    }
    /**
     * Injects js to specified tab and frame.
     *
     * @param tabId Tab id.
     * @param frameId Frame id.
     */
    static async applyScriptletsByTabAndFrame(tabId, frameId) {
        const frameContext = background_tabsApi.getFrameContext(tabId, frameId);
        if (!frameContext) {
            return;
        }
        const scriptletDataList = frameContext.preparedCosmeticResult?.scriptletDataList;
        if (!scriptletDataList) {
            return;
        }
        try {
            await Promise.all(scriptletDataList.map((scriptletData) => {
                // eslint-disable-next-line consistent-return
                return background_ScriptingApi.executeScriptlet({
                    tabId,
                    frameId,
                    scriptletData,
                    domainName: background_getDomain(frameContext.url),
                });
            }));
        }
        catch (e) {
            // TODO: getErrorMessage may not be needed since logger should handle arg types
            background_common_logger_logger.debug('[applyScriptletsByTabAndFrame] error occurred during injection', background_configuration_getErrorMessage(e));
        }
    }
    /**
     * Injects css to specified tab id and frame id.
     *
     * @param tabId Tab id.
     * @param frameId Frame id.
     */
    static async applyCssByTabAndFrame(tabId, frameId) {
        const requestContext = background_tabsApi.getFrameContext(tabId, frameId);
        const cssText = requestContext?.preparedCosmeticResult?.cssText;
        if (!cssText) {
            return;
        }
        try {
            await background_ScriptingApi.insertCSS({
                cssText,
                tabId,
                frameId,
            });
        }
        catch (e) {
            background_common_logger_logger.debug('[applyCssByTabAndFrame] error occurred during injection', background_configuration_getErrorMessage(e), 'with request context:', requestContext);
        }
    }
    /**
     * Predicate to filter out non-local script rules.
     *
     * @param rule Cosmetic rule.
     *
     * @returns True if the rule is a local script rule, otherwise false.
     */
    static shouldSanitizeScriptRule(rule) {
        const ruleText = rule.getContent();
        return background_localScriptRulesService.isLocalScript(ruleText);
    }
    /**
     * Logs js rules applied to specific frame.
     *
     * We need a separate function for logging because script rules can be logged before injection
     * to avoid duplicate logs while the js rule is being applied.
     *
     * See {@link WebRequestApi.onBeforeRequest} for details.
     *
     * @param params Data for js rule logging.
     */
    static logScriptRules(params) {
        super.logScriptRules(params, background_CosmeticApi.shouldSanitizeScriptRule);
    }
}

/**
 * Cosmetic frame processor.
 */
class background_CosmeticFrameProcessor {
    /**
     * Time threshold to consider two events as part of the same frame.
     * The value is chosen experimentally; in most cases, 100 ms is sufficient to consider the onBeforeNavigate
     * and onBeforeRequest events as related to the same frame. It is also small enough to ignore manual page
     * reloads by the user.
     */
    static SAME_FRAME_THRESHOLD_MS = 100;
    /**
     * Check if recalculation should be skipped.
     * If the time passed between two events is less than the threshold,
     * we consider it part of the same frame and do not recalculate.
     * Additionally, we check if the URL has changed.
     *
     * @param tabId Tab id.
     * @param frameId Frame id.
     * @param url Url.
     * @param timeStamp Event timestamp.
     *
     * @returns True if recalculation should be skipped.
     */
    static shouldSkipRecalculation(tabId, frameId, url, timeStamp) {
        const frameContext = background_tabsApi.getFrameContext(tabId, frameId);
        if (!frameContext) {
            return false;
        }
        // do not skip recalculation if the URL has changed
        if (frameContext.url !== url) {
            return false;
        }
        const timeDiff = Math.abs(frameContext.timeStamp - timeStamp);
        return timeDiff < background_CosmeticFrameProcessor.SAME_FRAME_THRESHOLD_MS;
    }
    /**
     * Handle sub frame without url.
     *
     * @param props Handle sub frame without url props.
     */
    static handleSubFrameWithoutUrl(props) {
        const { tabId, frameId, mainFrameUrl, parentDocumentId, } = props;
        let parentFrame;
        let tempParentDocumentId = parentDocumentId;
        while (tempParentDocumentId) {
            parentFrame = background_tabsApi.getByDocumentId(tabId, tempParentDocumentId);
            tempParentDocumentId = parentFrame?.parentDocumentId;
            if (background_isHttpRequest(parentFrame?.url)) {
                break;
            }
        }
        if (parentFrame) {
            background_tabsApi.updateFrameContext(tabId, frameId, {
                preparedCosmeticResult: parentFrame.preparedCosmeticResult,
                mainFrameUrl,
            });
        }
    }
    /**
     * Handle sub frame with url.
     *
     * @param props Handle sub frame with url props.
     */
    static handleSubFrameWithUrl(props) {
        const { url, tabId, frameId, mainFrameUrl, mainFrameRule, } = props;
        const result = background_engineApi.matchRequest({
            requestUrl: url,
            frameUrl: mainFrameUrl || url,
            requestType: background_request_type/* RequestType */.Y.SubDocument,
            frameRule: mainFrameRule,
        });
        if (!result) {
            return;
        }
        const cosmeticResult = background_engineApi.getCosmeticResult(url, result.getCosmeticOption());
        const { scriptTexts, scriptletDataList, } = background_CosmeticApi.getScriptsAndScriptletsData(cosmeticResult);
        const { configuration } = background_index_mv3_appContext;
        const areHitsStatsCollected = configuration?.settings.collectStats || false;
        const cssText = background_CosmeticApi.getCssText(cosmeticResult, areHitsStatsCollected);
        background_tabsApi.updateFrameContext(tabId, frameId, {
            mainFrameUrl,
            matchingResult: result,
            cosmeticResult,
            preparedCosmeticResult: {
                scriptTexts,
                scriptletDataList,
                cssText,
            },
        });
    }
    /**
     * Handle main frame.
     *
     * @param props Handle main frame props.
     */
    static handleMainFrame(props) {
        const { url, tabId, frameId, } = props;
        if (!background_isHttpRequest(url)) {
            return;
        }
        background_tabsApi.resetBlockedRequestsCount(tabId);
        const mainFrameRule = background_DocumentApi.matchFrame(url);
        background_tabsApi.setMainFrameRule(tabId, frameId, mainFrameRule);
        const result = background_engineApi.matchRequest({
            requestUrl: url,
            frameUrl: url,
            requestType: background_request_type/* RequestType */.Y.Document,
            frameRule: mainFrameRule,
        });
        if (!result) {
            return;
        }
        const cosmeticResult = background_engineApi.getCosmeticResult(url, result.getCosmeticOption());
        const { scriptTexts, scriptletDataList, } = background_CosmeticApi.getScriptsAndScriptletsData(cosmeticResult);
        const { configuration } = background_index_mv3_appContext;
        const areHitsStatsCollected = configuration?.settings.collectStats || false;
        const cssText = background_CosmeticApi.getCssText(cosmeticResult, areHitsStatsCollected);
        background_tabsApi.updateFrameContext(tabId, frameId, {
            matchingResult: result,
            cosmeticResult,
            preparedCosmeticResult: {
                scriptTexts,
                scriptletDataList,
                cssText,
            },
        });
    }
    /**
     * Handles frames used here and in the {@link TabsCosmeticInjector}.
     *
     * @param props Precalculate cosmetic props.
     */
    static handleFrame(props) {
        const { tabId, frameId, url, parentDocumentId, } = props;
        const isMainFrame = frameId === background_MAIN_FRAME_ID;
        if (isMainFrame) {
            background_CosmeticFrameProcessor.handleMainFrame({
                url,
                tabId,
                frameId,
            });
        }
        else {
            const mainFrame = background_tabsApi.getFrameContext(tabId, background_MAIN_FRAME_ID);
            const mainFrameRule = mainFrame?.frameRule;
            const mainFrameUrl = mainFrame?.url;
            if (!background_isHttpRequest(url)) {
                background_CosmeticFrameProcessor.handleSubFrameWithoutUrl({
                    tabId,
                    frameId,
                    mainFrameUrl,
                    parentDocumentId,
                });
            }
            else {
                background_CosmeticFrameProcessor.handleSubFrameWithUrl({
                    url,
                    tabId,
                    frameId,
                    mainFrameUrl,
                    mainFrameRule,
                });
            }
        }
    }
    /**
     * Precalculate cosmetic rules for the request.
     * This method used in the webNavigation.onBeforeNavigate event and webRequest.onBeforeRequest event.
     *
     * @param props Precalculate cosmetic props.
     */
    static precalculateCosmetics(props) {
        const { tabId, frameId, parentFrameId, url, timeStamp, parentDocumentId, documentId, } = props;
        if (this.shouldSkipRecalculation(tabId, frameId, url, timeStamp)) {
            return;
        }
        // set in the beginning to let other events know that cosmetic result will be calculated in this event to
        // avoid double calculation
        background_tabsApi.setFrameContext(tabId, frameId, new background_FrameMV3({
            tabId,
            frameId,
            parentFrameId,
            url,
            timeStamp,
            documentId,
            parentDocumentId,
        }));
        background_CosmeticFrameProcessor.handleFrame(props);
    }
}

/**
 * Injects cosmetic rules into tabs, opened before app initialization.
 */
class background_TabsCosmeticInjector {
    /**
     * Creates contexts for tabs opened before api initialization and
     * applies cosmetic rules for each frame.
     */
    static async processOpenTabs() {
        const currentTabs = await background_browser_polyfill.tabs.query({});
        const tasks = currentTabs.map((tab) => background_TabsCosmeticInjector.processOpenTab(tab));
        const promises = await Promise.allSettled(tasks);
        // Handles errors
        promises.forEach((promise) => {
            if (promise.status === 'rejected') {
                background_common_logger_logger.error('[tswebextension.processOpenTabs]: cannot inject cosmetic to open tab: ', promise.reason);
            }
        });
        background_index_mv3_appContext.cosmeticsInjectedOnStartup = true;
    }
    /**
     * Creates context for tab opened before api initialization and
     * applies cosmetic rules for each frame.
     *
     * @param tab Tab details.
     */
    static async processOpenTab(tab) {
        if (!background_TabContext.isBrowserTab(tab)) {
            return;
        }
        const tabContext = new background_TabContext(tab);
        const tabId = tab.id;
        background_tabsApi.context.set(tabId, tabContext);
        background_tabsApi.updateTabMainFrameRule(tabId);
        const frames = await chrome.webNavigation.getAllFrames({ tabId });
        if (!frames) {
            return;
        }
        const currentTime = Date.now();
        frames.forEach((frameDetails) => {
            const { url, frameId, parentFrameId, parentDocumentId, documentId, } = frameDetails;
            background_tabsApi.setFrameContext(tabId, frameId, new background_FrameMV3({
                tabId,
                frameId,
                parentFrameId,
                url,
                timeStamp: currentTime,
                parentDocumentId,
                documentId,
            }));
            background_CosmeticFrameProcessor.handleFrame({
                tabId,
                frameId,
                parentFrameId,
                url,
                timeStamp: currentTime,
                parentDocumentId,
                documentId,
            });
            // TODO: Instead of this, it’s better to use the runtime.onStartup and runtime.onInstalled
            // events to inject cosmetics once during the extension's initialization
            // and browser startup without flags.
            // However, this would require big refactoring of the extension.
            /**
             * This condition prevents applying cosmetic rules to the tab multiple times.
             * Applying them once after the extension's initialization is enough.
             */
            if (background_index_mv3_appContext.cosmeticsInjectedOnStartup) {
                return;
            }
            // TODO: Can be moved to CosmeticApi.injectCosmetic() like in MV2
            // since it is used not only here.
            // Note: this is an async function, but we will not await it because
            // events do not support async listeners.
            Promise.all([
                background_CosmeticApi.applyJsFuncsByTabAndFrame(tabId, frameId),
                background_CosmeticApi.applyCssByTabAndFrame(tabId, frameId),
                background_CosmeticApi.applyScriptletsByTabAndFrame(tabId, frameId),
            ]).catch((e) => background_common_logger_logger.error(e));
            const frameContext = background_tabsApi.getFrameContext(tabId, frameId);
            if (!frameContext?.cosmeticResult) {
                // eslint-disable-next-line max-len
                background_common_logger_logger.debug(`[tswebextension.processOpenTab]: cannot log script rules due to not having cosmetic result for tabId: ${tabId}, frameId: ${frameId}.`);
                return;
            }
            const isMainFrame = frameId === background_MAIN_FRAME_ID;
            background_CosmeticApi.logScriptRules({
                url,
                tabId,
                cosmeticResult: frameContext.cosmeticResult,
                timestamp: currentTime,
                contentType: isMainFrame ? background_ContentType.Document : background_ContentType.Subdocument,
            });
        });
    }
}

/**
 * Custom filter list configuration validator for MV3.
 */
const background_customFilterMV3Validator = background_es/* preprocessedFilterListValidator */.gC.extend({
    /**
     * Filter identifier.
     */
    filterId: background_zod_lib.z.number(),
    /**
     * Filter trusted flag.
     */
    trusted: background_zod_lib.z.boolean(),
});
const background_settingsConfigMV3 = background_settingsConfigValidator.extend({
    /**
     * Path to the content script that set GPC Signal.
     * Necessary for `Do Not Track` stealth option.
     * This content script will be dynamically registered and unregistered
     * by the tswebextension when the stealth option is enabled/disabled.
     */
    gpcScriptUrl: background_zod_lib.z.string(),
    /**
     * Path to the content script that hide document referrer.
     * Necessary for `Hide Search Queries` stealth option.
     * This content script will be dynamically registered and unregistered
     * by the tswebextension when the stealth option is enabled/disabled.
     */
    hideDocumentReferrerScriptUrl: background_zod_lib.z.string(),
});
/**
 * Configuration validator for MV3.
 */
const background_configurationMV3Validator = background_configurationValidator.extend({
    /**
     * List of static filters ids.
     * The content for these filters will be loaded by the tswebextension
     * from the "filtersPath" provided when needed.
     */
    staticFiltersIds: background_zod_lib.z.number().array(),
    /**
     * List of custom filters that can be added/edited/deleted by the user.
     */
    customFilters: background_customFilterMV3Validator.array(),
    /**
     * Path to directory with filters' text rules.
     */
    filtersPath: background_zod_lib.z.string(),
    /**
     * Path to directory with converted rule sets.
     * Note: it's better to convert filters with tsurlfilter.convertFilters.
     */
    ruleSetsPath: background_zod_lib.z.string(),
    /**
     * Enables logging declarative rules, which will increase used memory,
     * because to extract matched source rule text we need to load ruleset
     * in memory.
     */
    declarativeLogEnabled: background_zod_lib.z.boolean(),
    /**
     * List of hotfix rules which should applied dynamically.
     */
    quickFixesRules: background_customFilterMV3Validator.omit({ filterId: true }),
    settings: background_settingsConfigMV3,
    /**
     * List of rules added by user.
     */
    userrules: background_customFilterMV3Validator.omit({ filterId: true }),
});

/**
 * An error indicating that an operation timed out.
 */
class background_TimeoutError extends Error {
    /**
     * Constructs a new TimeoutError.
     *
     * @param message Optional error message. Defaults to 'Operation timed out'.
     */
    constructor(message = 'Operation timed out') {
        super(message);
        this.name = 'TimeoutError';
        // For proper work of the "instanceof" operator
        Object.setPrototypeOf(this, background_TimeoutError.prototype);
    }
}

/* eslint-disable max-classes-per-file */
/**
 * A mutual exclusion (mutex) primitive for coordinating asynchronous access to a critical section.
 *
 * Only one lock may be held at a time. Others attempting to acquire the lock will either:
 * - Wait in a queue until the lock is released, or
 * - Fail with a TimeoutError if not acquired within a given timeout.
 *
 * This class is useful in asynchronous environments (e.g. browser or Node.js)
 * where race conditions or critical sections need to be protected.
 */
class background_Mutex {
    /**
     * Indicates whether the mutex is currently locked.
     */
    locked = false;
    /**
     * Queue of resolvers waiting to acquire the mutex.
     */
    waitingResolvers = [];
    /**
     * Attempts to acquire the mutex lock within the specified timeout.
     *
     * If the mutex is free, acquires it immediately.
     * Otherwise, waits until the mutex is available or the timeout expires.
     * If the timeout expires before the lock is granted, a {@link TimeoutError} is thrown.
     *
     * @param timeoutMs The maximum time to wait (in milliseconds) to acquire the lock.
     *
     * @throws {TimeoutError} If the lock is not acquired within the specified time.
     */
    async lock(timeoutMs) {
        if (!this.locked) {
            this.locked = true;
            return;
        }
        let resolver;
        let timeoutId;
        const promise = new Promise((resolve) => {
            resolver = () => {
                clearTimeout(timeoutId);
                resolve();
            };
            this.waitingResolvers.push(resolver);
        });
        const timeoutPromise = new Promise((_, reject) => {
            timeoutId = setTimeout(() => {
                const index = this.waitingResolvers.indexOf(resolver);
                if (index !== -1) {
                    this.waitingResolvers.splice(index, 1);
                }
                reject(new background_TimeoutError());
            }, timeoutMs);
        });
        await Promise.race([promise, timeoutPromise]);
    }
    /**
     * Releases the mutex and grants the lock to the next waiter in the queue, if any.
     *
     * If no one is waiting, the mutex becomes unlocked.
     *
     * @throws {Error} If the mutex is already unlocked.
     */
    unlock() {
        if (!this.locked) {
            throw new Error('Cannot unlock an unlocked mutex');
        }
        const next = this.waitingResolvers.shift();
        if (next) {
            next();
        }
        else {
            this.locked = false;
        }
    }
    /**
     * Returns whether the mutex is currently locked.
     *
     * @returns `true` if the mutex is locked; `false` otherwise.
     */
    isLocked() {
        return this.locked;
    }
    /**
     * Returns a promise that resolves once the mutex is unlocked.
     *
     * If the mutex is already unlocked, the promise resolves immediately.
     * Otherwise, it waits until the lock is released.
     *
     * @returns A promise that resolves when the mutex becomes available.
     */
    async waitUntilUnlocked() {
        if (!this.locked) {
            return;
        }
        await new Promise((resolve) => {
            this.waitingResolvers.push(resolve);
        });
    }
}

/**
 * Request context storage used to keep track of request data
 * and calculated rules for it.
 */
class background_RequestContextStorage {
    /**
     * Map of request context data.
     */
    requestMap = new Map();
    /**
     * Sets requestData context by requestData id.
     *
     * @param requestId Request id.
     * @param requestData Request context data.
     */
    set(requestId, requestData) {
        this.requestMap.set(requestId, requestData);
    }
    /**
     * Updates request context fields. Can be done partially.
     *
     * @param requestId Request id.
     * @param data Partial request context.
     *
     * @returns Updated request context or undefined if request context not found.
     */
    update(requestId, data) {
        const requestContext = this.requestMap.get(requestId);
        if (requestContext) {
            Object.assign(requestContext, data);
            return requestContext;
        }
        return undefined;
    }
    /**
     * Returns request context by request id.
     *
     * @param requestId Request id.
     *
     * @returns Request context or undefined if request context not found.
     */
    get(requestId) {
        return this.requestMap.get(requestId);
    }
    /**
     * Removes non document/subdocument request context from the map by request id.
     *
     * @param requestId Request id.
     */
    delete(requestId) {
        const context = this.requestMap.get(requestId);
        if (!context) {
            return;
        }
        this.requestMap.delete(requestId);
    }
    /**
     * Clears all request context data.
     */
    clear() {
        this.requestMap.clear();
    }
}
const background_requestContextStorage = new background_RequestContextStorage();

/**
 * Generic wrapper for browser.webRequest with custom event implementation.
 */
class background_RequestEvent {
    listeners = [];
    /**
     * Register listener for the browser.webRequest events.
     *
     * @param event WebRequest event name.
     * @param handler Handler to register.
     * @param filter Filter of the events.
     * @param extraInfoSpec Extra info spec.
     */
    init(event, handler, filter, extraInfoSpec) {
        // TODO: Remove BlockingResponseOrPromise because in MV3 we cannot block
        // response, so we need to left only void or promise<void> as result
        // of handlers.
        const handleBrowserEvent = (details) => {
            const data = handler(details);
            /**
             * Execute all registered listeners one by one until a non-empty value is returned.
             */
            for (let i = 0; i < this.listeners.length; i += 1) {
                const res = this.listeners[i](data);
                if (res) {
                    return res;
                }
            }
            return undefined;
        };
        event.addListener(handleBrowserEvent, filter, extraInfoSpec);
    }
    /**
     * Register listener for the browser.webRequest events.
     *
     * @param listener Event callback.
     */
    addListener(listener) {
        this.listeners.push(listener);
    }
    /**
     * Remove listener from the browser.webRequest events.
     *
     * @param listener Event callback.
     */
    removeListener(listener) {
        const index = this.listeners.indexOf(listener);
        if (index !== -1) {
            this.listeners.splice(index, 1);
        }
    }
}

const background_MAX_URL_LENGTH = 1024 * 16;
/**
 * Request events class.
 * TODO: Can it be moved to common?
 */
class background_RequestEvents {
    static onBeforeRequest = new background_RequestEvent();
    static onResponseStarted = new background_RequestEvent();
    static onBeforeSendHeaders = new background_RequestEvent();
    static onHeadersReceived = new background_RequestEvent();
    static onCompleted = new background_RequestEvent();
    static onErrorOccurred = new background_RequestEvent();
    /**
     * Initializes request events service.
     */
    static init() {
        // TODO: Maybe remove RequestEvents and RequestEvent layers?
        background_RequestEvents.onBeforeRequest.init(background_browser_polyfill.webRequest.onBeforeRequest, background_RequestEvents.handleOnBeforeRequest, { urls: ['<all_urls>'] });
        const onBeforeSendHeadersOptions = ['requestHeaders'];
        const onBeforeSendHeadersOptionTypes = background_browser_polyfill.webRequest.OnBeforeSendHeadersOptions;
        if (typeof onBeforeSendHeadersOptionTypes !== 'undefined'
            && Object.prototype.hasOwnProperty.call(onBeforeSendHeadersOptionTypes, 'EXTRA_HEADERS')) {
            onBeforeSendHeadersOptions.push('extraHeaders');
        }
        background_RequestEvents.onBeforeSendHeaders.init(background_browser_polyfill.webRequest.onBeforeSendHeaders, background_RequestEvents.handleOnBeforeSendHeaders, { urls: ['<all_urls>'] }, onBeforeSendHeadersOptions);
        const onResponseStartedOptions = ['responseHeaders', 'extraHeaders'];
        background_RequestEvents.onResponseStarted.init(background_browser_polyfill.webRequest.onResponseStarted, background_RequestEvents.handleOnResponseStarted, { urls: ['<all_urls>'] }, onResponseStartedOptions);
        const onHeadersReceivedOptions = ['responseHeaders'];
        const onHeadersReceivedOptionTypes = background_browser_polyfill.webRequest.OnHeadersReceivedOptions;
        if (typeof onHeadersReceivedOptionTypes !== 'undefined'
            && Object.prototype.hasOwnProperty.call(onBeforeSendHeadersOptionTypes, 'EXTRA_HEADERS')) {
            onHeadersReceivedOptions.push('extraHeaders');
        }
        background_RequestEvents.onHeadersReceived.init(background_browser_polyfill.webRequest.onHeadersReceived, background_RequestEvents.handleOnHeadersReceived, { urls: ['<all_urls>'] }, onHeadersReceivedOptions);
        background_RequestEvents.onCompleted.init(background_browser_polyfill.webRequest.onCompleted, background_RequestEvents.handleOnCompleted, { urls: ['<all_urls>'] }, ['responseHeaders']);
        background_RequestEvents.onErrorOccurred.init(background_browser_polyfill.webRequest.onErrorOccurred, background_RequestEvents.handleOnErrorOccurred, { urls: ['<all_urls>'] });
    }
    /**
     * Handles onResponseStarted event.
     *
     * @param details WebRequest details.
     *
     * @returns Request data with context.
     */
    static handleOnResponseStarted(details) {
        const { requestId, timeStamp } = details;
        const context = background_requestContextStorage.update(requestId, {
            state: "responseStarted" /* RequestContextState.ResponseStarted */,
            timestamp: timeStamp,
        });
        return { details, context };
    }
    /**
     * Handles onBeforeRequest event.
     *
     * @param details WebRequest details.
     *
     * @returns Request data.
     */
    static handleOnBeforeRequest(details) {
        const { requestId, type, tabId, parentFrameId, originUrl, initiator, method, timeStamp, documentLifecycle, } = details;
        let { url, frameId } = details;
        /**
         * Truncate too long urls.
         *
         * @see {@link https://github.com/AdguardTeam/AdguardBrowserExtension/issues/1493}
         */
        if (url.length > background_MAX_URL_LENGTH) {
            url = url.slice(0, background_MAX_URL_LENGTH);
        }
        /**
         * FF sends http instead of ws protocol at the http-listeners layer
         * Although this is expected, as the Upgrade request is indeed an HTTP request,
         * we use a chromium based approach in this case.
         */
        if (type === 'websocket' && background_isHttpRequest(url)) {
            url = url.replace(/^http(s)?:/, 'ws$1:');
        }
        const { requestType, contentType } = background_getRequestType(type);
        const isDocumentRequest = requestType === background_request_type/* RequestType */.Y.Document;
        const isPrerenderRequest = documentLifecycle === background_DocumentLifecycle.Prerender;
        // Pre-rendered documents can have a frame ID other than zero.
        frameId = isDocumentRequest ? background_MAIN_FRAME_ID : frameId;
        let requestFrameId = isDocumentRequest ? frameId : parentFrameId;
        // If there is no parent frame ID, we assume that the request is a main
        // frame request.
        if (requestFrameId === -1) {
            requestFrameId = 0;
        }
        /*
         * To mark requests started via navigation from the address bar (real
         * request or pre-render, it does not matter) as first-party requests,
         * we get only part of the request context to record only the tab and
         * frame information before calculating the request referrer.
         */
        const tabFrameRequestContext = {
            requestUrl: url,
            requestType,
            requestId,
            frameId,
            tabId,
        };
        // We do not check for exists request context here (as it was in MV2),
        // because in MV3 $removeparam rules are applied by browser and does not
        // require page reload after the applying.
        if (isDocumentRequest) {
            // dispatch filtering log reload event
            background_defaultFilteringLog.publishEvent({
                type: background_FilteringEventType.TabReload,
                data: { tabId },
            });
        }
        // We rely on browser-provided values as the source of truth
        let referrerUrl = originUrl
            || initiator
            || '';
        /**
         * For prerender document requests, use the request URL itself, because
         * for prerender request `originUrl` and `initiator` are both undefined.
         */
        if (!referrerUrl && isPrerenderRequest && isDocumentRequest) {
            referrerUrl = url;
        }
        /**
         * If we still do not determine referrerUrl, try to extract url from the
         * tab context or fallback to the request URL.
         */
        if (!referrerUrl) {
            // Try to get referrer from tab state during address bar navigation.
            referrerUrl = background_tabsApi.getTabMainFrame(tabId)?.url
                || background_tabsApi.getTabFrame(tabId, requestFrameId)?.url
                || url;
        }
        // Retrieve the rest part of the request context for record all fields.
        const context = {
            ...tabFrameRequestContext,
            eventId: background_non_secure_nanoid(),
            state: "beforeRequest" /* RequestContextState.BeforeRequest */,
            timestamp: timeStamp,
            thirdParty: background_isThirdPartyRequest(url, referrerUrl),
            referrerUrl,
            contentType,
            method: method,
        };
        background_requestContextStorage.set(requestId, context);
        return { details, context };
    }
    /**
     * Handles onBeforeSendHeaders event.
     *
     * @param details WebRequest details.
     *
     * @returns Request data.
     */
    static handleOnBeforeSendHeaders(details) {
        const { requestId, timeStamp, requestHeaders } = details;
        const context = background_requestContextStorage.update(requestId, {
            state: "beforeSendHeaders" /* RequestContextState.BeforeSendHeaders */,
            timestamp: timeStamp,
            requestHeaders,
        });
        return { details, context };
    }
    /**
     * Handles onHeadersReceived event.
     *
     * @param details WebRequest details.
     *
     * @returns Request data with context.
     */
    static handleOnHeadersReceived(details) {
        const { requestId, responseHeaders, } = details;
        const context = background_requestContextStorage.update(requestId, {
            state: "headersReceived" /* RequestContextState.HeadersReceived */,
            responseHeaders,
        });
        return { details, context };
    }
    /**
     * Handles onCompleted event.
     *
     * @param details WebRequest details.
     *
     * @returns Request data with context.
     */
    static handleOnCompleted(details) {
        const { requestId, timeStamp } = details;
        const context = background_requestContextStorage.update(requestId, {
            state: "completed" /* RequestContextState.Completed */,
            timestamp: timeStamp,
        });
        return { details, context };
    }
    /**
     * Handles onErrorOccurred event.
     *
     * @param details WebRequest details.
     *
     * @returns Request data with context.
     */
    static handleOnErrorOccurred(details) {
        const { requestId, timeStamp } = details;
        const context = background_requestContextStorage.update(requestId, {
            state: "error" /* RequestContextState.Error */,
            timestamp: timeStamp,
        });
        return { details, context };
    }
}

/**
 * Declarative filtering log that can record information about the
 * applied declarative network rules with information about the original rule
 * text and the filter identifier.
 */
class background_DeclarativeFilteringLog {
    /**
     * Stores list of rule sets.
     */
    ruleSets = [];
    /**
     * Is there an active listener for declarativeNetRequest.onRuleMatchedDebug or not.
     */
    #isListening = false;
    /**
     * Mutex for managing concurrent access to rule set updates.
     */
    mutex = new background_Mutex();
    /**
     * Returns is there an active listener for declarativeNetRequest.onRuleMatchedDebug or not.
     *
     * @returns Boolean value.
     */
    get isListening() {
        return this.#isListening;
    }
    /**
     * Acquires the mutex lock within the specified timeout.
     * Used to prevent getting rule info during rule set updates.
     *
     * @param timeoutMs The maximum time to wait (in milliseconds) to acquire the lock.
     *
     * @throws {TimeoutError} If the lock is not acquired within the specified time.
     */
    async startUpdate(timeoutMs = 30000) {
        await this.mutex.lock(timeoutMs);
    }
    /**
     * Releases the mutex and sets the new rule sets.
     * Used to prevent getting rule info during rule set updates.
     * Also, you can specify whether to enable declarative logging after update.
     *
     * @param ruleSets List of {@link IRuleSet}.
     * @param enableLog Should we enable declarative logging after update.
     *
     * @throws Error if no update is in progress.
     */
    finishUpdate(ruleSets, enableLog) {
        this.ruleSets = ruleSets;
        this.mutex.unlock();
        if (enableLog) {
            this.start();
        }
        else {
            this.stop();
        }
    }
    /**
     * Returns converted declarative json rule, original text rule,
     * filter name and id.
     *
     * @param ruleSetId Rule set id.
     * @param ruleId Rule id in this filter.
     *
     * @returns Converted declarative json rule, original txt rule
     * and filter id.
     *
     * @throws Error when couldn't find ruleset or rule in ruleset.
     */
    getRuleInfo = async (ruleSetId, ruleId) => {
        if (this.mutex.isLocked()) {
            await this.mutex.waitUntilUnlocked();
        }
        const ruleSet = this.ruleSets.find((r) => r.getId() === ruleSetId);
        if (!ruleSet) {
            throw new Error(`Cannot find ruleset with id ${ruleSet}`);
        }
        const sourceRules = await ruleSet.getRulesById(ruleId);
        const declarativeRules = await ruleSet.getDeclarativeRules();
        const declarativeRule = declarativeRules.find((r) => r.id === ruleId);
        if (!declarativeRule) {
            throw new Error(`Cannot find rule with id ${ruleId} in ruleset ${ruleSet}`);
        }
        return {
            sourceRules,
            declarativeRuleJson: JSON.stringify(declarativeRule),
        };
    };
    /**
     * Fires an {@link FilteringEventType.MatchedDeclarativeRule} event with
     * matched declarative rule and source text rule.
     *
     * In current approach we will always load all rules from all rule sets in
     * unpacked extension to extract the rule info. This can be optimized and
     * log rule only if filtering log is opened.
     *
     * @param record Request details {@link browser.declarativeNetRequest.MatchedRuleInfoDebug}.
     */
    logMatchedRule = async (record) => {
        const { request: { requestId }, rule: { rulesetId, ruleId }, } = record;
        const context = background_requestContextStorage.get(requestId);
        if (!context) {
            background_common_logger_logger.debug('[logMatchedRule]: cannot find request context for request id', requestId);
            return;
        }
        let declarativeRuleInfo;
        try {
            declarativeRuleInfo = await this.getRuleInfo(rulesetId, ruleId);
        }
        catch (e) {
            background_common_logger_logger.debug(e);
            return;
        }
        background_defaultFilteringLog.publishEvent({
            type: background_FilteringEventType.MatchedDeclarativeRule,
            data: {
                eventId: context.eventId,
                tabId: context.tabId,
                declarativeRuleInfo,
            },
        });
    };
    /**
     * Toggles the listener for declarativeNetRequest.onRuleMatchedDebug.
     *
     * @param needToAddListener If true, the listener will be added, otherwise removed.
     */
    toggleListener = (needToAddListener) => {
        // Wrapped in try-catch to prevent the extension from crashing if browser
        // will change the API in the future.
        try {
            // onRuleMatchedDebug can be null if the extension is running
            // as a packed version
            if (!chrome.declarativeNetRequest.onRuleMatchedDebug) {
                return;
            }
            if (needToAddListener) {
                // Already listening
                if (this.#isListening) {
                    return;
                }
                chrome.declarativeNetRequest.onRuleMatchedDebug.addListener(this.logMatchedRule);
                this.#isListening = true;
            }
            else {
                chrome.declarativeNetRequest.onRuleMatchedDebug.removeListener(this.logMatchedRule);
                this.#isListening = false;
            }
        }
        catch (e) {
            const message = needToAddListener
                ? 'Cannot start recording declarative network rules due to: '
                : 'Cannot stop recording declarative network rules due to: ';
            background_common_logger_logger.debug(message, e);
        }
    };
    /**
     * Starts recording.
     */
    start = () => {
        this.toggleListener(true);
    };
    /**
     * Stops recording.
     */
    stop = () => {
        this.toggleListener(false);
    };
}
const background_declarativeFilteringLog = new background_DeclarativeFilteringLog();

/**
 * DynamicRulesApi knows how to handle dynamic rules: apply a list of custom
 * filters along with user rules, allowlist and quick fixes rules and disable
 * all dynamic rules when the filtration is stopped.
 */
class background_DynamicRulesApi {
    /**
     * The maximum number of regular expression rules that an extension can add.
     * This limit is evaluated separately for the set of session rules,
     * dynamic rules and those specified in the rule_resources file.
     *
     * @returns Maximum number of regular expression rules.
     */
    static get MAX_NUMBER_OF_REGEX_RULES() {
        return background_browser_polyfill.declarativeNetRequest.MAX_NUMBER_OF_REGEX_RULES;
    }
    /**
     * The maximum number of dynamic rules (safe and unsafe) an extension can add.
     *
     * In Chrome before v120, this limit is enforced for the combination of dynamic and session scoped rules.
     * In Firefox and Chrome (staring v121), each ruleset has its own quota.
     *
     * TODO: Maybe now we can move Quick Fixes rules to session ruleset.
     *
     * @returns Maximum number of dynamic rules.
     */
    static get MAX_NUMBER_OF_DYNAMIC_RULES() {
        return background_browser_polyfill.declarativeNetRequest.MAX_NUMBER_OF_DYNAMIC_RULES;
    }
    /**
     * The maximum number of **unsafe** dynamic rules an extension can add.
     *
     * @see {@link https://developer.chrome.com/docs/extensions/reference/api/declarativeNetRequest#property-MAX_NUMBER_OF_UNSAFE_DYNAMIC_RULES}
     *
     * @returns Maximum number of dynamic **unsafe** rules.
     */
    static get MAX_NUMBER_OF_UNSAFE_DYNAMIC_RULES() {
        // TODO: remove following default value and ts-ignore comment
        // when the value become available in webextension-polyfill
        let num = 5000;
        try {
            // @ts-ignore
            num = chrome.declarativeNetRequest.MAX_NUMBER_OF_UNSAFE_DYNAMIC_RULES;
        }
        catch (e) {
            // do nothing
        }
        return num;
    }
    /**
     * Converts custom filters and user rules on the fly into a single merged
     * rule set and applies it via the declarativeNetRequest API.
     *
     * Filters will combine into one in following order:
     * - quickFixesFilter - they are most important and should be applied first,
     * - allowlistRules,
     * - userRules,
     * - customFilters.
     *
     * @param quickFixesFilter Filter with hotfix rules.
     * @param allowlistRules Filter with allowlist rules.
     * @param userRules Filter with user rules.
     * @param customFilters List of custom filters.
     * @param enabledStaticRuleSets List of enabled static rule sets to apply
     * $badfilter rules from dynamic rules to static.
     * @param resourcesPath String path to web accessible resources,
     * relative to the extension root dir. Should start with leading slash '/'.
     *
     * @returns Converted dynamic rule set with rule set, errors and
     * limitations. @see {@link ConversionResult}.
     *
     * @throws Error if declarativeNetRequest.updateDynamicRules() receives invalid rules
     * e.g. with non-ASCII `urlFilter` value.
     * Details: {@link https://developer.chrome.com/docs/extensions/reference/api/declarativeNetRequest#property-RuleCondition-urlFilter}.
     */
    static async updateDynamicFiltering(quickFixesFilter, allowlistRules, userRules, customFilters, enabledStaticRuleSets, resourcesPath) {
        const filterList = [
            quickFixesFilter,
            allowlistRules,
            userRules,
            ...customFilters,
        ];
        // Create filter and convert into single rule set
        const converter = new background_DeclarativeFilterConverter();
        const conversionResult = await converter.convertDynamicRuleSets(filterList, enabledStaticRuleSets, {
            resourcesPath,
            maxNumberOfRules: background_DynamicRulesApi.MAX_NUMBER_OF_DYNAMIC_RULES,
            maxNumberOfUnsafeRules: background_DynamicRulesApi.MAX_NUMBER_OF_UNSAFE_DYNAMIC_RULES,
            maxNumberOfRegexpRules: background_DynamicRulesApi.MAX_NUMBER_OF_REGEX_RULES,
        });
        const { ruleSet, declarativeRulesToCancel } = conversionResult;
        const declarativeRules = await ruleSet.getDeclarativeRules();
        // Remove existing dynamic rules, in order their ids not interfere with new ones
        await this.removeAllRules();
        await background_browser_polyfill.declarativeNetRequest.updateDynamicRules({
            // TODO update rule types returned by getDeclarativeRules();
            addRules: declarativeRules,
        });
        if (declarativeRulesToCancel && declarativeRulesToCancel.length > 0) {
            // Apply $badfilter rules from dynamic filters.
            await this.applyBadFilterRules(declarativeRulesToCancel);
        }
        else {
            // TODO: (AG-34651) Check, if filter_1 has been enabled and we disable some
            // rules there - should we enable them back before disable filter?
            // Because in other case, when we will re-enable filter - maybe it
            // will contains already disabled rules?
            // Undoes all previously applied changes.
            await this.cancelAllStaticRulesUpdates(enabledStaticRuleSets);
        }
        return conversionResult;
    }
    /**
     * Cancels any disabled rules ids for all static rulesets.
     *
     * @param staticRuleSets List of static {@link IRuleSet}.
     */
    static async cancelAllStaticRulesUpdates(staticRuleSets) {
        const tasks = staticRuleSets.map(async (r) => {
            const rulesetId = r.getId();
            // Get list of current disabled rules ids.
            const enableRuleIds = await background_browser_polyfill.declarativeNetRequest.getDisabledRuleIds({ rulesetId });
            // And enable all of them.
            return background_browser_polyfill.declarativeNetRequest.updateStaticRules({
                rulesetId,
                enableRuleIds,
            });
        });
        try {
            await Promise.all(tasks);
        }
        catch (e) {
            // eslint-disable-next-line max-len
            background_common_logger_logger.error(`[tswebextension.cancelAllStaticRulesUpdates]: cannot cancel all updates to static rules due to: ${background_configuration_getErrorMessage(e)}`);
        }
    }
    /**
     * Applies rules with $badfilter modifier which can cancel other rules from
     * static filters which already converted to declarative rules.
     *
     * @param declarativeRulesToCancel List of {@link UpdateStaticRulesOptions}.
     */
    static async applyBadFilterRules(declarativeRulesToCancel) {
        const tasks = declarativeRulesToCancel.map(async ({ rulesetId, disableRuleIds: ruleIdsToDisable, }) => {
            // Get list of current disabled rules ids.
            const disabledRuleIds = await background_browser_polyfill.declarativeNetRequest.getDisabledRuleIds({ rulesetId });
            // Collect rules which should be enabled.
            const enableRuleIds = disabledRuleIds.filter((id) => !ruleIdsToDisable.includes(id));
            // Filter only that rules which are not disabled already.
            const disableRuleIds = ruleIdsToDisable.filter((id) => !disabledRuleIds.includes(id));
            return background_browser_polyfill.declarativeNetRequest.updateStaticRules({
                rulesetId,
                enableRuleIds,
                disableRuleIds,
            });
        });
        try {
            await Promise.all(tasks);
        }
        catch (e) {
            // eslint-disable-next-line max-len
            background_common_logger_logger.error(`[tswebextension.applyBadFilterRules]: cannot apply updates to static rules due to: ${background_configuration_getErrorMessage(e)}`);
        }
    }
    /**
     * Disables all enabled dynamic rules.
     */
    static async removeAllRules() {
        // Get existing dynamic rules
        const existingRules = await background_browser_polyfill.declarativeNetRequest.getDynamicRules();
        const existingRulesIds = existingRules.map((rule) => rule.id);
        // Remove existing dynamic rules
        await background_browser_polyfill.declarativeNetRequest.updateDynamicRules({ removeRuleIds: existingRulesIds });
    }
}

/**
 * Describes error when enabled static rule sets has been failed.
 */
class background_FailedEnableRuleSetsError extends Error {
    /**
     * A list of the IDs of the rule sets that were attempted to enable.
     */
    enableRulesetIds;
    /**
     * A list of the IDs of the rule sets that were attempted to disable.
     */
    disableRulesetIds;
    /**
     * Describes error when enabled static rule sets has been failed.
     *
     * @param message Message of error.
     * @param enableRulesetIds A list of the IDs of the rule sets that were
     * attempted to enable.
     * @param disableRulesetIds A list of the IDs of the rule sets that were
     * attempted to disable.
     * @param cause Specific browser.declarativeNetRequest error.
     */
    constructor(message, enableRulesetIds, disableRulesetIds, cause) {
        super(message, { cause });
        this.name = this.constructor.name;
        this.enableRulesetIds = enableRulesetIds;
        this.disableRulesetIds = disableRulesetIds;
        // For proper work of the "instanceof" operator
        Object.setPrototypeOf(this, background_FailedEnableRuleSetsError.prototype);
    }
}

background_zod_lib/* default.function */.Ay["function"]()
    .args(background_zod_lib/* default.number */.Ay.number())
    .returns(background_zod_lib/* default.promise */.Ay.promise(background_es/* preprocessedFilterListValidator */.gC));
/**
 * FiltersApi knows how to enable or disable static rule sets (which were built
 * with the extension) and how to create {@link Filter} through
 * loading its contents.
 */
class background_FiltersApi {
    /**
     * Cache for already created filters. Needed to avoid multiple loading
     * of the same filter.
     */
    static filtersCache = new Map();
    /**
     * Enables or disables the provided rule set identifiers.
     *
     * @param disableFiltersIds Rule sets to disable.
     * @param enableFiltersIds Rule sets to enable.
     *
     * @returns Promise resolved with result of updating {@link UpdateStaticFiltersResult}.
     */
    static async updateFiltering(disableFiltersIds, enableFiltersIds) {
        const res = {
            errors: [],
        };
        const enableRulesetIds = enableFiltersIds?.map((filterId) => `${background_RULESET_NAME_PREFIX}${filterId}`) || [];
        const disableRulesetIds = disableFiltersIds?.map((filterId) => `${background_RULESET_NAME_PREFIX}${filterId}`) || [];
        try {
            await background_browser_polyfill.declarativeNetRequest.updateEnabledRulesets({
                enableRulesetIds,
                disableRulesetIds,
            });
        }
        catch (e) {
            const msg = 'Cannot change list of enabled rule sets';
            const err = new background_FailedEnableRuleSetsError(msg, enableRulesetIds, disableRulesetIds, e);
            res.errors.push(err);
        }
        return res;
    }
    /**
     * Returns current enabled rule sets IDs.
     *
     * @returns List of extracted enabled rule sets ids.
     */
    static async getEnabledRuleSets() {
        const ruleSets = await background_browser_polyfill.declarativeNetRequest.getEnabledRulesets();
        return ruleSets.map((f) => Number.parseInt(f.slice(background_RULESET_NAME_PREFIX.length), 10));
    }
    /**
     * Wraps static filters into {@link IFilter}.
     *
     * @param filtersIds List of filters ids.
     * @param loadFilterContent Function to load filter content.
     *
     * @returns List of {@link IFilter} with a lazy content loading feature.
     */
    static createStaticFilters(filtersIds, loadFilterContent) {
        return filtersIds.map((filterId) => {
            const filterFromCache = this.filtersCache.get(filterId);
            if (filterFromCache) {
                return filterFromCache;
            }
            const filter = new background_Filter(filterId, { getContent: () => loadFilterContent(filterId) }, 
            /**
             * Static filters are trusted.
             */
            true);
            this.filtersCache.set(filterId, filter);
            return filter;
        });
    }
    /**
     * Wraps custom filter into {@link IFilter}.
     *
     * @param customFilters List of custom filters.
     *
     * @returns List of {@link IFilter} with a lazy content loading feature.
     */
    static createCustomFilters(customFilters) {
        return customFilters.map((f) => new background_Filter(f.filterId, {
            getContent: () => Promise.resolve(f),
        }, f.trusted));
    }
    /**
     * Loads filter content by filter id.
     *
     * @param filterId Filter identifier to load content for.
     *
     * @returns Promise that resolves to the filter content (see {@link PreprocessedFilterList})
     * or null if the filter is not found.
     *
     * @throws Error if the filter content cannot be loaded.
     */
    static loadFilterContent = async (filterId) => {
        try {
            const result = await background_filters_FiltersStorage.get(filterId);
            if (!result) {
                throw new Error(`Filter with id ${filterId} not found`);
            }
            return result;
        }
        catch (e) {
            throw new Error(`Failed to load filter content: ${e}`);
        }
    };
}

/**
 * Cookie filtering.
 *
 * The following public methods should be set as suitable webRequest events listeners, check sample extension in this
 * repo for an example.
 *
 * Logic introduction:
 *  CookieFiltering.onBeforeSendHeaders:
 *  - get all cookies for request url;
 *  - store cookies (first-party);
 *  - apply rules via modifying or removing them with browser.cookies api;
 *
 *  CookieFiltering.onHeadersReceived:
 *  - parse set-cookie header, only to detect if the cookie in header will be set from third-party request;
 *  - save third-party flag for this cookie cookie.thirdParty=request.thirdParty;
 *  - apply rules via modifying or removing them with browser.cookies api;
 *
 *  CookieFiltering.onCompleted:
 *  - apply rules via content script.
 *
 *  In content-scripts (check /src/content-script/cookie-controller.ts):
 *  - apply matched cookie rules.
 */
class background_CookieFiltering {
    browserCookieApi = new background_BrowserCookieApi();
    /**
     * Parses cookies from request headers and applies matched rules
     * via browser.cookies api.
     *
     * @param context Request context.
     */
    onBeforeSendHeaders(context) {
        const { requestHeaders, requestUrl, requestId } = context;
        if (!requestHeaders || !requestUrl) {
            return;
        }
        const cookieHeader = background_findHeaderByName(requestHeaders, 'Cookie');
        if (!cookieHeader?.value) {
            return;
        }
        const cookies = background_CookieUtils$1.parseCookies(cookieHeader.value, requestUrl);
        if (cookies.length === 0) {
            return;
        }
        // Saves cookies to context
        background_requestContextStorage.update(requestId, { cookies });
        // Removes cookies from browser with browser.cookies api, but not
        // removing them from context to correct process them in headers.
        this.applyRules(context)
            .catch((e) => {
            background_common_logger_logger.error('[tswebextension.onBeforeSendHeaders]: cannot apply rules due to: ', e);
        });
    }
    /**
     * Parses set-cookie header from response, looks up third-party cookies
     * and applies matched rules via browser.cookies api.
     *
     * @param context Request context.
     */
    onHeadersReceived(context) {
        const { responseHeaders, requestUrl, thirdParty, requestId, } = context;
        /**
         * Full context can be created in onBeforeRequest, partial context can
         * be created on every requestContextStorage.update method call and
         * because of that case - we explicitly checks fields in object.
         * TODO: Improve in AG-24428.
         */
        if (responseHeaders && requestUrl && typeof thirdParty !== 'undefined') {
            const cookies = background_CookieUtils$1.parseSetCookieHeaders(responseHeaders, requestUrl);
            const newCookies = cookies.filter((c) => !context.cookies?.includes(c));
            for (const cookie of newCookies) {
                cookie.thirdParty = thirdParty;
            }
            background_requestContextStorage.update(requestId, {
                cookies: context.cookies ? [...context.cookies, ...newCookies] : newCookies,
            });
        }
        // Removes cookies from browser with browser.cookies api, but not
        // removing them from context to correct process them in headers.
        this.applyRules(context)
            .catch((e) => {
            background_common_logger_logger.error('[tswebextension.onHeadersReceived]: cannot apply rules due to: ', e);
        });
    }
    /**
     * Applies rules.
     *
     * @param context Request context.
     */
    async applyRules(context) {
        const { matchingResult, cookies, requestUrl, tabId, } = context;
        if (!matchingResult || !cookies) {
            return;
        }
        const cookieRules = matchingResult.getCookieRules();
        const promises = cookies.map(async (cookie) => {
            await this.applyRulesToCookie(cookie, cookieRules, requestUrl, tabId);
        });
        await Promise.all(promises);
    }
    /**
     * Attempts to find a "parent" cookie with a wider "path" field,
     * the scope of which includes the specified cookie from
     * the function parameters.
     *
     * This needs to prevent create of multiple "child"-cookies
     * and only modified expiration of general "parent"-cookie,
     * which covered "children"-cookies by 'path' value.
     *
     * @param cookie Cookie, for which need to find the "parent" cookie.
     *
     * @returns Item of parent cookie {@link ParsedCookie} or null if not found.
     */
    async findParentCookie(cookie) {
        const pattern = {
            url: cookie.url,
            name: cookie.name,
            domain: cookie.domain,
            secure: cookie.secure,
        };
        const parentCookies = await this.browserCookieApi.findCookies(pattern);
        const sortedParentCookies = parentCookies.sort((a, b) => a.path.length - b.path.length);
        for (let i = 0; i < sortedParentCookies.length; i += 1) {
            const parentCookie = sortedParentCookies[i];
            if (cookie.path?.startsWith(parentCookie.path)) {
                return background_ParsedCookie.fromBrowserCookie(parentCookie, cookie.url);
            }
        }
        return null;
    }
    /**
     * Applies rules to cookie.
     *
     * @param cookie Cookie.
     * @param cookieRules Cookie rules.
     * @param requestUrl Request URL, needs to record filtering event.
     * @param tabId Tab id.
     */
    async applyRulesToCookie(cookie, cookieRules, requestUrl, tabId) {
        const cookieName = cookie.name;
        const isThirdPartyCookie = cookie.thirdParty;
        const bRule = background_CookieRulesFinder.lookupNotModifyingRule(cookieName, cookieRules, isThirdPartyCookie);
        if (bRule) {
            if (bRule.isAllowlist() || await this.browserCookieApi.removeCookie(cookie.name, cookie.url)) {
                background_CookieFiltering.recordCookieEvent(tabId, cookie, requestUrl, bRule, false, isThirdPartyCookie);
            }
            return;
        }
        const mRules = background_CookieRulesFinder.lookupModifyingRules(cookieName, cookieRules, isThirdPartyCookie);
        if (mRules.length > 0) {
            // Try to find "parent" cookie and modify it instead of creating
            // "child copy" cookie.
            const parentCookie = await this.findParentCookie(cookie);
            const cookieToModify = parentCookie || cookie;
            const appliedRules = background_CookieFiltering.applyRuleToBrowserCookie(cookieToModify, mRules);
            if (appliedRules.length === 0) {
                return;
            }
            if (await this.browserCookieApi.modifyCookie(cookieToModify)) {
                appliedRules.forEach((r) => {
                    background_CookieFiltering.recordCookieEvent(tabId, cookieToModify, requestUrl, r, true, isThirdPartyCookie);
                });
            }
        }
    }
    /**
     * Modifies instance of {@link ParsedCookie} with provided rules.
     *
     * @param cookie Cookie modify.
     * @param rules Cookie matching rules.
     *
     * @returns Applied rules.
     */
    static applyRuleToBrowserCookie(cookie, rules) {
        const appliedRules = [];
        for (let i = 0; i < rules.length; i += 1) {
            const rule = rules[i];
            if (rule.isAllowlist()) {
                appliedRules.push(rule);
                continue;
            }
            const cookieModifier = rule.getAdvancedModifier();
            let modified = false;
            const sameSite = cookieModifier.getSameSite();
            if (sameSite && cookie.sameSite !== sameSite) {
                // eslint-disable-next-line no-param-reassign
                cookie.sameSite = sameSite;
                modified = true;
            }
            const maxAge = cookieModifier.getMaxAge();
            if (maxAge) {
                if (background_CookieUtils$1.updateCookieMaxAge(cookie, maxAge)) {
                    modified = true;
                }
            }
            if (modified) {
                appliedRules.push(rule);
            }
        }
        return appliedRules;
    }
    /**
     * Looks up blocking rules for content-script.
     *
     * @param frameUrl Frame url.
     * @param tabId Tab id.
     * @param frameId Frame id.
     *
     * @returns List of blocking rules.
     */
    static getBlockingRules(frameUrl, tabId, frameId) {
        const tabContext = background_tabsApi.getTabContext(tabId);
        if (!tabContext?.info.url) {
            return [];
        }
        const matchQuery = background_createFrameMatchQuery(frameUrl, frameId, tabContext);
        const matchingResult = background_engineApi.matchRequest(matchQuery);
        if (!matchingResult) {
            return [];
        }
        const cookieRules = matchingResult.getCookieRules();
        return background_CookieRulesFinder.getBlockingRules(matchQuery.requestUrl, cookieRules);
    }
    /**
     * Records cookie event to filtering log.
     *
     * @param tabId Id of the tab.
     * @param cookie Item of {@link ParsedCookie}.
     * @param requestUrl URL of the request.
     * @param rule Applied modifying or deleting rule.
     * @param isModifyingCookieRule Is applied rule modifying or not.
     * @param requestThirdParty Whether request third party or not.
     */
    static recordCookieEvent(tabId, cookie, requestUrl, rule, isModifyingCookieRule, requestThirdParty) {
        background_defaultFilteringLog.publishEvent({
            type: background_FilteringEventType.Cookie,
            data: {
                eventId: background_non_secure_nanoid(),
                tabId,
                cookieName: cookie.name,
                cookieValue: cookie.value,
                frameDomain: background_getDomain(requestUrl) || requestUrl,
                filterId: rule.getFilterListId(),
                ruleIndex: rule.getIndex(),
                isModifyingCookieRule,
                requestThirdParty,
                timestamp: Date.now(),
                requestType: background_ContentType.Cookie,
                isAllowlist: rule.isAllowlist(),
                isImportant: rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Important),
                isDocumentLevel: rule.isDocumentLevelAllowlistRule(),
                isCsp: rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Csp),
                isCookie: rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Cookie),
                advancedModifier: rule.getAdvancedModifierValue(),
            },
        });
    }
}
const background_cookieFiltering = new background_CookieFiltering();

/**
 * Assistant class is the handler of messages and events related
 * to AdGuard assistant with extended detection of assistant frame.
 */
class background_Assistant extends background_CommonAssistant {
    /**
     * @inheritdoc
     */
    // eslint-disable-next-line class-methods-use-this
    injectAssistant(tabId, fileUrl) {
        return chrome.scripting.executeScript({
            target: { tabId },
            files: [fileUrl],
        });
    }
}
const background_assistant = new background_Assistant();

/**
 * MessageApi knows how to handle {@link Message}.
 * It is used to communicate with content scripts.
 *
 * TODO: Move to common folder.
 */
class background_MessagesApi {
    tsWebExtension;
    tabsApi;
    filteringLog;
    /**
     * Creates new {@link MessagesApi}.
     *
     * @param tsWebExtension Current {@link TsWebExtension} app.
     * @param tabsApi Tabs API.
     * @param filteringLog Filtering log.
     *
     * @returns New {@link MessagesApi} handler.
     */
    constructor(tsWebExtension, tabsApi, filteringLog) {
        this.tsWebExtension = tsWebExtension;
        this.tabsApi = tabsApi;
        this.filteringLog = filteringLog;
        this.handleMessage = this.handleMessage.bind(this);
    }
    /**
     * Handles message with {@link MessageType}.
     *
     * @param message Message.
     * @param sender Sender of message.
     *
     * @returns Data according to the received message.
     */
    async handleMessage(message, sender) {
        background_common_logger_logger.debug('[tswebextension.handleMessage]: ', message);
        try {
            message = background_messageValidator.parse(message);
        }
        catch (e) {
            background_common_logger_logger.error('[tswebextension.handleMessage]: cannot parse message: ', message);
            // Ignore this message
            return undefined;
        }
        const { type } = message;
        switch (type) {
            case background_message_constants_MessageType.GetCosmeticData: {
                return this.handleGetCosmeticData(sender, message.payload);
            }
            case background_message_constants_MessageType.AssistantCreateRule: {
                return this.handleAssistantCreateRuleMessage(sender, message.payload);
            }
            case background_message_constants_MessageType.GetCookieRules: {
                return this.getCookieRules(sender, message.payload);
            }
            case background_message_constants_MessageType.SaveCookieLogEvent: {
                return background_MessagesApi.handleSaveCookieLogEvent(sender, message.payload);
            }
            case background_message_constants_MessageType.SaveCssHitsStats: {
                return this.handleSaveCssHitsStats(sender, message.payload);
            }
            default: {
                background_common_logger_logger.error('[tswebextension.handleMessage]: did not found handler for message');
            }
        }
        return undefined;
    }
    /**
     * Handles get cosmetic message.
     *
     * @param sender Tab which sent message.
     * @param payload Message payload.
     *
     * @returns Content script data for applying cosmetic rules or null if no data.
     */
    handleGetCosmeticData(sender, payload) {
        background_common_logger_logger.debug('[tswebextension.handleGetCosmeticData]: received call: ', payload);
        if (!payload || !sender?.tab?.id) {
            return undefined;
        }
        if (!this.tsWebExtension.isStarted) {
            background_common_logger_logger.debug('[tswebextension.handleGetCosmeticData]: tswebextension is not started.');
            return undefined;
        }
        const res = background_getCosmeticDataPayloadValidator.safeParse(payload);
        if (!res.success) {
            background_common_logger_logger.error('[tswebextension.handleGetCosmeticData]: cannot parse payload: ', payload, res.error);
            return undefined;
        }
        const tabId = sender.tab?.id;
        let { frameId } = sender;
        if (!frameId) {
            frameId = background_MAIN_FRAME_ID;
        }
        return background_CosmeticApi.getContentScriptData(res.data.documentUrl, tabId, frameId);
    }
    /**
     * Handles message with new rule from assistant content script.
     *
     * @param sender An object containing information about the script context
     * that sent a message or request.
     * @param payload Object with rules text.
     *
     * @returns False if it cannot process the created rule,
     * or true for successful processing.
     */
    // eslint-disable-next-line class-methods-use-this
    handleAssistantCreateRuleMessage(sender, payload) {
        if (!payload || !sender?.tab?.id) {
            return false;
        }
        const res = background_getAssistantCreateRulePayloadValidator.safeParse(payload);
        if (!res.success) {
            return false;
        }
        const { ruleText } = res.data;
        background_Assistant.onCreateRule.dispatch(ruleText);
        return true;
    }
    /**
     * Returns cookie rules data for content script.
     *
     * @param sender Tab, which sent message.
     * @param payload Message payload.
     *
     * @returns Cookie rules data.
     */
    getCookieRules(sender, payload) {
        background_common_logger_logger.debug('[tswebextension.getCookieRules]: received call: ', payload);
        const { isStorageInitialized } = background_index_mv3_appContext;
        const data = {
            isAppStarted: false,
            cookieRules: [],
        };
        // if storage is not initialized, then app is not ready yet.
        if (!isStorageInitialized || !this.tsWebExtension.isStarted) {
            return data;
        }
        const res = background_getCookieRulesPayloadValidator.safeParse(payload);
        if (!res.success) {
            // this log message is added here as error for faster identification of the issue
            background_common_logger_logger.error('[tswebextension.getCookieRules]: cannot parse payload: ', payload, res.error);
            return undefined;
        }
        const { documentUrl } = res.data;
        if (background_isEmptySrcFrame(documentUrl)) {
            background_common_logger_logger.debug('[tswebextension.getCookieRules]: frame has empty src');
            return undefined;
        }
        const tabId = sender.tab?.id;
        if (tabId === undefined) {
            background_common_logger_logger.debug('[tswebextension.getCookieRules]: tabId is undefined');
            return undefined;
        }
        data.isAppStarted = true;
        let { frameId } = sender;
        if (!frameId) {
            frameId = background_MAIN_FRAME_ID;
        }
        const cookieRules = background_CookieFiltering.getBlockingRules(documentUrl, tabId, frameId);
        data.cookieRules = cookieRules.map((rule) => ({
            ruleIndex: rule.getIndex(),
            match: rule.getAdvancedModifierValue(),
            isThirdParty: rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.ThirdParty),
            filterId: rule.getFilterListId(),
            isAllowlist: rule.isAllowlist(),
            isImportant: rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Important),
            isDocumentLevel: rule.isDocumentLevelAllowlistRule(),
            isCsp: rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Csp),
            isCookie: rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Cookie),
            advancedModifier: rule.getAdvancedModifierValue(),
        }));
        return data;
    }
    /**
     * Handle message about saving css hits stats.
     *
     * @param sender Tab, which sent message.
     * @param payload Message payload.
     *
     * @returns True if stats was saved.
     */
    handleSaveCssHitsStats(sender, 
    // TODO add payload type
    payload) {
        if (!payload || !sender?.tab?.id) {
            return false;
        }
        const tabId = sender.tab.id;
        const tabContext = this.tabsApi.getTabContext(tabId);
        if (!tabContext?.info.url) {
            return false;
        }
        const { url } = tabContext.info;
        let published = false;
        for (let i = 0; i < payload.length; i += 1) {
            const stat = payload[i];
            this.filteringLog.publishEvent({
                type: background_FilteringEventType.ApplyCosmeticRule,
                data: {
                    tabId,
                    eventId: background_non_secure_nanoid(),
                    filterId: stat.filterId,
                    ruleIndex: stat.ruleIndex,
                    element: stat.element,
                    frameUrl: url,
                    frameDomain: (0,background_es6/* getDomain */.FB)(url),
                    requestType: background_ContentType.Document,
                    timestamp: Date.now(),
                    cssRule: true,
                    scriptRule: false,
                    contentRule: false,
                },
            });
            published = true;
        }
        return published;
    }
    /**
     * Calls filtering to add an event from cookie-controller content-script.
     *
     * @param sender Tab which sent the message.
     * @param payload Message payload.
     *
     * @returns True if event was published to filtering log.
     */
    static handleSaveCookieLogEvent(sender, payload) {
        if (!payload || !sender?.tab?.id) {
            return false;
        }
        const res = background_getSaveCookieLogEventPayloadValidator.safeParse(payload);
        if (!res.success) {
            return false;
        }
        const { data } = res;
        background_defaultFilteringLog.publishEvent({
            type: background_FilteringEventType.Cookie,
            data: {
                eventId: background_non_secure_nanoid(),
                tabId: sender.tab.id,
                cookieName: data.cookieName,
                frameDomain: data.cookieDomain,
                cookieValue: data.cookieValue,
                filterId: data.filterId,
                ruleIndex: data.ruleIndex,
                isModifyingCookieRule: false,
                requestThirdParty: data.thirdParty,
                timestamp: Date.now(),
                requestType: background_ContentType.Cookie,
                // Additional rule properties
                isAllowlist: data.isAllowlist,
                isImportant: data.isImportant,
                isDocumentLevel: data.isDocumentLevel,
                isCsp: data.isCsp,
                isCookie: data.isCookie,
                advancedModifier: data.advancedModifier,
            },
        });
        return true;
    }
}

/**
 * RuleSetsLoaderApi is responsible for creating {@link IRuleSet} instances from provided rule set IDs and paths.
 * It supports lazy loading, meaning the rule set contents are loaded only upon request.
 *
 * This class also manages a cache of metadata rule sets to optimize performance and reduce redundant fetches.
 *
 * The main functionalities include:
 * - Initializing the rule sets loader to prepare it for fetching rule sets.
 * - Fetching checksums of rule sets.
 * - Fetching specific byte ranges of rule sets to minimize memory usage.
 * - Creating new {@link IRuleSet} instances with lazy loading capabilities.
 *
 * @example
 * ```typescript
 * const loader = new RuleSetsLoaderApi('/path/to/rulesets');
 * await loader.initialize();
 * const ruleSet = await loader.createRuleSet('123', filters);
 * ```
 */
class background_RuleSetsLoaderApi {
    /**
     * Database store name.
     */
    static DB_STORE_NAME = 'rulesets';
    /**
     * Combiner for key prefix and rule set id.
     */
    static KEY_COMBINER = '_';
    /**
     * Prefix for checksum key.
     */
    static KEY_PREFIX_CHECKSUM = 'checksum';
    /**
     * Prefix for metadata rule set key.
     */
    static KEY_PREFIX_RULESET_METADATA = 'metadata';
    /**
     * Prefix for lazy metadata rule set key.
     */
    static KEY_PREFIX_RULESET_LAZY_METADATA = 'lazyMetadata';
    /**
     * Prefix for declarative rules key.
     */
    static KEY_PREFIX_RULESET_DECLARATIVE_RULES = 'declarativeRules';
    /**
     * Cache of metadata rule sets.
     */
    static metadataRulesetsCache = {};
    /**
     * Cache for already created rulesets. Needed to avoid multiple loading
     * of the same ruleset.
     */
    static ruleSetsCache;
    /**
     * Path to rule sets cache directory to invalidate it when path changes.
     */
    static ruleSetsCachePath;
    /**
     * Path to rule sets directory.
     */
    ruleSetsPath;
    /**
     * Indicates whether the rule sets loader is initialized.
     */
    isInitialized;
    /**
     * Promise that resolves when the initialization is complete.
     * This helps prevent multiple fetches by ensuring {@link RuleSetsLoaderApi.initialize}
     * is only called once, even if invoked multiple times in quick succession.
     */
    initializerPromise;
    /**
     * Cache of checksums of rule sets.
     */
    static idbChecksumsCache = new Map();
    /**
     * Race condition lock map per ruleSetId.
     */
    syncLocks;
    /**
     * Creates new {@link RuleSetsLoaderApi}.
     *
     * @param ruleSetsPath Path to rule sets directory.
     */
    constructor(ruleSetsPath) {
        this.ruleSetsPath = ruleSetsPath;
        this.isInitialized = false;
        this.syncLocks = new Map();
        if (background_RuleSetsLoaderApi.ruleSetsCachePath !== ruleSetsPath) {
            background_RuleSetsLoaderApi.ruleSetsCachePath = ruleSetsPath;
            background_RuleSetsLoaderApi.ruleSetsCache = new Map();
        }
    }
    /**
     * Returns key with prefix.
     * Key format: <prefix>_<ruleSetId>, e.g. `metadata_123`.
     *
     * @param keyPrefix Key prefix.
     * @param ruleSetId Rule set id.
     *
     * @returns Key with prefix.
     */
    static getKey(keyPrefix, ruleSetId) {
        return `${keyPrefix}${background_RuleSetsLoaderApi.KEY_COMBINER}${ruleSetId}`;
    }
    /**
     * Returns opened database.
     *
     * @param store Database store name.
     *
     * @returns Promise, resolved with opened database.
     */
    static async getOpenedDb(store) {
        return background_IdbSingleton.getOpenedDb(store, () => {
            background_RuleSetsLoaderApi.idbChecksumsCache.clear();
        });
    }
    /**
     * Gets the value from the IDB database.
     *
     * @param key The key to look up.
     *
     * @returns The value associated with the key, or undefined if the key is not found.
     */
    static async getValueFromIdb(key) {
        const db = await background_RuleSetsLoaderApi.getOpenedDb(background_RuleSetsLoaderApi.DB_STORE_NAME);
        const tx = db.transaction(background_RuleSetsLoaderApi.DB_STORE_NAME, 'readonly');
        const store = tx.objectStore(background_RuleSetsLoaderApi.DB_STORE_NAME);
        const value = await store.get(key);
        await tx.done;
        return value;
    }
    /**
     * Gets the checksums of the rule sets.
     *
     * @param ruleSetId Rule set id.
     *
     * @returns Checksums of the rule sets.
     *
     * @throws If the rule sets loader is not initialized or the checksum for the specified rule set is not found.
     */
    async getChecksum(ruleSetId) {
        if (!this.isInitialized) {
            await this.initialize();
        }
        const ruleSetIdWithPrefix = background_declarative_converter_utils_getRuleSetId(ruleSetId);
        return background_RuleSetsLoaderApi.metadataRulesetsCache[this.ruleSetsPath]?.getChecksum(ruleSetIdWithPrefix);
    }
    /**
     * Initializes the rule sets loader.
     * It is needed to be called before any other method, because it loads byte range maps collection,
     * which is used to fetch certain parts of the rule set files instead of the whole files
     * and makes possible to use less memory.
     *
     * @throws Error if the byte range maps collection file is not found or its content is invalid.
     */
    async initialize() {
        if (this.isInitialized) {
            return;
        }
        if (this.initializerPromise) {
            await this.initializerPromise;
            return;
        }
        const initialize = async () => {
            try {
                if (!background_RuleSetsLoaderApi.metadataRulesetsCache[this.ruleSetsPath]) {
                    const metadataRulesetPath = background_getRuleSetPath(background_METADATA_RULESET_ID, this.ruleSetsPath);
                    const rawMetadataRuleset = await (0,background_es/* fetchExtensionResourceText */.tF)(background_browser_polyfill.runtime.getURL(metadataRulesetPath));
                    // eslint-disable-next-line max-len
                    background_RuleSetsLoaderApi.metadataRulesetsCache[this.ruleSetsPath] = background_MetadataRuleSet.deserialize(rawMetadataRuleset);
                }
                this.isInitialized = true;
                this.initializerPromise = undefined;
            }
            catch (error) {
                background_common_logger_logger.error('Failed to initialize RuleSetsLoaderApi. Got error:', background_configuration_getErrorMessage(error));
                throw error;
            }
        };
        this.initializerPromise = initialize();
        await this.initializerPromise;
    }
    /**
     * Synchronizes the rule set with the IDB database.
     * This method ensures that the rule set is up-to-date in the IDB database.
     * If the rule set is not found in the IDB database, it will be added.
     * If the rule set is found but its checksum does not match, it will be updated.
     *
     * @param ruleSetId Rule set id.
     */
    async syncRuleSetWithIdb(ruleSetId) {
        // Use a per-ruleSet lock to avoid parallel syncs
        const existingLock = this.syncLocks.get(ruleSetId);
        if (existingLock) {
            await existingLock;
            return;
        }
        const syncPromise = (async () => {
            try {
                if (!this.isInitialized) {
                    await this.initialize();
                }
                const checksum = await this.getChecksum(ruleSetId);
                if (!checksum) {
                    return;
                }
                let idbChecksum;
                const cacheKey = `${this.ruleSetsPath}_${ruleSetId}`;
                if (background_RuleSetsLoaderApi.idbChecksumsCache.has(cacheKey)) {
                    idbChecksum = background_RuleSetsLoaderApi.idbChecksumsCache.get(cacheKey);
                }
                else {
                    idbChecksum = await background_RuleSetsLoaderApi.getValueFromIdb(background_RuleSetsLoaderApi.getKey(background_RuleSetsLoaderApi.KEY_PREFIX_CHECKSUM, ruleSetId));
                    background_RuleSetsLoaderApi.idbChecksumsCache.set(cacheKey, idbChecksum);
                }
                if (idbChecksum === checksum) {
                    return;
                }
                const ruleSetIdNumber = background_extractRuleSetId(ruleSetId);
                if (!ruleSetIdNumber) {
                    throw new Error(`Invalid rule set id: ${ruleSetId}`);
                }
                // eslint-disable-next-line max-len
                background_common_logger_logger.info(`Syncing rule set with IDB: ${ruleSetId} (previous checksum: ${idbChecksum}, current checksum: ${checksum})`);
                const ruleSetPath = background_getRuleSetPath(ruleSetId, this.ruleSetsPath);
                const rawRuleSet = await (0,background_es/* fetchExtensionResourceText */.tF)(background_browser_polyfill.runtime.getURL(ruleSetPath));
                const parsedRuleSet = JSON.parse(rawRuleSet);
                const { metadata } = parsedRuleSet[0];
                const db = await background_RuleSetsLoaderApi.getOpenedDb(background_RuleSetsLoaderApi.DB_STORE_NAME);
                const tx = db.transaction(background_RuleSetsLoaderApi.DB_STORE_NAME, 'readwrite');
                const store = tx.objectStore(background_RuleSetsLoaderApi.DB_STORE_NAME);
                const puts = [
                    store.put(checksum, background_RuleSetsLoaderApi.getKey(background_RuleSetsLoaderApi.KEY_PREFIX_CHECKSUM, ruleSetId)),
                    store.put(JSON.stringify(metadata.metadata), background_RuleSetsLoaderApi.getKey(background_RuleSetsLoaderApi.KEY_PREFIX_RULESET_METADATA, ruleSetId)),
                    store.put(JSON.stringify(metadata.lazyMetadata), background_RuleSetsLoaderApi.getKey(background_RuleSetsLoaderApi.KEY_PREFIX_RULESET_LAZY_METADATA, ruleSetId)),
                    store.put(JSON.stringify(parsedRuleSet.slice(1)), background_RuleSetsLoaderApi.getKey(background_RuleSetsLoaderApi.KEY_PREFIX_RULESET_DECLARATIVE_RULES, ruleSetId)),
                ];
                await Promise.all(puts);
                await tx.done;
                const { conversionMap, rawFilterList } = metadata;
                const preprocessedFilterList = background_es/* FilterListPreprocessor */.aQ.preprocessLightweight({
                    rawFilterList,
                    conversionMap,
                });
                await background_filters_FiltersStorage.setMultiple({
                    [ruleSetIdNumber]: {
                        ...preprocessedFilterList,
                        checksum,
                    },
                });
                background_common_logger_logger.info(`Synced rule set with IDB: ${ruleSetId}`);
            }
            catch (err) {
                background_common_logger_logger.error(`Failed to sync rule set ${ruleSetId}:`, background_configuration_getErrorMessage(err));
                throw err;
            }
            finally {
                this.syncLocks.delete(ruleSetId);
            }
        })();
        this.syncLocks.set(ruleSetId, syncPromise);
        await syncPromise;
    }
    /**
     * If the rule set with the provided ID is already loaded, it will
     * be returned from the cache. Otherwise, it will create a new {@link IRuleSet}
     * from the provided ID and list of {@link IFilter|filters} with lazy
     * loading of this rule set contents.
     *
     * @param ruleSetId Rule set id.
     * @param filterList List of all available {@link IFilter|filters}.
     *
     * @returns New {@link IRuleSet}.
     *
     * @throws If initialization fails or the rule set with the provided ID is not found or invalid.
     */
    async createRuleSet(ruleSetId, filterList) {
        const ruleSetIdNumber = background_extractRuleSetId(ruleSetId);
        if (ruleSetIdNumber === null) {
            throw new Error(`Invalid rule set id: ${ruleSetId}`);
        }
        const ruleSetCache = background_RuleSetsLoaderApi.ruleSetsCache.get(ruleSetId);
        if (ruleSetCache) {
            return ruleSetCache;
        }
        if (!this.isInitialized) {
            await this.initialize();
        }
        await this.syncRuleSetWithIdb(ruleSetId);
        const rawData = await background_RuleSetsLoaderApi.getValueFromIdb(background_RuleSetsLoaderApi.getKey(background_RuleSetsLoaderApi.KEY_PREFIX_RULESET_METADATA, ruleSetId));
        const loadLazyData = async () => background_RuleSetsLoaderApi.getValueFromIdb(background_RuleSetsLoaderApi.getKey(background_RuleSetsLoaderApi.KEY_PREFIX_RULESET_LAZY_METADATA, ruleSetId));
        const loadDeclarativeRules = () => background_RuleSetsLoaderApi.getValueFromIdb(background_RuleSetsLoaderApi.getKey(background_RuleSetsLoaderApi.KEY_PREFIX_RULESET_DECLARATIVE_RULES, ruleSetId));
        const { data: { regexpRulesCount, unsafeRulesCount, rulesCount, ruleSetHashMapRaw, badFilterRulesRaw, }, ruleSetContentProvider, } = await background_RuleSet.deserialize(ruleSetId, rawData, loadLazyData, loadDeclarativeRules, filterList);
        const sources = background_RulesHashMap.deserializeSources(ruleSetHashMapRaw);
        const ruleSetHashMap = new background_RulesHashMap(sources);
        // We don't need filter id and line index because this
        // indexedRulesWithHash will be used only for matching $badfilter rules.
        const badFilterRules = badFilterRulesRaw
            .map((rawString) => background_IndexedNetworkRuleWithHash.createFromNode(0, 0, background_rule_parser/* RuleParser */.G.parse(rawString)))
            .flat();
        const ruleset = new background_RuleSet(ruleSetId, rulesCount, 
        // it is ok to set 0 since this method is used for static rulesets where unsafe rules are not used
        unsafeRulesCount || 0, regexpRulesCount, ruleSetContentProvider, badFilterRules, ruleSetHashMap);
        if (filterList.some((f) => f.getId() === ruleSetIdNumber)) {
            // We save the rule set in the cache only if its filter is loaded.
            background_RuleSetsLoaderApi.ruleSetsCache.set(ruleSetId, ruleset);
        }
        return ruleset;
    }
}

const background_searchEngineDomains = [
    // Google domains
    // src: https://www.google.com/supported_domains
    'google.com',
    'google.ad',
    'google.ae',
    'google.com.af',
    'google.com.ag',
    'google.al',
    'google.am',
    'google.co.ao',
    'google.com.ar',
    'google.as',
    'google.at',
    'google.com.au',
    'google.az',
    'google.ba',
    'google.com.bd',
    'google.be',
    'google.bf',
    'google.bg',
    'google.com.bh',
    'google.bi',
    'google.bj',
    'google.com.bn',
    'google.com.bo',
    'google.com.br',
    'google.bs',
    'google.bt',
    'google.co.bw',
    'google.by',
    'google.com.bz',
    'google.ca',
    'google.cd',
    'google.cf',
    'google.cg',
    'google.ch',
    'google.ci',
    'google.co.ck',
    'google.cl',
    'google.cm',
    'google.cn',
    'google.com.co',
    'google.co.cr',
    'google.com.cu',
    'google.cv',
    'google.com.cy',
    'google.cz',
    'google.de',
    'google.dj',
    'google.dk',
    'google.dm',
    'google.com.do',
    'google.dz',
    'google.com.ec',
    'google.ee',
    'google.com.eg',
    'google.es',
    'google.com.et',
    'google.fi',
    'google.com.fj',
    'google.fm',
    'google.fr',
    'google.ga',
    'google.ge',
    'google.gg',
    'google.com.gh',
    'google.com.gi',
    'google.gl',
    'google.gm',
    'google.gr',
    'google.com.gt',
    'google.gy',
    'google.com.hk',
    'google.hn',
    'google.hr',
    'google.ht',
    'google.hu',
    'google.co.id',
    'google.ie',
    'google.co.il',
    'google.im',
    'google.co.in',
    'google.iq',
    'google.is',
    'google.it',
    'google.je',
    'google.com.jm',
    'google.jo',
    'google.co.jp',
    'google.co.ke',
    'google.com.kh',
    'google.ki',
    'google.kg',
    'google.co.kr',
    'google.com.kw',
    'google.kz',
    'google.la',
    'google.com.lb',
    'google.li',
    'google.lk',
    'google.co.ls',
    'google.lt',
    'google.lu',
    'google.lv',
    'google.com.ly',
    'google.co.ma',
    'google.md',
    'google.me',
    'google.mg',
    'google.mk',
    'google.ml',
    'google.com.mm',
    'google.mn',
    'google.com.mt',
    'google.mu',
    'google.mv',
    'google.mw',
    'google.com.mx',
    'google.com.my',
    'google.co.mz',
    'google.com.na',
    'google.com.ng',
    'google.com.ni',
    'google.ne',
    'google.nl',
    'google.no',
    'google.com.np',
    'google.nr',
    'google.nu',
    'google.co.nz',
    'google.com.om',
    'google.com.pa',
    'google.com.pe',
    'google.com.pg',
    'google.com.ph',
    'google.com.pk',
    'google.pl',
    'google.pn',
    'google.com.pr',
    'google.ps',
    'google.pt',
    'google.com.py',
    'google.com.qa',
    'google.ro',
    'google.ru',
    'google.rw',
    'google.com.sa',
    'google.com.sb',
    'google.sc',
    'google.se',
    'google.com.sg',
    'google.sh',
    'google.si',
    'google.sk',
    'google.com.sl',
    'google.sn',
    'google.so',
    'google.sm',
    'google.sr',
    'google.st',
    'google.com.sv',
    'google.td',
    'google.tg',
    'google.co.th',
    'google.com.tj',
    'google.tl',
    'google.tm',
    'google.tn',
    'google.to',
    'google.com.tr',
    'google.tt',
    'google.com.tw',
    'google.co.tz',
    'google.com.ua',
    'google.co.ug',
    'google.co.uk',
    'google.com.uy',
    'google.co.uz',
    'google.com.vc',
    'google.co.ve',
    'google.co.vi',
    'google.com.vn',
    'google.vu',
    'google.ws',
    'google.rs',
    'google.co.za',
    'google.co.zm',
    'google.co.zw',
    'google.cat',
    // Yandex domains
    // src: https://serpapi.com/yandex-domains
    'yandex.com',
    'yandex.ru',
    'ya.ru',
    'yandex.by',
    'yandex.kz',
    'yandex.uz',
    'yandex.com.tr',
    'yandex.fr',
    'yandex.az',
    'yandex.com.ge',
    'yandex.com.am',
    'yandex.co.il',
    'yandex.lv',
    'yandex.lt',
    'yandex.ee',
    'yandex.md',
    'yandex.tm',
    'yandex.tj',
    'yandex.eu',
    // Other search engines
    'yahoo.com',
    'bing.com',
    'go.mail.ru',
    'ask.com',
    'aol.com',
    'baidu.com',
    'seznam.cz',
];

/**
 * Reserved stealth rule ids for the DNR.
 */
var background_StealthRuleId;
(function (StealthRuleId) {
    StealthRuleId[StealthRuleId["HideReferrer"] = 1] = "HideReferrer";
    StealthRuleId[StealthRuleId["BlockChromeClientData"] = 2] = "BlockChromeClientData";
    StealthRuleId[StealthRuleId["SendDoNotTrack"] = 3] = "SendDoNotTrack";
    StealthRuleId[StealthRuleId["HideSearchQueries"] = 4] = "HideSearchQueries";
})(background_StealthRuleId || (background_StealthRuleId = {}));
/**
 * Reserved stealth content script ids.
 */
var background_StealthContentScriptId;
(function (StealthContentScriptId) {
    StealthContentScriptId["Gpc"] = "gpc";
    StealthContentScriptId["DocumentReferrer"] = "documentReferrer";
})(background_StealthContentScriptId || (background_StealthContentScriptId = {}));
/**
 * Stealth service module.
 */
class background_StealthService {
    /**
     * Required permissions for the stealth options related to browser settings.
     */
    static REQUIRED_PERMISSIONS = ['privacy'];
    /**
     * Scope of the applied browser setting related to the stealth options.
     * Regular scope means that the setting is applied to the both incognito and regular windows.
     */
    static SETTING_SCOPE = 'regular';
    /**
     * Stealth headers.
     */
    static HEADERS = {
        REFERRER: {
            name: 'Referer',
        },
        X_CLIENT_DATA: {
            name: 'X-Client-Data',
        },
        DO_NOT_TRACK: {
            name: 'DNT',
            value: '1',
        },
        GLOBAL_PRIVACY_CONTROL: {
            name: 'Sec-GPC',
            value: '1',
        },
    };
    /**
     * Types of resources to apply the stealth declarative network rules.
     *
     * @returns Array of resource types.
     */
    static get RESOURCE_TYPES() {
        return [
            chrome.declarativeNetRequest.ResourceType.MAIN_FRAME,
            chrome.declarativeNetRequest.ResourceType.SUB_FRAME,
            chrome.declarativeNetRequest.ResourceType.STYLESHEET,
            chrome.declarativeNetRequest.ResourceType.SCRIPT,
            chrome.declarativeNetRequest.ResourceType.IMAGE,
            chrome.declarativeNetRequest.ResourceType.FONT,
            chrome.declarativeNetRequest.ResourceType.OBJECT,
            chrome.declarativeNetRequest.ResourceType.XMLHTTPREQUEST,
            chrome.declarativeNetRequest.ResourceType.PING,
            chrome.declarativeNetRequest.ResourceType.CSP_REPORT,
            chrome.declarativeNetRequest.ResourceType.MEDIA,
            chrome.declarativeNetRequest.ResourceType.WEBSOCKET,
            chrome.declarativeNetRequest.ResourceType.OTHER,
        ];
    }
    /**
     * Temporary flag that used to identify is stealth allowlist implemented or not.
     * It's used to identify should we check for allowlist rule in order
     * to publish `StealthAllowlistAction` event.
     *
     * TODO: After adding stealth allowlist we should remove it.
     */
    static IS_ALLOWLIST_IMPLEMENTED = false;
    /**
     * Temporary flag that used to identify is stealth `Hide Referrer`
     * and `Hide Search Queries` checkboxes is presented or not.
     *
     * TODO: After reverting that checkboxes we should remove it (AG-34765).
     */
    static IS_REFERRER_CHECKBOX_PRESENT = false;
    /**
     * Applies stealth actions to request headers and publishes filtering log event.
     *
     * @param context Request context.
     */
    static onBeforeSendHeaders(context) {
        const settings = background_index_mv3_appContext.configuration?.settings;
        if (!settings || !settings.stealthModeEnabled) {
            return;
        }
        let stealthActions = background_StealthActions.None;
        const { requestUrl, requestHeaders, matchingResult, tabId, eventId, referrerUrl, contentType, timestamp, requestId, } = context;
        if (!requestHeaders || matchingResult?.documentRule) {
            return;
        }
        /**
         * Regarding stealth rule modifier, stealth options can be disabled on two occasions:
         * - stealth modifier does not have specific values, thus disabling stealth entirely
         * - stealth modifier has specific options to disable.
         */
        matchingResult?.getStealthRule();
        const { blockChromeClientData, sendDoNotTrack, } = settings.stealth;
        const headersToRemove = new Set();
        const headersToAdd = [];
        // Collect applied allowlist rules in a set to only publish
        // one filtering event per applied allowlist rule
        const appliedAllowlistRules = new Set();
        // Removes `X-Client-Data` header if present
        if (blockChromeClientData) {
            matchingResult?.getStealthRule(background_es/* StealthOptionName */._L.XClientData);
            if (background_hasHeaderByName(requestHeaders, background_StealthService.HEADERS.X_CLIENT_DATA.name)) {
                stealthActions |= background_StealthActions.BlockChromeClientData;
                headersToRemove.add(background_StealthService.HEADERS.X_CLIENT_DATA.name.toLowerCase());
            }
        }
        // Adds `Do-Not-Track (DNT)` and `Global-Privacy-Control (Sec-GPC)` headers if not present
        if (sendDoNotTrack) {
            matchingResult?.getStealthRule(background_es/* StealthOptionName */._L.DoNotTrack);
            {
                let headerAdded = false;
                if (!background_hasHeader(requestHeaders, background_StealthService.HEADERS.DO_NOT_TRACK)) {
                    headersToAdd.push(background_StealthService.HEADERS.DO_NOT_TRACK);
                    headerAdded = true;
                }
                if (!background_hasHeader(requestHeaders, background_StealthService.HEADERS.GLOBAL_PRIVACY_CONTROL)) {
                    headersToAdd.push(background_StealthService.HEADERS.GLOBAL_PRIVACY_CONTROL);
                    headerAdded = true;
                }
                if (headerAdded) {
                    stealthActions |= background_StealthActions.SendDoNotTrack;
                }
            }
        }
        // Removing headers
        let newRequestHeaders = requestHeaders;
        if (headersToRemove.size > 0) {
            newRequestHeaders = requestHeaders.filter((header) => {
                return !headersToRemove.has(header.name.toLowerCase());
            });
        }
        // Adding headers
        for (const header of headersToAdd) {
            const foundHeader = background_findHeaderByName(newRequestHeaders, header.name);
            if (foundHeader) {
                foundHeader.value = header.value;
            }
            else {
                newRequestHeaders.push(header);
            }
        }
        background_requestContextStorage.update(requestId, {
            requestHeaders: newRequestHeaders,
        });
        if (appliedAllowlistRules.size > 0) {
            background_defaultFilteringLog.publishEvent({
                type: background_FilteringEventType.StealthAllowlistAction,
                data: {
                    tabId,
                    eventId,
                    rules: Array.from(appliedAllowlistRules).map((rule) => ({
                        filterId: rule.getFilterListId(),
                        ruleIndex: rule.getIndex(),
                        isAllowlist: rule.isAllowlist(),
                        isImportant: rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Important),
                        isDocumentLevel: rule.isDocumentLevelAllowlistRule(),
                        isCsp: rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Csp),
                        isCookie: rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Cookie),
                        advancedModifier: rule.getAdvancedModifierValue(),
                    })),
                    requestUrl,
                    frameUrl: referrerUrl,
                    requestType: contentType,
                    timestamp,
                },
            });
        }
        if (stealthActions > 0) {
            background_defaultFilteringLog.publishEvent({
                type: background_FilteringEventType.StealthAction,
                data: {
                    tabId,
                    eventId,
                    stealthActions,
                },
            });
        }
    }
    /**
     * Applies the stealth options from the settings configuration.
     *
     * @param settingsConfig Settings configuration.
     *
     * @returns Partial stealth configuration with boolean status of applied
     * changes.
     */
    static async applySettings(settingsConfig) {
        const { stealthModeEnabled, stealth, gpcScriptUrl, hideDocumentReferrerScriptUrl, } = settingsConfig;
        // "Syntax sugar" to fit into 120 max characters per line.
        const enabled = stealthModeEnabled;
        const [hideReferrer, blockWebRTC, blockChromeClientData, sendDoNotTrack, hideSearchQueries,] = await Promise.all([
            background_StealthService.setHideReferrer(enabled && stealth.hideReferrer),
            background_StealthService.setDisableWebRTC(enabled && stealth.blockWebRTC),
            background_StealthService.setBlockChromeClientData(enabled && stealth.blockChromeClientData),
            background_StealthService.setSendDoNotTrack(enabled && stealth.sendDoNotTrack, gpcScriptUrl),
            background_StealthService.setHideSearchQueries(enabled && stealth.hideSearchQueries, hideDocumentReferrerScriptUrl),
        ]);
        return {
            hideReferrer,
            blockWebRTC,
            blockChromeClientData,
            sendDoNotTrack,
            hideSearchQueries,
        };
    }
    /**
     * Set the referrer header to be hidden.
     *
     * @param isReferrerHidden Flag that determines if the referrer should be hidden.
     *
     * @returns Promise that resolves with current state of the referrer header.
     */
    static async setHideReferrer(isReferrerHidden) {
        if (!isReferrerHidden) {
            try {
                await background_StealthService.removeSessionRule(background_StealthRuleId.HideReferrer);
                return isReferrerHidden;
            }
            catch (e) {
                // eslint-disable-next-line max-len
                background_common_logger_logger.error('[tswebextension.setHideReferrer]: error on removing the stealth rule "hide-referrer": ', e);
                return !isReferrerHidden;
            }
        }
        try {
            await background_StealthService.setSessionRule({
                id: background_StealthRuleId.HideReferrer,
                action: {
                    type: chrome.declarativeNetRequest.RuleActionType.MODIFY_HEADERS,
                    requestHeaders: [{
                            header: background_StealthService.HEADERS.REFERRER.name,
                            operation: chrome.declarativeNetRequest.HeaderOperation.REMOVE,
                        }],
                },
                condition: {
                    urlFilter: '*',
                    resourceTypes: background_StealthService.RESOURCE_TYPES,
                },
            });
            return isReferrerHidden;
        }
        catch (e) {
            background_common_logger_logger.error('[tswebextension.setHideReferrer]: error on setting the stealth rule $referrer: ', e);
            return !isReferrerHidden;
        }
    }
    /**
     * If {@link isBlockChromeClientData} is true, add the declarative network rule to remove
     * `X-Client-Data` header from every request.
     *
     * @param isBlockChromeClientData Flag that determines if the `X-Client-Data` header is removed.
     *
     * @returns Promise that resolves with current state of the referrer header.
     */
    static async setBlockChromeClientData(isBlockChromeClientData) {
        if (!isBlockChromeClientData) {
            try {
                await background_StealthService.removeSessionRule(background_StealthRuleId.BlockChromeClientData);
                return isBlockChromeClientData;
            }
            catch (e) {
                // eslint-disable-next-line max-len
                background_common_logger_logger.error('[tswebextension.setBlockChromeClientData]: error on removing the stealth rule $xclientdata: ', e);
                return !isBlockChromeClientData;
            }
        }
        try {
            await background_StealthService.setSessionRule({
                id: background_StealthRuleId.BlockChromeClientData,
                action: {
                    type: chrome.declarativeNetRequest.RuleActionType.MODIFY_HEADERS,
                    requestHeaders: [{
                            header: background_StealthService.HEADERS.X_CLIENT_DATA.name,
                            operation: chrome.declarativeNetRequest.HeaderOperation.REMOVE,
                        }],
                },
                condition: {
                    urlFilter: '*',
                    resourceTypes: background_StealthService.RESOURCE_TYPES,
                },
            });
            return isBlockChromeClientData;
        }
        catch (e) {
            // eslint-disable-next-line max-len
            background_common_logger_logger.error('[tswebextension.setBlockChromeClientData]: error on setting the stealth rule $xclientdata: ', e);
            return !isBlockChromeClientData;
        }
    }
    /**
     * If {@link isSendDoNotTrack} is true, add the declarative network rule to set `DNT`
     * and `Sec-GPC` headers for every request.
     *
     * @param isSendDoNotTrack Flag that determines if the `Do Not Track` and `Global Privacy Control` signals is set.
     * @param gpcScriptUrl Path to content script for injecting GPC signal.
     *
     * @returns Promise that resolves with current state of the referrer header.
     */
    static async setSendDoNotTrack(isSendDoNotTrack, gpcScriptUrl) {
        if (!isSendDoNotTrack) {
            try {
                await Promise.all([
                    background_StealthService.removeSessionRule(background_StealthRuleId.SendDoNotTrack),
                    background_StealthService.removeContentScript(background_StealthContentScriptId.Gpc),
                ]);
                return isSendDoNotTrack;
            }
            catch (e) {
                background_common_logger_logger.error('[tswebextension.setSendDoNotTrack]: error on removing the stealth rule $donottrack: ', e);
                return !isSendDoNotTrack;
            }
        }
        try {
            await Promise.all([
                background_StealthService.setSessionRule({
                    id: background_StealthRuleId.SendDoNotTrack,
                    action: {
                        type: chrome.declarativeNetRequest.RuleActionType.MODIFY_HEADERS,
                        requestHeaders: [{
                                header: background_StealthService.HEADERS.DO_NOT_TRACK.name,
                                value: background_StealthService.HEADERS.DO_NOT_TRACK.value,
                                operation: chrome.declarativeNetRequest.HeaderOperation.SET,
                            }, {
                                header: background_StealthService.HEADERS.GLOBAL_PRIVACY_CONTROL.name,
                                value: background_StealthService.HEADERS.GLOBAL_PRIVACY_CONTROL.value,
                                operation: chrome.declarativeNetRequest.HeaderOperation.SET,
                            }],
                    },
                    condition: {
                        urlFilter: '*',
                        resourceTypes: background_StealthService.RESOURCE_TYPES,
                    },
                }),
                background_StealthService.setContentScript({
                    id: background_StealthContentScriptId.Gpc,
                    js: [gpcScriptUrl],
                    world: 'MAIN',
                    runAt: 'document_start',
                    matches: [
                        'http://*/*',
                        'https://*/*',
                    ],
                    persistAcrossSessions: false,
                }),
            ]);
            return isSendDoNotTrack;
        }
        catch (e) {
            background_common_logger_logger.error('[tswebextension.setSendDoNotTrack]: error on setting the stealth rule $donottrack: ', e);
            return !isSendDoNotTrack;
        }
    }
    /**
     * If {@link isHideSearchQueries} is true, adds the declarative network rule to set the
     * `Referrer-Policy` header to `no-referrer` for the search pages like Google, Bing, etc.
     *
     * @param isHideSearchQueries Flag that determines if the search queries should be hidden.
     * @param hideDocumentReferrerScriptUrl Path to content script for hiding the document referrer.
     *
     * @returns Promise that resolves with current state of the referrer header.
     */
    static async setHideSearchQueries(isHideSearchQueries, hideDocumentReferrerScriptUrl) {
        if (!isHideSearchQueries) {
            try {
                await Promise.all([
                    background_StealthService.removeSessionRule(background_StealthRuleId.HideSearchQueries),
                    background_StealthService.removeContentScript(background_StealthContentScriptId.DocumentReferrer),
                ]);
                return isHideSearchQueries;
            }
            catch (e) {
                // eslint-disable-next-line max-len
                background_common_logger_logger.error('[tswebextension.setHideSearchQueries]: error on removing the stealth rule $searchqueries: ', e);
                return !isHideSearchQueries;
            }
        }
        try {
            await Promise.all([
                background_StealthService.setSessionRule({
                    id: background_StealthRuleId.HideSearchQueries,
                    action: {
                        type: chrome.declarativeNetRequest.RuleActionType.MODIFY_HEADERS,
                        requestHeaders: [{
                                header: background_StealthService.HEADERS.REFERRER.name,
                                operation: chrome.declarativeNetRequest.HeaderOperation.REMOVE,
                            }],
                    },
                    condition: {
                        urlFilter: '*',
                        resourceTypes: background_StealthService.RESOURCE_TYPES,
                        initiatorDomains: background_searchEngineDomains,
                    },
                }),
                background_StealthService.setContentScript({
                    id: background_StealthContentScriptId.DocumentReferrer,
                    js: [hideDocumentReferrerScriptUrl],
                    world: 'MAIN',
                    runAt: 'document_start',
                    matches: [
                        'http://*/*',
                        'https://*/*',
                    ],
                    persistAcrossSessions: false,
                }),
            ]);
            return isHideSearchQueries;
        }
        catch (e) {
            // eslint-disable-next-line max-len
            background_common_logger_logger.error('[tswebextension.setHideSearchQueries]: error on setting the stealth rule $searchqueries: ', e);
            return !isHideSearchQueries;
        }
    }
    /**
     * If {@link isWebRTCDisabled} is true, sets the browser IP policy to `disable_non_proxied_udp`,
     * otherwise restore default policy.
     *
     * @param isWebRTCDisabled Flag that determines if the WebRTC should be disabled.
     *
     * @returns Promise that resolves with current state of the referrer header.
     *
     * @throws Error if the permissions are not granted, but required to set the WebRTC policy.
     */
    static async setDisableWebRTC(isWebRTCDisabled) {
        const isPermissionGranted = await chrome.permissions.contains({
            permissions: background_StealthService.REQUIRED_PERMISSIONS,
        });
        if (!isPermissionGranted) {
            // If the option is disabled, do nothing.
            if (!isWebRTCDisabled) {
                return isWebRTCDisabled;
            }
            background_common_logger_logger.error(`Permissions are not granted: ${background_StealthService.REQUIRED_PERMISSIONS.join(', ')}`);
            return !isWebRTCDisabled;
        }
        try {
            const setting = chrome.privacy.network.webRTCIPHandlingPolicy;
            if (isWebRTCDisabled) {
                await background_StealthService.setSetting(setting, chrome.privacy.IPHandlingPolicy.DISABLE_NON_PROXIED_UDP);
            }
            else {
                await background_StealthService.clearSetting(setting);
            }
            return isWebRTCDisabled;
        }
        catch (e) {
            background_common_logger_logger.error('[tswebextension.setDisableWebRTC]: error on setting the WebRTC policy ($webrtc): ', e);
            /**
             * Edge case: If error occurred while applying WebRTC
             * setting, it means that other extension might be
             * blocking it, we should return false as a indicator
             * of that WebRTC can not be enabled.
             */
            return false;
        }
    }
    /**
     * Sets the browser settings value.
     *
     * @param setting Webextension setting API.
     * @param value Setting value to set.
     *
     * @returns Resolves when the setting is set.
     *
     * @throws Error if the setting is not controllable or controlled by other extensions.
     */
    static async setSetting(setting, value) {
        await background_StealthService.validateLevelOfControl(setting);
        return setting.set({ value, scope: background_StealthService.SETTING_SCOPE });
    }
    /**
     * Gets the browser settings value and webextension level of control.
     *
     * @param setting Webextension browser setting API.
     *
     * @returns Resolved promise with the setting value and level of control.
     *
     * @throws Error if something went wrong.
     */
    static async getSetting(setting) {
        // TODO: Check, should we use ChromeSettingGetDetails.incognito flag?
        return setting.get({});
    }
    /**
     * Sets the browser settings value to the default.
     *
     * @param setting Webextension browser setting API.
     *
     * @returns Resolved promise when the setting is cleared.
     *
     * @throws Error if something went wrong.
     */
    static async clearSetting(setting) {
        await background_StealthService.validateLevelOfControl(setting);
        return setting.clear({ scope: background_StealthService.SETTING_SCOPE });
    }
    /**
     * Checks if the setting is controllable.
     *
     * @param setting Webextension browser setting API.
     *
     * @throws Error, if setting is not controllable.
     */
    static async validateLevelOfControl(setting) {
        const { levelOfControl } = await background_StealthService.getSetting(setting);
        if (levelOfControl === 'not_controllable') {
            throw new Error('Setting is not controllable');
        }
        if (levelOfControl === 'controlled_by_other_extensions') {
            throw new Error('Setting is controlled by other extensions');
        }
    }
    /**
     * Set the stealth rule in the session ruleset.
     * If the rule with the same id already exists, it will be replaced.
     *
     * @param rule Stealth rule to set.
     *
     * @returns Resolved promise when the rule is set.
     */
    static async setSessionRule(rule) {
        return chrome.declarativeNetRequest.updateSessionRules({
            addRules: [rule],
            removeRuleIds: [rule.id],
        });
    }
    /**
     * Remove the stealth rule from the session ruleset.
     *
     * @param ruleId Stealth rule id.
     *
     * @returns Resolved promise when the rule is removed.
     */
    static async removeSessionRule(ruleId) {
        return chrome.declarativeNetRequest.updateSessionRules({
            removeRuleIds: [ruleId],
        });
    }
    /**
     * Unregister content script with specified {@link contentScriptId}.
     * If content script is not found, do nothing.
     *
     * @param contentScriptId Content script id.
     */
    static async removeContentScript(contentScriptId) {
        const existedContentScripts = await chrome.scripting.getRegisteredContentScripts({
            ids: [contentScriptId],
        });
        if (existedContentScripts.length > 0) {
            await chrome.scripting.unregisterContentScripts({
                ids: existedContentScripts.map(((script) => script.id)),
            });
        }
    }
    /**
     * Register content script.
     * If content script with {@link contentScript} has already registered, update it.
     *
     * @param contentScript Content script to set.
     */
    static async setContentScript(contentScript) {
        await background_StealthService.removeContentScript(contentScript.id);
        await chrome.scripting.registerContentScripts([contentScript]);
    }
    /**
     * Removes all stealth rules and content scripts.
     */
    static async clearAll() {
        const ruleIds = Object.keys(background_StealthRuleId)
            .map((key) => Number(key))
            .filter((keyNumber) => !Number.isNaN(keyNumber));
        await chrome.declarativeNetRequest.updateSessionRules({ removeRuleIds: ruleIds });
        const contentScriptIds = Object.values(background_StealthContentScriptId);
        contentScriptIds.forEach(async (id) => {
            await background_StealthService.removeContentScript(id);
        });
    }
    /**
     * Is url search engine.
     *
     * @param url Url for check.
     *
     * @returns True if url is search engine.
     */
    static isSearchEngine(url) {
        const domain = background_getDomain(url);
        return background_searchEngineDomains.some((searchEngine) => searchEngine === domain);
    }
}

/**
 * Api for processing request filtering.
 *
 * Method {@link getBlockingResponse} processes rule applying for request and computes response
 * for {@link WebRequestApi.onBeforeRequest} listener.
 *
 * Method {@link shouldCollapseElement} checks, if initializer for request should be collapsed by content-script.
 *
 * This class also provides method {@link isRequestBlockedByRule} for checking, if rule is blocking rule.
 */
class background_RequestBlockingApi {
    /**
     * Checks if request rule is blocked.
     *
     * @param requestRule Request network rule or null.
     *
     * @returns True, if rule is request blocking, else returns false.
     */
    static isRequestBlockedByRule(requestRule) {
        return !!requestRule
            && !requestRule.isAllowlist()
            && !requestRule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Replace)
            && !requestRule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Redirect);
    }
    /**
     * Closes the tab which considered as a popup.
     *
     * @param data Needed data for logging closing of tab.
     * @param appliedRule Network rule which was applied to request. This field
     * is needed because data contains two rules: one for the request and
     * one for the popup. And we should log only the rule which was applied
     * to the request.
     *
     * @returns Response for {@link RequestApi.onBeforeRequest} listener.
     */
    static closeTab(data, appliedRule) {
        background_RequestBlockingApi.logRuleApplying(data, appliedRule);
        background_browser_polyfill.tabs.remove(data.tabId);
        return { cancel: true };
    }
    /**
     * Processes rule applying for request and compute response for {@link WebRequestApi.onBeforeRequest} listener.
     *
     * @param data Data for request processing.
     *
     * @returns Response for {@link WebRequestApi.onBeforeRequest} listener.
     */
    static getBlockingResponse(data) {
        const { rule, popupRule, requestType, tabId, eventId, requestId, requestUrl, contentType, referrerUrl, } = data;
        if (!rule) {
            return undefined;
        }
        // popup rule will be handled in the condition with requestType === document below
        if (popupRule === rule && requestType !== background_request_type/* RequestType */.Y.Document) {
            return undefined;
        }
        if (rule.isAllowlist()) {
            background_RequestBlockingApi.logRuleApplying(data, rule);
            return undefined;
        }
        if (rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Redirect)) {
            background_defaultFilteringLog.publishEvent({
                type: background_FilteringEventType.ApplyBasicRule,
                data: {
                    tabId,
                    eventId,
                    requestType: contentType,
                    frameUrl: referrerUrl,
                    requestId,
                    requestUrl,
                    companyCategoryName: background_companiesDbService.match(requestUrl),
                    filterId: rule.getFilterListId(),
                    ruleIndex: rule.getIndex(),
                    isAllowlist: rule.isAllowlist(),
                    isImportant: rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Important),
                    isDocumentLevel: rule.isDocumentLevelAllowlistRule(),
                    isCsp: rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Csp),
                    isCookie: rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Cookie),
                    advancedModifier: rule.getAdvancedModifierValue(),
                    isAssuredlyBlocked: true,
                },
            });
            // TODO: Check that redirected url exists in our resources as in mv2.
            return { redirectUrl: '' };
        }
        // Basic rules for blocking requests are applied only to sub-requests
        // so `||example.com^` will not block the main page
        // https://adguard.com/kb/general/ad-filtering/create-own-filters/#basic-rules
        // For document requests we need to show blocking page or close tab.
        if (requestType === background_request_type/* RequestType */.Y.Document) {
            // Blocking rule can be with $popup modifier - in this case we need
            // to close the tab as soon as possible.
            // https://adguard.com/kb/general/ad-filtering/create-own-filters/#popup-modifier
            if (popupRule && background_tabsApi.isNewPopupTab(tabId)) {
                return background_RequestBlockingApi.closeTab(data, popupRule);
            }
            // to handle rules with $all modifier, where popup was added implicitly
            if (rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Popup) && background_tabsApi.isNewPopupTab(tabId)) {
                return background_RequestBlockingApi.closeTab(data, rule);
            }
            // we do not want to block the main page if rule has only $popup modifier
            if (rule === popupRule && !background_tabsApi.isNewPopupTab(tabId)) {
                return undefined;
            }
            // but if the blocking rule has $document modifier, blocking page should be shown
            // e.g. `||example.com^$document`
            if ((rule.getPermittedRequestTypes() & background_request_type/* RequestType */.Y.Document) === background_request_type/* RequestType */.Y.Document) {
                background_RequestBlockingApi.logRuleApplying(data, rule);
                return { cancel: true };
            }
            return undefined;
        }
        background_RequestBlockingApi.logRuleApplying(data, rule);
        return { cancel: true };
    }
    /**
     * Creates {@link FilteringLog} event of rule applying for processed request.
     *
     * @param data Data for request processing.
     * @param appliedRule Network rule which was applied to request.
     */
    static logRuleApplying(data, appliedRule) {
        const { tabId, eventId, referrerUrl, requestId, requestUrl, requestType, contentType, } = data;
        if (!appliedRule || requestType === 0) {
            return;
        }
        background_defaultFilteringLog.publishEvent({
            type: background_FilteringEventType.ApplyBasicRule,
            data: {
                tabId,
                eventId,
                requestType: contentType,
                frameUrl: referrerUrl,
                requestId,
                requestUrl,
                filterId: appliedRule.getFilterListId(),
                ruleIndex: appliedRule.getIndex(),
                isAllowlist: appliedRule.isAllowlist(),
                isImportant: appliedRule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Important),
                isDocumentLevel: appliedRule.isDocumentLevelAllowlistRule(),
                isCsp: appliedRule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Csp),
                isCookie: appliedRule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Cookie),
                advancedModifier: appliedRule.getAdvancedModifierValue(),
            },
        });
    }
}

/**
 * Content Security Policy Headers filtering service module.
 */
class background_CspService {
    /**
     * Applies CSP rules to response headers and returns modified headers.
     * It is applied when webRequest.onHeadersReceived event is fired.
     *
     * @param context Request context.
     */
    static onHeadersReceived(context) {
        const { matchingResult, responseHeaders, requestId, tabId, requestUrl, referrerUrl, } = context;
        if (!matchingResult) {
            return;
        }
        const cspHeaders = [];
        const cspRules = matchingResult.getCspRules();
        for (let i = 0; i < cspRules.length; i += 1) {
            const rule = cspRules[i];
            if (rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Header)) {
                const responseHeaderMatch = rule.matchResponseHeaders(responseHeaders);
                if (!responseHeaderMatch || rule.isAllowlist()) {
                    continue;
                }
            }
            // Don't forget: getCspRules returns all $csp rules, we must directly check that the rule is blocking.
            if (background_RequestBlockingApi.isRequestBlockedByRule(rule)) {
                const cspHeaderValue = rule.getAdvancedModifierValue();
                if (cspHeaderValue) {
                    cspHeaders.push({
                        name: background_es/* CSP_HEADER_NAME */.B$,
                        value: cspHeaderValue,
                    });
                }
            }
            background_defaultFilteringLog.publishEvent({
                type: background_FilteringEventType.ApplyCspRule,
                data: {
                    tabId,
                    eventId: background_non_secure_nanoid(),
                    requestUrl,
                    frameUrl: referrerUrl,
                    frameDomain: (0,background_es6/* getDomain */.FB)(referrerUrl),
                    requestType: background_ContentType.Csp,
                    filterId: rule.getFilterListId(),
                    ruleIndex: rule.getIndex(),
                    timestamp: Date.now(),
                    isAllowlist: rule.isAllowlist(),
                    isImportant: rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Important),
                    isDocumentLevel: rule.isDocumentLevelAllowlistRule(),
                    isCsp: rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Csp),
                    isCookie: rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Cookie),
                    advancedModifier: rule.getAdvancedModifierValue(),
                },
            });
        }
        if (cspHeaders.length > 0) {
            background_requestContextStorage.update(requestId, {
                responseHeaders: responseHeaders ? [...responseHeaders, ...cspHeaders] : cspHeaders,
            });
        }
    }
}

/**
 * Permissions Policy service.
 */
class background_PermissionsPolicyService {
    /**
     * Checks if a network rule is sub document rule.
     *
     * @param rule Rule to check.
     *
     * @returns `true` if the rule is sub document rule.
     */
    static isSubDocumentRule(rule) {
        return (rule.getPermittedRequestTypes() & background_request_type/* RequestType */.Y.SubDocument) === background_request_type/* RequestType */.Y.SubDocument;
    }
    /**
     * Applies permissions policy directives to the response headers.
     *
     * @param context Request context.
     */
    static onHeadersReceived(context) {
        const { matchingResult, responseHeaders, requestId, requestType, tabId, requestUrl, referrerUrl, } = context;
        if (!matchingResult) {
            return;
        }
        const permissionsPolicyRules = matchingResult.getPermissionsPolicyRules();
        const permissionsPolicyHeaders = [];
        if (permissionsPolicyRules.length === 0) {
            return;
        }
        // Check if a global allowlist rule is present.
        if (permissionsPolicyRules.some((rule) => rule.isAllowlist()
            && !rule.getAdvancedModifierValue()
            && !background_PermissionsPolicyService.isSubDocumentRule(rule))) {
            return;
        }
        for (let i = 0; i < permissionsPolicyRules.length; i += 1) {
            const rule = permissionsPolicyRules[i];
            // Sub frames can only be affected by a rule where the $subdocument modifier has been set.
            if (background_PermissionsPolicyService.isSubDocumentRule(rule) !== (requestType === background_request_type/* RequestType */.Y.SubDocument)) {
                continue;
            }
            const directives = rule.getAdvancedModifierValue();
            if (directives) {
                if (!rule.isAllowlist()) {
                    permissionsPolicyHeaders.push({
                        name: background_es/* PERMISSIONS_POLICY_HEADER_NAME */.iw,
                        value: directives,
                    });
                }
                background_defaultFilteringLog.publishEvent({
                    type: background_FilteringEventType.ApplyPermissionsRule,
                    data: {
                        tabId,
                        // for proper filtering log request info rule displaying
                        // event id should be unique for each event, not copied from request
                        // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2341
                        eventId: background_non_secure_nanoid(),
                        requestUrl,
                        frameUrl: referrerUrl,
                        frameDomain: (0,background_es6/* getDomain */.FB)(referrerUrl),
                        requestType: background_ContentType.PermissionsPolicy,
                        filterId: rule.getFilterListId(),
                        ruleIndex: rule.getIndex(),
                        timestamp: Date.now(),
                        isAllowlist: rule.isAllowlist(),
                        isImportant: rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Important),
                        isDocumentLevel: rule.isDocumentLevelAllowlistRule(),
                        isCsp: rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Csp),
                        isCookie: rule.isOptionEnabled(background_es/* NetworkRuleOption */.iR.Cookie),
                        advancedModifier: rule.getAdvancedModifierValue(),
                    },
                });
            }
        }
        background_requestContextStorage.update(requestId, {
            responseHeaders: responseHeaders ? [
                ...responseHeaders,
                ...permissionsPolicyHeaders,
            ] : permissionsPolicyHeaders,
        });
    }
}

/**
 * @file
 * API for applying rules from background service
 * by handling web Request API and web navigation events.
 *
 * This scheme describes flow for MV3.
 *
 * Event data is aggregated into two contexts: {@link RequestContext},
 * which contains data about the specified request
 * and {@link TabContext} which contains data about the specified tab and frames inside it.
 *
 * Applying {@link NetworkRule} from the background page:
 *
 * The cssText, scriptText, scriptletDataList for specified frame are calculated and stored in tab context storage,
 * at the time {@link RequestEvents.onBeforeRequest} or {@link WebNavigation.onBeforeNavigate} is processed.
 * In the most cases the onBeforeNavigate event is processed before onBeforeRequest.
 *
 * At {@link RequestEvents.onBeforeSendHeaders}, the request headers will be parsed to apply $cookie rules
 * based on the {@link MatchingResult} stored in {@link requestContextStorage}.
 * At {@link RequestEvents.onHeadersReceived}, the response headers are handled in the same way.
 *
 * At {@link RequestEvents.onErrorOccurred}, the blocked request url will be matched by {@link companiesDbService}
 * for collecting precise statistics of blocked requests.
 *
 * The specified {@link RequestContext} or frame context {@link Frame} will be removed from the storage
 * on {@link WebNavigation.onCommitted} after injection or {@link RequestEvents.onErrorOccurred} events.
 *
 *
 * Web Request API Event Handling:
 *
 *                                       ┌─────────────────────────────┐
 * Matches {@link MatchingResult}        │                             │
 * for the request.                      │       onBeforeRequest       ◄─┐
 * If this is a frame request,           │                             │ │
 * also matches the                      └──────────────┬──────────────┘ │
 * {@link CosmeticResult}                               │                │
 *                                                      │                │
 *                                                      │                │
 *                                       ┌──────────────▼──────────────┐ │
 * Parses request headers and applies    │                             │ │
 * $cookie rules based on                │      onBeforeSendHeaders    ◄─┼─┐
 * {@link MatchingResult}.               │                             │ │ │
 *                                       └──────────────┬──────────────┘ │ │
 *                                                      │                │ │
 *                                       ┌──────────────▼──────────────┐ │ │
 *                                       │                             │ │ │
 *                                       │        onSendHeaders        │ │ │
 *                                       │                             │ │ │
 *                                       └──────────────┬──────────────┘ │ │
 *                                                      │                │ │
 *                                       ┌──────────────▼──────────────┐ │ │
 * Parses response headers and applies   │                             │ │ │
 * $cookie rules based on              ┌─┤      onHeadersReceived      │ │ │
 * {@link MatchingResult}.             │ │                             │ │ │
 *                                     │ └─────────────────────────────┘ │ │
 *                                     │                                 │ │
 *                                     │ ┌─────────────────────────────┐ │ │
 *                                     │ │                             │ │ │
 *                                     ├─►       onBeforeRedirect      ├─┘ │
 *                                     │ │                             │   │
 *                                     │ └─────────────────────────────┘   │
 *                                     │                                   │
 *                                     │ ┌─────────────────────────────┐   │
 *                                     │ │                             │   │
 *                                     ├─►        onAuthRequired       ├───┘
 *                                     │ │                             │
 *                                     │ └─────────────────────────────┘
 *                                     │
 *   On response started               │ ┌─────────────────────────────┐
 *   We try to inject js               │ │                             │
 *                                     └─►      onResponseStarted      │
 *                                       │                             │
 *                                       └──────────────┬──────────────┘
 *                                                      │
 *                                       ┌──────────────▼──────────────┐
 *                                       │                             │
 * Removes the request information       │         onCompleted         │
 * from {@link requestContextStorage}.   │                             │
 *                                       └─────────────────────────────┘.
 *
 *                                       ┌─────────────────────────────┐
 * Matches blocked request url           │                             │
 * by {@link companiesDbService}         │                             │
 * for collecting statistics.            │       onErrorOccurred       │
 * Also removes the request information  │                             │
 * from {@link requestContextStorage}.   │                             │
 *                                       └─────────────────────────────┘.
 *
 *
 * Web Navigation API Event Handling:
 *
 *                                       ┌─────────────────────────────┐
 *                                       │                             │
 *                                       │  onCreatedNavigationTarget  │
 *                                       │                             │
 *                                       └──────────────┬──────────────┘
 *                                                      │
 *                                       ┌──────────────▼──────────────┐
 * Update main frame data with           │                             │
 * {@link updateMainFrameData}           │       onBeforeNavigate      │
 * and matches {@link CosmeticResult}.   │                             │
 *                                       └──────────────┬──────────────┘
 *                                                      │
 *                                       ┌──────────────▼──────────────┐
 * Try injecting js and css              │                             │
 * into the frame with source            │         onCommitted         │
 * based on {@link CosmeticRule}.        │                             │
 * and remove data from the              └──────────────┬──────────────┘
 * {@link RequestContextStorage}                        │
 *                                       ┌──────────────▼──────────────┐
 *                                       │                             │
 *                                       │      onDOMContentLoaded     ├─┐
 *                                       │                             │ │
 *                                       └──────────────┬──────────────┘ │
 *                                                      │                │
 *                                       ┌──────────────▼──────────────┐ │
 * Remove the frame data                 │                             │ │
 * from {@link TabContext}.            ┌─┤         onCompleted         │ │
 *                                     │ │                             │ │
 *                                     │ └─────────────────────────────┘ │
 *                                     │                                 │
 *                                     │ ┌─────────────────────────────┐ │
 *                                     │ │                             │ │
 *                                     ├─►    onHistoryStateUpdated    ◄─┤
 *                                     │ │                             │ │
 *                                     │ └─────────────────────────────┘ │
 *                                     │                                 │
 *                                     │ ┌─────────────────────────────┐ │
 *                                     │ │                             │ │
 *                                     └─►  onReferenceFragmentUpdated ◄─┘
 *                                       │                             │
 *                                       └─────────────────────────────┘.
 *
 *                                       ┌─────────────────────────────┐
 * Remove the frame data                 │                             │
 * from {@link TabContext}.              │       onErrorOccurred       │
 *                                       │                             │
 *                                       └─────────────────────────────┘.
 */
/**
 * API for applying rules from background service by handling
 * Web Request API and web navigation events.
 */
class background_WebRequestApi {
    /**
     * Adds listeners to web request events.
     */
    static start() {
        // browser.webRequest Events
        background_RequestEvents.onBeforeRequest.addListener(background_WebRequestApi.onBeforeRequest);
        background_RequestEvents.onResponseStarted.addListener(background_WebRequestApi.onResponseStarted);
        background_RequestEvents.onBeforeSendHeaders.addListener(background_WebRequestApi.onBeforeSendHeaders);
        background_RequestEvents.onHeadersReceived.addListener(background_WebRequestApi.onHeadersReceived);
        background_RequestEvents.onErrorOccurred.addListener(background_WebRequestApi.onErrorOccurred);
        background_RequestEvents.onCompleted.addListener(background_WebRequestApi.onCompleted);
        // browser.webNavigation Events
        // 'chrome' is used here because MV3 is mainly for Chrome,
        // and it provides better types compared to 'browser' from webextension-polyfill.
        chrome.webNavigation.onBeforeNavigate.addListener(background_WebRequestApi.onBeforeNavigate);
        chrome.webNavigation.onCommitted.addListener(background_WebRequestApi.onCommitted);
        background_browser_polyfill.webNavigation.onErrorOccurred.addListener(background_WebRequestApi.deleteFrameContext);
        background_browser_polyfill.webNavigation.onCompleted.addListener(background_WebRequestApi.deleteFrameContext);
    }
    /**
     * Removes web request event handlers.
     */
    static stop() {
        // browser.webRequest Events
        background_RequestEvents.onBeforeRequest.removeListener(background_WebRequestApi.onBeforeRequest);
        background_RequestEvents.onResponseStarted.removeListener(background_WebRequestApi.onResponseStarted);
        background_RequestEvents.onBeforeSendHeaders.removeListener(background_WebRequestApi.onBeforeSendHeaders);
        background_RequestEvents.onHeadersReceived.removeListener(background_WebRequestApi.onHeadersReceived);
        background_RequestEvents.onErrorOccurred.removeListener(background_WebRequestApi.onErrorOccurred);
        background_RequestEvents.onCompleted.removeListener(background_WebRequestApi.onCompleted);
        // browser.webNavigation Events
        chrome.webNavigation.onBeforeNavigate.removeListener(background_WebRequestApi.onBeforeNavigate);
        chrome.webNavigation.onCommitted.removeListener(background_WebRequestApi.onCommitted);
        background_browser_polyfill.webNavigation.onErrorOccurred.removeListener(background_WebRequestApi.deleteFrameContext);
        background_browser_polyfill.webNavigation.onCompleted.removeListener(background_WebRequestApi.deleteFrameContext);
    }
    /**
     * Flush browser in-memory cache.
     *
     * This function is called after an engine update or filtering switch to ensure
     * that new rules are applied to requests that may have been cached by the browser.
     */
    static async flushMemoryCache() {
        try {
            await background_browser_polyfill.webRequest.handlerBehaviorChanged();
        }
        catch (e) {
            const errorMessage = background_configuration_getErrorMessage(e);
            throw new Error(`Cannot flush memory cache and call browser.handlerBehaviorChanged: ${errorMessage}`);
        }
    }
    /**
     * On before request event handler. This is the earliest event in the chain of the web request events.
     *
     * @param requestData Object containing request context and details.
     * @param requestData.context Request context.
     * @param requestData.details Event details.
     */
    static onBeforeRequest({ context, details }) {
        if (!context) {
            return;
        }
        // TODO: In getBlockingResponse we need extract requestType from context
        // to save it for filtering log. Check, if we really need this in MV3.
        const { requestType, requestUrl, referrerUrl, requestId, method, tabId, frameId, eventId, contentType, timestamp, thirdParty, } = context;
        if (!background_isHttpOrWsRequest(requestUrl)) {
            return;
        }
        /**
         * We use here referrerUrl as frameUrl for all type of requests, because
         * we have pre-process for this in {@link RequestEvents.handleOnBeforeRequest},
         * where we can set `referrerUrl` to `requestUrl` for prerender requests.
         */
        const frameUrl = referrerUrl;
        background_defaultFilteringLog.publishEvent({
            type: background_FilteringEventType.SendRequest,
            data: {
                tabId,
                eventId,
                requestUrl,
                requestDomain: background_getDomain(requestUrl),
                frameUrl,
                frameDomain: background_getDomain(referrerUrl),
                requestType: contentType,
                timestamp,
                requestThirdParty: thirdParty,
                method,
            },
        });
        let frameRule;
        /**
         * For Document and Subdocument requests, we match frame, because
         * these requests are first (in page lifecycle), but for other requests
         * we get the frame rule from tabsApi, assuming the frame rule is
         * already in the tab context.
         */
        if (requestType === background_request_type/* RequestType */.Y.Document || requestType === background_request_type/* RequestType */.Y.SubDocument) {
            frameRule = background_DocumentApi.matchFrame(frameUrl);
        }
        else {
            frameRule = background_tabsApi.getTabFrameRule(tabId);
        }
        const matchingResult = background_engineApi.matchRequest({
            requestUrl,
            frameUrl,
            requestType,
            frameRule,
            method,
        });
        if (!matchingResult) {
            return;
        }
        // Save matching result to the request context.
        background_requestContextStorage.update(requestId, { matchingResult });
        if (requestType === background_request_type/* RequestType */.Y.Document || requestType === background_request_type/* RequestType */.Y.SubDocument) {
            const { parentFrameId } = details;
            background_CosmeticFrameProcessor.precalculateCosmetics({
                tabId,
                frameId,
                parentFrameId,
                url: requestUrl,
                timeStamp: timestamp,
            });
        }
        const response = background_RequestBlockingApi.getBlockingResponse({
            rule: matchingResult.getBasicResult(),
            popupRule: matchingResult.getPopupRule(),
            eventId,
            requestId,
            requestUrl,
            referrerUrl,
            requestType,
            contentType,
            tabId,
        });
        // redirects should be considered as blocked for the tab blocked request count
        // which is displayed on the extension badge
        // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2443
        if (response?.cancel || response?.redirectUrl !== undefined) {
            background_tabsApi.incrementTabBlockedRequestCount(tabId, referrerUrl);
        }
    }
    /**
     * On response started event handler.
     *
     * @param event On response started event.
     * @param event.context Event context.
     * @param event.details Event details.
     */
    static onResponseStarted({ context, details }) {
        if (!context) {
            return;
        }
        const { requestType, tabId, frameId } = context;
        if (requestType !== background_request_type/* RequestType */.Y.Document
            && requestType !== background_request_type/* RequestType */.Y.SubDocument) {
            return;
        }
        if (background_WebRequestApi.isAssistantFrame(tabId, details)) {
            background_common_logger_logger.debug(`Assistant frame detected, skipping cosmetics injection for tabId ${tabId} and frameId: ${frameId}`);
            return;
        }
        background_CosmeticApi.applyJsFuncsByTabAndFrame(tabId, frameId);
        background_CosmeticApi.applyScriptletsByTabAndFrame(tabId, frameId);
    }
    /**
     * On before send headers event handler.
     *
     * @param details On before send headers details.
     * @param details.context Details context.
     */
    static onBeforeSendHeaders({ context }) {
        if (!context) {
            return;
        }
        const { referrerUrl, tabId, } = context;
        /**
         * TODO: Remove Cookie header from requests initiated by the background
         * extension via Declarative Net Request to implement SanitizeApi
         * functionality from MV2.
         */
        if (tabId === background_constants_BACKGROUND_TAB_ID && background_isExtensionUrl(referrerUrl)) {
            return;
        }
        // If the current request does not comply with any rules - we do not
        // need to call any other processing services (e.g. cookie, header)
        if (context?.matchingResult) {
            background_cookieFiltering.onBeforeSendHeaders(context);
        }
        background_StealthService.onBeforeSendHeaders(context);
    }
    /**
     * On headers received event handler.
     *
     * @param event On headers received event.
     * @param event.context Event context.
     * @param event.details On headers received details.
     */
    static onHeadersReceived({ context, details, }) {
        if (!context) {
            return;
        }
        background_defaultFilteringLog.publishEvent({
            type: background_FilteringEventType.ReceiveResponse,
            data: {
                tabId: context.tabId,
                // It's important to use same eventId as onBeforeRequest to match
                // the request in the filtering log and update it's status.
                eventId: context.eventId,
                statusCode: details.statusCode,
            },
        });
        const { requestUrl, requestType } = context;
        if (requestUrl && (requestType === background_request_type/* RequestType */.Y.Document || requestType === background_request_type/* RequestType */.Y.SubDocument)) {
            background_CspService.onHeadersReceived(context);
            background_PermissionsPolicyService.onHeadersReceived(context);
        }
        background_cookieFiltering.onHeadersReceived(context);
    }
    /**
     * On before navigate web navigation event handler.
     *
     * @param details Event details.
     */
    static onBeforeNavigate(details) {
        const { tabId, frameId, parentFrameId, url, parentDocumentId, timeStamp, } = details;
        background_CosmeticFrameProcessor.precalculateCosmetics({
            tabId,
            frameId,
            parentFrameId,
            url,
            timeStamp,
            parentDocumentId,
        });
    }
    /**
     * Event handler for onErrorOccurred event. It fires when an error occurs, e.g. request is blocked.
     * So if the request is blocked by DNR rule,
     * we should log this event for collecting statistics due to {@link companiesDbService}.
     *
     * @param event On error occurred event.
     * @param event.details On error occurred event details.
     */
    static onErrorOccurred({ details, }) {
        const { tabId, requestId, url, parentFrameId, error, } = details;
        /**
         * Error related to request blocking by DNR rule.
         */
        const CLIENT_BLOCKED_ERROR = 'net::ERR_BLOCKED_BY_CLIENT';
        // filter out non-related errors, e.g. 'net::ERR_ABORTED'
        if (error !== CLIENT_BLOCKED_ERROR) {
            return;
        }
        const context = background_requestContextStorage.get(requestId);
        if (!context) {
            return;
        }
        const { eventId, referrerUrl, contentType, } = context;
        // TODO: we consider that only we block requests,
        // so we do not care (for now) if the request is blocked by other browser extension.
        // it may be handled by checking the matchingResult in the context.
        const companyCategoryName = background_companiesDbService.match(url);
        background_defaultFilteringLog.publishEvent({
            type: background_FilteringEventType.ApplyBasicRule,
            data: {
                tabId,
                eventId,
                requestType: contentType,
                frameUrl: referrerUrl,
                requestId,
                requestUrl: url,
                companyCategoryName,
                filterId: null,
                ruleIndex: null,
                isAllowlist: false,
                isImportant: false,
                isDocumentLevel: background_TabsApiCommon.isDocumentLevelFrame(parentFrameId),
                isCsp: false,
                isCookie: false,
                advancedModifier: null,
                isAssuredlyBlocked: true,
            },
        });
        background_WebRequestApi.deleteRequestContext(details.requestId);
    }
    /**
     * Handler for the last event in the request lifecycle.
     *
     * @param event The event that occurred upon completion of the request.
     * @param event.context The context of the completed event.
     */
    static onCompleted({ context, }) {
        if (!context) {
            return;
        }
        const { tabId, frameId, requestUrl, requestType, contentType, timestamp, } = context;
        if (requestType === background_request_type/* RequestType */.Y.Document || requestType === background_request_type/* RequestType */.Y.SubDocument) {
            const frameContext = background_tabsApi.getFrameContext(tabId, frameId);
            if (!frameContext?.cosmeticResult) {
                // eslint-disable-next-line max-len
                background_common_logger_logger.debug(`[RequestEvents.onCompleted]: cannot log script rules due to not having cosmetic result for tabId: ${tabId}, frameId: ${frameId}.`);
                return;
            }
            background_CosmeticApi.logScriptRules({
                tabId,
                cosmeticResult: frameContext.cosmeticResult,
                url: requestUrl,
                contentType,
                timestamp,
            });
        }
        background_WebRequestApi.deleteRequestContext(context.requestId);
    }
    /**
     * Deletes the request context immediately or after a timeout,
     * depending on whether declarativeFilteringLog is listening.
     *
     * @param requestId The ID of the request.
     */
    static deleteRequestContext(requestId) {
        // If declarativeFilteringLog is listening, wait for a specified timeout
        // before deleting the request context to extract the context event ID,
        // allowing the request to be linked with the matched declarative rule.
        if (background_declarativeFilteringLog.isListening) {
            setTimeout(() => {
                background_requestContextStorage.delete(requestId);
            }, background_FRAME_DELETION_TIMEOUT_MS);
        }
        else {
            background_requestContextStorage.delete(requestId);
        }
    }
    /**
     * Delete frame data from tab context when navigation is finished.
     *
     * @param details Navigation event details.
     */
    static deleteFrameContext(details) {
        const { tabId, frameId } = details;
        setTimeout(() => {
            background_tabsApi.deleteFrameContext(tabId, frameId, background_FRAME_DELETION_TIMEOUT_MS);
        }, background_FRAME_DELETION_TIMEOUT_MS);
    }
    /**
     * On WebNavigation.onCommitted event we will try to inject scripts into tab.
     *
     * @param details Navigation event details.
     */
    static onCommitted(details) {
        const { tabId, frameId, documentId } = details;
        // This is necessary mainly to update documentId
        background_tabsApi.updateFrameContext(tabId, frameId, { documentId });
        if (background_WebRequestApi.isAssistantFrame(tabId, details)) {
            background_common_logger_logger.debug(`Assistant frame detected, skipping cosmetics injection for tabId ${tabId} and frameId: ${frameId}`);
            return;
        }
        // Note: this is an async function, but we will not await it because
        // events do not support async listeners.
        Promise.all([
            background_CosmeticApi.applyJsFuncsByTabAndFrame(tabId, frameId),
            background_CosmeticApi.applyCssByTabAndFrame(tabId, frameId),
            background_CosmeticApi.applyScriptletsByTabAndFrame(tabId, frameId),
        ]).catch((e) => background_common_logger_logger.error(e));
    }
    /**
     * Checks whether the frame is an assistant frame.
     *
     * Needed to prevent cosmetic rules injection into the assistant frame.
     *
     * @param tabId Tab id.
     * @param details Event details.
     *
     * @returns True if the frame is an assistant frame, false otherwise.
     */
    static isAssistantFrame(tabId, details) {
        const tabContext = background_tabsApi.getTabContext(tabId);
        return background_CommonAssistant.isAssistantFrame(details, tabContext);
    }
}

/**
 * The TsWebExtension class is a facade for working with the Chrome
 * declarativeNetRequest module: enabling/disabling static filters,
 * adding/editing/deleting custom filters or custom rules,
 * starting/stopping declarative filtering log.
 */
class background_TsWebExtension {
    /**
     * Fires on filtering log event.
     */
    onFilteringLogEvent = background_defaultFilteringLog.onLogEvent;
    /**
     * Fires when a rule has been created from the helper.
     */
    onAssistantCreateRule = background_Assistant.onCreateRule;
    /**
     * This is where the configuration is stored, excluding "heavy" fields:
     * the contents of filters, custom rules and the allowlist.
     *
     * @returns Configuration context.
     */
    // eslint-disable-next-line class-methods-use-this
    get configuration() {
        return background_index_mv3_appContext.configuration;
    }
    /**
     * Sets app configuration context.
     *
     * @param value Status value.
     */
    // eslint-disable-next-line class-methods-use-this
    set configuration(value) {
        background_index_mv3_appContext.configuration = value;
    }
    /**
     * Whether filtering is enabled or not.
     */
    isStarted = false;
    /**
     * Stores the initialize promise to prevent multiple initialize calls when
     * a large number of messages are received when the service worker
     * starts or wakes up.
     */
    startPromise;
    /**
     * Web accessible resources path in the result bundle
     * relative to the root dir. Should start with leading slash '/'.
     */
    webAccessibleResourcesPath;
    /**
     * Creates new {@link TsWebExtension} class.
     *
     * @see {@link TsWebExtension.webAccessibleResourcesPath} for details.
     *
     * @param webAccessibleResourcesPath Path to resources.
     */
    constructor(webAccessibleResourcesPath) {
        this.webAccessibleResourcesPath = webAccessibleResourcesPath;
    }
    /**
     * Starts the configuration process, keeping the promise to prevent multiple
     * initialize calls, and executes scripts after configuration.
     *
     * @param config {@link ConfigurationMV3} Configuration object which contains all
     * needed information to start.
     *
     * @returns Promise resolved with result of configuration
     * {@link ConfigurationResult}.
     */
    async innerStart(config) {
        background_common_logger_logger.debug('[tswebextension.innerStart]: start');
        if (!background_index_mv3_appContext.startTimeMs) {
            background_index_mv3_appContext.startTimeMs = Date.now();
        }
        try {
            const res = await this.configure(config);
            // Start listening for request events.
            background_RequestEvents.init();
            // Start handle request events.
            background_WebRequestApi.start();
            // Start handle onRuleMatchedDebug event.
            background_declarativeFilteringLog.start();
            // Add tabs listeners
            await background_tabsApi.start();
            // Compute and save matching result for tabs, opened before app initialization.
            await background_TabsCosmeticInjector.processOpenTabs();
            // Do it only once on first start, because path to assistantUrl can
            // not be changed during runtime.
            background_Assistant.setAssistantUrl(config.settings.assistantUrl);
            background_index_mv3_appContext.isAppStarted = true;
            this.isStarted = true;
            this.startPromise = undefined;
            background_common_logger_logger.debug('[tswebextension.innerStart]: started');
            return res;
        }
        catch (e) {
            this.startPromise = undefined;
            background_common_logger_logger.debug('[tswebextension.innerStart]: failed due to ', background_configuration_getErrorMessage(e));
            throw new Error('Cannot be started: ', { cause: e });
        }
    }
    /**
     * Synchronize rule set with IDB.
     *
     * @param ruleSetId Rule set identifier.
     * @param ruleSetsPath Path to rule sets.
     */
    static async syncRuleSetWithIdb(ruleSetId, ruleSetsPath) {
        const ruleSetsLoaderApi = new background_RuleSetsLoaderApi(ruleSetsPath);
        await ruleSetsLoaderApi.syncRuleSetWithIdb(String(ruleSetId));
    }
    /**
     * Starts filtering along with launching the tab listener, which will record
     * tab urls to work correctly with domain blocking/allowing rules, for
     * example: cosmetic rules in iframes.
     *
     * @param config {@link ConfigurationMV3} Configuration object to start with.
     *
     * @returns Promise resolved with result of configuration {@link ConfigurationResult}.
     */
    async start(config) {
        // Update log level before first log message.
        background_TsWebExtension.updateLogLevel(config.logLevel);
        background_common_logger_logger.debug('[tswebextension.start]: is started ', this.isStarted);
        if (this.isStarted) {
            throw new Error('Already started');
        }
        if (this.startPromise) {
            background_common_logger_logger.debug('[tswebextension.start]: already called start, waiting');
            const res = await this.startPromise;
            background_common_logger_logger.debug('[tswebextension.start]: awaited start');
            return res;
        }
        // Call and wait for promise for allow multiple calling start
        this.startPromise = this.innerStart(config);
        return this.startPromise;
    }
    /**
     * Removes all static and dynamic DNR rules and stops tsurlfilter engine.
     */
    static async removeAllFilteringRules() {
        await background_DynamicRulesApi.removeAllRules();
        const disableFiltersIds = await background_FiltersApi.getEnabledRuleSets();
        await background_FiltersApi.updateFiltering(disableFiltersIds);
        await background_StealthService.clearAll();
        background_declarativeFilteringLog.startUpdate();
        background_declarativeFilteringLog.finishUpdate([], false);
        background_engineApi.stopEngine();
    }
    /**
     * Stops service, disables all user rules and filters.
     */
    async stop() {
        // Stop handle onRuleMatchedDebug event.
        // It should be stopped before removing rules,
        // otherwise, it may try to log applying of removed rules. AG-36068.
        background_declarativeFilteringLog.stop();
        await background_TsWebExtension.removeAllFilteringRules();
        // Stop handle request events.
        background_WebRequestApi.stop();
        // Stop handle request events.
        background_WebRequestApi.stop();
        // Remove tabs listeners and clear context storage
        background_tabsApi.stop();
        background_index_mv3_appContext.isAppStarted = false;
        this.isStarted = false;
    }
    /**
     * Applies new configuration: enables/disables static filters, creates rule
     * sets from provided filters, updates dynamic filters (converts custom
     * filters and user rules on the fly to a single merged rule set), starts
     * declarative filtering log and restarts the engine to reload cosmetic
     * rules.
     *
     * @param config A {@link ConfigurationMV3} to apply.
     *
     * @returns ConfigurationResult {@link ConfigurationResult} which contains:
     * - list of errors for static filters, if any of them has been thrown
     * - converted dynamic rule set with rule set, errors and limitations.
     * Details: {@link ConversionResult}.
     *
     * @throws Error if the filter content is not provided and not already set in the class instance.
     */
    async configure(config) {
        const loader = new background_RuleSetsLoaderApi(config.ruleSetsPath);
        await Promise.all(config.staticFiltersIds.map((staticFilterId) => loader.syncRuleSetWithIdb(String(staticFilterId))));
        // Update log level before first log message.
        background_TsWebExtension.updateLogLevel(config.logLevel);
        // Exclude binary fields from logged config.
        const binaryFields = ['userrules', 'sourceMap', 'rawFilterList', 'filterList', 'conversionMap'];
        background_common_logger_logger.debug('[tswebextension.configure]: start with ', background_stringifyObjectWithoutKeys(config, binaryFields));
        const configuration = background_configurationMV3Validator.parse(config);
        const res = {
            staticFiltersStatus: {
                errors: [],
            },
            staticFilters: [],
        };
        if (configuration.settings.filteringEnabled) {
            background_declarativeFilteringLog.startUpdate();
            res.stealthResult = await background_StealthService.applySettings(configuration.settings);
            // Extract filters info from configuration and wrap them into IFilters.
            const { staticFilters, customFilters, filtersIdsToEnable, filtersIdsToDisable, } = await background_TsWebExtension.getFiltersUpdateInfo(configuration, background_FiltersApi.loadFilterContent);
            // Update list of enabled static filters
            res.staticFiltersStatus = await background_FiltersApi.updateFiltering(filtersIdsToDisable, filtersIdsToEnable);
            // Create static rulesets.
            const staticRuleSets = await background_TsWebExtension.loadStaticRuleSets(configuration.ruleSetsPath, staticFilters);
            // Get enabled static rule sets
            const enabledRuleSetsIds = await background_browser_polyfill.declarativeNetRequest.getEnabledRulesets();
            const enabledStaticRuleSets = staticRuleSets.filter((ruleSet) => {
                const ruleSetId = ruleSet.getId();
                return enabledRuleSetsIds.includes(ruleSetId);
            });
            // Update allowlist settings.
            background_allowlistApi.configure(configuration);
            // Combine all allowlist rules into one network rule.
            const combinedAllowlistRules = background_allowlistApi.combineAllowListRulesForDNR();
            const userRulesFilter = new background_Filter(background_USER_FILTER_ID, { getContent: () => Promise.resolve(configuration.userrules) }, true);
            const allowlistFilter = new background_Filter(background_ALLOWLIST_FILTER_ID, 
            // TODO: Generate AST directly for allowlist rules.
            { getContent: () => Promise.resolve(background_es/* FilterListPreprocessor */.aQ.preprocess(combinedAllowlistRules)) }, true);
            const quickFixesFilter = new background_Filter(background_QUICK_FIXES_FILTER_ID, { getContent: () => Promise.resolve(configuration.quickFixesRules) }, true);
            // Convert quick fixes rules, allowlist, custom filters and user
            // rules into one rule set and apply it.
            res.dynamicRules = await background_DynamicRulesApi.updateDynamicFiltering(quickFixesFilter, allowlistFilter, userRulesFilter, customFilters, enabledStaticRuleSets, this.webAccessibleResourcesPath);
            // Reload engine for cosmetic rules
            background_engineApi.waitingForEngine = background_engineApi.startEngine({
                filters: [
                    ...staticFilters,
                    ...customFilters,
                ],
                userrules: configuration.userrules,
                quickFixesRules: configuration.quickFixesRules,
            });
            await background_engineApi.waitingForEngine;
            // TODO: Recreate only dynamic rule set, because static cannot be changed
            const ruleSets = [
                ...staticRuleSets,
                res.dynamicRules.ruleSet,
            ];
            // Update rulesets in declarative filtering log.
            background_declarativeFilteringLog.finishUpdate(ruleSets, configuration.declarativeLogEnabled);
            res.staticFilters = staticRuleSets;
        }
        else {
            await background_TsWebExtension.removeAllFilteringRules();
        }
        this.configuration = background_TsWebExtension.createConfigurationContext(configuration);
        // Update previously opened tabs with new rules - find for each tab
        // new main frame rule.
        await background_tabsApi.updateCurrentTabsMainFrameRules();
        // Reload request events listeners.
        await background_WebRequestApi.flushMemoryCache();
        background_common_logger_logger.debug('[tswebextension.configure]: end');
        return res;
    }
    /**
     * Sets prebuild local **script** rules.
     *
     * @param localScriptRules Object with pre-build JS rules. @see {@link LocalScriptRulesService}.
     */
    static setLocalScriptRules(localScriptRules) {
        background_localScriptRulesService.setLocalScriptRules(localScriptRules);
    }
    /**
     * Updates `hideReferrer` stealth config value without re-initialization of engine.
     *
     * @param isHideReferrer `isHideReferrer` stealth config value.
     *
     * @returns True if the value was successfully updated, false otherwise.
     *
     * @throws Error if {@link configuration} not set.
     */
    async setHideReferrer(isHideReferrer) {
        if (!this.configuration) {
            throw new Error('Configuration not set');
        }
        const currentValue = await background_StealthService.setHideReferrer(isHideReferrer);
        this.configuration.settings.stealth.hideReferrer = currentValue;
        return currentValue;
    }
    /**
     * Updates `blockWebRTC` stealth config value without re-initialization of engine.
     * Also updates webRTC privacy.network settings on demand.
     *
     * @param isBlockWebRTC `blockWebRTC` stealth config value.
     *
     * @returns True if the value was successfully updated, false otherwise.
     *
     * @throws Error if {@link configuration} not set.
     */
    async setBlockWebRTC(isBlockWebRTC) {
        if (!this.configuration) {
            throw new Error('Configuration not set');
        }
        const currentValue = await background_StealthService.setDisableWebRTC(isBlockWebRTC);
        this.configuration.settings.stealth.blockWebRTC = currentValue;
        return currentValue;
    }
    /**
     * Updates `blockChromeClientData` stealth config value without re-initialization of engine.
     *
     * @param isBlockChromeClientData `blockChromeClientData` stealth config value.
     *
     * @returns True if the value was successfully updated, false otherwise.
     *
     * @throws Error if {@link configuration} not set.
     */
    async setBlockChromeClientData(isBlockChromeClientData) {
        if (!this.configuration) {
            throw new Error('Configuration not set');
        }
        const currentValue = await background_StealthService.setBlockChromeClientData(isBlockChromeClientData);
        this.configuration.settings.stealth.blockChromeClientData = currentValue;
        return currentValue;
    }
    /**
     * Updates `sendDoNotTrack` stealth config value without re-initialization of engine.
     *
     * @param isSendDoNotTrack `sendDoNotTrack` stealth config value.
     *
     * @returns True if the value was successfully updated, false otherwise.
     *
     * @throws Error if {@link configuration} not set.
     */
    async setSendDoNotTrack(isSendDoNotTrack) {
        if (!this.configuration) {
            throw new Error('Configuration not set');
        }
        const currentValue = await background_StealthService.setSendDoNotTrack(isSendDoNotTrack, this.configuration.settings.gpcScriptUrl);
        this.configuration.settings.stealth.sendDoNotTrack = currentValue;
        return currentValue;
    }
    /**
     * Updates `hideSearchQueries` stealth config value without re-initialization of engine.
     *
     * @param isHideSearchQueries `hideSearchQueries` stealth config value.
     *
     * @returns True if the value was successfully updated, false otherwise.
     *
     * @throws Error if {@link configuration} not set.
     */
    async setHideSearchQueries(isHideSearchQueries) {
        if (!this.configuration) {
            throw new Error('Configuration not set');
        }
        const currentValue = await background_StealthService.setHideSearchQueries(isHideSearchQueries, this.configuration.settings.hideDocumentReferrerScriptUrl);
        this.configuration.settings.stealth.hideSearchQueries = currentValue;
        return currentValue;
    }
    /**
     * Opens the AdGuard assistant in the specified tab.
     *
     * @param tabId The ID of the tab where is needed to open
     * the AdGuard assistant.
     */
    // eslint-disable-next-line class-methods-use-this
    async openAssistant(tabId) {
        background_tabsApi.setAssistantInitTimestamp(tabId);
        await background_assistant.openAssistant(tabId);
    }
    /**
     * Closes the AdGuard assistant in the specified tab.
     *
     * @param tabId The ID of the tab where is needed to close
     * the AdGuard assistant.
     */
    // eslint-disable-next-line class-methods-use-this
    async closeAssistant(tabId) {
        background_tabsApi.resetAssistantInitTimestamp(tabId);
        await background_Assistant.closeAssistant(tabId);
    }
    /**
     * Gets current loaded rules in the filtering engine
     * (except declarative rules).
     *
     * @returns Number of loaded rules in the filtering engine.
     */
    // eslint-disable-next-line class-methods-use-this
    getRulesCount() {
        return background_engineApi.getRulesCount();
    }
    /**
     * Returns a message handler that will listen to internal messages,
     * for example: get css for content-script, or start/stop declarative
     * filtering log.
     *
     * @returns Messages handler.
     */
    getMessageHandler() {
        // Keep app context when handle message.
        const messagesApi = new background_MessagesApi(this, background_tabsApi, background_defaultFilteringLog);
        return messagesApi.handleMessage;
    }
    /**
     * Extract partial configuration {@link ConfigurationMV3Context} from whole
     * {@link ConfigurationMV3}, excluding heavyweight fields which
     * contains rules.
     *
     * @param configuration Configuration.
     *
     * @returns ConfigurationContext.
     */
    static createConfigurationContext(configuration) {
        const { staticFiltersIds, customFilters, verbose, settings, filtersPath, ruleSetsPath, declarativeLogEnabled, } = configuration;
        return {
            staticFiltersIds,
            customFilters: customFilters.map(({ filterId }) => filterId),
            filtersPath,
            ruleSetsPath,
            declarativeLogEnabled,
            verbose,
            settings,
        };
    }
    /**
     * Extract configuration update info from already parsed configuration.
     *
     * @param parsedConfiguration Already parsed {@link ConfigurationMV3}.
     * @param loadFilterContent Lazy load filter content function.
     *
     * @returns Item of {@link FiltersUpdateInfo}.
     */
    static async getFiltersUpdateInfo(parsedConfiguration, loadFilterContent) {
        // Wrap filters to tsurlfilter.IFilter
        const staticFilters = background_FiltersApi.createStaticFilters(parsedConfiguration.staticFiltersIds, loadFilterContent);
        const customFilters = background_FiltersApi.createCustomFilters(parsedConfiguration.customFilters);
        const filtersIdsToEnable = staticFilters
            .map((filter) => filter.getId());
        const enabledRuleSetsIds = await background_FiltersApi.getEnabledRuleSets();
        const filtersIdsToDisable = enabledRuleSetsIds
            .filter((id) => !filtersIdsToEnable.includes(id));
        return {
            staticFilters,
            customFilters,
            filtersIdsToEnable,
            filtersIdsToDisable,
        };
    }
    /**
     * Wraps static filters into rule sets.
     *
     * @param ruleSetsPath Path to the rule set metadata.
     * @param staticFilters List of static {@link IFilter}.
     *
     * @returns A list of static {@link IRuleSet}, or an empty list if an error
     * occurred during the rule scanning step.
     */
    static async loadStaticRuleSets(ruleSetsPath, staticFilters) {
        // Wrap filters into rule sets
        const ruleSetsLoaderApi = new background_RuleSetsLoaderApi(ruleSetsPath);
        const manifest = background_browser_polyfill.runtime.getManifest();
        if (!manifest.declarative_net_request) {
            throw new Error('Cannot find declarative_net_request in manifest');
        }
        // Note: we cannot create rulesets only for enabled filters because we
        // need to get all rulesets' counters for checking limits on the client.
        // Note: we skip metadata ruleset, because it is not a real ruleset.
        const manifestRuleSets = manifest.declarative_net_request.rule_resources
            .filter(({ id }) => id !== background_declarative_converter_utils_getRuleSetId(background_METADATA_RULESET_ID));
        const staticRuleSetsTasks = manifestRuleSets.map(({ id }) => {
            return ruleSetsLoaderApi.createRuleSet(id, staticFilters);
        });
        try {
            const staticRuleSets = await Promise.all(staticRuleSetsTasks);
            return staticRuleSets;
        }
        catch (e) {
            const filterListIds = staticFilters.map((f) => f.getId());
            // eslint-disable-next-line max-len
            background_common_logger_logger.error(`[tswebextension.loadStaticRuleSets]: Cannot scan rules of filter list with ids ${filterListIds} due to: ${background_configuration_getErrorMessage(e)}`);
            return [];
        }
    }
    /**
     * Initialize app persistent data.
     * This method called as soon as possible and allows access
     * to the actual context before the app is started.
     */
    // eslint-disable-next-line class-methods-use-this
    async initStorage() {
        await background_extSessionStorage.init();
        background_index_mv3_appContext.isStorageInitialized = true;
    }
    /**
     * Sets the debug scriptlets state.
     *
     * @param debug Debug filtering state.
     *
     * @throws Error if {@link configuration} not set.
     */
    setDebugScriptlets(debug) {
        if (!this.configuration) {
            throw new Error('Configuration not set');
        }
        this.configuration.settings.debugScriptlets = debug;
    }
    /**
     * Updates `collectStats` configuration value without re-initialization of engine.
     *
     * @param isCollectStats `collectStats` config value.
     *
     * @throws Error if {@link configuration} not set.
     */
    setCollectHitStats(isCollectStats) {
        if (!this.configuration) {
            throw new Error('Configuration not set');
        }
        this.configuration.settings.collectStats = isCollectStats;
    }
    /**
     * Updates the log level.
     *
     * @param logLevel Log level.
     */
    static updateLogLevel(logLevel) {
        try {
            background_common_logger_logger.currentLevel = logLevel || background_LogLevel.Info;
        }
        catch (e) {
            background_common_logger_logger.currentLevel = background_LogLevel.Info;
        }
    }
    /**
     * Retrieves a rule node by its filter list identifier and rule index.
     *
     * If there's no rule by that index or the rule structure is invalid, it will return null.
     *
     * @param filterId Filter list identifier.
     * @param ruleIndex Rule index.
     *
     * @returns Rule node or `null`.
     */
    // eslint-disable-next-line class-methods-use-this
    retrieveRuleNode(filterId, ruleIndex) {
        return background_engineApi.retrieveRuleNode(filterId, ruleIndex);
    }
}



;// ./Extension/src/background/events/settings.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_events_settings_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}

/**
 * Type-safe mediator for setting options change events.
 */ class background_SettingsEvents {
    /**
     * Adds a listener for settings events. Only one listener per event.
     *
     * @param event Event with some generic type.
     * @param listener Listener for this event.
     *
     * @throws Basic {@link Error} if a listener was registered for the event.
     */ addListener(event, listener) {
        if (this.listenersMap.has(event)) {
            throw new Error(`${event} listener has already been registered`);
        }
        this.listenersMap.set(event, listener);
    }
    /**
     * Publishes the event and, if a listener is found, notifies the listener.
     *
     * @param event Event with some generic type.
     * @param value Some filed in the {@link Settings} object.
     *
     * @returns Promise that resolves when the listener is notified.
     */ async publishEvent(event, value) {
        const listener = this.listenersMap.get(event);
        if (listener) {
            return Promise.resolve(listener(value));
        }
    }
    /**
     * Removes all listeners.
     */ removeListeners() {
        this.listenersMap.clear();
    }
    constructor(){
        background_events_settings_define_property(this, "listenersMap", new Map());
    }
}
const background_settingsEvents = new background_SettingsEvents();

;// ./Extension/src/background/events/context-menu.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_context_menu_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}


var background_ContextMenuAction = /*#__PURE__*/ function(ContextMenuAction) {
    ContextMenuAction["SiteProtectionDisabled"] = "context_site_protection_disabled";
    ContextMenuAction["SiteFilteringDisabled"] = "context_site_filtering_disabled";
    ContextMenuAction["SiteException"] = "context_site_exception";
    ContextMenuAction["BlockSiteAds"] = "context_block_site_ads";
    ContextMenuAction["SecurityReport"] = "context_security_report";
    ContextMenuAction["ComplaintWebsite"] = "context_complaint_website";
    ContextMenuAction["SiteFilteringOn"] = "context_site_filtering_on";
    ContextMenuAction["SiteFilteringOff"] = "context_site_filtering_off";
    ContextMenuAction["EnableProtection"] = "context_enable_protection";
    ContextMenuAction["DisableProtection"] = "context_disable_protection";
    ContextMenuAction["OpenSettings"] = "context_open_settings";
    ContextMenuAction["OpenLog"] = "context_open_log";
    ContextMenuAction["UpdateFilters"] = "context_update_antibanner_filters";
    return ContextMenuAction;
}({});
/**
 * Type-safe mediator for context menu events.
 */ class background_ContextMenuEvents {
    /**
     * Adds a listener for context menu events.
     * Only one listener per event.
     *
     * @param event Event with some generic type.
     * @param listener Listener for this event.
     *
     * @throws Basic {@link Error} if a listener was registered for the event.
     */ addListener(event, listener) {
        if (this.listenersMap.has(event)) {
            throw new Error(`${event} listener has already been registered`);
        }
        this.listenersMap.set(event, listener);
    }
    /**
     * Publishes the event and, if a listener is found, notifies the listener.
     *
     * @param event Event with some generic type.
     *
     * @returns Promise with the result of the listener.
     */ async publishEvent(event) {
        const listener = this.listenersMap.get(event);
        if (!listener) {
            background_logger_logger.error(`ContextMenuEvent not found listener for ${event}!`);
            return;
        }
        return Promise.resolve(listener());
    }
    /**
     * Removes all listeners.
     */ removeListeners() {
        this.listenersMap.clear();
    }
    constructor(){
        background_context_menu_define_property(this, "listenersMap", new Map());
    }
}
const background_contextMenuEvents = new background_ContextMenuEvents();

;// ./Extension/src/background/events/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 


;// ./Extension/src/common/settings.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

var background_AppearanceTheme = /*#__PURE__*/ function(AppearanceTheme) {
    AppearanceTheme["System"] = "system";
    AppearanceTheme["Dark"] = "dark";
    AppearanceTheme["Light"] = "light";
    return AppearanceTheme;
}({});
const background_DEFAULT_FILTERS_UPDATE_PERIOD = -1;
const background_DEFAULT_FIRST_PARTY_COOKIES_SELF_DESTRUCT_MIN = 4320;
const background_DEFAULT_THIRD_PARTY_COOKIES_SELF_DESTRUCT_MIN = 2880;
const background_DEFAULT_ALLOWLIST = [];
const background_DEFAULT_INVERTED_ALLOWLIST = [];
const background_defaultSettings = {
    [background_SettingOption.DisableShowAdguardPromoInfo]: !(background_UserAgent.isWindows || background_UserAgent.isMacOs) || background_UserAgent.isEdge,
    [background_SettingOption.DisableSafebrowsing]: true,
    [background_SettingOption.DisableCollectHits]: true,
    [background_SettingOption.DefaultAllowlistMode]: true,
    [background_SettingOption.AllowlistEnabled]: true,
    // TODO: consider ditching optimized filters for mobile mv3 builds if (or when) they become available
    [background_SettingOption.UseOptimizedFilters]: background_UserAgent.isAndroid,
    [background_SettingOption.DisableDetectFilters]: false,
    [background_SettingOption.DisableShowAppUpdatedNotification]: false,
    [background_SettingOption.FiltersUpdatePeriod]: background_DEFAULT_FILTERS_UPDATE_PERIOD,
    [background_SettingOption.DisableStealthMode]: true,
    [background_SettingOption.HideReferrer]: true,
    [background_SettingOption.HideSearchQueries]: true,
    [background_SettingOption.SendDoNotTrack]: true,
    [background_SettingOption.RemoveXClientData]: background_UserAgent.isChrome,
    [background_SettingOption.BlockWebRTC]: false,
    [background_SettingOption.SelfDestructThirdPartyCookies]: true,
    [background_SettingOption.SelfDestructThirdPartyCookiesTime]: background_DEFAULT_THIRD_PARTY_COOKIES_SELF_DESTRUCT_MIN,
    [background_SettingOption.SelfDestructFirstPartyCookies]: false,
    [background_SettingOption.SelfDestructFirstPartyCookiesTime]: background_DEFAULT_FIRST_PARTY_COOKIES_SELF_DESTRUCT_MIN,
    [background_SettingOption.AppearanceTheme]: "system",
    [background_SettingOption.UserFilterEnabled]: true,
    [background_SettingOption.HideRateBlock]: false,
    [background_SettingOption.UserRulesEditorWrap]: false,
    [background_SettingOption.DisableFiltering]: false,
    [background_SettingOption.DisableShowPageStats]: false,
    [background_SettingOption.DisableShowContextMenu]: false,
    [background_SettingOption.AllowlistDomains]: JSON.stringify(background_DEFAULT_ALLOWLIST),
    [background_SettingOption.InvertedAllowlistDomains]: JSON.stringify(background_DEFAULT_INVERTED_ALLOWLIST)
};

;// ./Extension/src/background/notifier.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_notifier_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}



/**
 * The Notifier class contains all events, their listeners and handlers,
 * as well as manages the work with them: add, delete, notify.
 */ class background_Notifier {
    /**
     * Subscribes listener to the specified events.
     *
     * @param events Event type listener will be notified of.
     * @param listener Listener callback.
     *
     * @returns Listener id.
     *
     * @throws Error if listener is not a function.
     */ addSpecifiedListener(events, listener) {
        if (typeof listener !== 'function') {
            throw new Error('Illegal listener');
        }
        const listenerId = this.listenerId + 1;
        this.listenerId = listenerId;
        this.listenersMap[listenerId] = listener;
        this.listenersEventsMap[listenerId] = events;
        return listenerId;
    }
    /**
     * Subscribe specified listener to all events.
     *
     * @param listener Listener callback.
     *
     * @returns Listener id.
     *
     * @throws Error if listener is not a function.
     */ addListener(listener) {
        if (typeof listener !== 'function') {
            throw new Error('Illegal listener');
        }
        const listenerId = this.listenerId + 1;
        this.listenerId = listenerId;
        this.listenersMap[listenerId] = listener;
        return listenerId;
    }
    /**
     * Unsubscribe listener.
     *
     * @param listenerId Listener id.
     */ removeListener(listenerId) {
        delete this.listenersMap[listenerId];
        delete this.listenersEventsMap[listenerId];
    }
    /**
     * Notifies listeners about the events passed as arguments of this function.
     *
     * @param args Notifier event types.
     *
     * @throws Error if some event is illegal.
     */ notifyListeners(...args) {
        const [event] = args;
        if (!event || !(event in this.eventNotifierEventsMap)) {
            throw new Error(`Illegal event: ${event}`);
        }
        Object.entries(this.listenersMap).forEach(([listenerId, listener])=>{
            const events = this.listenersEventsMap[Number(listenerId)];
            if (events && events.length > 0 && events.indexOf(event) < 0) {
                return;
            }
            try {
                listener.apply(listener, args);
            } catch (ex) {
                background_logger_logger.error(`Error invoking listener for ${event} cause:`, ex);
            }
        });
    }
    /**
     * Creates new item of {@link Notifier}.
     */ constructor(){
        background_notifier_define_property(this, "listenerId", 0);
        background_notifier_define_property(this, "eventNotifierEventsMap", {});
        background_notifier_define_property(this, "listenersMap", {});
        background_notifier_define_property(this, "listenersEventsMap", {});
        /**
     * Make accessible only constants without functions. They will be passed to content-page.
     */ background_notifier_define_property(this, "events", background_constants_NotifierType);
        Object.entries(background_constants_NotifierType).forEach(([key, value])=>{
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-ignore
            this[key] = value;
            this.eventNotifierEventsMap[value] = key;
        });
    }
}
const background_notifier_notifier = new background_Notifier();

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isKey.js



/** Used to match property names within property paths. */
var background_reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
    background_reIsPlainProp = /^\w*$/;

/**
 * Checks if `value` is a property name and not a property path.
 *
 * @private
 * @param {*} value The value to check.
 * @param {Object} [object] The object to query keys on.
 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
 */
function background_isKey(value, object) {
  if (background_lodash_es_isArray(value)) {
    return false;
  }
  var type = typeof value;
  if (type == 'number' || type == 'symbol' || type == 'boolean' ||
      value == null || background_lodash_es_isSymbol(value)) {
    return true;
  }
  return background_reIsPlainProp.test(value) || !background_reIsDeepProp.test(value) ||
    (object != null && value in Object(object));
}

/* harmony default export */ const pages_background_isKey = (background_isKey);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/memoize.js


/** Error message constants. */
var background_memoize_FUNC_ERROR_TEXT = 'Expected a function';

/**
 * Creates a function that memoizes the result of `func`. If `resolver` is
 * provided, it determines the cache key for storing the result based on the
 * arguments provided to the memoized function. By default, the first argument
 * provided to the memoized function is used as the map cache key. The `func`
 * is invoked with the `this` binding of the memoized function.
 *
 * **Note:** The cache is exposed as the `cache` property on the memoized
 * function. Its creation may be customized by replacing the `_.memoize.Cache`
 * constructor with one whose instances implement the
 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
 * method interface of `clear`, `delete`, `get`, `has`, and `set`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to have its output memoized.
 * @param {Function} [resolver] The function to resolve the cache key.
 * @returns {Function} Returns the new memoized function.
 * @example
 *
 * var object = { 'a': 1, 'b': 2 };
 * var other = { 'c': 3, 'd': 4 };
 *
 * var values = _.memoize(_.values);
 * values(object);
 * // => [1, 2]
 *
 * values(other);
 * // => [3, 4]
 *
 * object.a = 2;
 * values(object);
 * // => [1, 2]
 *
 * // Modify the result cache.
 * values.cache.set(object, ['a', 'b']);
 * values(object);
 * // => ['a', 'b']
 *
 * // Replace `_.memoize.Cache`.
 * _.memoize.Cache = WeakMap;
 */
function background_memoize(func, resolver) {
  if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
    throw new TypeError(background_memoize_FUNC_ERROR_TEXT);
  }
  var memoized = function() {
    var args = arguments,
        key = resolver ? resolver.apply(this, args) : args[0],
        cache = memoized.cache;

    if (cache.has(key)) {
      return cache.get(key);
    }
    var result = func.apply(this, args);
    memoized.cache = cache.set(key, result) || cache;
    return result;
  };
  memoized.cache = new (background_memoize.Cache || pages_background_MapCache);
  return memoized;
}

// Expose `MapCache`.
background_memoize.Cache = pages_background_MapCache;

/* harmony default export */ const background_lodash_es_memoize = (background_memoize);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_memoizeCapped.js


/** Used as the maximum memoize cache size. */
var background_MAX_MEMOIZE_SIZE = 500;

/**
 * A specialized version of `_.memoize` which clears the memoized function's
 * cache when it exceeds `MAX_MEMOIZE_SIZE`.
 *
 * @private
 * @param {Function} func The function to have its output memoized.
 * @returns {Function} Returns the new memoized function.
 */
function background_memoizeCapped(func) {
  var result = background_lodash_es_memoize(func, function(key) {
    if (cache.size === background_MAX_MEMOIZE_SIZE) {
      cache.clear();
    }
    return key;
  });

  var cache = result.cache;
  return result;
}

/* harmony default export */ const pages_background_memoizeCapped = (background_memoizeCapped);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stringToPath.js


/** Used to match property names within property paths. */
var background_rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;

/** Used to match backslashes in property paths. */
var background_reEscapeChar = /\\(\\)?/g;

/**
 * Converts `string` to a property path array.
 *
 * @private
 * @param {string} string The string to convert.
 * @returns {Array} Returns the property path array.
 */
var background_stringToPath = pages_background_memoizeCapped(function(string) {
  var result = [];
  if (string.charCodeAt(0) === 46 /* . */) {
    result.push('');
  }
  string.replace(background_rePropName, function(match, number, quote, subString) {
    result.push(quote ? subString.replace(background_reEscapeChar, '$1') : (number || match));
  });
  return result;
});

/* harmony default export */ const pages_background_stringToPath = (background_stringToPath);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayMap.js
/**
 * A specialized version of `_.map` for arrays without support for iteratee
 * shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the new mapped array.
 */
function background_arrayMap(array, iteratee) {
  var index = -1,
      length = array == null ? 0 : array.length,
      result = Array(length);

  while (++index < length) {
    result[index] = iteratee(array[index], index, array);
  }
  return result;
}

/* harmony default export */ const pages_background_arrayMap = (background_arrayMap);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseToString.js





/** Used as references for various `Number` constants. */
var background_INFINITY = 1 / 0;

/** Used to convert symbols to primitives and strings. */
var background_baseToString_symbolProto = background_Symbol ? background_Symbol.prototype : undefined,
    background_symbolToString = background_baseToString_symbolProto ? background_baseToString_symbolProto.toString : undefined;

/**
 * The base implementation of `_.toString` which doesn't convert nullish
 * values to empty strings.
 *
 * @private
 * @param {*} value The value to process.
 * @returns {string} Returns the string.
 */
function background_baseToString(value) {
  // Exit early for strings to avoid a performance hit in some environments.
  if (typeof value == 'string') {
    return value;
  }
  if (background_lodash_es_isArray(value)) {
    // Recursively convert values (susceptible to call stack limits).
    return pages_background_arrayMap(value, background_baseToString) + '';
  }
  if (background_lodash_es_isSymbol(value)) {
    return background_symbolToString ? background_symbolToString.call(value) : '';
  }
  var result = (value + '');
  return (result == '0' && (1 / value) == -background_INFINITY) ? '-0' : result;
}

/* harmony default export */ const pages_background_baseToString = (background_baseToString);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/toString.js


/**
 * Converts `value` to a string. An empty string is returned for `null`
 * and `undefined` values. The sign of `-0` is preserved.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {string} Returns the converted string.
 * @example
 *
 * _.toString(null);
 * // => ''
 *
 * _.toString(-0);
 * // => '-0'
 *
 * _.toString([1, 2, 3]);
 * // => '1,2,3'
 */
function background_toString_toString(value) {
  return value == null ? '' : pages_background_baseToString(value);
}

/* harmony default export */ const background_lodash_es_toString = (background_toString_toString);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_castPath.js





/**
 * Casts `value` to a path array if it's not one.
 *
 * @private
 * @param {*} value The value to inspect.
 * @param {Object} [object] The object to query keys on.
 * @returns {Array} Returns the cast property path array.
 */
function background_castPath(value, object) {
  if (background_lodash_es_isArray(value)) {
    return value;
  }
  return pages_background_isKey(value, object) ? [value] : pages_background_stringToPath(background_lodash_es_toString(value));
}

/* harmony default export */ const pages_background_castPath = (background_castPath);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_toKey.js


/** Used as references for various `Number` constants. */
var background_toKey_INFINITY = 1 / 0;

/**
 * Converts `value` to a string key if it's not a string or symbol.
 *
 * @private
 * @param {*} value The value to inspect.
 * @returns {string|symbol} Returns the key.
 */
function background_toKey(value) {
  if (typeof value == 'string' || background_lodash_es_isSymbol(value)) {
    return value;
  }
  var result = (value + '');
  return (result == '0' && (1 / value) == -background_toKey_INFINITY) ? '-0' : result;
}

/* harmony default export */ const pages_background_toKey = (background_toKey);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGet.js



/**
 * The base implementation of `_.get` without support for default values.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the property to get.
 * @returns {*} Returns the resolved value.
 */
function background_baseGet(object, path) {
  path = pages_background_castPath(path, object);

  var index = 0,
      length = path.length;

  while (object != null && index < length) {
    object = object[pages_background_toKey(path[index++])];
  }
  return (index && index == length) ? object : undefined;
}

/* harmony default export */ const pages_background_baseGet = (background_baseGet);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/get.js


/**
 * Gets the value at `path` of `object`. If the resolved value is
 * `undefined`, the `defaultValue` is returned in its place.
 *
 * @static
 * @memberOf _
 * @since 3.7.0
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the property to get.
 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
 * @returns {*} Returns the resolved value.
 * @example
 *
 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
 *
 * _.get(object, 'a[0].b.c');
 * // => 3
 *
 * _.get(object, ['a', '0', 'b', 'c']);
 * // => 3
 *
 * _.get(object, 'a.b.c', 'default');
 * // => 'default'
 */
function background_get(object, path, defaultValue) {
  var result = object == null ? undefined : pages_background_baseGet(object, path);
  return result === undefined ? defaultValue : result;
}

/* harmony default export */ const background_lodash_es_get = (background_get);

;// ./Extension/src/common/unknown.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
/**
 * Helper util used for work with unknown type.
 */ class background_Unknown {
    /**
     * Returns key from object with `unknown` type.
     *
     * @param obj Object with type `unknown`.
     * @param key Key for search and return its value from object.
     *
     * @returns Undefined if key doesn't exist in the object
     * or value of key in this object.
     */ static get(obj, key) {
        return background_lodash_es_get(obj, key);
    }
    /**
     * Checks if property exists in the object, and narrows the type of the object.
     *
     * @param obj An unknown object.
     * @param key All possible keys of the object.
     *
     * @returns True if property exists, otherwise false.
     */ static hasProp(obj, key) {
        return key != null && obj != null && typeof obj === 'object' && key in obj;
    }
}

;// ./Extension/src/pages/services/messenger.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_messenger_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}





var background_Page = /*#__PURE__*/ function(Page) {
    Page["FullscreenUserRules"] = "fullscreen-user-rules";
    Page["FilteringLog"] = "filtering-log";
    return Page;
}({});
/**
 * Messenger class, used to communicate with the background page from the UI.
 * Actually, it's a wrapper around the browser.runtime.sendMessage method.
 */ class background_Messenger {
    /**
     * Sends a message to the background page.
     *
     * All messages described in the {@link MessageType} enum.
     * All answers described in the {@link MessageMap} type.
     *
     * @param type Message type.
     * @param data Message data. Optional because not all messages have data.
     *
     * @returns Promise that resolves with the response from the background page.
     * Type of the response depends on the message type. Go to {@link MessageMap}
     * to see all possible message types and their responses.
     */ // eslint-disable-next-line class-methods-use-this
    async sendMessage(type, data) {
        const response = await background_browser_polyfill_default().runtime.sendMessage({
            handlerName: background_APP_MESSAGE_HANDLER_NAME,
            type,
            data
        });
        return response;
    }
    /**
     * Sends a message from background page to update listeners on the UI.
     *
     * @returns Promise that resolves when the message is sent.
     */ async updateListeners() {
        return this.sendMessage(background_constants_MessageType.UpdateListeners);
    }
    /**
     * Sends a message to the background page to get the settings data for
     * the options page with some additional info.
     *
     * @returns Promise that resolves with the settings data for
     * the options page with some additional info.
     */ async getOptionsData() {
        return this.sendMessage(background_constants_MessageType.GetOptionsData);
    }
    /**
     * Sends a message to the background page to change the user setting.
     *
     * @param settingId Setting identifier.
     * @param value Setting value.
     *
     * @returns Promise that resolves after the message is sent.
     */ async changeUserSetting(settingId, value) {
        await this.sendMessage(background_constants_MessageType.ChangeUserSettings, {
            key: settingId,
            value
        });
    }
    /**
     * Sends a message to the background page to open the extension store.
     *
     * @returns Promise that resolves after the message is sent.
     */ async openExtensionStore() {
        return this.sendMessage(background_constants_MessageType.OpenExtensionStore);
    }
    /**
     * Sends a message to the background page to open the compare page.
     *
     * @returns Promise that resolves after the message is sent.
     */ async openComparePage() {
        return this.sendMessage(background_constants_MessageType.OpenComparePage);
    }
    /**
     * Sends a message to the background page to enable a filter by filter id.
     *
     * @param filterId Filter identifier.
     *
     * @returns Promise that resolves after the message is sent.
     */ async enableFilter(filterId) {
        return this.sendMessage(background_constants_MessageType.AddAndEnableFilter, {
            filterId
        });
    }
    /**
     * Sends a message to the background page to disable a filter by filter id.
     *
     * @param filterId Filter identifier.
     *
     * @returns Promise that resolves after the message is sent.
     */ async disableFilter(filterId) {
        return this.sendMessage(background_constants_MessageType.DisableFilter, {
            filterId
        });
    }
    /**
     * Sends a message to the background page to apply settings from a JSON object.
     *
     * @param json JSON object representing the settings to apply.
     *
     * @returns Promise that resolves after the message is sent.
     */ async applySettingsJson(json) {
        return this.sendMessage(background_constants_MessageType.ApplySettingsJson, {
            json
        });
    }
    /**
     * Sends a message to the background page to open the filtering log.
     *
     * @returns Promise that resolves after the message is sent.
     */ async openFilteringLog() {
        return this.sendMessage(background_constants_MessageType.OpenFilteringLog);
    }
    /**
     * Sends a message to the background page to reset the blocked ads statistics.
     *
     * @returns Promise that resolves after the message is sent.
     */ async resetStatistics() {
        return this.sendMessage(background_constants_MessageType.ResetBlockedAdsCount);
    }
    /**
     * Sends a message to the background page to set the filtering log window state.
     *
     * @param windowState State of the filtering log window.
     *
     * @returns Promise that resolves after the message is sent.
     */ async setFilteringLogWindowState(windowState) {
        return this.sendMessage(background_constants_MessageType.SetFilteringLogWindowState, {
            windowState
        });
    }
    /**
     * Sends a message to the background page to reset the settings.
     *
     * @returns Promise that resolves after the message is sent.
     */ async resetSettings() {
        return this.sendMessage(background_constants_MessageType.ResetSettings);
    }
    /**
     * Sends a message to the background page to get the user rules.
     *
     * @returns Promise that resolves with the user rules.
     */ async getUserRules() {
        return this.sendMessage(background_constants_MessageType.GetUserRules);
    }
    /**
     * Sends a message to the background page to save user rules.
     *
     * @param value User rules value to save.
     *
     * @returns Promise that resolves after the message is sent.
     */ async saveUserRules(value) {
        await this.sendMessage(background_constants_MessageType.SaveUserRules, {
            value
        });
    }
    /**
     * Sends a message to the background page to open user rules editor in fullscreen.
     *
     * @returns Promise that resolves after the message is sent.
     */ async openFullscreenUserRules() {
        return this.sendMessage(background_constants_MessageType.OpenFullscreenUserRules);
    }
    /**
     * Sends a message to the background page to get the allowlist domains.
     *
     * @returns Promise that resolves with the list of allowlist domains.
     */ async getAllowlist() {
        return this.sendMessage(background_constants_MessageType.GetAllowlistDomains);
    }
    /**
     * Sends a message to the background page to save the allowlist domains.
     *
     * @param value Allowlist domains value to save.
     *
     * @returns Promise that resolves after the message is sent.
     */ async saveAllowlist(value) {
        await this.sendMessage(background_constants_MessageType.SaveAllowlistDomains, {
            value
        });
    }
    /**
     * Sends a message to the background page to mark a notification as viewed.
     *
     * @param withDelay Whether the notification should be marked as viewed after a delay.
     *
     * @returns Promise that resolves after the message is sent.
     */ async setNotificationViewed(withDelay) {
        await this.sendMessage(background_constants_MessageType.SetNotificationViewed, {
            withDelay
        });
    }
    /**
     * Sends a message to the background page to update filters.
     *
     * @returns Promise that resolves with the list of filters.
     */ async updateFilters() {
        if (true) {
            background_logger_logger.debug('Filters update is not supported in MV3');
            return [];
        }
        return this.sendMessage(background_constants_MessageType.CheckFiltersUpdate);
    }
    /**
     * Sends a message to the background page to update the status of a filter group.
     *
     * @param id Group identifier.
     * @param enabled Whether the group should be enabled or disabled.
     *
     * @returns Promise that resolves after the message is sent.
     */ async updateGroupStatus(id, enabled) {
        const type = enabled ? background_constants_MessageType.EnableFiltersGroup : background_constants_MessageType.DisableFiltersGroup;
        const groupId = Number.parseInt(id, 10);
        return this.sendMessage(type, {
            groupId
        });
    }
    /**
     * Sends a message to the background page to set consented filters.
     *
     * @param filterIds List of filter identifiers.
     *
     * @returns Promise that resolves after the message is sent.
     */ async setConsentedFilters(filterIds) {
        return this.sendMessage(background_constants_MessageType.SetConsentedFilters, {
            filterIds
        });
    }
    /**
     * Sends a message to the background page to check if a filter is consented.
     *
     * @param filterId Filter identifier.
     *
     * @returns Promise that resolves with the result of the check.
     */ async getIsConsentedFilter(filterId) {
        return this.sendMessage(background_constants_MessageType.GetIsConsentedFilter, {
            filterId
        });
    }
    /**
     * Sends a message to the background page to check a custom filter URL.
     *
     * @param url Custom filter URL.
     *
     * @returns Promise that resolves with the result of the check.
     */ async checkCustomUrl(url) {
        return this.sendMessage(background_constants_MessageType.LoadCustomFilterInfo, {
            url
        });
    }
    /**
     * Sends a message to the background page to add a custom filter.
     *
     * @param {CustomFilterSubscriptionData} filter Custom filter data.
     *
     * @returns {Promise<CustomFilterMetadata>} Custom filter metadata.
     */ async addCustomFilter(filter) {
        return this.sendMessage(background_constants_MessageType.SubscribeToCustomFilter, {
            filter
        });
    }
    /**
     * Sends a message to the background page to remove a custom filter.
     *
     * @param filterId Custom filter ID.
     *
     * @returns Promise that resolves after the filter is removed.
     */ async removeCustomFilter(filterId) {
        await this.sendMessage(background_constants_MessageType.RemoveAntiBannerFilter, {
            filterId
        });
    }
    /**
     * Sends a message to the background page to check if the engine is started.
     *
     * @returns Promise that resolves to a boolean value:
     * true if the engine is started, false otherwise.
     */ async getIsEngineStarted() {
        return this.sendMessage(background_constants_MessageType.GetIsEngineStarted);
    }
    /**
     * Sends a message to the background to get the tab info for the popup.
     *
     * @param tabId Tab ID.
     *
     * @returns Promise that resolves with the tab info or undefined.
     */ async getTabInfoForPopup(tabId) {
        return this.sendMessage(background_constants_MessageType.GetTabInfoForPopup, {
            tabId
        });
    }
    /**
     * Sends a message to the background page to change application filtering state.
     *
     * @param state Application filtering state.
     *
     * @returns Promise that resolves after the state is changed.
     */ async changeApplicationFilteringPaused(state) {
        return this.sendMessage(background_constants_MessageType.ChangeApplicationFilteringPaused, {
            state
        });
    }
    /**
     * Sends a message to the background page to update the theme of the fullscreen user rules.
     *
     * @param theme Theme to set.
     *
     * @returns Promise that resolves after the theme is updated.
     */ async updateFullscreenUserRulesTheme(theme) {
        return this.sendMessage(background_constants_MessageType.UpdateFullscreenUserRulesTheme, {
            theme
        });
    }
    /**
     * Sends a message to the background page to open the rules limits tab.
     *
     * @returns Promise that resolves after the tab is opened.
     */ async openRulesLimitsTab() {
        return this.sendMessage(background_constants_MessageType.OpenRulesLimitsTab);
    }
    /**
     * Sends a message to the background page to open the settings tab.
     *
     * @returns Promise that resolves after the tab is opened.
     */ async openSettingsTab() {
        return this.sendMessage(background_constants_MessageType.OpenSettingsTab);
    }
    /**
     * Sends a message to the background page to open the assistant.
     *
     * @returns Promise that resolves after the assistant is opened.
     */ async openAssistant() {
        return this.sendMessage(background_constants_MessageType.OpenAssistant);
    }
    /**
     * Sends a message to the background page to open the abuse reporting tab for a site.
     *
     * @param url The URL of the site to report abuse for.
     * @param from The source of the request.
     *
     * @returns Promise that resolves after the tab is opened.
     */ async openAbuseSite(url, from) {
        return this.sendMessage(background_constants_MessageType.OpenAbuseTab, {
            url,
            from
        });
    }
    /**
     * Sends a message to the background page to check site security.
     *
     * @param url The URL of the site to check.
     * @param from The source of the request.
     *
     * @returns Promise that resolves with the site security info.
     */ async checkSiteSecurity(url, from) {
        return this.sendMessage(background_constants_MessageType.OpenSiteReportTab, {
            url,
            from
        });
    }
    /**
     * Sends a message to the background page to reset user rules for a specific page.
     *
     * @param url The URL of the page.
     *
     * @returns Promise that resolves after the user rules are reset.
     */ async resetUserRulesForPage(url) {
        const [currentTab] = await background_browser_polyfill_default().tabs.query({
            active: true,
            currentWindow: true
        });
        if (!(currentTab === null || currentTab === void 0 ? void 0 : currentTab.id)) {
            background_logger_logger.debug('[resetUserRulesForPage]: cannot get current tab id');
            return;
        }
        return this.sendMessage(background_constants_MessageType.ResetUserRulesForPage, {
            url,
            tabId: currentTab === null || currentTab === void 0 ? void 0 : currentTab.id
        });
    }
    /**
     * Sends a message to the background page to remove an allowlist domain.
     *
     * @param tabId The ID of the tab.
     * @param tabRefresh Whether the tab should be refreshed.
     *
     * @returns Promise that resolves after the domain is removed.
     */ async removeAllowlistDomain(tabId, tabRefresh) {
        return this.sendMessage(background_constants_MessageType.RemoveAllowlistDomain, {
            tabId,
            tabRefresh
        });
    }
    /**
     * Sends a message to the background page to add an allowlist domain.
     *
     * @param tabId The ID of the tab.
     *
     * @returns Promise that resolves after the domain is added.
     */ async addAllowlistDomain(tabId) {
        return this.sendMessage(background_constants_MessageType.AddAllowlistDomain, {
            tabId
        });
    }
    /**
     * Works only in MV2, since MV3 doesn't support filtering log yet.
     *
     * @returns Promise that resolves after the filtering log page is opened.
     */ async onOpenFilteringLogPage() {
        await this.sendMessage(background_constants_MessageType.OnOpenFilteringLogPage);
    }
    /**
     * Sends a message to the background page to get filtering log data.
     *
     * @returns Promise that resolves with filtering log data.
     */ async getFilteringLogData() {
        return this.sendMessage(background_constants_MessageType.GetFilteringLogData);
    }
    /**
     * Sends a message to the background page to close the filtering log page.
     *
     * @returns Promise that resolves after the page is closed.
     */ async onCloseFilteringLogPage() {
        await this.sendMessage(background_constants_MessageType.OnCloseFilteringLogPage);
    }
    /**
     * Sends a message to the background page to get filtering info by tab ID.
     *
     * @param tabId The ID of the tab.
     *
     * @returns Promise that resolves with filtering info about the tab.
     */ async getFilteringInfoByTabId(tabId) {
        return this.sendMessage(background_constants_MessageType.GetFilteringInfoByTabId, {
            tabId
        });
    }
    /**
     * Sends a message to the background page to synchronize the list of open tabs.
     *
     * @returns Promise that resolves with an array of filtering info about open tabs.
     */ async synchronizeOpenTabs() {
        return this.sendMessage(background_constants_MessageType.SynchronizeOpenTabs);
    }
    /**
     * Sends a message to the background page to clear events by tab ID.
     *
     * @param tabId The ID of the tab.
     * @param ignorePreserveLog Optional flag to ignore the preserve log state.
     *
     * @returns Promise that resolves after the events are cleared.
     */ async clearEventsByTabId(tabId, ignorePreserveLog) {
        return this.sendMessage(background_constants_MessageType.ClearEventsByTabId, {
            tabId,
            ignorePreserveLog
        });
    }
    /**
     * Sends a message to the background page to refresh the current page by tab ID.
     *
     * @param tabId The ID of the tab.
     *
     * @returns Promise that resolves after the page is refreshed.
     */ async refreshPage(tabId) {
        await this.sendMessage(background_constants_MessageType.RefreshPage, {
            tabId
        });
    }
    /**
     * Sends a message to the background page to add a user rule.
     *
     * @param ruleText User rule text to be added.
     *
     * @returns Promise that resolves after the message is sent.
     */ async addUserRule(ruleText) {
        await this.sendMessage(background_constants_MessageType.AddUserRule, {
            ruleText
        });
    }
    /**
     * Sends a message to the background page to remove a user rule.
     *
     * @param ruleText User rule text to be removed.
     *
     * @returns Promise that resolves after the message is sent.
     */ async removeUserRule(ruleText) {
        await this.sendMessage(background_constants_MessageType.RemoveUserRule, {
            ruleText
        });
    }
    /**
     * Sends a message to the background page to set the preserve log state.
     *
     * @param state State indicating whether to preserve the log.
     *
     * @returns Promise that resolves after the message is sent.
     */ async setPreserveLogState(state) {
        return this.sendMessage(background_constants_MessageType.SetPreserveLogState, {
            state
        });
    }
    /**
     * Sends a message to the background page to get the editor storage content.
     *
     * @returns Promise that resolves with the editor storage content.
     */ async getEditorStorageContent() {
        return this.sendMessage(background_constants_MessageType.GetEditorStorageContent);
    }
    /**
     * Sends a message to the background page to set the editor storage content.
     *
     * @param content Content to be stored in the editor.
     *
     * @returns Promise that resolves after the message is sent.
     */ async setEditorStorageContent(content) {
        return this.sendMessage(background_constants_MessageType.SetEditorStorageContent, {
            content
        });
    }
    /**
     * Sends a message to the background page to get the rules limits counters for MV3.
     *
     * @returns Promise that resolves with the rules limits counters for MV3.
     */ async getRulesLimitsCounters() {
        return this.sendMessage(background_constants_MessageType.GetRulesLimitsCountersMv3);
    }
    /**
     * Sends a message to the background page to check if it is possible to enable a static filter.
     *
     * @param filterId Filter ID to check.
     *
     * @returns Promise that resolves with the result of the static filter check.
     *
     * @throws Error If the filter is not static.
     */ async canEnableStaticFilter(filterId) {
        return this.sendMessage(background_constants_MessageType.CanEnableStaticFilterMv3, {
            filterId
        });
    }
    /**
     * Sends a message to the background page to check if all dynamic rules for a user rules' group can be enabled.
     *
     * @param groupId Group identifier to check.
     *
     * @returns Promise that resolves with the result of the static group check.
     */ async canEnableStaticGroup(groupId) {
        return this.sendMessage(background_constants_MessageType.CanEnableStaticGroupMv3, {
            groupId
        });
    }
    /**
     * Sends a message to the background page to get the current static filters limits.
     *
     * @returns Promise that resolves with the current static filters limits.
     */ async getCurrentLimits() {
        return this.sendMessage(background_constants_MessageType.CurrentLimitsMv3);
    }
    /**
     * Sends a message to the background page to check if the request filter is ready.
     *
     * @returns Promise that resolves to a boolean indicating if the request filter is ready.
     */ async checkRequestFilterReady() {
        return this.sendMessage(background_constants_MessageType.CheckRequestFilterReady);
    }
    /**
     * Sends a message to the background page to add a URL to the trusted list.
     *
     * @param url URL to be added to the trusted list.
     *
     * @returns Promise that resolves after the message is sent.
     */ async addUrlToTrusted(url) {
        return this.sendMessage(background_constants_MessageType.AddUrlToTrusted, {
            url
        });
    }
    /**
     * Sends a message to the background page to get user rules editor data.
     *
     * @returns Promise that resolves with the user rules editor data.
     */ async getUserRulesEditorData() {
        return this.sendMessage(background_constants_MessageType.GetUserRulesEditorData);
    }
    /**
     * Sends a message to the background page to restore filters in MV3.
     *
     * @returns Promise that resolves after the message is sent.
     */ async restoreFiltersMv3() {
        return this.sendMessage(background_constants_MessageType.RestoreFiltersMv3);
    }
    /**
     * Sends a message to the background page to clear the rules limits warning in MV3.
     *
     * @returns Promise that resolves after the message is sent.
     */ async clearRulesLimitsWarningMv3() {
        return this.sendMessage(background_constants_MessageType.ClearRulesLimitsWarningMv3);
    }
    /**
     * Sends a message to the background page to get the allowlist domains.
     *
     * @returns Promise that resolves with the allowlist domains.
     */ async getAllowlistDomains() {
        return this.sendMessage(background_constants_MessageType.GetAllowlistDomains);
    }
    /**
     * Sends a message to the background page to load the settings JSON.
     *
     * @returns Promise that resolves with the loaded settings JSON.
     */ async loadSettingsJson() {
        return this.sendMessage(background_constants_MessageType.LoadSettingsJson);
    }
    /**
     * Sends a message to the background page to open the thank you page.
     *
     * @returns Promise that resolves after the message is sent.
     */ async openThankyouPage() {
        return this.sendMessage(background_constants_MessageType.OpenThankyouPage);
    }
    /**
     * Sends a message to the background page to initialize the frame script.
     *
     * @returns Promise that resolves with the initialization data for the frame script.
     */ async initializeFrameScript() {
        return this.sendMessage(background_constants_MessageType.InitializeFrameScript);
    }
    /**
     * Sends a message to the background page to mark url as trusted and ignore
     * safebrowsing checks for it.
     *
     * @returns Promise that resolves with the initialization data for the frame script.
     */ async openSafebrowsingTrusted(url) {
        return this.sendMessage(background_constants_MessageType.OpenSafebrowsingTrusted, {
            url
        });
    }
    /**
     * Creates an instance of the Messenger class.
     */ constructor(){
        background_messenger_define_property(this, "onMessage", (background_browser_polyfill_default()).runtime.onMessage);
        /**
     * Method subscribes to notifier module events.
     *
     * @param events List of events to which subscribe.
     * @param callback Callback called when event fires.
     * @param onUnloadCallback Callback used to remove listener on unload.
     *
     * @returns Function to remove listener on unload.
     */ background_messenger_define_property(this, "createEventListener", async (events, callback, onUnloadCallback)=>{
            let listenerId;
            const response = await this.sendMessage(background_constants_MessageType.CreateEventListener, {
                events
            });
            listenerId = response.listenerId;
            const onUpdateListeners = async ()=>{
                const updatedResponse = await this.sendMessage(background_constants_MessageType.CreateEventListener, {
                    events
                });
                listenerId = updatedResponse.listenerId;
            };
            background_browser_polyfill_default().runtime.onMessage.addListener((message)=>{
                if (!background_messageHasTypeField(message)) {
                    background_logger_logger.error('Received message in Messenger.createEventListener has no type field: ', message);
                    return undefined;
                }
                if (message.type === background_constants_MessageType.NotifyListeners) {
                    if (!background_messageHasTypeAndDataFields(message)) {
                        background_logger_logger.error('Received message with type MessageType.NotifyListeners has no data: ', message);
                        return undefined;
                    }
                    const castedMessage = message;
                    const [type, ...data] = castedMessage.data;
                    if (events.includes(type)) {
                        callback({
                            type,
                            data
                        });
                    }
                }
                if (message.type === background_constants_MessageType.UpdateListeners) {
                    onUpdateListeners();
                }
            });
            const onUnload = ()=>{
                if (!listenerId) {
                    return;
                }
                this.sendMessage(background_constants_MessageType.RemoveListener, {
                    listenerId
                });
                listenerId = null;
                if (typeof onUnloadCallback === 'function') {
                    onUnloadCallback();
                }
            };
            window.addEventListener('beforeunload', onUnload);
            window.addEventListener('unload', onUnload);
            return onUnload;
        });
        this.resetUserRulesForPage = this.resetUserRulesForPage.bind(this);
        this.updateFilters = this.updateFilters.bind(this);
        this.removeAllowlistDomain = this.removeAllowlistDomain.bind(this);
        this.addAllowlistDomain = this.addAllowlistDomain.bind(this);
    }
}
/**
     * Creates long-lived connections between popup and background page.
     *
     * @param page Page name.
     * @param events List of events to which subscribe.
     * @param callback Callback called when event fires.
     *
     * @returns Function to remove listener on unload.
     */ background_messenger_define_property(background_Messenger, "createLongLivedConnection", (page, events, callback)=>{
    let port;
    let forceDisconnected = false;
    const connect = ()=>{
        port = background_browser_polyfill_default().runtime.connect({
            name: `${page}_${background_nanoid()}`
        });
        port.postMessage({
            type: background_constants_MessageType.AddLongLivedConnection,
            data: {
                events
            }
        });
        port.onMessage.addListener((message)=>{
            if (!background_messageHasTypeField(message)) {
                background_logger_logger.error('Received message in Messenger.createLongLivedConnection has no type field: ', message);
                return;
            }
            if (message.type === background_constants_MessageType.NotifyListeners) {
                if (!background_messageHasTypeAndDataFields(message)) {
                    background_logger_logger.error('Received message with type MessageType.NotifyListeners has no data: ', message);
                    return;
                }
                const castedMessage = message;
                const [type, ...data] = castedMessage.data;
                callback({
                    type,
                    data
                });
            }
        });
        port.onDisconnect.addListener(()=>{
            if ((background_browser_polyfill_default()).runtime.lastError) {
                background_logger_logger.error((background_browser_polyfill_default()).runtime.lastError.message);
            }
            // we try to connect again if the background page was terminated
            if (!forceDisconnected) {
                connect();
            }
        });
    };
    connect();
    const onUnload = ()=>{
        if (port) {
            forceDisconnected = true;
            port.disconnect();
        }
    };
    window.addEventListener('beforeunload', onUnload);
    window.addEventListener('unload', onUnload);
    return onUnload;
});
const background_messenger = new background_Messenger();


;// ./Extension/src/background/message-handler.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 



/**
 * Common message handler {@link MessageHandler} specified for background
 * messages with type {@link EngineMessage}.
 *
 * @augments MessageHandler {@link MessageHandler}.
 */ class background_BackgroundMessageHandler extends background_MessageHandler {
    /**
     * Handles messages for webextension engine {@link EngineMessage}.
     *
     * @param message Message of basic type {@link Message} or {@link EngineMessage}.
     * @param sender Item of {@link Runtime.MessageSender}.
     *
     * @returns {Promise<unknown> | undefined} The result from the listener,
     * if the listener was found. If not found, an undefined value is returned.
     */ handleMessage(message, sender) {
        if (message.handlerName === background_Engine.messageHandlerName) {
            return background_engine_engine.handleMessage(message, sender);
        }
        if (message.handlerName === background_APP_MESSAGE_HANDLER_NAME) {
            // Check type
            if (!background_BackgroundMessageHandler.isValidMessageType(message)) {
                background_logger_logger.error('Invalid message in BackgroundMessageHandler:', message);
                return;
            }
            const listener = this.listeners.get(message.type);
            if (!listener) {
                return;
            }
            const fn = async ()=>{
                try {
                    return await listener(message, sender);
                } catch (e) {
                    background_logger_logger.error('An error occurred while handling message:', message, 'error:', e);
                    throw e;
                }
            };
            return fn();
        }
    }
}
const background_message_handler_messageHandler = new background_BackgroundMessageHandler();

;// ./Extension/src/background/services/userrules.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ // it is okay to import directly from `@adguard/tswebextension/mv3` without using manifest-dependant alias,
// because checkUserRulesRegexpErrors use only in engine-mv3
function background_userrules_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}








/**
 * Service for handling user rules: reading, adding, deleting.
 */ class background_UserRulesService {
    /**
     * Initializes UserRulesService: creates handlers for operations on user rules.
     *
     * @param engine Engine instance.
     */ static async init(engine) {
        background_UserRulesService.engine = engine;
        background_message_handler_messageHandler.addListener(background_constants_MessageType.GetUserRules, background_UserRulesService.getUserRules);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.GetUserRulesEditorData, background_UserRulesService.getUserRulesEditorData);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.SaveUserRules, background_UserRulesService.handleUserRulesSave);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.AddUserRule, background_UserRulesService.handleUserRuleAdd);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.RemoveUserRule, background_UserRulesService.handleUserRuleRemove);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.GetEditorStorageContent, background_UserRulesService.getEditorStorageContent);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.SetEditorStorageContent, background_UserRulesService.setEditorStorageContent);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.ResetUserRulesForPage, background_UserRulesService.resetUserRulesForPage);
        background_UserRulesService.engine.api.onAssistantCreateRule.subscribe(background_UserRulesService.addUserRule);
        background_settingsEvents.addListener(background_SettingOption.UserFilterEnabled, background_UserRulesService.handleEnableStateChange);
    }
    /**
     * Returns all user rules concatenated via '\n' divider.
     *
     * @returns All user rules concatenated via '\n' divider.
     */ static async getUserRules() {
        return {
            content: await background_UserRulesApi.getOriginalUserRules(),
            appVersion: background_Prefs.version
        };
    }
    /**
     * Returns all user rules concatenated via '\n' divider for the editor.
     *
     * @returns User rules editor content and settings.
     */ static async getUserRulesEditorData() {
        return {
            userRules: await background_UserRulesApi.getOriginalUserRules(),
            settings: background_SettingsApi.getData()
        };
    }
    /**
     * Adds one new user rule.
     *
     * @param rule New user rule.
     */ static async addUserRule(rule) {
        await background_UserRulesApi.addUserRule(rule);
        // update the engine only if the module is enabled
        if (background_UserRulesApi.isEnabled()) {
            background_UserRulesService.engine.debounceUpdate();
        }
    }
    /**
     * Saves new rules and updates the engine.
     *
     * @param message Message of type {@link SaveUserRulesMessage} with new user rules.
     */ static async handleUserRulesSave(message) {
        const { value } = message.data;
        await background_UserRulesApi.setUserRules(value);
        // update the engine only if the module is enabled
        if (background_UserRulesApi.isEnabled()) {
            await background_UserRulesService.engine.update();
        }
    }
    /**
     * Adds new rule and updates the tswebextension engine.
     *
     * @param message Message of type {@link AddUserRuleMessage} with new user rule.
     */ static async handleUserRuleAdd(message) {
        const { ruleText } = message.data;
        await background_UserRulesApi.addUserRule(ruleText);
        // update the engine only if the module is enabled
        if (background_UserRulesApi.isEnabled()) {
            background_UserRulesService.engine.debounceUpdate();
        }
    }
    /**
     * Removes specified rule and updates the tswebextension engine.
     *
     * @param message Message of type {@link RemoveUserRuleMessage} with user rule to delete.
     */ static async handleUserRuleRemove(message) {
        const { ruleText } = message.data;
        await background_UserRulesApi.removeUserRule(ruleText);
        // update the engine only if the module is enabled
        if (background_UserRulesApi.isEnabled()) {
            background_UserRulesService.engine.debounceUpdate();
        }
    }
    /**
     * Updates the tswebextension engine on {@link SettingOption.UserFilterEnabled} setting change.
     * This setting can be changed by the switch ui element, so it is important to update the engine config
     * via debounce function for MV2, as this is a heavyweight call.
     * For MV3 we should wait for the engine to be ready and then check for
     * possible exceeding the limits.
     */ static async handleEnableStateChange() {
        if (true) {
            await background_UserRulesService.engine.update();
        } else {}
    }
    /**
     * Removes user rules for provided url on the specified tab.
     *
     * @param message Message of type {@link ResetUserRulesForPageMessage} with url and tab info.
     */ static async resetUserRulesForPage(message) {
        const { url, tabId } = message.data;
        await background_UserRulesApi.removeRulesByUrl(url);
        await background_UserRulesService.engine.update();
        await background_TabsApi.reload(tabId);
    }
    /**
     * Returns persisted rules during switches between common and fullscreen modes.
     *
     * @returns User rules editor content or undefined if not found.
     */ static getEditorStorageContent() {
        return background_UserRulesApi.getEditorStorageData();
    }
    /**
     * Sets persisted rules during switches between common and fullscreen modes.
     *
     * @param message Message of type {@link SetEditorStorageContentMessage} with content of editor.
     */ static setEditorStorageContent(message) {
        const { content } = message.data;
        background_UserRulesApi.setEditorStorageData(content);
    }
    /**
     * Checks for user rules parsing errors in the configuration result.
     *
     * @param result Configuration result from the engine.
     */ static checkUserRulesRegexpErrors(result) {
        var _result_dynamicRules_errors, _result_dynamicRules;
        if (!background_UserRulesApi.isEnabled()) {
            return;
        }
        const errors = ((_result_dynamicRules = result.dynamicRules) === null || _result_dynamicRules === void 0 ? void 0 : (_result_dynamicRules_errors = _result_dynamicRules.errors) === null || _result_dynamicRules_errors === void 0 ? void 0 : _result_dynamicRules_errors.filter((error)=>error instanceof background_UnsupportedRegexpError)) || [];
        if (errors.length > 0) {
            errors.forEach((error)=>{
                background_logger_logger.error('User rule parsing error:', `\nRule: ${error.networkRule.getText()}`, `\nReason: ${error.reason}`);
            });
        }
    }
}
background_userrules_define_property(background_UserRulesService, "engine", void 0);

// EXTERNAL MODULE: ./node_modules/.pnpm/core-js@3.40.0/node_modules/core-js/modules/web.dom-exception.stack.js
var background_web_dom_exception_stack = __webpack_require__(83659);
// EXTERNAL MODULE: ./node_modules/.pnpm/core-js@3.40.0/node_modules/core-js/modules/es.reflect.to-string-tag.js
var background_es_reflect_to_string_tag = __webpack_require__(24376);
// EXTERNAL MODULE: ./node_modules/.pnpm/core-js@3.40.0/node_modules/core-js/modules/es.string.replace-all.js
var background_es_string_replace_all = __webpack_require__(22114);
// EXTERNAL MODULE: ./node_modules/.pnpm/core-js@3.40.0/node_modules/core-js/modules/es.string.at-alternative.js
var background_es_string_at_alternative = __webpack_require__(59077);
// EXTERNAL MODULE: ./node_modules/.pnpm/core-js@3.40.0/node_modules/core-js/modules/es.array.at.js
var background_es_array_at = __webpack_require__(9539);
;// ./Extension/filters/chromium-mv3/local_script_rules.js
/**
 * By the rules of Chrome Web Store, we cannot use remote scripts.
 *    Because of that, we use the following approach
 *    (you can search the described steps by 'JS_RULES_EXECUTION' in the bundled background.js):
 *
 * 1. We collect and pre-build script rules from the filters (which are pre-built into the extension)
 *    into the add-on (STEP 1.1 and 1.2). See 'updateLocalResourcesForChromiumMv3' in
 *    https://github.com/AdguardTeam/AdguardBrowserExtension/blob/master/tools/resources/update-local-script-rules.ts
 *    and the files called "local_script_rules.js".
 * 2. Collected local scripts are passed to the engine (STEP 2.1 and 2.2).
 * 3. At runtime we check every script rule whether it is included in "local_script_rules.js" (STEP 3).
 * 4. Execution of script rules:
 *     - If the rule is included, we allow this rule to be executed.
 *       Such rules are executed by chrome.scripting API (STEP 4.1 and 4.2). Other rules are discarded.
 */ 











const background_localScriptRules = {
    '(function(){var a=document.currentScript,b=String.prototype.charCodeAt,c=function(){return true;};Object.defineProperty(String.prototype,"charCodeAt",{get:function(){return document.currentScript===a?b:c},set:function(a){}})})();': ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString.a415b8ebbf930b083a9d813bb1a1367a === t) return;
            !function() {
                var t = document.currentScript, e = String.prototype.charCodeAt, r = function() {
                    return !0;
                };
                Object.defineProperty(String.prototype, "charCodeAt", {
                    get: function() {
                        return document.currentScript === t ? e : r;
                    },
                    set: function(t) {}
                });
            }();
            Object.defineProperty(Window.prototype.toString, "a415b8ebbf930b083a9d813bb1a1367a", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "a415b8ebbf930b083a9d813bb1a1367a" due to: ' + t);
        }
    },
    "(function() { var isSet = false; Object.defineProperty(window, 'vas', { get: function() { return isSet ? false : undefined; }, set: function() { isSet = false; } }); })();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.d818588d2f70a2feaf95e6d52f17ccbe === e) return;
            !function() {
                var e = !1;
                Object.defineProperty(window, "vas", {
                    get: function() {
                        return !e && void 0;
                    },
                    set: function() {
                        e = !1;
                    }
                });
            }();
            Object.defineProperty(Window.prototype.toString, "d818588d2f70a2feaf95e6d52f17ccbe", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "d818588d2f70a2feaf95e6d52f17ccbe" due to: ' + e);
        }
    },
    "window.trckd = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["9694a84d652f8dc20c14bac2f5d04885"] === e) return;
            window.trckd = !0;
            Object.defineProperty(Window.prototype.toString, "9694a84d652f8dc20c14bac2f5d04885", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "9694a84d652f8dc20c14bac2f5d04885" due to: ' + e);
        }
    },
    "window.ab = false;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["4b8a3a3cee481368c865f50cdb63083f"] === e) return;
            window.ab = !1;
            Object.defineProperty(Window.prototype.toString, "4b8a3a3cee481368c865f50cdb63083f", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "4b8a3a3cee481368c865f50cdb63083f" due to: ' + e);
        }
    },
    "window.aadnet = {};": ()=>{
        try {
            const d = "done";
            if (Window.prototype.toString["723ed96afa36adad6fac95f60ddc793d"] === d) return;
            window.aadnet = {};
            Object.defineProperty(Window.prototype.toString, "723ed96afa36adad6fac95f60ddc793d", {
                value: d,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (d) {
            console.error('Error executing AG js rule with uniqueId "723ed96afa36adad6fac95f60ddc793d" due to: ' + d);
        }
    },
    "var isadblock=1;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["0528f2e6eabb867d601e3b5619e18249"] === e) return;
            var isadblock = 1;
            Object.defineProperty(Window.prototype.toString, "0528f2e6eabb867d601e3b5619e18249", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "0528f2e6eabb867d601e3b5619e18249" due to: ' + e);
        }
    },
    "function setTimeout() {};": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["2fe08ac469bce8e0959ec04f0f994427"] === e) return;
            function setTimeout1() {}
            Object.defineProperty(Window.prototype.toString, "2fe08ac469bce8e0959ec04f0f994427", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "2fe08ac469bce8e0959ec04f0f994427" due to: ' + t);
        }
    },
    "window.google_jobrunner = function() {};": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["59956228dfe006ac6f5c8faa9d7247e2"] === e) return;
            window.google_jobrunner = function() {};
            Object.defineProperty(Window.prototype.toString, "59956228dfe006ac6f5c8faa9d7247e2", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "59956228dfe006ac6f5c8faa9d7247e2" due to: ' + e);
        }
    },
    "var block = false;": ()=>{
        try {
            const a = "done";
            if (Window.prototype.toString["84381f8c4a4c9c214a07baa32a8b8a38"] === a) return;
            var block = !1;
            Object.defineProperty(Window.prototype.toString, "84381f8c4a4c9c214a07baa32a8b8a38", {
                value: a,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (a) {
            console.error('Error executing AG js rule with uniqueId "84381f8c4a4c9c214a07baa32a8b8a38" due to: ' + a);
        }
    },
    "window.setTimeout=function() {};": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["61f2a933309703d6e7d9383e4428a8e6"] === e) return;
            window.setTimeout = function() {};
            Object.defineProperty(Window.prototype.toString, "61f2a933309703d6e7d9383e4428a8e6", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "61f2a933309703d6e7d9383e4428a8e6" due to: ' + e);
        }
    },
    "var canRunAds = true;": ()=>{
        try {
            const c = "done";
            if (Window.prototype.toString["8a68886c66c8ca4dccac563705f5891c"] === c) return;
            var canRunAds = !0;
            Object.defineProperty(Window.prototype.toString, "8a68886c66c8ca4dccac563705f5891c", {
                value: c,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (c) {
            console.error('Error executing AG js rule with uniqueId "8a68886c66c8ca4dccac563705f5891c" due to: ' + c);
        }
    },
    "Element.prototype.attachShadow = function(){};": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["34432d844bc8123e149136a1ccd4dca3"] === e) return;
            Element.prototype.attachShadow = function() {};
            Object.defineProperty(Window.prototype.toString, "34432d844bc8123e149136a1ccd4dca3", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "34432d844bc8123e149136a1ccd4dca3" due to: ' + e);
        }
    },
    "window.atob = function() {};": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["1dd67b659846dea638d69419abe06c73"] === e) return;
            window.atob = function() {};
            Object.defineProperty(Window.prototype.toString, "1dd67b659846dea638d69419abe06c73", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "1dd67b659846dea638d69419abe06c73" due to: ' + e);
        }
    },
    "window.Worker = function() { this.postMessage = function() {} };": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.f9e77f2ee05d700d3205a8848507f6b1 === e) return;
            window.Worker = function() {
                this.postMessage = function() {};
            };
            Object.defineProperty(Window.prototype.toString, "f9e77f2ee05d700d3205a8848507f6b1", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "f9e77f2ee05d700d3205a8848507f6b1" due to: ' + e);
        }
    },
    "(function() { var intervalId = 0; var blockAds = function() { try { if (typeof BeSeedRotator != 'undefined' && BeSeedRotator.Container.player) { clearInterval(intervalId); BeSeedRotator.showDismissButton(); BeSeedRotator.reCache(); } } catch (ex) {}  }; intervalId = setInterval(blockAds, 100); })();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["52c186b38202f876b11210bbe1307dcf"] === e) return;
            !function() {
                var e = 0;
                e = setInterval(function() {
                    try {
                        if ("undefined" != typeof BeSeedRotator && BeSeedRotator.Container.player) {
                            clearInterval(e);
                            BeSeedRotator.showDismissButton();
                            BeSeedRotator.reCache();
                        }
                    } catch (e) {}
                }, 100);
            }();
            Object.defineProperty(Window.prototype.toString, "52c186b38202f876b11210bbe1307dcf", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "52c186b38202f876b11210bbe1307dcf" due to: ' + e);
        }
    },
    '(function(){var getElementsByTagName=document.getElementsByTagName;document.getElementsByTagName=function(tagName){if(tagName=="script")return[];return getElementsByTagName.call(this,tagName)}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.b1d2d1ecc236da7e56f0c6627c80f309 === e) return;
            !function() {
                var e = document.getElementsByTagName;
                document.getElementsByTagName = function(t) {
                    return "script" == t ? [] : e.call(this, t);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "b1d2d1ecc236da7e56f0c6627c80f309", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "b1d2d1ecc236da7e56f0c6627c80f309" due to: ' + e);
        }
    },
    '(function(){var b={};(function(a,c,d){"undefined"!==typeof window[a]?window[a][c]=d:Object.defineProperty(window,a,{get:function(){return b[a]},set:function(e){b[a]=e;e[c]=d}})})("authConfig","adfox",[])})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.f08e1e484fb2ed477eff5477b270c3ab === e) return;
            !function() {
                var e, o, t, n1 = {};
                e = "authConfig", o = "adfox", t = [], void 0 !== window[e] ? window[e][o] = t : Object.defineProperty(window, e, {
                    get: function() {
                        return n1[e];
                    },
                    set: function(r) {
                        n1[e] = r;
                        r[o] = t;
                    }
                });
            }();
            Object.defineProperty(Window.prototype.toString, "f08e1e484fb2ed477eff5477b270c3ab", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "f08e1e484fb2ed477eff5477b270c3ab" due to: ' + e);
        }
    },
    '!function(){const p={apply:(p,e,n)=>{const r=Reflect.apply(p,e,n),s=r?.[0]?.props?.data;return s&&null===s.user&&(r[0].props.data.user="guest"),r}};window.JSON.parse=new Proxy(window.JSON.parse,p)}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.ff8cf9783100a66d151550ce6ced34a2 === e) return;
            !function() {
                const e = {
                    apply: (e, r, t)=>{
                        var _o__props, _o_;
                        const o = Reflect.apply(e, r, t), n1 = o === null || o === void 0 ? void 0 : (_o_ = o[0]) === null || _o_ === void 0 ? void 0 : (_o__props = _o_.props) === null || _o__props === void 0 ? void 0 : _o__props.data;
                        return n1 && null === n1.user && (o[0].props.data.user = "guest"), o;
                    }
                };
                window.JSON.parse = new Proxy(window.JSON.parse, e);
            }();
            Object.defineProperty(Window.prototype.toString, "ff8cf9783100a66d151550ce6ced34a2", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "ff8cf9783100a66d151550ce6ced34a2" due to: ' + e);
        }
    },
    '(()=>{const a=(a,b,c)=>{const d=Reflect.apply(a,b,c),e="div[id^=\'atf\']:empty { display: none !important; }";if("adoptedStyleSheets"in document){const a=new CSSStyleSheet;a.replaceSync(e),d.adoptedStyleSheets=[a]}else{const a=document.createElement("style");a.innerText=e,d.appendChild(a)}return d};window.Element.prototype.attachShadow=new Proxy(window.Element.prototype.attachShadow,{apply:a})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.b8fa834f4adf06d6a85a989a38de37be === e) return;
            window.Element.prototype.attachShadow = new Proxy(window.Element.prototype.attachShadow, {
                apply: (e, t, a)=>{
                    const o = Reflect.apply(e, t, a), n1 = "div[id^='atf']:empty { display: none !important; }";
                    if ("adoptedStyleSheets" in document) {
                        const e = new CSSStyleSheet;
                        e.replaceSync(n1), o.adoptedStyleSheets = [
                            e
                        ];
                    } else {
                        const e = document.createElement("style");
                        e.innerText = n1, o.appendChild(e);
                    }
                    return o;
                }
            });
            Object.defineProperty(Window.prototype.toString, "b8fa834f4adf06d6a85a989a38de37be", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "b8fa834f4adf06d6a85a989a38de37be" due to: ' + e);
        }
    },
    '(()=>{const o=Math.floor(1e5+9e5*Math.random()),a=`${Date.now()}${o}`;var t,e,m,$;t="_ym_uid",e=a,m="/",$=".gecmisi.com.tr",document.cookie=`${t}=${e};path=${m};domain=${$};`})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["0104074ac36239af0632fc0f2aa96707"] === e) return;
            (()=>{
                const e = Math.floor(1e5 + 9e5 * Math.random());
                var o;
                o = `${Date.now()}${e}`, document.cookie = `_ym_uid=${o};path=/;domain=.gecmisi.com.tr;`;
            })();
            Object.defineProperty(Window.prototype.toString, "0104074ac36239af0632fc0f2aa96707", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "0104074ac36239af0632fc0f2aa96707" due to: ' + e);
        }
    },
    '(()=>{document.addEventListener("DOMContentLoaded",(()=>{const e=document.querySelector(".adsbygoogle:not(.adsbygoogle-noablate)"),t=document.createElement("div");t.textContent=".".repeat(3e3),e.appendChild(t)}));})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.bdadee2d2471bf842565a6d2880f96f2 === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                const e = document.querySelector(".adsbygoogle:not(.adsbygoogle-noablate)"), t = document.createElement("div");
                t.textContent = ".".repeat(3e3), e.appendChild(t);
            });
            Object.defineProperty(Window.prototype.toString, "bdadee2d2471bf842565a6d2880f96f2", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "bdadee2d2471bf842565a6d2880f96f2" due to: ' + e);
        }
    },
    "window.samDetected = false;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.c377d77d43a05809c9a0d8a9ceab3d41 === e) return;
            window.samDetected = !1;
            Object.defineProperty(Window.prototype.toString, "c377d77d43a05809c9a0d8a9ceab3d41", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "c377d77d43a05809c9a0d8a9ceab3d41" due to: ' + e);
        }
    },
    "var _amw1 = 1;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["18c5b42ee23d66b2e421249a57fa79b6"] === e) return;
            var _amw1 = 1;
            Object.defineProperty(Window.prototype.toString, "18c5b42ee23d66b2e421249a57fa79b6", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "18c5b42ee23d66b2e421249a57fa79b6" due to: ' + e);
        }
    },
    "var AdmostClient = 1;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["68f39c1ee25950ec0093a17497f1746a"] === e) return;
            var AdmostClient = 1;
            Object.defineProperty(Window.prototype.toString, "68f39c1ee25950ec0093a17497f1746a", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "68f39c1ee25950ec0093a17497f1746a" due to: ' + e);
        }
    },
    "var advertisement_not_blocked = 1;": ()=>{
        try {
            const d = "done";
            if (Window.prototype.toString["7d86fff0df182d87d917f92dd5565564"] === d) return;
            var advertisement_not_blocked = 1;
            Object.defineProperty(Window.prototype.toString, "7d86fff0df182d87d917f92dd5565564", {
                value: d,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (d) {
            console.error('Error executing AG js rule with uniqueId "7d86fff0df182d87d917f92dd5565564" due to: ' + d);
        }
    },
    "var criteo_medyanet_loaded = 1;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["36a1a7ba76fefd6b56dea5d5a3260cf4"] === e) return;
            var criteo_medyanet_loaded = 1;
            Object.defineProperty(Window.prototype.toString, "36a1a7ba76fefd6b56dea5d5a3260cf4", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "36a1a7ba76fefd6b56dea5d5a3260cf4" due to: ' + e);
        }
    },
    '(function(){var b=window.setTimeout;window.setTimeout=function(a,c){if(!/RTCPeerConnection[\\s\\S]*?new MouseEvent\\("click"/.test(a.toString()))return b(a,c)};})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.ad3cc2fb594ccbd52529466a1f774118 === e) return;
            !function() {
                var e = window.setTimeout;
                window.setTimeout = function(t, o) {
                    if (!/RTCPeerConnection[\s\S]*?new MouseEvent\("click"/.test(t.toString())) return e(t, o);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "ad3cc2fb594ccbd52529466a1f774118", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "ad3cc2fb594ccbd52529466a1f774118" due to: ' + e);
        }
    },
    '!function(){if(-1<window.location.href.indexOf("/?u=aHR0c")){var a=location.href.split("/?u=");if(a[1])try{window.location=atob(a[1])}catch(b){}}}();': ()=>{
        try {
            const o = "done";
            if (Window.prototype.toString["8286156f54f298badd47131511830b06"] === o) return;
            !function() {
                if (-1 < window.location.href.indexOf("/?u=aHR0c")) {
                    var o = location.href.split("/?u=");
                    if (o[1]) try {
                        window.location = atob(o[1]);
                    } catch (o) {}
                }
            }();
            Object.defineProperty(Window.prototype.toString, "8286156f54f298badd47131511830b06", {
                value: o,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (o) {
            console.error('Error executing AG js rule with uniqueId "8286156f54f298badd47131511830b06" due to: ' + o);
        }
    },
    'document.cookie="modalads=yes; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["48f46432b0c186dccc332dff0c8a87fe"] === e) return;
            document.cookie = "modalads=yes; path=/;";
            Object.defineProperty(Window.prototype.toString, "48f46432b0c186dccc332dff0c8a87fe", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "48f46432b0c186dccc332dff0c8a87fe" due to: ' + e);
        }
    },
    "if(window.sessionStorage) { window.sessionStorage.pageCount = 0; }": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["96c1872f8a0322e86045b358d415f5c4"] === e) return;
            window.sessionStorage && (window.sessionStorage.pageCount = 0);
            Object.defineProperty(Window.prototype.toString, "96c1872f8a0322e86045b358d415f5c4", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "96c1872f8a0322e86045b358d415f5c4" due to: ' + e);
        }
    },
    'setTimeout ("HideFloatAdBanner()", 1000);': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["56182d371d85af85aa5af8cbd48e5b34"] === e) return;
            setTimeout("HideFloatAdBanner()", 1e3);
            Object.defineProperty(Window.prototype.toString, "56182d371d85af85aa5af8cbd48e5b34", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "56182d371d85af85aa5af8cbd48e5b34" due to: ' + e);
        }
    },
    '!function(){const e={apply:(e,t,n)=>(n&&n[1]&&"useAdBlockerDetector"===n[1]&&n[2]&&n[2].get&&(n[2].get=function(){return function(){return!1}}),Reflect.apply(e,t,n))};window.Object.defineProperty=new Proxy(window.Object.defineProperty,e)}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["121f6100a828e1c169bfff6bafc69bfd"] === e) return;
            !function() {
                const e = {
                    apply: (e, t, r)=>(r && r[1] && "useAdBlockerDetector" === r[1] && r[2] && r[2].get && (r[2].get = function() {
                            return function() {
                                return !1;
                            };
                        }), Reflect.apply(e, t, r))
                };
                window.Object.defineProperty = new Proxy(window.Object.defineProperty, e);
            }();
            Object.defineProperty(Window.prototype.toString, "121f6100a828e1c169bfff6bafc69bfd", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "121f6100a828e1c169bfff6bafc69bfd" due to: ' + e);
        }
    },
    "window.google_tag_manager = function() {};": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["62de8ad86c59d0b7297a578a18ec0db3"] === e) return;
            window.google_tag_manager = function() {};
            Object.defineProperty(Window.prototype.toString, "62de8ad86c59d0b7297a578a18ec0db3", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "62de8ad86c59d0b7297a578a18ec0db3" due to: ' + e);
        }
    },
    '(()=>{window.TATM=window.TATM||{},TATM.init=()=>{},TATM.initAdUnits=()=>{},TATM.pageReady=()=>{},TATM.getVast=function(n){return new Promise((n=>{n()}))},TATM.push=function(n){if("function"==typeof n)try{n()}catch(n){console.debug(n)}};})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["103de1b5e23e730a477b9b7da10564a4"] === e) return;
            window.TATM = window.TATM || {}, TATM.init = ()=>{}, TATM.initAdUnits = ()=>{}, TATM.pageReady = ()=>{}, TATM.getVast = function(e) {
                return new Promise((e)=>{
                    e();
                });
            }, TATM.push = function(e) {
                if ("function" == typeof e) try {
                    e();
                } catch (e) {
                    console.debug(e);
                }
            };
            Object.defineProperty(Window.prototype.toString, "103de1b5e23e730a477b9b7da10564a4", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "103de1b5e23e730a477b9b7da10564a4" due to: ' + e);
        }
    },
    '(()=>{document.location.href.includes("/pop_advisor")&&window.addEventListener("load",()=>{const e=new CustomEvent("visibilitychange"),t=t=>{Object.defineProperty(t.view.top.document,"hidden",{value:!0,writable:!0}),t.view.top.document.dispatchEvent(e),setTimeout((()=>{Object.defineProperty(t.view.top.document,"hidden",{value:!1,writable:!0}),t.view.top.document.dispatchEvent(e)}),100)},n=document.querySelector("button.btn-continu");n&&n.addEventListener("click",t)});})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["962185cb0a55f058eae7c7389bbc7327"] === e) return;
            document.location.href.includes("/pop_advisor") && window.addEventListener("load", ()=>{
                const e = new CustomEvent("visibilitychange"), t = document.querySelector("button.btn-continu");
                t && t.addEventListener("click", (t)=>{
                    Object.defineProperty(t.view.top.document, "hidden", {
                        value: !0,
                        writable: !0
                    }), t.view.top.document.dispatchEvent(e), setTimeout(()=>{
                        Object.defineProperty(t.view.top.document, "hidden", {
                            value: !1,
                            writable: !0
                        }), t.view.top.document.dispatchEvent(e);
                    }, 100);
                });
            });
            Object.defineProperty(Window.prototype.toString, "962185cb0a55f058eae7c7389bbc7327", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "962185cb0a55f058eae7c7389bbc7327" due to: ' + e);
        }
    },
    '(()=>{document.location.href.includes("/iframe_ad")&&window.addEventListener("load",(()=>{const e=new CustomEvent("visibilitychange"),t=()=>{Object.defineProperty(document,"hidden",{value:!0,writable:!0}),document.dispatchEvent(e),setTimeout((()=>{Object.defineProperty(document,"hidden",{value:!1,writable:!0}),document.dispatchEvent(e)}),100)},n=document.querySelector("a.btn-ad-iframe");n&&n.addEventListener("click",t)}));})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.a715b406996eaeeeaf44515461187620 === e) return;
            document.location.href.includes("/iframe_ad") && window.addEventListener("load", ()=>{
                const e = new CustomEvent("visibilitychange"), t = document.querySelector("a.btn-ad-iframe");
                t && t.addEventListener("click", ()=>{
                    Object.defineProperty(document, "hidden", {
                        value: !0,
                        writable: !0
                    }), document.dispatchEvent(e), setTimeout(()=>{
                        Object.defineProperty(document, "hidden", {
                            value: !1,
                            writable: !0
                        }), document.dispatchEvent(e);
                    }, 100);
                });
            });
            Object.defineProperty(Window.prototype.toString, "a715b406996eaeeeaf44515461187620", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "a715b406996eaeeeaf44515461187620" due to: ' + e);
        }
    },
    '(function(){var a={cmd:[],public:{getVideoAdUrl:function(){},createNewPosition:function(){},refreshAds:function(){},setTargetingOnPosition:function(){},getDailymotionAdsParamsForScript:function(c,a){if("function"==typeof a)try{if(1===a.length){a({})}}catch(a){}}}};a.cmd.push=function(b){let a=function(){try{"function"==typeof b&&b()}catch(a){}};"complete"===document.readyState?a():window.addEventListener("load",()=>{a()})},window.jad=a})();': ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString["176456e95ac0c8ff1ac49bbf30461c8b"] === t) return;
            !function() {
                var t = {
                    cmd: [],
                    public: {
                        getVideoAdUrl: function() {},
                        createNewPosition: function() {},
                        refreshAds: function() {},
                        setTargetingOnPosition: function() {},
                        getDailymotionAdsParamsForScript: function(t, e) {
                            if ("function" == typeof e) try {
                                1 === e.length && e({});
                            } catch (e) {}
                        }
                    }
                };
                t.cmd.push = function(t) {
                    let e = function() {
                        try {
                            "function" == typeof t && t();
                        } catch (t) {}
                    };
                    "complete" === document.readyState ? e() : window.addEventListener("load", ()=>{
                        e();
                    });
                }, window.jad = t;
            }();
            Object.defineProperty(Window.prototype.toString, "176456e95ac0c8ff1ac49bbf30461c8b", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "176456e95ac0c8ff1ac49bbf30461c8b" due to: ' + t);
        }
    },
    "var _st = window.setTimeout; window.setTimeout = function(a, b) { if(!/target_url/.test(a)){ _st(a,b);}};": ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString["315672b76833d426a2a0b83c85c50797"] === t) return;
            var _st = window.setTimeout;
            window.setTimeout = function(t, e) {
                /target_url/.test(t) || _st(t, e);
            };
            Object.defineProperty(Window.prototype.toString, "315672b76833d426a2a0b83c85c50797", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "315672b76833d426a2a0b83c85c50797" due to: ' + t);
        }
    },
    '(function(){let callCounter=0;const nativeJSONParse=JSON.parse;const handler={apply(){callCounter++;const obj=Reflect.apply(...arguments);if(callCounter<=10){if(obj.hasOwnProperty("appName")){if(obj.applaunch?.data?.player?.features?.ad?.enabled){obj.applaunch.data.player.features.ad.enabled=false}if(obj.applaunch?.data?.player?.features?.ad?.dai?.enabled){obj.applaunch.data.player.features.ad.dai.enabled=false}}}else{JSON.parse=nativeJSONParse}return obj}};JSON.parse=new Proxy(JSON.parse,handler)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["03b60dbf8e3b5b8f2423393210afcf06"] === e) return;
            !function() {
                let e = 0;
                const a = JSON.parse, r = {
                    apply () {
                        e++;
                        const r = Reflect.apply(...arguments);
                        if (e <= 10) {
                            if (r.hasOwnProperty("appName")) {
                                var _r_applaunch_data_player_features_ad, _r_applaunch_data_player_features, _r_applaunch_data_player, _r_applaunch_data, _r_applaunch, _r_applaunch_data_player_features_ad_dai, _r_applaunch_data_player_features_ad1, _r_applaunch_data_player_features1, _r_applaunch_data_player1, _r_applaunch_data1, _r_applaunch1;
                                ((_r_applaunch = r.applaunch) === null || _r_applaunch === void 0 ? void 0 : (_r_applaunch_data = _r_applaunch.data) === null || _r_applaunch_data === void 0 ? void 0 : (_r_applaunch_data_player = _r_applaunch_data.player) === null || _r_applaunch_data_player === void 0 ? void 0 : (_r_applaunch_data_player_features = _r_applaunch_data_player.features) === null || _r_applaunch_data_player_features === void 0 ? void 0 : (_r_applaunch_data_player_features_ad = _r_applaunch_data_player_features.ad) === null || _r_applaunch_data_player_features_ad === void 0 ? void 0 : _r_applaunch_data_player_features_ad.enabled) && (r.applaunch.data.player.features.ad.enabled = !1);
                                ((_r_applaunch1 = r.applaunch) === null || _r_applaunch1 === void 0 ? void 0 : (_r_applaunch_data1 = _r_applaunch1.data) === null || _r_applaunch_data1 === void 0 ? void 0 : (_r_applaunch_data_player1 = _r_applaunch_data1.player) === null || _r_applaunch_data_player1 === void 0 ? void 0 : (_r_applaunch_data_player_features1 = _r_applaunch_data_player1.features) === null || _r_applaunch_data_player_features1 === void 0 ? void 0 : (_r_applaunch_data_player_features_ad1 = _r_applaunch_data_player_features1.ad) === null || _r_applaunch_data_player_features_ad1 === void 0 ? void 0 : (_r_applaunch_data_player_features_ad_dai = _r_applaunch_data_player_features_ad1.dai) === null || _r_applaunch_data_player_features_ad_dai === void 0 ? void 0 : _r_applaunch_data_player_features_ad_dai.enabled) && (r.applaunch.data.player.features.ad.dai.enabled = !1);
                            }
                        } else JSON.parse = a;
                        return r;
                    }
                };
                JSON.parse = new Proxy(JSON.parse, r);
            }();
            Object.defineProperty(Window.prototype.toString, "03b60dbf8e3b5b8f2423393210afcf06", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "03b60dbf8e3b5b8f2423393210afcf06" due to: ' + e);
        }
    },
    "(function(){let callCounter=0;const nativeJSONParse=JSON.parse;const handler={apply(){callCounter++;const obj=Reflect.apply(...arguments);if(callCounter<=10){if(obj.hasOwnProperty('env')&&obj.env.hasOwnProperty('origin')){if(!obj.hasOwnProperty('ads')){obj.ads={};}obj.ads.enable=false;obj.ads._prerolls=false;obj.ads._midrolls=false;}}else{JSON.parse=nativeJSONParse;}return obj;}};JSON.parse=new Proxy(JSON.parse,handler);})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["076ec28f8d5bd40b7dc4be56dc82b841"] === e) return;
            !function() {
                let e = 0;
                const r = JSON.parse, o = {
                    apply () {
                        e++;
                        const o = Reflect.apply(...arguments);
                        if (e <= 10) {
                            if (o.hasOwnProperty("env") && o.env.hasOwnProperty("origin")) {
                                o.hasOwnProperty("ads") || (o.ads = {});
                                o.ads.enable = !1;
                                o.ads._prerolls = !1;
                                o.ads._midrolls = !1;
                            }
                        } else JSON.parse = r;
                        return o;
                    }
                };
                JSON.parse = new Proxy(JSON.parse, o);
            }();
            Object.defineProperty(Window.prototype.toString, "076ec28f8d5bd40b7dc4be56dc82b841", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "076ec28f8d5bd40b7dc4be56dc82b841" due to: ' + e);
        }
    },
    '(()=>{window.patroniteGdprData={google_recaptcha:"allow"}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.fc25d8c99ebbbc3be6aedb39d0c00819 === e) return;
            window.patroniteGdprData = {
                google_recaptcha: "allow"
            };
            Object.defineProperty(Window.prototype.toString, "fc25d8c99ebbbc3be6aedb39d0c00819", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "fc25d8c99ebbbc3be6aedb39d0c00819" due to: ' + e);
        }
    },
    '(()=>{let t;const e=new MutationObserver(((e,o)=>{const n=t?.querySelector(\'button[data-testid="button-agree"]\');n&&(setTimeout((()=>{n.click()}),500),o.disconnect())})),o={apply:(o,n,c)=>{const a=Reflect.apply(o,n,c);return n.matches(".szn-cmp-dialog-container")&&(t=a),e.observe(a,{subtree:!0,childList:!0}),a}};window.Element.prototype.attachShadow=new Proxy(window.Element.prototype.attachShadow,o)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["2bca593aa0d901f23a66e9e0ba973abc"] === e) return;
            (()=>{
                let e;
                const t = new MutationObserver((t, a)=>{
                    const o = e === null || e === void 0 ? void 0 : e.querySelector('button[data-testid="button-agree"]');
                    o && (setTimeout(()=>{
                        o.click();
                    }, 500), a.disconnect());
                }), a = {
                    apply: (a, o, r)=>{
                        const n1 = Reflect.apply(a, o, r);
                        return o.matches(".szn-cmp-dialog-container") && (e = n1), t.observe(n1, {
                            subtree: !0,
                            childList: !0
                        }), n1;
                    }
                };
                window.Element.prototype.attachShadow = new Proxy(window.Element.prototype.attachShadow, a);
            })();
            Object.defineProperty(Window.prototype.toString, "2bca593aa0d901f23a66e9e0ba973abc", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "2bca593aa0d901f23a66e9e0ba973abc" due to: ' + e);
        }
    },
    '(function(){var noopFunc=function(){};var tcData={eventStatus:"tcloaded",gdprApplies:!1,listenerId:noopFunc,vendor:{consents:{967:true}},purpose:{consents:[]}};window.__tcfapi=function(command,version,callback){"function"==typeof callback&&"removeEventListener"!==command&&callback(tcData,!0)}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["905285a22b2c90f963ab16245e1f463b"] === e) return;
            !function() {
                var e = {
                    eventStatus: "tcloaded",
                    gdprApplies: !1,
                    listenerId: function() {},
                    vendor: {
                        consents: {
                            967: !0
                        }
                    },
                    purpose: {
                        consents: []
                    }
                };
                window.__tcfapi = function(t, n1, o) {
                    "function" == typeof o && "removeEventListener" !== t && o(e, !0);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "905285a22b2c90f963ab16245e1f463b", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "905285a22b2c90f963ab16245e1f463b" due to: ' + e);
        }
    },
    'document.cookie="PostAnalytics=inactive; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["8dd64e0e5c7cfb7ada0186747714df1b"] === e) return;
            document.cookie = "PostAnalytics=inactive; path=/;";
            Object.defineProperty(Window.prototype.toString, "8dd64e0e5c7cfb7ada0186747714df1b", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "8dd64e0e5c7cfb7ada0186747714df1b" due to: ' + e);
        }
    },
    "document.cookie='cmplz_consented_services={\"youtube\":true};path=/;';": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["8cbd0cd2ffcfd41b8dd501b4861c18e3"] === e) return;
            document.cookie = 'cmplz_consented_services={"youtube":true};path=/;';
            Object.defineProperty(Window.prototype.toString, "8cbd0cd2ffcfd41b8dd501b4861c18e3", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "8cbd0cd2ffcfd41b8dd501b4861c18e3" due to: ' + e);
        }
    },
    '(function(){if(!document.cookie.includes("CookieInformationConsent=")){var a=encodeURIComponent(\'{"website_uuid":"","timestamp":"","consent_url":"","consent_website":"jysk.nl","consent_domain":"jysk.nl","user_uid":"","consents_approved":["cookie_cat_necessary","cookie_cat_functional","cookie_cat_statistic"],"consents_denied":[],"user_agent":""}\');document.cookie="CookieInformationConsent="+a+"; path=/;"}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["4e7a66fe06a58f87f9deb67cb85b8a2c"] === e) return;
            !function() {
                if (!document.cookie.includes("CookieInformationConsent=")) {
                    var e = encodeURIComponent('{"website_uuid":"","timestamp":"","consent_url":"","consent_website":"jysk.nl","consent_domain":"jysk.nl","user_uid":"","consents_approved":["cookie_cat_necessary","cookie_cat_functional","cookie_cat_statistic"],"consents_denied":[],"user_agent":""}');
                    document.cookie = "CookieInformationConsent=" + e + "; path=/;";
                }
            }();
            Object.defineProperty(Window.prototype.toString, "4e7a66fe06a58f87f9deb67cb85b8a2c", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "4e7a66fe06a58f87f9deb67cb85b8a2c" due to: ' + e);
        }
    },
    'document.cookie=\'cookie_consent_level={"functionality":true,"strictly-necessary":true,"targeting":false,"tracking":false}; path=/;\';': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.bee65ec0755ccff706db52148c4173c7 === e) return;
            document.cookie = 'cookie_consent_level={"functionality":true,"strictly-necessary":true,"targeting":false,"tracking":false}; path=/;';
            Object.defineProperty(Window.prototype.toString, "bee65ec0755ccff706db52148c4173c7", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "bee65ec0755ccff706db52148c4173c7" due to: ' + e);
        }
    },
    '(function(){try{var a=location.pathname.split("/")[1],b="dra_cookie_consent_allowed_"+a,c=new RegExp(/[a-z]+_[a-z]+/);if(!document.cookie.includes(b)&&c.test(a)){var d=encodeURIComponent("v=1&t=1&f=1&s=0&m=0");document.cookie=b+"="+d+"; path=/;"}}catch(e){}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["89284264a9e746e269120c04d8e07578"] === e) return;
            !function() {
                try {
                    var e = location.pathname.split("/")[1], o = "dra_cookie_consent_allowed_" + e, t = new RegExp(/[a-z]+_[a-z]+/);
                    if (!document.cookie.includes(o) && t.test(e)) {
                        var n1 = encodeURIComponent("v=1&t=1&f=1&s=0&m=0");
                        document.cookie = o + "=" + n1 + "; path=/;";
                    }
                } catch (e) {}
            }();
            Object.defineProperty(Window.prototype.toString, "89284264a9e746e269120c04d8e07578", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "89284264a9e746e269120c04d8e07578" due to: ' + e);
        }
    },
    'document.cookie="dw_cookies_accepted=D; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["65ddec250513cfa895af9e691c980515"] === e) return;
            document.cookie = "dw_cookies_accepted=D; path=/;";
            Object.defineProperty(Window.prototype.toString, "65ddec250513cfa895af9e691c980515", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "65ddec250513cfa895af9e691c980515" due to: ' + e);
        }
    },
    '(function(){document.cookie.includes("cookies-consents")||(document.cookie=\'cookies-consents={"ad_storage":false,"analytics_storage":false}\')})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.ccaa77db2be3c96b3a11b73a501af1f1 === e) return;
            document.cookie.includes("cookies-consents") || (document.cookie = 'cookies-consents={"ad_storage":false,"analytics_storage":false}');
            Object.defineProperty(Window.prototype.toString, "ccaa77db2be3c96b3a11b73a501af1f1", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "ccaa77db2be3c96b3a11b73a501af1f1" due to: ' + e);
        }
    },
    'document.cookie="ubCmpSettings=eyJnZW1laW5kZW5fc2VsZWN0ZWRfdmFsdWUiOnRydWUsImdvb2dsZV9hbmFseXRpY3MiOmZhbHNlLCJhZF90cmFja2luZyI6ZmFsc2UsInNvY2lhbF9lbWJlZHMiOnRydWV9;path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["58bc9348bcf4f1f2b6163529b3298384"] === e) return;
            document.cookie = "ubCmpSettings=eyJnZW1laW5kZW5fc2VsZWN0ZWRfdmFsdWUiOnRydWUsImdvb2dsZV9hbmFseXRpY3MiOmZhbHNlLCJhZF90cmFja2luZyI6ZmFsc2UsInNvY2lhbF9lbWJlZHMiOnRydWV9;path=/;";
            Object.defineProperty(Window.prototype.toString, "58bc9348bcf4f1f2b6163529b3298384", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "58bc9348bcf4f1f2b6163529b3298384" due to: ' + e);
        }
    },
    'document.cookie="cookieconsent_status=allow; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["95e24d457a7de10b441b7cbe6b509b42"] === e) return;
            document.cookie = "cookieconsent_status=allow; path=/;";
            Object.defineProperty(Window.prototype.toString, "95e24d457a7de10b441b7cbe6b509b42", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "95e24d457a7de10b441b7cbe6b509b42" due to: ' + e);
        }
    },
    'document.cookie="cookieConsentLevel=functional; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["787f6ec1d270f080d84075658a3154bd"] === e) return;
            document.cookie = "cookieConsentLevel=functional; path=/;";
            Object.defineProperty(Window.prototype.toString, "787f6ec1d270f080d84075658a3154bd", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "787f6ec1d270f080d84075658a3154bd" due to: ' + e);
        }
    },
    'document.cookie="cookies_accept=all; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["25fbbc330687fea937e26e0888468fc1"] === e) return;
            document.cookie = "cookies_accept=all; path=/;";
            Object.defineProperty(Window.prototype.toString, "25fbbc330687fea937e26e0888468fc1", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "25fbbc330687fea937e26e0888468fc1" due to: ' + e);
        }
    },
    'document.cookie="waconcookiemanagement=min; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["0898665962f7d4da16a3e93e72148415"] === e) return;
            document.cookie = "waconcookiemanagement=min; path=/;";
            Object.defineProperty(Window.prototype.toString, "0898665962f7d4da16a3e93e72148415", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "0898665962f7d4da16a3e93e72148415" due to: ' + e);
        }
    },
    'document.cookie="apcAcceptedTrackingCookie3=1111000; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.ebce46e2aa13a6690a7be922ea601529 === e) return;
            document.cookie = "apcAcceptedTrackingCookie3=1111000; path=/;";
            Object.defineProperty(Window.prototype.toString, "ebce46e2aa13a6690a7be922ea601529", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "ebce46e2aa13a6690a7be922ea601529" due to: ' + e);
        }
    },
    'document.cookie="bbDatenstufe=stufe3; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["9d2c1d25c86235dc271dab2c2b2e99b2"] === e) return;
            document.cookie = "bbDatenstufe=stufe3; path=/;";
            Object.defineProperty(Window.prototype.toString, "9d2c1d25c86235dc271dab2c2b2e99b2", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "9d2c1d25c86235dc271dab2c2b2e99b2" due to: ' + e);
        }
    },
    'document.cookie="newsletter-signup=viewed; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["0cee21006fa668615b19188582a82e34"] === e) return;
            document.cookie = "newsletter-signup=viewed; path=/;";
            Object.defineProperty(Window.prototype.toString, "0cee21006fa668615b19188582a82e34", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "0cee21006fa668615b19188582a82e34" due to: ' + e);
        }
    },
    'document.cookie="user_cookie_consent=essential; path=/";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["00c1162ebf92fa57d12e33c78f9ab876"] === e) return;
            document.cookie = "user_cookie_consent=essential; path=/";
            Object.defineProperty(Window.prototype.toString, "00c1162ebf92fa57d12e33c78f9ab876", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "00c1162ebf92fa57d12e33c78f9ab876" due to: ' + e);
        }
    },
    'document.cookie="cookiebanner=closed; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["64b6a01f2a020125dffd898bafb19615"] === e) return;
            document.cookie = "cookiebanner=closed; path=/;";
            Object.defineProperty(Window.prototype.toString, "64b6a01f2a020125dffd898bafb19615", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "64b6a01f2a020125dffd898bafb19615" due to: ' + e);
        }
    },
    'document.cookie=\'allow_cookies={"essential":"1","functional":{"all":"1"},"marketing":{"all":"0"}}; path=/;\';': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.d61d4bd09c7716fa4e2f0235b892e274 === e) return;
            document.cookie = 'allow_cookies={"essential":"1","functional":{"all":"1"},"marketing":{"all":"0"}}; path=/;';
            Object.defineProperty(Window.prototype.toString, "d61d4bd09c7716fa4e2f0235b892e274", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "d61d4bd09c7716fa4e2f0235b892e274" due to: ' + e);
        }
    },
    '(function(){-1==document.cookie.indexOf("GPRD")&&(document.cookie="GPRD=128; path=/;",location.reload())})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.dcadc5846fed7b2f033974e6075c5fed === e) return;
            -1 == document.cookie.indexOf("GPRD") && (document.cookie = "GPRD=128; path=/;", location.reload());
            Object.defineProperty(Window.prototype.toString, "dcadc5846fed7b2f033974e6075c5fed", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "dcadc5846fed7b2f033974e6075c5fed" due to: ' + e);
        }
    },
    'document.cookie="acceptRodoSie=hide; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.d52e913bca352f639daec5b240f07513 === e) return;
            document.cookie = "acceptRodoSie=hide; path=/;";
            Object.defineProperty(Window.prototype.toString, "d52e913bca352f639daec5b240f07513", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "d52e913bca352f639daec5b240f07513" due to: ' + e);
        }
    },
    '(function(){-1==document.cookie.indexOf("cookie-functional")&&(document.cookie="cookie-functional=1; path=/;",document.cookie="popupek=1; path=/;",location.reload())})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["23d2c0ec8e7bc0167527c1acc5bb5355"] === e) return;
            -1 == document.cookie.indexOf("cookie-functional") && (document.cookie = "cookie-functional=1; path=/;", document.cookie = "popupek=1; path=/;", location.reload());
            Object.defineProperty(Window.prototype.toString, "23d2c0ec8e7bc0167527c1acc5bb5355", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "23d2c0ec8e7bc0167527c1acc5bb5355" due to: ' + e);
        }
    },
    '(function(){-1==document.cookie.indexOf("ccb")&&(document.cookie="ccb=facebookAccepted=0&googleAnalyticsAccepted=0&commonCookies=1; path=/;",location.reload())})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.f2aea7e44ba000bb61336ea707125580 === e) return;
            -1 == document.cookie.indexOf("ccb") && (document.cookie = "ccb=facebookAccepted=0&googleAnalyticsAccepted=0&commonCookies=1; path=/;", location.reload());
            Object.defineProperty(Window.prototype.toString, "f2aea7e44ba000bb61336ea707125580", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "f2aea7e44ba000bb61336ea707125580" due to: ' + e);
        }
    },
    "(function(){-1===document.cookie.indexOf(\"CookieConsent\")&&(document.cookie='CookieConsent=mandatory|osm; path=/;')})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.f7a28a06b7a2a2e94cb072030083586d === e) return;
            -1 === document.cookie.indexOf("CookieConsent") && (document.cookie = "CookieConsent=mandatory|osm; path=/;");
            Object.defineProperty(Window.prototype.toString, "f7a28a06b7a2a2e94cb072030083586d", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "f7a28a06b7a2a2e94cb072030083586d" due to: ' + e);
        }
    },
    '(function(){-1===document.cookie.indexOf("CookieControl")&&(document.cookie=\'CookieControl={"necessaryCookies":["wordpress_*","wordpress_logged_in_*","CookieControl"],"optionalCookies":{"functional_cookies":"accepted"}}\')})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["06ad4ed929d84e1793e13be6c4a31b38"] === e) return;
            -1 === document.cookie.indexOf("CookieControl") && (document.cookie = 'CookieControl={"necessaryCookies":["wordpress_*","wordpress_logged_in_*","CookieControl"],"optionalCookies":{"functional_cookies":"accepted"}}');
            Object.defineProperty(Window.prototype.toString, "06ad4ed929d84e1793e13be6c4a31b38", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "06ad4ed929d84e1793e13be6c4a31b38" due to: ' + e);
        }
    },
    '(function(){if(-1==document.cookie.indexOf("CONSENT")){var c=new Date, d=c.getTime(), date = new Date(d + 365 * 60 * 60 * 1000); document.cookie="CONSENT=301212NN; path=/; expires=" + date.toUTCString(), location.reload()}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["2f7b46464b7a29f89080a98e454b73a8"] === e) return;
            !function() {
                if (-1 == document.cookie.indexOf("CONSENT")) {
                    var e = (new Date).getTime(), o = new Date(e + 1314e6);
                    document.cookie = "CONSENT=301212NN; path=/; expires=" + o.toUTCString(), location.reload();
                }
            }();
            Object.defineProperty(Window.prototype.toString, "2f7b46464b7a29f89080a98e454b73a8", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "2f7b46464b7a29f89080a98e454b73a8" due to: ' + e);
        }
    },
    'document.cookie="dsgvo=basic; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.c8f808a7e878f97d64286800484605d0 === e) return;
            document.cookie = "dsgvo=basic; path=/;";
            Object.defineProperty(Window.prototype.toString, "c8f808a7e878f97d64286800484605d0", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "c8f808a7e878f97d64286800484605d0" due to: ' + e);
        }
    },
    '(function(){if(!document.cookie.includes("CookieInformationConsent=")){var a=encodeURIComponent(\'{"website_uuid":"","timestamp":"","consent_url":"","consent_website":"elkjop.no","consent_domain":"elkjop.no","user_uid":"","consents_approved":["cookie_cat_necessary","cookie_cat_functional","cookie_cat_statistic"],"consents_denied":[],"user_agent":""}\');document.cookie="CookieInformationConsent="+a+"; path=/;"}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["6051620f594fcf9636bd68b417cb0e5b"] === e) return;
            !function() {
                if (!document.cookie.includes("CookieInformationConsent=")) {
                    var e = encodeURIComponent('{"website_uuid":"","timestamp":"","consent_url":"","consent_website":"elkjop.no","consent_domain":"elkjop.no","user_uid":"","consents_approved":["cookie_cat_necessary","cookie_cat_functional","cookie_cat_statistic"],"consents_denied":[],"user_agent":""}');
                    document.cookie = "CookieInformationConsent=" + e + "; path=/;";
                }
            }();
            Object.defineProperty(Window.prototype.toString, "6051620f594fcf9636bd68b417cb0e5b", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "6051620f594fcf9636bd68b417cb0e5b" due to: ' + e);
        }
    },
    '(function(){var a={timestamp:(new Date).getTime(),choice:2,version:"1.0"};document.cookie="mxp="+JSON.stringify(a)+"; path=/"})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["4cdd2100913b4096462563fee10f5daa"] === e) return;
            !function() {
                var e = {
                    timestamp: (new Date).getTime(),
                    choice: 2,
                    version: "1.0"
                };
                document.cookie = "mxp=" + JSON.stringify(e) + "; path=/";
            }();
            Object.defineProperty(Window.prototype.toString, "4cdd2100913b4096462563fee10f5daa", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "4cdd2100913b4096462563fee10f5daa" due to: ' + e);
        }
    },
    '(function(){if(-1==document.cookie.indexOf("_chorus_privacy_consent")&&document.location.hostname.includes("bavarianfootballworks.com")){var c=new Date, d=c.getTime(), date = new Date(d + 365 * 60 * 60 * 1000); document.cookie="_chorus_privacy_consent="+d+"; path=/; expires=" + date.toUTCString(), location.reload()}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["504f6b7ac8c9c857fc49addc0eb518fd"] === e) return;
            !function() {
                if (-1 == document.cookie.indexOf("_chorus_privacy_consent") && document.location.hostname.includes("bavarianfootballworks.com")) {
                    var e = (new Date).getTime(), o = new Date(e + 1314e6);
                    document.cookie = "_chorus_privacy_consent=" + e + "; path=/; expires=" + o.toUTCString(), location.reload();
                }
            }();
            Object.defineProperty(Window.prototype.toString, "504f6b7ac8c9c857fc49addc0eb518fd", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "504f6b7ac8c9c857fc49addc0eb518fd" due to: ' + e);
        }
    },
    '(function(){if(-1==document.cookie.indexOf("_chorus_privacy_consent")&&document.location.hostname.includes("goldenstateofmind.com")){var c=new Date, d=c.getTime(), date = new Date(d + 365 * 60 * 60 * 1000); document.cookie="_chorus_privacy_consent="+d+"; path=/; expires=" + date.toUTCString(), location.reload()}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["62fd4c05daebdd55280e0b23009cc9aa"] === e) return;
            !function() {
                if (-1 == document.cookie.indexOf("_chorus_privacy_consent") && document.location.hostname.includes("goldenstateofmind.com")) {
                    var e = (new Date).getTime(), o = new Date(e + 1314e6);
                    document.cookie = "_chorus_privacy_consent=" + e + "; path=/; expires=" + o.toUTCString(), location.reload();
                }
            }();
            Object.defineProperty(Window.prototype.toString, "62fd4c05daebdd55280e0b23009cc9aa", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "62fd4c05daebdd55280e0b23009cc9aa" due to: ' + e);
        }
    },
    '(function(){if(-1==document.cookie.indexOf("_chorus_privacy_consent")&&document.location.hostname.includes("mmafighting.com")){var c=new Date, d=c.getTime(), date = new Date(d + 365 * 60 * 60 * 1000); document.cookie="_chorus_privacy_consent="+d+"; path=/; expires=" + date.toUTCString(), location.reload()}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["1a42ed4d4e4e6922f6fda946f00f4816"] === e) return;
            !function() {
                if (-1 == document.cookie.indexOf("_chorus_privacy_consent") && document.location.hostname.includes("mmafighting.com")) {
                    var e = (new Date).getTime(), o = new Date(e + 1314e6);
                    document.cookie = "_chorus_privacy_consent=" + e + "; path=/; expires=" + o.toUTCString(), location.reload();
                }
            }();
            Object.defineProperty(Window.prototype.toString, "1a42ed4d4e4e6922f6fda946f00f4816", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "1a42ed4d4e4e6922f6fda946f00f4816" due to: ' + e);
        }
    },
    '(function(){-1==document.cookie.indexOf("cms_cookies")&&(document.cookie="cms_cookies=6; path=/;",document.cookie="cms_cookies_saved=true; path=/;",location.reload())})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.c69eca07b387ee449234ff30bf5ce30e === e) return;
            -1 == document.cookie.indexOf("cms_cookies") && (document.cookie = "cms_cookies=6; path=/;", document.cookie = "cms_cookies_saved=true; path=/;", location.reload());
            Object.defineProperty(Window.prototype.toString, "c69eca07b387ee449234ff30bf5ce30e", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "c69eca07b387ee449234ff30bf5ce30e" due to: ' + e);
        }
    },
    'document.cookie="erlaubte_cookies=1; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.fa4fb1ef63a96ddb1e25a44e7d9cfcfe === e) return;
            document.cookie = "erlaubte_cookies=1; path=/;";
            Object.defineProperty(Window.prototype.toString, "fa4fb1ef63a96ddb1e25a44e7d9cfcfe", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "fa4fb1ef63a96ddb1e25a44e7d9cfcfe" due to: ' + e);
        }
    },
    'document.cookie="klaviano_police=1; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["0625bed2a838c73f77094993c60b81cc"] === e) return;
            document.cookie = "klaviano_police=1; path=/;";
            Object.defineProperty(Window.prototype.toString, "0625bed2a838c73f77094993c60b81cc", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "0625bed2a838c73f77094993c60b81cc" due to: ' + e);
        }
    },
    'document.cookie=\'cookieConsent={"statistical":0,"personalization":0,"targeting":0}; path=/;\';': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.f5b9b753afe5738b6731ee8166dcd891 === e) return;
            document.cookie = 'cookieConsent={"statistical":0,"personalization":0,"targeting":0}; path=/;';
            Object.defineProperty(Window.prototype.toString, "f5b9b753afe5738b6731ee8166dcd891", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "f5b9b753afe5738b6731ee8166dcd891" due to: ' + e);
        }
    },
    '(function(){if(!document.cookie.includes("trackingPermissionConsentsValue=")){var a=encodeURIComponent(\'"cookies_analytics":false,"cookies_personalization":false,"cookies_advertisement":false\');document.cookie="trackingPermissionConsentsValue={"+a+"}; path=/;"}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.c99384d0ca41c87dbb63212ebb71470f === e) return;
            !function() {
                if (!document.cookie.includes("trackingPermissionConsentsValue=")) {
                    var e = encodeURIComponent('"cookies_analytics":false,"cookies_personalization":false,"cookies_advertisement":false');
                    document.cookie = "trackingPermissionConsentsValue={" + e + "}; path=/;";
                }
            }();
            Object.defineProperty(Window.prototype.toString, "c99384d0ca41c87dbb63212ebb71470f", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "c99384d0ca41c87dbb63212ebb71470f" due to: ' + e);
        }
    },
    'document.cookie="allowTracking=false; path=/;"; document.cookie="trackingSettings={%22ads%22:false%2C%22performance%22:false}; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["380715610fe9f7be74ee211b5df06559"] === e) return;
            document.cookie = "allowTracking=false; path=/;";
            document.cookie = "trackingSettings={%22ads%22:false%2C%22performance%22:false}; path=/;";
            Object.defineProperty(Window.prototype.toString, "380715610fe9f7be74ee211b5df06559", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "380715610fe9f7be74ee211b5df06559" due to: ' + e);
        }
    },
    'document.cookie="userConsent=%7B%22marketing%22%3Afalse%2C%22version%22%3A%221%22%7D; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["967efe0b8b7e9d602d9c0ecdf20fc0cf"] === e) return;
            document.cookie = "userConsent=%7B%22marketing%22%3Afalse%2C%22version%22%3A%221%22%7D; path=/;";
            Object.defineProperty(Window.prototype.toString, "967efe0b8b7e9d602d9c0ecdf20fc0cf", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "967efe0b8b7e9d602d9c0ecdf20fc0cf" due to: ' + e);
        }
    },
    'document.cookie="sendgb_cookiewarning=1; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["190bccd6dfb21f403e2765c76b59110f"] === e) return;
            document.cookie = "sendgb_cookiewarning=1; path=/;";
            Object.defineProperty(Window.prototype.toString, "190bccd6dfb21f403e2765c76b59110f", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "190bccd6dfb21f403e2765c76b59110f" due to: ' + e);
        }
    },
    'document.cookie="rodopop=1; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["9ed981f72e0e18755c3a1ffe09bbd2ba"] === e) return;
            document.cookie = "rodopop=1; path=/;";
            Object.defineProperty(Window.prototype.toString, "9ed981f72e0e18755c3a1ffe09bbd2ba", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "9ed981f72e0e18755c3a1ffe09bbd2ba" due to: ' + e);
        }
    },
    'document.cookie="eu_cn=1; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["868ecbdfeac245c25b130bfba6792d71"] === e) return;
            document.cookie = "eu_cn=1; path=/;";
            Object.defineProperty(Window.prototype.toString, "868ecbdfeac245c25b130bfba6792d71", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "868ecbdfeac245c25b130bfba6792d71" due to: ' + e);
        }
    },
    'document.cookie="gdprAccepted=true; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["2c12d864ca83dfdf8bc7e1c395c19fef"] === e) return;
            document.cookie = "gdprAccepted=true; path=/;";
            Object.defineProperty(Window.prototype.toString, "2c12d864ca83dfdf8bc7e1c395c19fef", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "2c12d864ca83dfdf8bc7e1c395c19fef" due to: ' + e);
        }
    },
    '(function(){if(-1==document.cookie.indexOf("BCPermissionLevel")){var c=new Date, d=c.getTime(), date = new Date(d + 365 * 60 * 60 * 1000); document.cookie="BCPermissionLevel=PERSONAL; path=/; expires=" + date.toUTCString(), location.reload()}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["29fd06a58b635f18a26d675807f87ee7"] === e) return;
            !function() {
                if (-1 == document.cookie.indexOf("BCPermissionLevel")) {
                    var e = (new Date).getTime(), o = new Date(e + 1314e6);
                    document.cookie = "BCPermissionLevel=PERSONAL; path=/; expires=" + o.toUTCString(), location.reload();
                }
            }();
            Object.defineProperty(Window.prototype.toString, "29fd06a58b635f18a26d675807f87ee7", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "29fd06a58b635f18a26d675807f87ee7" due to: ' + e);
        }
    },
    '(function(){if(-1==document.cookie.indexOf("_chorus_privacy_consent")){var c=new Date, d=c.getTime(), date = new Date(d + 365 * 60 * 60 * 1000); document.cookie="_chorus_privacy_consent="+d+"; path=/; expires=" + date.toUTCString(), location.reload()}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.e7ea60642fa9501751b42fd2fe95103b === e) return;
            !function() {
                if (-1 == document.cookie.indexOf("_chorus_privacy_consent")) {
                    var e = (new Date).getTime(), o = new Date(e + 1314e6);
                    document.cookie = "_chorus_privacy_consent=" + e + "; path=/; expires=" + o.toUTCString(), location.reload();
                }
            }();
            Object.defineProperty(Window.prototype.toString, "e7ea60642fa9501751b42fd2fe95103b", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "e7ea60642fa9501751b42fd2fe95103b" due to: ' + e);
        }
    },
    "!function(a,b,c,f,g,d,e){e=a[c]||a['WebKit'+c]||a['Moz'+c],e&&(d=new e(function(){b[f].contains(g)&&(b[f].remove(g),d.disconnect())}),d.observe(b,{attributes:!0,attributeFilter:['class']}))}(window,document.documentElement,'MutationObserver','classList','layer_cookie__visible');": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["61e6ac2655edf1e9450373c1fd849cd0"] === e) return;
            !function(e, t, o, n1, r, c, i1) {
                (i1 = e[o] || e["WebKit" + o] || e["Moz" + o]) && (c = new i1(function() {
                    t[n1].contains(r) && (t[n1].remove(r), c.disconnect());
                })).observe(t, {
                    attributes: !0,
                    attributeFilter: [
                        "class"
                    ]
                });
            }(window, document.documentElement, "MutationObserver", "classList", "layer_cookie__visible");
            Object.defineProperty(Window.prototype.toString, "61e6ac2655edf1e9450373c1fd849cd0", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "61e6ac2655edf1e9450373c1fd849cd0" due to: ' + e);
        }
    },
    'var cw;Object.defineProperty(window,"cookieWallSettings",{get:function(){return cw},set:function(a){document.cookie="rtlcookieconsent="+a.version.toString()+";";cw=a}});': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.b32831777a037cfe79fc602cdef09ab7 === e) return;
            var cw;
            Object.defineProperty(window, "cookieWallSettings", {
                get: function() {
                    return cw;
                },
                set: function(e) {
                    document.cookie = "rtlcookieconsent=" + e.version.toString() + ";";
                    cw = e;
                }
            });
            Object.defineProperty(Window.prototype.toString, "b32831777a037cfe79fc602cdef09ab7", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "b32831777a037cfe79fc602cdef09ab7" due to: ' + e);
        }
    },
    '(()=>{if(!location.pathname.includes("/search"))return;const t={attributes:!0,childList:!0,subtree:!0},e=(t,e)=>{for(const n of t){const t=n.target.querySelector(".privacy-statement + .get-started-btn-wrapper > button.inline-explicit");t&&(t.click(),e.disconnect())}},n={apply:(n,o,c)=>{const r=Reflect.apply(n,o,c);if(o&&o.matches("cib-muid-consent")){new MutationObserver(e).observe(r,t)}return r}};window.Element.prototype.attachShadow=new Proxy(window.Element.prototype.attachShadow,n)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["36fc3a243e85a682dd99c26376ad6c57"] === e) return;
            (()=>{
                if (!location.pathname.includes("/search")) return;
                const e = {
                    attributes: !0,
                    childList: !0,
                    subtree: !0
                }, t = (e, t)=>{
                    for (const o of e){
                        const e = o.target.querySelector(".privacy-statement + .get-started-btn-wrapper > button.inline-explicit");
                        e && (e.click(), t.disconnect());
                    }
                }, o = {
                    apply: (o, r, n1)=>{
                        const c = Reflect.apply(o, r, n1);
                        r && r.matches("cib-muid-consent") && new MutationObserver(t).observe(c, e);
                        return c;
                    }
                };
                window.Element.prototype.attachShadow = new Proxy(window.Element.prototype.attachShadow, o);
            })();
            Object.defineProperty(Window.prototype.toString, "36fc3a243e85a682dd99c26376ad6c57", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "36fc3a243e85a682dd99c26376ad6c57" due to: ' + e);
        }
    },
    '(()=>{let t,e=!1;const o=new MutationObserver(((e,o)=>{const c=t?.querySelector("button.uc-deny-button");c&&(c.click(),o.disconnect())})),c={apply:(c,n,p)=>{const r=Reflect.apply(c,n,p);return!e&&n.matches("#usercentrics-cmp-ui")&&(e=!0,t=r),o.observe(r,{subtree:!0,childList:!0}),r}};window.Element.prototype.attachShadow=new Proxy(window.Element.prototype.attachShadow,c)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["7d2a68c5db67d5c0b987bcc67516ef8e"] === e) return;
            (()=>{
                let e, t = !1;
                const c = new MutationObserver((t, c)=>{
                    const o = e === null || e === void 0 ? void 0 : e.querySelector("button.uc-deny-button");
                    o && (o.click(), c.disconnect());
                }), o = {
                    apply: (o, r, n1)=>{
                        const d = Reflect.apply(o, r, n1);
                        return !t && r.matches("#usercentrics-cmp-ui") && (t = !0, e = d), c.observe(d, {
                            subtree: !0,
                            childList: !0
                        }), d;
                    }
                };
                window.Element.prototype.attachShadow = new Proxy(window.Element.prototype.attachShadow, o);
            })();
            Object.defineProperty(Window.prototype.toString, "7d2a68c5db67d5c0b987bcc67516ef8e", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "7d2a68c5db67d5c0b987bcc67516ef8e" due to: ' + e);
        }
    },
    '(()=>{let t,e=!1;const o=new MutationObserver(((e,o)=>{const c=t?.querySelector(\'button[data-testid="uc-accept-all-button"]\');c&&(c.click(),o.disconnect())})),c={apply:(c,n,p)=>{const r=Reflect.apply(c,n,p);return!e&&n.matches("#usercentrics-root")&&(e=!0,t=r),o.observe(r,{subtree:!0,childList:!0}),r}};window.Element.prototype.attachShadow=new Proxy(window.Element.prototype.attachShadow,c)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.c3fa9bec7cb9559b8965f87071a37fc6 === e) return;
            (()=>{
                let e, t = !1;
                const c = new MutationObserver((t, c)=>{
                    const o = e === null || e === void 0 ? void 0 : e.querySelector('button[data-testid="uc-accept-all-button"]');
                    o && (o.click(), c.disconnect());
                }), o = {
                    apply: (o, r, n1)=>{
                        const a = Reflect.apply(o, r, n1);
                        return !t && r.matches("#usercentrics-root") && (t = !0, e = a), c.observe(a, {
                            subtree: !0,
                            childList: !0
                        }), a;
                    }
                };
                window.Element.prototype.attachShadow = new Proxy(window.Element.prototype.attachShadow, o);
            })();
            Object.defineProperty(Window.prototype.toString, "c3fa9bec7cb9559b8965f87071a37fc6", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "c3fa9bec7cb9559b8965f87071a37fc6" due to: ' + e);
        }
    },
    '(()=>{let t,e=!1;const o=new MutationObserver(((e,o)=>{const c=t?.querySelector("#cmpbox a.cmptxt_btn_yes");c&&(c.click(),o.disconnect())})),c={apply:(c,n,p)=>{const r=Reflect.apply(c,n,p);return!e&&n.matches("#cmpwrapper")&&(e=!0,t=r),o.observe(r,{subtree:!0,childList:!0}),r}};window.Element.prototype.attachShadow=new Proxy(window.Element.prototype.attachShadow,c)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["9c5d8cfc5b5533f486ab90d24d15e42c"] === e) return;
            (()=>{
                let e, t = !1;
                const c = new MutationObserver((t, c)=>{
                    const o = e === null || e === void 0 ? void 0 : e.querySelector("#cmpbox a.cmptxt_btn_yes");
                    o && (o.click(), c.disconnect());
                }), o = {
                    apply: (o, r, n1)=>{
                        const d = Reflect.apply(o, r, n1);
                        return !t && r.matches("#cmpwrapper") && (t = !0, e = d), c.observe(d, {
                            subtree: !0,
                            childList: !0
                        }), d;
                    }
                };
                window.Element.prototype.attachShadow = new Proxy(window.Element.prototype.attachShadow, o);
            })();
            Object.defineProperty(Window.prototype.toString, "9c5d8cfc5b5533f486ab90d24d15e42c", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "9c5d8cfc5b5533f486ab90d24d15e42c" due to: ' + e);
        }
    },
    '(function(){window.self!==window.top||document.cookie.includes("visitor=")||(document.cookie="visitor=1; path=/;",document.cookie&&location.reload())})();': ()=>{
        try {
            const o = "done";
            if (Window.prototype.toString["9907768cd527256baba4120870996330"] === o) return;
            window.self !== window.top || document.cookie.includes("visitor=") || (document.cookie = "visitor=1; path=/;", document.cookie && location.reload());
            Object.defineProperty(Window.prototype.toString, "9907768cd527256baba4120870996330", {
                value: o,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (o) {
            console.error('Error executing AG js rule with uniqueId "9907768cd527256baba4120870996330" due to: ' + o);
        }
    },
    '(function(){try{var time=(new Date).getTime();var cookieDate=new Date(time+1314E6);var hostname=location.host;var locSubString=null;if(!hostname.startsWith("google.")&&!hostname.startsWith("youtube."))locSubString=hostname.substring(hostname.indexOf(".")+1);var loc=locSubString||hostname;if(document.cookie.indexOf("CONSENT=YES")!==-1)return;document.cookie="CONSENT=YES+; domain="+loc+"; path=/; expires="+cookieDate.toUTCString()}catch(ex){console.error("AG: failed to set consent cookie: "+ex)}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.e1a7ebd323b27eb0aa0e7a309ebca4e9 === e) return;
            !function() {
                try {
                    var e = (new Date).getTime(), t = new Date(e + 1314e6), o = location.host, r = null;
                    o.startsWith("google.") || o.startsWith("youtube.") || (r = o.substring(o.indexOf(".") + 1));
                    var a = r || o;
                    if (-1 !== document.cookie.indexOf("CONSENT=YES")) return;
                    document.cookie = "CONSENT=YES+; domain=" + a + "; path=/; expires=" + t.toUTCString();
                } catch (e) {
                    console.error("AG: failed to set consent cookie: " + e);
                }
            }();
            Object.defineProperty(Window.prototype.toString, "e1a7ebd323b27eb0aa0e7a309ebca4e9", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "e1a7ebd323b27eb0aa0e7a309ebca4e9" due to: ' + e);
        }
    },
    '(function(o){function a(a){return{get:function(){return a},set:b}}function b(){}function c(){throw"Adguard: stopped a script execution.";}var d={},e=a(function(a){a(!1)}),f={},g=EventTarget.prototype.addEventListener;o(d,{spid_control_callback:a(b),content_control_callback:a(b),vid_control_callback:a(b)});o(f,{config:a(d),_setSpKey:{get:c,set:c},checkState:e,isAdBlocking:e,getSafeUri:a(function(a){return a}),pageChange:a(b),setupSmartBeacons:a(b)});Object.defineProperty(window,"_sp_",a(f));EventTarget.prototype.addEventListener=function(a){"sp.blocking"!=a&&"sp.not_blocking"!=a&&g.apply(this,arguments)}})(Object.defineProperties);': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.a1233e00aac3b1e9bd547e64ca938543 === e) return;
            !function(e) {
                function t(e) {
                    return {
                        get: function() {
                            return e;
                        },
                        set: n1
                    };
                }
                function n1() {}
                function o() {
                    throw "Adguard: stopped a script execution.";
                }
                var r = {}, c = t(function(e) {
                    e(!1);
                }), a = {}, i1 = EventTarget.prototype.addEventListener;
                e(r, {
                    spid_control_callback: t(n1),
                    content_control_callback: t(n1),
                    vid_control_callback: t(n1)
                });
                e(a, {
                    config: t(r),
                    _setSpKey: {
                        get: o,
                        set: o
                    },
                    checkState: c,
                    isAdBlocking: c,
                    getSafeUri: t(function(e) {
                        return e;
                    }),
                    pageChange: t(n1),
                    setupSmartBeacons: t(n1)
                });
                Object.defineProperty(window, "_sp_", t(a));
                EventTarget.prototype.addEventListener = function(e) {
                    "sp.blocking" != e && "sp.not_blocking" != e && i1.apply(this, arguments);
                };
            }(Object.defineProperties);
            Object.defineProperty(Window.prototype.toString, "a1233e00aac3b1e9bd547e64ca938543", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "a1233e00aac3b1e9bd547e64ca938543" due to: ' + e);
        }
    },
    '(()=>{window.admiral=function(d,a,b){if("function"==typeof b)try{b({})}catch(a){}}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.f27629071c2547fb2b0857e3b647320e === e) return;
            window.admiral = function(e, t, o) {
                if ("function" == typeof o) try {
                    o({});
                } catch (t) {}
            };
            Object.defineProperty(Window.prototype.toString, "f27629071c2547fb2b0857e3b647320e", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "f27629071c2547fb2b0857e3b647320e" due to: ' + e);
        }
    },
    '(()=>{const d={getUserConsentStatusForVendor:()=>!0};window.didomiOnReady=window.didomiOnReady||[],window.didomiOnReady.push=n=>{"function"==typeof n&&n(d)}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["4f42a63fdc8f353f50712cbd342cc7be"] === e) return;
            (()=>{
                const e = {
                    getUserConsentStatusForVendor: ()=>!0
                };
                window.didomiOnReady = window.didomiOnReady || [], window.didomiOnReady.push = (o)=>{
                    "function" == typeof o && o(e);
                };
            })();
            Object.defineProperty(Window.prototype.toString, "4f42a63fdc8f353f50712cbd342cc7be", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "4f42a63fdc8f353f50712cbd342cc7be" due to: ' + e);
        }
    },
    '(()=>{const e={apply:async(e,t,a)=>{if(a[0]&&a[0]?.match(/adsbygoogle|doubleclick|googlesyndication|static\\.cloudflareinsights\\.com\\/beacon\\.min\\.js/)){const e=(e="{}",t="",a="opaque")=>{const n=new Response(e,{statusText:"OK"}),o=String((s=50800,r=50900,Math.floor(Math.random()*(r-s+1)+s)));var s,r;return n.headers.set("Content-Length",o),Object.defineProperties(n,{type:{value:a},status:{value:0},statusText:{value:""},url:{value:""}}),Promise.resolve(n)};return e("{}",a[0])}return Reflect.apply(e,t,a)}};window.fetch=new Proxy(window.fetch,e)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["9dbd26c8d0d4dcb61410c72cac73374e"] === e) return;
            (()=>{
                const e = {
                    apply: async (e, t, o)=>{
                        var _o_;
                        if (o[0] && ((_o_ = o[0]) === null || _o_ === void 0 ? void 0 : _o_.match(/adsbygoogle|doubleclick|googlesyndication|static\.cloudflareinsights\.com\/beacon\.min\.js/))) {
                            const e = (e = "{}", t = "", o = "opaque")=>{
                                const c = new Response(e, {
                                    statusText: "OK"
                                }), n1 = String(Math.floor(101 * Math.random() + 50800));
                                return c.headers.set("Content-Length", n1), Object.defineProperties(c, {
                                    type: {
                                        value: o
                                    },
                                    status: {
                                        value: 0
                                    },
                                    statusText: {
                                        value: ""
                                    },
                                    url: {
                                        value: ""
                                    }
                                }), Promise.resolve(c);
                            };
                            return e("{}", o[0]);
                        }
                        return Reflect.apply(e, t, o);
                    }
                };
                window.fetch = new Proxy(window.fetch, e);
            })();
            Object.defineProperty(Window.prototype.toString, "9dbd26c8d0d4dcb61410c72cac73374e", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "9dbd26c8d0d4dcb61410c72cac73374e" due to: ' + e);
        }
    },
    "window.ad_allowed = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["049921132ffe411b4692a70bec90d335"] === e) return;
            window.ad_allowed = !0;
            Object.defineProperty(Window.prototype.toString, "049921132ffe411b4692a70bec90d335", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "049921132ffe411b4692a70bec90d335" due to: ' + e);
        }
    },
    "(function(){var b=window.setTimeout;window.setTimeout=function(a,c){if(!/google_ads_frame/.test(a.toString()))return b(a,c)};})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["47f456fa4a14a6df26efb37ac4b35e9a"] === e) return;
            !function() {
                var e = window.setTimeout;
                window.setTimeout = function(t, o) {
                    if (!/google_ads_frame/.test(t.toString())) return e(t, o);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "47f456fa4a14a6df26efb37ac4b35e9a", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "47f456fa4a14a6df26efb37ac4b35e9a" due to: ' + e);
        }
    },
    'var _st = window.setTimeout; window.setTimeout = function(a, b) { if(!/var ad = document\\.querySelector\\("ins\\.adsbygoogle"\\);/.test(a)){ _st(a,b);}};': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["8468c20094b47b4c6230a90bb0cf2d54"] === e) return;
            var _st = window.setTimeout;
            window.setTimeout = function(e, t) {
                /var ad = document\.querySelector\("ins\.adsbygoogle"\);/.test(e) || _st(e, t);
            };
            Object.defineProperty(Window.prototype.toString, "8468c20094b47b4c6230a90bb0cf2d54", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "8468c20094b47b4c6230a90bb0cf2d54" due to: ' + e);
        }
    },
    "document.avp_ready = 1;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["1cd8368bac9abff3d844c605b628fee9"] === e) return;
            document.avp_ready = 1;
            Object.defineProperty(Window.prototype.toString, "1cd8368bac9abff3d844c605b628fee9", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "1cd8368bac9abff3d844c605b628fee9" due to: ' + e);
        }
    },
    "window.ADTECH = function() {};": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.e42f31b21c3855d599c00a3f8701ede6 === e) return;
            window.ADTECH = function() {};
            Object.defineProperty(Window.prototype.toString, "e42f31b21c3855d599c00a3f8701ede6", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "e42f31b21c3855d599c00a3f8701ede6" due to: ' + e);
        }
    },
    "fuckAdBlock = function() {};": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["5c3f48e3f24ff8813da9609a53a72433"] === e) return;
            fuckAdBlock = function() {};
            Object.defineProperty(Window.prototype.toString, "5c3f48e3f24ff8813da9609a53a72433", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "5c3f48e3f24ff8813da9609a53a72433" due to: ' + e);
        }
    },
    "window.IM = [1,2,3];": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["6e0b841e576ac763f81d5c219813906b"] === e) return;
            window.IM = [
                1,
                2,
                3
            ];
            Object.defineProperty(Window.prototype.toString, "6e0b841e576ac763f81d5c219813906b", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "6e0b841e576ac763f81d5c219813906b" due to: ' + e);
        }
    },
    "window.google_jobrunner = function() { };": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.c155982f45f07c347701b45fce31f5d3 === e) return;
            window.google_jobrunner = function() {};
            Object.defineProperty(Window.prototype.toString, "c155982f45f07c347701b45fce31f5d3", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "c155982f45f07c347701b45fce31f5d3" due to: ' + e);
        }
    },
    "(function(){var c=window.setTimeout;window.setTimeout=function(f,g){return !Number.isNaN(g)&&/\\$\\('#l'\\+|#linkdiv/.test(f.toString())&&(g*=0.01),c.apply(this,arguments)}.bind(window)})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["009922e6198163d89edac4a47ce341c7"] === e) return;
            !function() {
                var e = window.setTimeout;
                window.setTimeout = (function(t, o) {
                    return !Number.isNaN(o) && /\$\('#l'\+|#linkdiv/.test(t.toString()) && (o *= .01), e.apply(this, arguments);
                }).bind(window);
            }();
            Object.defineProperty(Window.prototype.toString, "009922e6198163d89edac4a47ce341c7", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "009922e6198163d89edac4a47ce341c7" due to: ' + e);
        }
    },
    "window.blockAdBlock = function() {};": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["7b0fe49ca4878b71af2e77dfe4259f5a"] === e) return;
            window.blockAdBlock = function() {};
            Object.defineProperty(Window.prototype.toString, "7b0fe49ca4878b71af2e77dfe4259f5a", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "7b0fe49ca4878b71af2e77dfe4259f5a" due to: ' + e);
        }
    },
    '!function(){const e={apply:(e,t,o)=>{const i=o[1];if(!i||"object"!=typeof i.QiyiPlayerProphetData)return Reflect.apply(e,t,o)}};window.Object.defineProperties=new Proxy(window.Object.defineProperties,e)}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["545a0289c2a1afd8dd9039c82074c2b7"] === e) return;
            !function() {
                const e = {
                    apply: (e, t, o)=>{
                        const r = o[1];
                        if (!r || "object" != typeof r.QiyiPlayerProphetData) return Reflect.apply(e, t, o);
                    }
                };
                window.Object.defineProperties = new Proxy(window.Object.defineProperties, e);
            }();
            Object.defineProperty(Window.prototype.toString, "545a0289c2a1afd8dd9039c82074c2b7", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "545a0289c2a1afd8dd9039c82074c2b7" due to: ' + e);
        }
    },
    "!function(){const s={apply:(c,e,n)=>(n[0]?.adSlots&&(n[0].adSlots=[]),n[1]?.success&&(n[1].success=new Proxy(n[1].success,s)),Reflect.apply(c,e,n))};window.Object.assign=new Proxy(window.Object.assign,s)}();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["7c9eb641391ed7a82e455b87f3672582"] === e) return;
            !function() {
                const e = {
                    apply: (o, t, n1)=>{
                        var _n_, _n_1;
                        return ((_n_ = n1[0]) === null || _n_ === void 0 ? void 0 : _n_.adSlots) && (n1[0].adSlots = []), ((_n_1 = n1[1]) === null || _n_1 === void 0 ? void 0 : _n_1.success) && (n1[1].success = new Proxy(n1[1].success, e)), Reflect.apply(o, t, n1);
                    }
                };
                window.Object.assign = new Proxy(window.Object.assign, e);
            }();
            Object.defineProperty(Window.prototype.toString, "7c9eb641391ed7a82e455b87f3672582", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "7c9eb641391ed7a82e455b87f3672582" due to: ' + e);
        }
    },
    "\"use strict\"; window.Function.prototype.apply = new Proxy(window.Function.prototype.apply, { apply(Target, ThisArg, Args) { let FunctionContext = ThisArg.toString(); if (FunctionContext.includes('veta') && FunctionContext.includes('http') && FunctionContext.includes('/gfp/') && FunctionContext.includes('().mark((')) { return Reflect.apply(Target, async () => false, []); } return Reflect.apply(Target, ThisArg, Args); } });": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["2eb1c0de2ccaf6cb36c187f9ae65492e"] === e) return;
            window.Function.prototype.apply = new Proxy(window.Function.prototype.apply, {
                apply (e, t, c) {
                    let n1 = t.toString();
                    return n1.includes("veta") && n1.includes("http") && n1.includes("/gfp/") && n1.includes("().mark((") ? Reflect.apply(e, async ()=>!1, []) : Reflect.apply(e, t, c);
                }
            });
            Object.defineProperty(Window.prototype.toString, "2eb1c0de2ccaf6cb36c187f9ae65492e", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "2eb1c0de2ccaf6cb36c187f9ae65492e" due to: ' + e);
        }
    },
    '(()=>{const e=document.documentElement;new MutationObserver((()=>{const e=document.querySelector(\'body > div[role="dialog"].neon-border-purple > p.text-center + button.neon-button-purple\');e&&e.textContent.includes("I Understand")&&e.click()})).observe(e,{attributes:!0,childList:!0,subtree:!0})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["7ff1ec00ee1e83864c8bcaba82126a50"] === e) return;
            (()=>{
                const e = document.documentElement;
                new MutationObserver(()=>{
                    const e = document.querySelector('body > div[role="dialog"].neon-border-purple > p.text-center + button.neon-button-purple');
                    e && e.textContent.includes("I Understand") && e.click();
                }).observe(e, {
                    attributes: !0,
                    childList: !0,
                    subtree: !0
                });
            })();
            Object.defineProperty(Window.prototype.toString, "7ff1ec00ee1e83864c8bcaba82126a50", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "7ff1ec00ee1e83864c8bcaba82126a50" due to: ' + e);
        }
    },
    'document.cookie="popup=9999999999999; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.dd5fb4eeed8b7505e5767b7045cb23cc === e) return;
            document.cookie = "popup=9999999999999; path=/;";
            Object.defineProperty(Window.prototype.toString, "dd5fb4eeed8b7505e5767b7045cb23cc", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "dd5fb4eeed8b7505e5767b7045cb23cc" due to: ' + e);
        }
    },
    'document.cookie="overlay-geschenk=donotshowfor7days; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.c244d6b503d07944e92dae676220ac14 === e) return;
            document.cookie = "overlay-geschenk=donotshowfor7days; path=/;";
            Object.defineProperty(Window.prototype.toString, "c244d6b503d07944e92dae676220ac14", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "c244d6b503d07944e92dae676220ac14" due to: ' + e);
        }
    },
    'document.cookie="popupSubscription=1; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["07e3ab9b26da8896b57fb83067364723"] === e) return;
            document.cookie = "popupSubscription=1; path=/;";
            Object.defineProperty(Window.prototype.toString, "07e3ab9b26da8896b57fb83067364723", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "07e3ab9b26da8896b57fb83067364723" due to: ' + e);
        }
    },
    'document.cookie="hide_footer_login_layer=T; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["6610b2172699f352e936bdda56179645"] === e) return;
            document.cookie = "hide_footer_login_layer=T; path=/;";
            Object.defineProperty(Window.prototype.toString, "6610b2172699f352e936bdda56179645", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "6610b2172699f352e936bdda56179645" due to: ' + e);
        }
    },
    '!function(){const t={apply:(t,e,n)=>{if(n[0]&&"function"==typeof n[0])try{if(n[0].toString().includes("LOGIN_FORCE_TIME"))return}catch(t){console.trace(t)}return Reflect.apply(t,e,n)}},e=new Proxy(window.setTimeout,t);Object.defineProperty(window,"setTimeout",{set:function(){},get:function(){return e}})}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.af15a185bba3bf6f247f74549465a83e === e) return;
            !function() {
                const e = {
                    apply: (e, t, n1)=>{
                        if (n1[0] && "function" == typeof n1[0]) try {
                            if (n1[0].toString().includes("LOGIN_FORCE_TIME")) return;
                        } catch (e) {
                            console.trace(e);
                        }
                        return Reflect.apply(e, t, n1);
                    }
                }, t = new Proxy(window.setTimeout, e);
                Object.defineProperty(window, "setTimeout", {
                    set: function() {},
                    get: function() {
                        return t;
                    }
                });
            }();
            Object.defineProperty(Window.prototype.toString, "af15a185bba3bf6f247f74549465a83e", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "af15a185bba3bf6f247f74549465a83e" due to: ' + e);
        }
    },
    "(function(){window.setTimeout=new Proxy(window.setTimeout,{apply:(a,b,c)=>c&&c[0]&&/SkipMsg\\(\\)/.test(c[0].toString())&&c[1]?(c[1]=1,Reflect.apply(a,b,c)):Reflect.apply(a,b,c)})})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.ddae51deac37af19fec2771965b890e1 === e) return;
            window.setTimeout = new Proxy(window.setTimeout, {
                apply: (e, t, o)=>o && o[0] && /SkipMsg\(\)/.test(o[0].toString()) && o[1] ? (o[1] = 1, Reflect.apply(e, t, o)) : Reflect.apply(e, t, o)
            });
            Object.defineProperty(Window.prototype.toString, "ddae51deac37af19fec2771965b890e1", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "ddae51deac37af19fec2771965b890e1" due to: ' + e);
        }
    },
    'document.cookie="show_share=true; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["9fa386e4a7f5a25377523a2c743da6d9"] === e) return;
            document.cookie = "show_share=true; path=/;";
            Object.defineProperty(Window.prototype.toString, "9fa386e4a7f5a25377523a2c743da6d9", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "9fa386e4a7f5a25377523a2c743da6d9" due to: ' + e);
        }
    },
    '(function(){var a=new Date,b=a.getTime();document.cookie="ips4_bacalltoactionpopup="+b})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["21f664952df8e1eaf1fb9a92db8b174e"] === e) return;
            !function() {
                var e = (new Date).getTime();
                document.cookie = "ips4_bacalltoactionpopup=" + e;
            }();
            Object.defineProperty(Window.prototype.toString, "21f664952df8e1eaf1fb9a92db8b174e", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "21f664952df8e1eaf1fb9a92db8b174e" due to: ' + e);
        }
    },
    "if (window.PushManager) { window.PushManager.prototype.subscribe = function () { return { then: function (func) { } }; }; }": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.f271f5a04b96c738d8491cb877889952 === e) return;
            window.PushManager && (window.PushManager.prototype.subscribe = function() {
                return {
                    then: function(e) {}
                };
            });
            Object.defineProperty(Window.prototype.toString, "f271f5a04b96c738d8491cb877889952", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "f271f5a04b96c738d8491cb877889952" due to: ' + e);
        }
    },
    '(()=>{const t={construct:(t,e,n)=>{const r=e[0],o=r?.toString(),c=o?.includes("e[0].intersectionRatio");return c&&(e[0]=()=>{}),Reflect.construct(t,e,n)}};window.IntersectionObserver=new Proxy(window.IntersectionObserver,t)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.c12b1283487b21a0e823718579c18ede === e) return;
            (()=>{
                const e = {
                    construct: (e, t, r)=>{
                        const n1 = t[0], o = n1 === null || n1 === void 0 ? void 0 : n1.toString(), c = o === null || o === void 0 ? void 0 : o.includes("e[0].intersectionRatio");
                        return c && (t[0] = ()=>{}), Reflect.construct(e, t, r);
                    }
                };
                window.IntersectionObserver = new Proxy(window.IntersectionObserver, e);
            })();
            Object.defineProperty(Window.prototype.toString, "c12b1283487b21a0e823718579c18ede", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "c12b1283487b21a0e823718579c18ede" due to: ' + e);
        }
    },
    '(function(){var b=document.addEventListener;document.addEventListener=function(c,a,d){if(a&&-1==a.toString().indexOf("adsBlocked"))return b(c,a,d)}.bind(window)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["62c4837e2d6ffab7f90fde5590cc73ab"] === e) return;
            !function() {
                var e = document.addEventListener;
                document.addEventListener = (function(t, n1, r) {
                    if (n1 && -1 == n1.toString().indexOf("adsBlocked")) return e(t, n1, r);
                }).bind(window);
            }();
            Object.defineProperty(Window.prototype.toString, "62c4837e2d6ffab7f90fde5590cc73ab", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "62c4837e2d6ffab7f90fde5590cc73ab" due to: ' + e);
        }
    },
    '(function(b){Object.defineProperty(Element.prototype,"innerHTML",{get:function(){return b.get.call(this)},set:function(a){/^(?:<([abisuq]) id="[^"]*"><\\/\\1>)*$/.test(a)||b.set.call(this,a)},enumerable:!0,configurable:!0})})(Object.getOwnPropertyDescriptor(Element.prototype,"innerHTML"));': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.a45ed61db8e971a6cfde1b21ffc65573 === e) return;
            !function(e) {
                Object.defineProperty(Element.prototype, "innerHTML", {
                    get: function() {
                        return e.get.call(this);
                    },
                    set: function(t) {
                        /^(?:<([abisuq]) id="[^"]*"><\/\1>)*$/.test(t) || e.set.call(this, t);
                    },
                    enumerable: !0,
                    configurable: !0
                });
            }(Object.getOwnPropertyDescriptor(Element.prototype, "innerHTML"));
            Object.defineProperty(Window.prototype.toString, "a45ed61db8e971a6cfde1b21ffc65573", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "a45ed61db8e971a6cfde1b21ffc65573" due to: ' + e);
        }
    },
    '(function(a){Object.defineProperty(window,"upManager",{get:function(){return{push:a,register:a,fireNow:a,start:a}},set:function(a){if(!(a instanceof Error))throw Error();}})})(function(){});': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.e7cde92d3ed85b2159f3eefcc50b7ab6 === e) return;
            !function(e) {
                Object.defineProperty(window, "upManager", {
                    get: function() {
                        return {
                            push: e,
                            register: e,
                            fireNow: e,
                            start: e
                        };
                    },
                    set: function(e) {
                        if (!(e instanceof Error)) throw Error();
                    }
                });
            }(function() {});
            Object.defineProperty(Window.prototype.toString, "e7cde92d3ed85b2159f3eefcc50b7ab6", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "e7cde92d3ed85b2159f3eefcc50b7ab6" due to: ' + e);
        }
    },
    '(function(){var b=XMLHttpRequest.prototype.open,c=/[/.@](piguiqproxy\\.com|rcdn\\.pro|amgload\\.net|dsn-fishki\\.ru|v6t39t\\.ru|greencuttlefish\\.com|rgy1wk\\.ru|vt4dlx\\.ru|d38dub\\.ru)[:/]/i;XMLHttpRequest.prototype.open=function(d,a){if("GET"===d&&c.test(a))this.send=function(){return null},this.setRequestHeader=function(){return null},console.log("AG has blocked request: ",a);else return b.apply(this,arguments)}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["8d3f556a4543374ea8319bc03583025f"] === e) return;
            !function() {
                var e = XMLHttpRequest.prototype.open, t = /[/.@](piguiqproxy\.com|rcdn\.pro|amgload\.net|dsn-fishki\.ru|v6t39t\.ru|greencuttlefish\.com|rgy1wk\.ru|vt4dlx\.ru|d38dub\.ru)[:/]/i;
                XMLHttpRequest.prototype.open = function(r, o) {
                    if ("GET" !== r || !t.test(o)) return e.apply(this, arguments);
                    this.send = function() {
                        return null;
                    }, this.setRequestHeader = function() {
                        return null;
                    }, console.log("AG has blocked request: ", o);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "8d3f556a4543374ea8319bc03583025f", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "8d3f556a4543374ea8319bc03583025f" due to: ' + e);
        }
    },
    '(function(){var b=XMLHttpRequest.prototype.open,c=/[/.@](piguiqproxy\\.com|rcdn\\.pro|amgload\\.net|dsn-fishki\\.ru|v6t39t\\.ru|greencuttlefish\\.com|rgy1wk\\.ru|vt4dlx\\.ru|d38dub\\.ru|csp-oz66pp\\.ru|ok9ydq\\.ru|kingoablc\\.com)[:/]/i;XMLHttpRequest.prototype.open=function(d,a){if("GET"===d&&c.test(a))this.send=function(){return null},this.setRequestHeader=function(){return null},console.log("AG has blocked request: ",a);else return b.apply(this,arguments)}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["22514194ad8441cc56e68716b1f75f69"] === e) return;
            !function() {
                var e = XMLHttpRequest.prototype.open, t = /[/.@](piguiqproxy\.com|rcdn\.pro|amgload\.net|dsn-fishki\.ru|v6t39t\.ru|greencuttlefish\.com|rgy1wk\.ru|vt4dlx\.ru|d38dub\.ru|csp-oz66pp\.ru|ok9ydq\.ru|kingoablc\.com)[:/]/i;
                XMLHttpRequest.prototype.open = function(r, o) {
                    if ("GET" !== r || !t.test(o)) return e.apply(this, arguments);
                    this.send = function() {
                        return null;
                    }, this.setRequestHeader = function() {
                        return null;
                    }, console.log("AG has blocked request: ", o);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "22514194ad8441cc56e68716b1f75f69", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "22514194ad8441cc56e68716b1f75f69" due to: ' + e);
        }
    },
    '(()=>{window.addEventListener("load",(()=>{setTimeout((()=>{if(!document.querySelector(".plyr--video video"))for(const o in window)if("function"==typeof window[o]&&window[o].toString().includes("Hls.isSupported")){try{window[o]()}catch(e){console.stack(`Error occurred while calling ${o}:`,e)}break}}),1e3)}));})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.fc7e03df62426e566b625183c2be9408 === e) return;
            window.addEventListener("load", ()=>{
                setTimeout(()=>{
                    if (!document.querySelector(".plyr--video video")) {
                        for(const e in window)if ("function" == typeof window[e] && window[e].toString().includes("Hls.isSupported")) {
                            try {
                                window[e]();
                            } catch (o) {
                                console.stack(`Error occurred while calling ${e}:`, o);
                            }
                            break;
                        }
                    }
                }, 1e3);
            });
            Object.defineProperty(Window.prototype.toString, "fc7e03df62426e566b625183c2be9408", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "fc7e03df62426e566b625183c2be9408" due to: ' + e);
        }
    },
    '(()=>{window.GADS={init:function(n){n&&"function"==typeof n.onFinish&&n.onFinish()}};})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.c2ffc94b6ce8e97f2c432d64690cfc9d === e) return;
            window.GADS = {
                init: function(e) {
                    e && "function" == typeof e.onFinish && e.onFinish();
                }
            };
            Object.defineProperty(Window.prototype.toString, "c2ffc94b6ce8e97f2c432d64690cfc9d", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "c2ffc94b6ce8e97f2c432d64690cfc9d" due to: ' + e);
        }
    },
    '(()=>{const e={apply:(e,o,t)=>(null===t[0]&&(t[0]={isUserSubscriber:!0}),Reflect.apply(e,o,t))},o={apply:(o,t,n)=>{const r=n[0];return"function"==typeof r&&r.toString().includes("AdBlockDetector")&&(n[0]=()=>{}),"function"==typeof r&&r.toString().includes("Preroll Ad")&&(n[0]=new Proxy(n[0],e)),Reflect.apply(o,t,n)}};window.Promise.prototype.then=new Proxy(window.Promise.prototype.then,o)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["785fddde2c2648fbf7b3c872780aab8f"] === e) return;
            (()=>{
                const e = {
                    apply: (e, t, o)=>(null === o[0] && (o[0] = {
                            isUserSubscriber: !0
                        }), Reflect.apply(e, t, o))
                }, t = {
                    apply: (t, o, r)=>{
                        const n1 = r[0];
                        return "function" == typeof n1 && n1.toString().includes("AdBlockDetector") && (r[0] = ()=>{}), "function" == typeof n1 && n1.toString().includes("Preroll Ad") && (r[0] = new Proxy(r[0], e)), Reflect.apply(t, o, r);
                    }
                };
                window.Promise.prototype.then = new Proxy(window.Promise.prototype.then, t);
            })();
            Object.defineProperty(Window.prototype.toString, "785fddde2c2648fbf7b3c872780aab8f", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "785fddde2c2648fbf7b3c872780aab8f" due to: ' + e);
        }
    },
    '(()=>{const a=function(a){"function"==typeof a&&a()};window.aiptag={adplayer:"",cmd:[]},window.aiptag.cmd.player=[],window.aiptag.cmd.display=[],window.aiptag.cmd.push=a,window.aiptag.cmd.player.push=a,window.aiptag.cmd.display.push=a,window.aipDisplayTag={display:function(){}},window.aipPlayer=function(a){a&&a.AIP_COMPLETE&&(this.startPreRoll=a.AIP_COMPLETE)}})();': ()=>{
        try {
            const a = "done";
            if (Window.prototype.toString["8e9df515585941ac85187baf28cedac1"] === a) return;
            (()=>{
                const a = function(a) {
                    "function" == typeof a && a();
                };
                window.aiptag = {
                    adplayer: "",
                    cmd: []
                }, window.aiptag.cmd.player = [], window.aiptag.cmd.display = [], window.aiptag.cmd.push = a, window.aiptag.cmd.player.push = a, window.aiptag.cmd.display.push = a, window.aipDisplayTag = {
                    display: function() {}
                }, window.aipPlayer = function(a) {
                    a && a.AIP_COMPLETE && (this.startPreRoll = a.AIP_COMPLETE);
                };
            })();
            Object.defineProperty(Window.prototype.toString, "8e9df515585941ac85187baf28cedac1", {
                value: a,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (a) {
            console.error('Error executing AG js rule with uniqueId "8e9df515585941ac85187baf28cedac1" due to: ' + a);
        }
    },
    '(()=>{const e={breakStatus:"done"},o=["beforeReward","adViewed","adBreakDone"];window.adsbygoogle=window.adsbygoogle||[],window.adsbygoogle.push=function(d){var a;d&&"object"==typeof d&&(a=d,o.every((e=>e in a&&"function"==typeof a[e])))&&(d.beforeReward(),d.adViewed(),d.adBreakDone(e))}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["36fd3167269f896e4009a009ae54edb3"] === e) return;
            (()=>{
                const e = {
                    breakStatus: "done"
                }, o = [
                    "beforeReward",
                    "adViewed",
                    "adBreakDone"
                ];
                window.adsbygoogle = window.adsbygoogle || [], window.adsbygoogle.push = function(r) {
                    var d;
                    r && "object" == typeof r && (d = r, o.every((e)=>e in d && "function" == typeof d[e])) && (r.beforeReward(), r.adViewed(), r.adBreakDone(e));
                };
            })();
            Object.defineProperty(Window.prototype.toString, "36fd3167269f896e4009a009ae54edb3", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "36fd3167269f896e4009a009ae54edb3" due to: ' + e);
        }
    },
    '(()=>{document.addEventListener(\'DOMContentLoaded\',()=>{const t=document.querySelector(\'a[href*="uploadmall.com/cgi-bin/dl.cgi/"]\');if(t){const e=t.getAttribute("href");t.addEventListener("click",(t=>{try{const t=`{"link":"${e}"}`,c=`https://mendationforc.info/?cc=${btoa(t)}`;window.open(c)}catch(t){console.debug(t)}}))}})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["0c91eaeaf0d6e2a52ab9be668bbd08a5"] === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                const e = document.querySelector('a[href*="uploadmall.com/cgi-bin/dl.cgi/"]');
                if (e) {
                    const t = e.getAttribute("href");
                    e.addEventListener("click", (e)=>{
                        try {
                            const e = `{"link":"${t}"}`, o = `https://mendationforc.info/?cc=${btoa(e)}`;
                            window.open(o);
                        } catch (e) {
                            console.debug(e);
                        }
                    });
                }
            });
            Object.defineProperty(Window.prototype.toString, "0c91eaeaf0d6e2a52ab9be668bbd08a5", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "0c91eaeaf0d6e2a52ab9be668bbd08a5" due to: ' + e);
        }
    },
    '(()=>{let e;const t={apply:(t,n,o)=>(o[0]?.behavior?.controlType&&o[0]?.initialItems&&"function"==typeof o[0].update&&(e=o[0].update,o[0].update=function(){this.update=e}),Reflect.apply(t,n,o))};window.Object.keys=new Proxy(window.Object.keys,t)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.ca0d0ab35fc86cd11d58ae07707d23fa === e) return;
            (()=>{
                let e;
                const t = {
                    apply: (t, o, a)=>{
                        var _a__behavior, _a_, _a_1;
                        return ((_a_ = a[0]) === null || _a_ === void 0 ? void 0 : (_a__behavior = _a_.behavior) === null || _a__behavior === void 0 ? void 0 : _a__behavior.controlType) && ((_a_1 = a[0]) === null || _a_1 === void 0 ? void 0 : _a_1.initialItems) && "function" == typeof a[0].update && (e = a[0].update, a[0].update = function() {
                            this.update = e;
                        }), Reflect.apply(t, o, a);
                    }
                };
                window.Object.keys = new Proxy(window.Object.keys, t);
            })();
            Object.defineProperty(Window.prototype.toString, "ca0d0ab35fc86cd11d58ae07707d23fa", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "ca0d0ab35fc86cd11d58ae07707d23fa" due to: ' + e);
        }
    },
    '(()=>{const e={apply:(e,n,t)=>{const o=t[1];return o&&["adBlockingDetected","assessAdBlocking"].includes(o)&&t[2]&&"function"==typeof t[2].value&&(t[2].value=()=>{}),Reflect.apply(e,n,t)}};window.Object.defineProperty=new Proxy(window.Object.defineProperty,e)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.dd013aac8504d0cebb16580d054020f6 === e) return;
            (()=>{
                const e = {
                    apply: (e, t, o)=>{
                        const d = o[1];
                        return d && [
                            "adBlockingDetected",
                            "assessAdBlocking"
                        ].includes(d) && o[2] && "function" == typeof o[2].value && (o[2].value = ()=>{}), Reflect.apply(e, t, o);
                    }
                };
                window.Object.defineProperty = new Proxy(window.Object.defineProperty, e);
            })();
            Object.defineProperty(Window.prototype.toString, "dd013aac8504d0cebb16580d054020f6", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "dd013aac8504d0cebb16580d054020f6" due to: ' + e);
        }
    },
    "(()=>{const e=()=>{};window.powerTag={Init:[]},window.powerTag.Init.push=function(e){try{e()}catch(e){console.debug(e)}},window.powerAPITag={initRewarded:function(e,o){o&&o.onComplete&&setTimeout((()=>{try{o.onComplete()}catch(e){console.debug(e)}}),1e3)},display:e,mobileDetect:e,initStickyBanner:e,getRewardedAd:e}})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["208df12815c78a46fb392dc8afb56295"] === e) return;
            (()=>{
                const e = ()=>{};
                window.powerTag = {
                    Init: []
                }, window.powerTag.Init.push = function(e) {
                    try {
                        e();
                    } catch (e) {
                        console.debug(e);
                    }
                }, window.powerAPITag = {
                    initRewarded: function(e, t) {
                        t && t.onComplete && setTimeout(()=>{
                            try {
                                t.onComplete();
                            } catch (e) {
                                console.debug(e);
                            }
                        }, 1e3);
                    },
                    display: e,
                    mobileDetect: e,
                    initStickyBanner: e,
                    getRewardedAd: e
                };
            })();
            Object.defineProperty(Window.prototype.toString, "208df12815c78a46fb392dc8afb56295", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "208df12815c78a46fb392dc8afb56295" due to: ' + e);
        }
    },
    "(()=>{window.detectIncognito=()=>new Promise((e=>e({isPrivate:!0})));})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.b8746b82569fc49e330a8e697f35c050 === e) return;
            window.detectIncognito = ()=>new Promise((e)=>e({
                        isPrivate: !0
                    }));
            Object.defineProperty(Window.prototype.toString, "b8746b82569fc49e330a8e697f35c050", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "b8746b82569fc49e330a8e697f35c050" due to: ' + e);
        }
    },
    '(()=>{const e={apply:(e,p,t)=>(!0===t[0]&&(t[0]=!1),Reflect.apply(e,p,t))},p={apply:(p,t,a)=>("__updateState"===a[1]&&a[2]&&a[2].value&&(a[2].value=new Proxy(a[2].value,e)),Reflect.apply(p,t,a))};window.Object.defineProperty=new Proxy(window.Object.defineProperty,p)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["7c7972b55daaed8f85903876788453e9"] === e) return;
            (()=>{
                const e = {
                    apply: (e, t, r)=>(!0 === r[0] && (r[0] = !1), Reflect.apply(e, t, r))
                }, t = {
                    apply: (t, r, o)=>("__updateState" === o[1] && o[2] && o[2].value && (o[2].value = new Proxy(o[2].value, e)), Reflect.apply(t, r, o))
                };
                window.Object.defineProperty = new Proxy(window.Object.defineProperty, t);
            })();
            Object.defineProperty(Window.prototype.toString, "7c7972b55daaed8f85903876788453e9", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "7c7972b55daaed8f85903876788453e9" due to: ' + e);
        }
    },
    '(()=>{const e={apply:(e,t,n)=>{const o=n[0];if(o&&o.status.includes("success"))for(const e in n[0])"1"===n[0][e]?n[0][e]="0":1===n[0][e]&&(n[0][e]=0);return Reflect.apply(e,t,n)}},t=["adblockEnabled","=!!parseInt(","disable_adb"],n={apply:(n,o,s)=>{const p=s[0];return"function"==typeof p&&t.some((e=>p.toString().includes(e)))&&(s[0]=new Proxy(s[0],e)),Reflect.apply(n,o,s)}};window.Promise.prototype.then=new Proxy(window.Promise.prototype.then,n)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["363a12f3db4852d23e4d57b5c84f4d68"] === e) return;
            (()=>{
                const e = {
                    apply: (e, t, o)=>{
                        const n1 = o[0];
                        if (n1 && n1.status.includes("success")) for(const e in o[0])"1" === o[0][e] ? o[0][e] = "0" : 1 === o[0][e] && (o[0][e] = 0);
                        return Reflect.apply(e, t, o);
                    }
                }, t = [
                    "adblockEnabled",
                    "=!!parseInt(",
                    "disable_adb"
                ], o = {
                    apply: (o, n1, r)=>{
                        const d = r[0];
                        return "function" == typeof d && t.some((e)=>d.toString().includes(e)) && (r[0] = new Proxy(r[0], e)), Reflect.apply(o, n1, r);
                    }
                };
                window.Promise.prototype.then = new Proxy(window.Promise.prototype.then, o);
            })();
            Object.defineProperty(Window.prototype.toString, "363a12f3db4852d23e4d57b5c84f4d68", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "363a12f3db4852d23e4d57b5c84f4d68" due to: ' + e);
        }
    },
    '(()=>{const t={apply:(t,n,e)=>{if(e[0]&&null===e[0].html?.detected&&"function"==typeof e[0].html?.instance?.start&&"function"==typeof e[0].env?.instance?.start&&"function"==typeof e[0].http?.instance?.start){const t=function(){Object.keys(this).forEach((t=>{"boolean"==typeof this[t]&&(this[t]=!1)}))};["html","env","http"].forEach((n=>{e[0][n].instance.start=t}))}return Reflect.apply(t,n,e)}};window.Object.keys=new Proxy(window.Object.keys,t)})();': ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString["8e5af140bb8ff6dfac87d2aa8a7181a7"] === t) return;
            (()=>{
                const t = {
                    apply: (t, e, n1)=>{
                        var _n__html, _n__html_instance, _n__html1, _n__env_instance, _n__env, _n__http_instance, _n__http;
                        if (n1[0] && null === ((_n__html = n1[0].html) === null || _n__html === void 0 ? void 0 : _n__html.detected) && "function" == typeof ((_n__html1 = n1[0].html) === null || _n__html1 === void 0 ? void 0 : (_n__html_instance = _n__html1.instance) === null || _n__html_instance === void 0 ? void 0 : _n__html_instance.start) && "function" == typeof ((_n__env = n1[0].env) === null || _n__env === void 0 ? void 0 : (_n__env_instance = _n__env.instance) === null || _n__env_instance === void 0 ? void 0 : _n__env_instance.start) && "function" == typeof ((_n__http = n1[0].http) === null || _n__http === void 0 ? void 0 : (_n__http_instance = _n__http.instance) === null || _n__http_instance === void 0 ? void 0 : _n__http_instance.start)) {
                            const t = function() {
                                Object.keys(this).forEach((t)=>{
                                    "boolean" == typeof this[t] && (this[t] = !1);
                                });
                            };
                            [
                                "html",
                                "env",
                                "http"
                            ].forEach((e)=>{
                                n1[0][e].instance.start = t;
                            });
                        }
                        return Reflect.apply(t, e, n1);
                    }
                };
                window.Object.keys = new Proxy(window.Object.keys, t);
            })();
            Object.defineProperty(Window.prototype.toString, "8e5af140bb8ff6dfac87d2aa8a7181a7", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "8e5af140bb8ff6dfac87d2aa8a7181a7" due to: ' + t);
        }
    },
    "(()=>{document.addEventListener('DOMContentLoaded',()=>{var el=document.body; var ce=document.createElement('div'); if(el) { el.appendChild(ce); ce.setAttribute(\"id\", \"QGSBETJjtZkYH\"); }})})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["660d8dc0098c8febc0f6d884977e6d4e"] === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                var e = document.body, t = document.createElement("div");
                if (e) {
                    e.appendChild(t);
                    t.setAttribute("id", "QGSBETJjtZkYH");
                }
            });
            Object.defineProperty(Window.prototype.toString, "660d8dc0098c8febc0f6d884977e6d4e", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "660d8dc0098c8febc0f6d884977e6d4e" due to: ' + e);
        }
    },
    '(()=>{document.addEventListener(\'DOMContentLoaded\',()=>{const e=document.querySelector("#widescreen1");if(e){const t=document.createElement("div");t.setAttribute("id","google_ads_iframe_"),e.appendChild(t)}})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["44c722190e3d03dbed05660dc5040600"] === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                const e = document.querySelector("#widescreen1");
                if (e) {
                    const t = document.createElement("div");
                    t.setAttribute("id", "google_ads_iframe_"), e.appendChild(t);
                }
            });
            Object.defineProperty(Window.prototype.toString, "44c722190e3d03dbed05660dc5040600", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "44c722190e3d03dbed05660dc5040600" due to: ' + e);
        }
    },
    '(()=>{const n=window.String.prototype.includes,o={apply:(o,t,i)=>{const c=i[0];return!(!i||!n.call(c,"function onclick(lczxsusin)"))||Reflect.apply(o,t,i)}};window.String.prototype.includes=new Proxy(window.String.prototype.includes,o)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["2e3a208e2520b56c4a151edf4ed886f4"] === e) return;
            (()=>{
                const e = window.String.prototype.includes, t = {
                    apply: (t, o, n1)=>{
                        const r = n1[0];
                        return !(!n1 || !e.call(r, "function onclick(lczxsusin)")) || Reflect.apply(t, o, n1);
                    }
                };
                window.String.prototype.includes = new Proxy(window.String.prototype.includes, t);
            })();
            Object.defineProperty(Window.prototype.toString, "2e3a208e2520b56c4a151edf4ed886f4", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "2e3a208e2520b56c4a151edf4ed886f4" due to: ' + e);
        }
    },
    '(()=>{const e=new Set(["fimg","faimg","fbmg","fcmg","fdmg","femg","ffmg","fgmg","fjmg","fkmg"]),t={apply:(t,c,n)=>{const s=n[2];if(s){const t=Object.keys(s).length;if(t>1&&t<20)for(let t in s)if(e.has(t)&&!0===n[2][t])try{n[2][t]=!1}catch(e){console.trace(e)}else if(!0===s[t])try{const e=(new Error).stack;/NodeList\\.forEach|(<anonymous>|blob):[\\s\\S]{1,500}$/.test(e)&&(s[t]=!1)}catch(e){console.trace(e)}}return Reflect.apply(t,c,n)}};window.Object.assign=new Proxy(window.Object.assign,t)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["26f59c9e189170e8d303a40a632b2e28"] === e) return;
            (()=>{
                const e = new Set([
                    "fimg",
                    "faimg",
                    "fbmg",
                    "fcmg",
                    "fdmg",
                    "femg",
                    "ffmg",
                    "fgmg",
                    "fjmg",
                    "fkmg"
                ]), t = {
                    apply: (t, o, n1)=>{
                        const r = n1[2];
                        if (r) {
                            const t = Object.keys(r).length;
                            if (t > 1 && t < 20) {
                                for(let t in r)if (e.has(t) && !0 === n1[2][t]) try {
                                    n1[2][t] = !1;
                                } catch (e) {
                                    console.trace(e);
                                }
                                else if (!0 === r[t]) try {
                                    const e = (new Error).stack;
                                    /NodeList\.forEach|(<anonymous>|blob):[\s\S]{1,500}$/.test(e) && (r[t] = !1);
                                } catch (e) {
                                    console.trace(e);
                                }
                            }
                        }
                        return Reflect.apply(t, o, n1);
                    }
                };
                window.Object.assign = new Proxy(window.Object.assign, t);
            })();
            Object.defineProperty(Window.prototype.toString, "26f59c9e189170e8d303a40a632b2e28", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "26f59c9e189170e8d303a40a632b2e28" due to: ' + e);
        }
    },
    '(()=>{const e={apply:(e,t,p)=>{const o=p[1];return o&&"string"==typeof o&&o.match(/pagead2\\.googlesyndication\\.com|google.*\\.js|\\/.*?\\/.*?ad.*?\\.js|\\.(shop|quest|autos)\\/.*?\\.(js|php|html)/)&&(t.prevent=!0),Reflect.apply(e,t,p)}};window.XMLHttpRequest.prototype.open=new Proxy(window.XMLHttpRequest.prototype.open,e);const t={apply:(e,t,p)=>{if(!t.prevent)return Reflect.apply(e,t,p)}};window.XMLHttpRequest.prototype.send=new Proxy(window.XMLHttpRequest.prototype.send,t)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.c7605ee2684a2146beda3b04ccfa8bec === e) return;
            (()=>{
                const e = {
                    apply: (e, t, o)=>{
                        const p = o[1];
                        return p && "string" == typeof p && p.match(/pagead2\.googlesyndication\.com|google.*\.js|\/.*?\/.*?ad.*?\.js|\.(shop|quest|autos)\/.*?\.(js|php|html)/) && (t.prevent = !0), Reflect.apply(e, t, o);
                    }
                };
                window.XMLHttpRequest.prototype.open = new Proxy(window.XMLHttpRequest.prototype.open, e);
                const t = {
                    apply: (e, t, o)=>{
                        if (!t.prevent) return Reflect.apply(e, t, o);
                    }
                };
                window.XMLHttpRequest.prototype.send = new Proxy(window.XMLHttpRequest.prototype.send, t);
            })();
            Object.defineProperty(Window.prototype.toString, "c7605ee2684a2146beda3b04ccfa8bec", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "c7605ee2684a2146beda3b04ccfa8bec" due to: ' + e);
        }
    },
    '(()=>{const e=()=>{document.querySelectorAll(".chakra-portal").forEach((e=>{e.querySelector(\'.chakra-modal__overlay[style*="opacity"]\')&&e.setAttribute("style","display: none !important;")}))},t=()=>{},a=function(t,a){const r={name:t,listener:a};requestAnimationFrame((()=>{try{"rewardedSlotGranted"===r.name&&setTimeout(e,2e3),r.listener()}catch(e){}}))};window.googletag={cmd:[],pubads:()=>({addEventListener:a,removeEventListener:t,refresh:t,getTargeting:()=>[],setTargeting:t,disableInitialLoad:t,enableSingleRequest:t,collapseEmptyDivs:t,getSlots:t}),defineSlot:()=>({addService(){}}),defineOutOfPageSlot:t,enableServices:t,display:t,enums:{OutOfPageFormat:{REWARDED:1}}},googletag.cmd.push=e=>{try{e()}catch(e){}return 1}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["788553a11ab6cd27600ce601f07d7af8"] === e) return;
            (()=>{
                const e = ()=>{
                    document.querySelectorAll(".chakra-portal").forEach((e)=>{
                        e.querySelector('.chakra-modal__overlay[style*="opacity"]') && e.setAttribute("style", "display: none !important;");
                    });
                }, t = ()=>{}, r = function(t, r) {
                    const a = {
                        name: t,
                        listener: r
                    };
                    requestAnimationFrame(()=>{
                        try {
                            "rewardedSlotGranted" === a.name && setTimeout(e, 2e3), a.listener();
                        } catch (e) {}
                    });
                };
                window.googletag = {
                    cmd: [],
                    pubads: ()=>({
                            addEventListener: r,
                            removeEventListener: t,
                            refresh: t,
                            getTargeting: ()=>[],
                            setTargeting: t,
                            disableInitialLoad: t,
                            enableSingleRequest: t,
                            collapseEmptyDivs: t,
                            getSlots: t
                        }),
                    defineSlot: ()=>({
                            addService () {}
                        }),
                    defineOutOfPageSlot: t,
                    enableServices: t,
                    display: t,
                    enums: {
                        OutOfPageFormat: {
                            REWARDED: 1
                        }
                    }
                }, googletag.cmd.push = (e)=>{
                    try {
                        e();
                    } catch (e) {}
                    return 1;
                };
            })();
            Object.defineProperty(Window.prototype.toString, "788553a11ab6cd27600ce601f07d7af8", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "788553a11ab6cd27600ce601f07d7af8" due to: ' + e);
        }
    },
    '(()=>{document.addEventListener(\'DOMContentLoaded\',()=>{if(window.CryptoJSAesJson&&window.CryptoJSAesJson.decrypt){const e=document.createElement("link");function t(){const t=document.querySelector(".entry-header.header");return parseInt(t.getAttribute("data-id"))}e.setAttribute("rel","stylesheet"),e.setAttribute("media","all"),e.setAttribute("href","/wp-content/cache/autoptimize/css/autoptimize_92c5b1cf0217cba9b3fab27d39f320b9.css"),document.head.appendChild(e);const r=3,n=5,o=13,a="07";let c="",i="";const d=1,l=6,g=1,s=5,u=2,p=8,m=8,A=(t,e)=>parseInt(t.toString()+e.toString()),b=(t,e,r)=>t.toString()+e.toString()+r.toString(),S=()=>{const e=document.querySelectorAll(".reading-content .page-break img").length;let c=parseInt((t()+A(o,a))*r-e);return c=A(2*n+1,c),c},h=()=>{const e=document.querySelectorAll(".reading-content .page-break img").length;let r=parseInt((t()+A(p,m))*(2*d)-e-(2*d*2+1));return r=b(2*l+g+g+1,c,r),r},y=()=>{const e=document.querySelectorAll(".reading-content .page-break img").length;return b(t()+2*s*2,i,e*(2*u))},f=(t,e)=>CryptoJSAesJson.decrypt(t,e);let k=document.querySelectorAll(".reading-content .page-break img");k.forEach((t=>{const e=t.getAttribute("id"),r=f(e,S().toString());t.setAttribute("id",r)})),k=document.querySelectorAll(".reading-content .page-break img"),k.forEach((t=>{const e=t.getAttribute("id"),r=parseInt(e.replace(/image-(\\d+)[a-z]+/i,"$1"));document.querySelectorAll(".reading-content .page-break")[r].appendChild(t)})),k=document.querySelectorAll(".reading-content .page-break img"),k.forEach((t=>{const e=t.getAttribute("id"),r=e.slice(-1);c+=r,t.setAttribute("id",e.slice(0,-1))})),k=document.querySelectorAll(".reading-content .page-break img"),k.forEach((t=>{const e=t.getAttribute("dta"),r=f(e,h().toString());t.setAttribute("dta",r)})),k=document.querySelectorAll(".reading-content .page-break img"),k.forEach((t=>{const e=t.getAttribute("dta").slice(-2);i+=e,t.removeAttribute("dta")})),k.forEach((t=>{var e=t.getAttribute("data-src"),r=f(e,y().toString());t.setAttribute("data-src",r)})),k.forEach((t=>{t.classList.add("wp-manga-chapter-img","img-responsive","lazyload","effect-fade")}))}})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["793501cfe6b6465e5f629489b079c172"] === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                if (window.CryptoJSAesJson && window.CryptoJSAesJson.decrypt) {
                    const t = document.createElement("link");
                    function e() {
                        const e = document.querySelector(".entry-header.header");
                        return parseInt(e.getAttribute("data-id"));
                    }
                    t.setAttribute("rel", "stylesheet"), t.setAttribute("media", "all"), t.setAttribute("href", "/wp-content/cache/autoptimize/css/autoptimize_92c5b1cf0217cba9b3fab27d39f320b9.css"), document.head.appendChild(t);
                    const r = 3, n1 = 5, o = 13, c = "07";
                    let a = "", i1 = "";
                    const d = 1, l = 6, u = 1, g = 5, s = 2, b = 8, p = 8, m = (e, t)=>parseInt(e.toString() + t.toString()), A = (e, t, r)=>e.toString() + t.toString() + r.toString(), f = ()=>{
                        const t = document.querySelectorAll(".reading-content .page-break img").length;
                        let a = parseInt((e() + m(o, c)) * r - t);
                        return a = m(2 * n1 + 1, a), a;
                    }, S = ()=>{
                        const t = document.querySelectorAll(".reading-content .page-break img").length;
                        let r = parseInt((e() + m(b, p)) * (2 * d) - t - (2 * d * 2 + 1));
                        return r = A(2 * l + u + u + 1, a, r), r;
                    }, y = ()=>{
                        const t = document.querySelectorAll(".reading-content .page-break img").length;
                        return A(e() + 2 * g * 2, i1, t * (2 * s));
                    }, h = (e, t)=>CryptoJSAesJson.decrypt(e, t);
                    let q = document.querySelectorAll(".reading-content .page-break img");
                    q.forEach((e)=>{
                        const t = e.getAttribute("id"), r = h(t, f().toString());
                        e.setAttribute("id", r);
                    }), q = document.querySelectorAll(".reading-content .page-break img"), q.forEach((e)=>{
                        const t = e.getAttribute("id"), r = parseInt(t.replace(/image-(\d+)[a-z]+/i, "$1"));
                        document.querySelectorAll(".reading-content .page-break")[r].appendChild(e);
                    }), q = document.querySelectorAll(".reading-content .page-break img"), q.forEach((e)=>{
                        const t = e.getAttribute("id"), r = t.slice(-1);
                        a += r, e.setAttribute("id", t.slice(0, -1));
                    }), q = document.querySelectorAll(".reading-content .page-break img"), q.forEach((e)=>{
                        const t = e.getAttribute("dta"), r = h(t, S().toString());
                        e.setAttribute("dta", r);
                    }), q = document.querySelectorAll(".reading-content .page-break img"), q.forEach((e)=>{
                        const t = e.getAttribute("dta").slice(-2);
                        i1 += t, e.removeAttribute("dta");
                    }), q.forEach((e)=>{
                        var t = e.getAttribute("data-src"), r = h(t, y().toString());
                        e.setAttribute("data-src", r);
                    }), q.forEach((e)=>{
                        e.classList.add("wp-manga-chapter-img", "img-responsive", "lazyload", "effect-fade");
                    });
                }
            });
            Object.defineProperty(Window.prototype.toString, "793501cfe6b6465e5f629489b079c172", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "793501cfe6b6465e5f629489b079c172" due to: ' + e);
        }
    },
    '(()=>{const e=new Map,t=function(){},o=t;o.prototype.dispose=t,o.prototype.setNetwork=t,o.prototype.resize=t,o.prototype.setServer=t,o.prototype.setLogLevel=t,o.prototype.newContext=function(){return this},o.prototype.setParameter=t,o.prototype.addEventListener=function(t,o){t&&(console.debug(`Type: ${t}, callback: ${o}`),e.set(t,o))},o.prototype.removeEventListener=t,o.prototype.setProfile=t,o.prototype.setCapability=t,o.prototype.setVideoAsset=t,o.prototype.setSiteSection=t,o.prototype.addKeyValue=t,o.prototype.addTemporalSlot=t,o.prototype.registerCustomPlayer=t,o.prototype.setVideoDisplaySize=t,o.prototype.setContentVideoElement=t,o.prototype.registerVideoDisplayBase=t,o.prototype.submitRequest=function(){const t={type:tv.freewheel.SDK.EVENT_SLOT_ENDED},o=e.get("EVENT_SLOT_ENDED");o&&setTimeout((()=>{try{o(t)}catch(e){console.error(e)}}),1)},window.tv={freewheel:{SDK:{Ad:t,AdManager:o,AdListener:t,_instanceQueue:{},setLogLevel:t,EVENT_SLOT_ENDED:"EVENT_SLOT_ENDED"}}}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["75be2f053259701edcb277b5ff24cd28"] === e) return;
            (()=>{
                const e = new Map, t = function() {}, o = t;
                o.prototype.dispose = t, o.prototype.setNetwork = t, o.prototype.resize = t, o.prototype.setServer = t, o.prototype.setLogLevel = t, o.prototype.newContext = function() {
                    return this;
                }, o.prototype.setParameter = t, o.prototype.addEventListener = function(t, o) {
                    t && (console.debug(`Type: ${t}, callback: ${o}`), e.set(t, o));
                }, o.prototype.removeEventListener = t, o.prototype.setProfile = t, o.prototype.setCapability = t, o.prototype.setVideoAsset = t, o.prototype.setSiteSection = t, o.prototype.addKeyValue = t, o.prototype.addTemporalSlot = t, o.prototype.registerCustomPlayer = t, o.prototype.setVideoDisplaySize = t, o.prototype.setContentVideoElement = t, o.prototype.registerVideoDisplayBase = t, o.prototype.submitRequest = function() {
                    const t = {
                        type: tv.freewheel.SDK.EVENT_SLOT_ENDED
                    }, o = e.get("EVENT_SLOT_ENDED");
                    o && setTimeout(()=>{
                        try {
                            o(t);
                        } catch (e) {
                            console.error(e);
                        }
                    }, 1);
                }, window.tv = {
                    freewheel: {
                        SDK: {
                            Ad: t,
                            AdManager: o,
                            AdListener: t,
                            _instanceQueue: {},
                            setLogLevel: t,
                            EVENT_SLOT_ENDED: "EVENT_SLOT_ENDED"
                        }
                    }
                };
            })();
            Object.defineProperty(Window.prototype.toString, "75be2f053259701edcb277b5ff24cd28", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "75be2f053259701edcb277b5ff24cd28" due to: ' + e);
        }
    },
    '(()=>{const e=window.Promise,o={construct:(o,t,n)=>t[0]&&t[0]?.toString()?.includes("[!1,!1,!1,!1]")&&t[0]?.toString()?.includes(".responseText")?e.resolve(!1):Reflect.construct(o,t,n)},t=new Proxy(window.Promise,o);Object.defineProperty(window,"Promise",{set:e=>{},get:()=>t})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["4e4e57eff747aed19b1eb6c7b2758126"] === e) return;
            (()=>{
                const e = window.Promise, t = {
                    construct: (t, o, r)=>{
                        var _o__toString, _o_, _o__toString1, _o_1;
                        return o[0] && ((_o_ = o[0]) === null || _o_ === void 0 ? void 0 : (_o__toString = _o_.toString()) === null || _o__toString === void 0 ? void 0 : _o__toString.includes("[!1,!1,!1,!1]")) && ((_o_1 = o[0]) === null || _o_1 === void 0 ? void 0 : (_o__toString1 = _o_1.toString()) === null || _o__toString1 === void 0 ? void 0 : _o__toString1.includes(".responseText")) ? e.resolve(!1) : Reflect.construct(t, o, r);
                    }
                }, o = new Proxy(window.Promise, t);
                Object.defineProperty(window, "Promise", {
                    set: (e)=>{},
                    get: ()=>o
                });
            })();
            Object.defineProperty(Window.prototype.toString, "4e4e57eff747aed19b1eb6c7b2758126", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "4e4e57eff747aed19b1eb6c7b2758126" due to: ' + e);
        }
    },
    "(()=>{window.viAPItag={init(){}}})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["88012e776a891c545cc6e77db0f643af"] === e) return;
            window.viAPItag = {
                init () {}
            };
            Object.defineProperty(Window.prototype.toString, "88012e776a891c545cc6e77db0f643af", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "88012e776a891c545cc6e77db0f643af" due to: ' + e);
        }
    },
    '(()=>{document.addEventListener("DOMContentLoaded",(()=>{ "function"==typeof ViewModelBase&&"object"==typeof ViewModelBase.prototype&&"function"==typeof ViewModelBase.prototype.LoadBrandAdAsync&&(ViewModelBase.prototype.LoadBrandAdAsync=function(){}) }));})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.ac3452ef83db17c4e84323d15083a03b === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                "function" == typeof ViewModelBase && "object" == typeof ViewModelBase.prototype && "function" == typeof ViewModelBase.prototype.LoadBrandAdAsync && (ViewModelBase.prototype.LoadBrandAdAsync = function() {});
            });
            Object.defineProperty(Window.prototype.toString, "ac3452ef83db17c4e84323d15083a03b", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "ac3452ef83db17c4e84323d15083a03b" due to: ' + e);
        }
    },
    '(()=>{document.addEventListener("DOMContentLoaded",(()=>{ var a=document.querySelectorAll("ins.adsbygoogle");a.length&&a.forEach(a=>{var b=document.createElement("iframe");b.style="display: none !important;",a.setAttribute("data-ad-status","filled"),a.appendChild(b)}) }));})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["81b55e3b01cb8f931036cccb4d1056b6"] === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                var e = document.querySelectorAll("ins.adsbygoogle");
                e.length && e.forEach((e)=>{
                    var t = document.createElement("iframe");
                    t.style = "display: none !important;", e.setAttribute("data-ad-status", "filled"), e.appendChild(t);
                });
            });
            Object.defineProperty(Window.prototype.toString, "81b55e3b01cb8f931036cccb4d1056b6", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "81b55e3b01cb8f931036cccb4d1056b6" due to: ' + e);
        }
    },
    '(function(){window.adnPopConfig={zoneId:"149"}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.cdb400a346ffb8cf37f33a522644f2cb === e) return;
            window.adnPopConfig = {
                zoneId: "149"
            };
            Object.defineProperty(Window.prototype.toString, "cdb400a346ffb8cf37f33a522644f2cb", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "cdb400a346ffb8cf37f33a522644f2cb" due to: ' + e);
        }
    },
    '!function(){window.adsbygoogle={loaded:!0,push:function(){"undefined"===typeof this.length&&(this.length=0,this.length+=1)}}}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["065d3c28da0404a4fdfd569932271571"] === e) return;
            window.adsbygoogle = {
                loaded: !0,
                push: function() {
                    void 0 === this.length && (this.length = 0, this.length += 1);
                }
            };
            Object.defineProperty(Window.prototype.toString, "065d3c28da0404a4fdfd569932271571", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "065d3c28da0404a4fdfd569932271571" due to: ' + e);
        }
    },
    '(()=>{document.addEventListener("DOMContentLoaded",(()=>{ var b=new MutationObserver(function(){try{for(var a,d=function(c){for(var a="",d=0;d<c;d++)a+="0123456789".charAt(Math.floor(10*Math.random()));return a},e=document.querySelectorAll(".adsbygoogle, script[data-ad-client]"),f=0;f<e.length;f++)if(e[f].getAttribute("data-ad-client")){a=e[f].getAttribute("data-ad-client");break}if(a){var g=`<ins class="adsbygoogle" data-adsbygoogle-status="done" style="display: block; height: 200px; width: 200px;" data-ad-status="unfilled"><ins id="aswift_0_expand" style="border: none; height: 0px; width: 0px; margin: 0px; padding: 0px; position: relative; visibility: visible; background-color: transparent; display: inline-table;" tabindex="0" title="Advertisement" aria-label="Advertisement"><ins id="aswift_0_anchor" style="border: none; height: 0px; width: 0px; margin: 0px; padding: 0px; position: relative; visibility: visible; background-color: transparent; display: block;"><iframe id="aswift_0" name="aswift_0" style="left:0;position:absolute;top:0;border:0;width:200px;height:200px;" sandbox="allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-top-navigation-by-user-activation" frameborder="0" src="https://googleads.g.doubleclick.net/pagead/ads?client=${a}&amp;output=html&amp;adk=${d(10)}&amp;adf=${d(10)}&amp;lmt=${d(10)}&amp;plat=${d(100)};&amp;format=0x0&amp;url=${encodeURIComponent(document.location.href)}&amp;ea=0&amp;flash=0&amp;pra=5&amp;wgl=1&amp;uach=${d(100)}&amp;bpp=2&amp;bdt=${d(3)}&amp;idt=${d(3)}&amp;shv=r${d(8)}&amp;mjsv=m${d(8)}&amp;ptt=${d(1)}&amp;saldr=aa&amp;abxe=1&amp;nras=1&amp;correlator=${d(8)}&amp;frm=${d(2)}&amp;pv=2&amp;ga_vid=${d(10)}.${d(10)}&amp;ga_sid=${d(10)}&amp;ga_hid=${d(10)}&amp;ga_fc=0&amp;u_tz=${d(3)}&amp;u_his=8&amp;u_java=0&amp;u_h=${d(4)}&amp;u_w=${d(4)}&amp;u_ah=${d(4)}&amp;u_aw=${d(4)}&amp;u_cd=${d(2)}&amp;u_nplug=${d(1)}&amp;u_nmime=${d(1)}&amp;adx=-${d(8)}&amp;ady=-${d(8)}&amp;biw=${d(4)}&amp;bih=${d(4)}&amp;scr_x=0&amp;scr_y=0&amp;eid=${d(30)}&amp;oid=${d(1)}&amp;pvsid=${d(16)}&amp;pem=${d(3)}&amp;eae=${d(1)}&amp;fc=${d(4)}&amp;brdim=${d(20)}&amp;vis=1&amp;rsz=${d(6)}&amp;abl=NS&amp;fu=${d(4)}&amp;bc=${d(2)}&amp;ifi=1&amp;uci=a!1&amp;fsb=1&amp;dtd=128" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" allowfullscreen="true" data-google-container-id="a!1" data-load-complete="true"></iframe></ins></ins></ins>`,h=document.querySelector("body > *"),j=document.querySelectorAll(".phpbb-ads-center > .adsbygoogle");h&&j.length&&(!h.querySelector("iframe#aswift_0")&&h.insertAdjacentHTML("afterend",g),j.forEach(a=>{a.querySelector("iframe#aswift_0")||(a.parentNode.style.height="200px",a.parentNode.style.width="200px",a.parentNode.innerHTML=g)}))}var k=document.querySelector(".page-body"),l=document.querySelectorAll(".adsbygoogle, .phpbb-ads-center");k&&!k.innerText.includes("deactivating your Ad-Blocker")&&l.length&&(l.forEach(a=>{a.remove()}),b.disconnect())}catch(a){}});b.observe(document,{childList:!0,subtree:!0}),setTimeout(function(){b.disconnect()},1E4) }));})();': ()=>{
        try {
            const a = "done";
            if (Window.prototype.toString["802366024dd441867900263826a1b687"] === a) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                var a = new MutationObserver(function() {
                    try {
                        for(var e, t = function(a) {
                            for(var e = "", t = 0; t < a; t++)e += "0123456789".charAt(Math.floor(10 * Math.random()));
                            return e;
                        }, i1 = document.querySelectorAll(".adsbygoogle, script[data-ad-client]"), o = 0; o < i1.length; o++)if (i1[o].getAttribute("data-ad-client")) {
                            e = i1[o].getAttribute("data-ad-client");
                            break;
                        }
                        if (e) {
                            var r = `<ins class="adsbygoogle" data-adsbygoogle-status="done" style="display: block; height: 200px; width: 200px;" data-ad-status="unfilled"><ins id="aswift_0_expand" style="border: none; height: 0px; width: 0px; margin: 0px; padding: 0px; position: relative; visibility: visible; background-color: transparent; display: inline-table;" tabindex="0" title="Advertisement" aria-label="Advertisement"><ins id="aswift_0_anchor" style="border: none; height: 0px; width: 0px; margin: 0px; padding: 0px; position: relative; visibility: visible; background-color: transparent; display: block;"><iframe id="aswift_0" name="aswift_0" style="left:0;position:absolute;top:0;border:0;width:200px;height:200px;" sandbox="allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-top-navigation-by-user-activation" frameborder="0" src="https://googleads.g.doubleclick.net/pagead/ads?client=${e}&amp;output=html&amp;adk=${t(10)}&amp;adf=${t(10)}&amp;lmt=${t(10)}&amp;plat=${t(100)};&amp;format=0x0&amp;url=${encodeURIComponent(document.location.href)}&amp;ea=0&amp;flash=0&amp;pra=5&amp;wgl=1&amp;uach=${t(100)}&amp;bpp=2&amp;bdt=${t(3)}&amp;idt=${t(3)}&amp;shv=r${t(8)}&amp;mjsv=m${t(8)}&amp;ptt=${t(1)}&amp;saldr=aa&amp;abxe=1&amp;nras=1&amp;correlator=${t(8)}&amp;frm=${t(2)}&amp;pv=2&amp;ga_vid=${t(10)}.${t(10)}&amp;ga_sid=${t(10)}&amp;ga_hid=${t(10)}&amp;ga_fc=0&amp;u_tz=${t(3)}&amp;u_his=8&amp;u_java=0&amp;u_h=${t(4)}&amp;u_w=${t(4)}&amp;u_ah=${t(4)}&amp;u_aw=${t(4)}&amp;u_cd=${t(2)}&amp;u_nplug=${t(1)}&amp;u_nmime=${t(1)}&amp;adx=-${t(8)}&amp;ady=-${t(8)}&amp;biw=${t(4)}&amp;bih=${t(4)}&amp;scr_x=0&amp;scr_y=0&amp;eid=${t(30)}&amp;oid=${t(1)}&amp;pvsid=${t(16)}&amp;pem=${t(3)}&amp;eae=${t(1)}&amp;fc=${t(4)}&amp;brdim=${t(20)}&amp;vis=1&amp;rsz=${t(6)}&amp;abl=NS&amp;fu=${t(4)}&amp;bc=${t(2)}&amp;ifi=1&amp;uci=a!1&amp;fsb=1&amp;dtd=128" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" allowfullscreen="true" data-google-container-id="a!1" data-load-complete="true"></iframe></ins></ins></ins>`, p = document.querySelector("body > *"), n1 = document.querySelectorAll(".phpbb-ads-center > .adsbygoogle");
                            p && n1.length && (!p.querySelector("iframe#aswift_0") && p.insertAdjacentHTML("afterend", r), n1.forEach((a)=>{
                                a.querySelector("iframe#aswift_0") || (a.parentNode.style.height = "200px", a.parentNode.style.width = "200px", a.parentNode.innerHTML = r);
                            }));
                        }
                        var d = document.querySelector(".page-body"), l = document.querySelectorAll(".adsbygoogle, .phpbb-ads-center");
                        d && !d.innerText.includes("deactivating your Ad-Blocker") && l.length && (l.forEach((a)=>{
                            a.remove();
                        }), a.disconnect());
                    } catch (e) {}
                });
                a.observe(document, {
                    childList: !0,
                    subtree: !0
                }), setTimeout(function() {
                    a.disconnect();
                }, 1e4);
            });
            Object.defineProperty(Window.prototype.toString, "802366024dd441867900263826a1b687", {
                value: a,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (a) {
            console.error('Error executing AG js rule with uniqueId "802366024dd441867900263826a1b687" due to: ' + a);
        }
    },
    "window.adsbygoogle = { loaded: !0 };": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.df4e0801aa685812f605b6558f08d2df === e) return;
            window.adsbygoogle = {
                loaded: !0
            };
            Object.defineProperty(Window.prototype.toString, "df4e0801aa685812f605b6558f08d2df", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "df4e0801aa685812f605b6558f08d2df" due to: ' + e);
        }
    },
    '!function(){const e={apply:(e,l,t)=>{const o=t[0];return o?.includes(".b_ad,")?t[0]="#b_results":o?.includes(".b_restorableLink")&&(t[0]=".b_algo"),Reflect.apply(e,l,t)}};window.Element.prototype.querySelectorAll=new Proxy(window.Element.prototype.querySelectorAll,e)}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["009a684340d0a5680676bfe531438c9e"] === e) return;
            !function() {
                const e = {
                    apply: (e, t, o)=>{
                        const r = o[0];
                        return (r === null || r === void 0 ? void 0 : r.includes(".b_ad,")) ? o[0] = "#b_results" : (r === null || r === void 0 ? void 0 : r.includes(".b_restorableLink")) && (o[0] = ".b_algo"), Reflect.apply(e, t, o);
                    }
                };
                window.Element.prototype.querySelectorAll = new Proxy(window.Element.prototype.querySelectorAll, e);
            }();
            Object.defineProperty(Window.prototype.toString, "009a684340d0a5680676bfe531438c9e", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "009a684340d0a5680676bfe531438c9e" due to: ' + e);
        }
    },
    "(function(){var b=window.setTimeout;window.setTimeout=function(a,c){if(!/\\]\\.bab\\(window/.test(a.toString()))return b(a,c)};})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["346833de4a18e6e5f53bde8d214083c7"] === e) return;
            !function() {
                var e = window.setTimeout;
                window.setTimeout = function(t, o) {
                    if (!/\]\.bab\(window/.test(t.toString())) return e(t, o);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "346833de4a18e6e5f53bde8d214083c7", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "346833de4a18e6e5f53bde8d214083c7" due to: ' + e);
        }
    },
    "(function(){var b=window.setInterval;window.setInterval=function(a,c){if(!/.\\.display=='hidden'[\\s\\S]*?.\\.visibility=='none'/.test(a.toString()))return b(a,c)}.bind(window)})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["2610380c7215f8ed3dab7859b677c07e"] === e) return;
            !function() {
                var e = window.setInterval;
                window.setInterval = (function(t, n1) {
                    if (!/.\.display=='hidden'[\s\S]*?.\.visibility=='none'/.test(t.toString())) return e(t, n1);
                }).bind(window);
            }();
            Object.defineProperty(Window.prototype.toString, "2610380c7215f8ed3dab7859b677c07e", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "2610380c7215f8ed3dab7859b677c07e" due to: ' + e);
        }
    },
    "(function(){var b=window.setInterval;window.setInterval=function(a,c){if(!/e\\.display=='hidden'[\\s\\S]*?e\\.visibility=='none'/.test(a.toString()))return b(a,c)}.bind(window)})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["799170846df78b2e8c6f8f1ecbe9f9ab"] === e) return;
            !function() {
                var e = window.setInterval;
                window.setInterval = (function(t, n1) {
                    if (!/e\.display=='hidden'[\s\S]*?e\.visibility=='none'/.test(t.toString())) return e(t, n1);
                }).bind(window);
            }();
            Object.defineProperty(Window.prototype.toString, "799170846df78b2e8c6f8f1ecbe9f9ab", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "799170846df78b2e8c6f8f1ecbe9f9ab" due to: ' + e);
        }
    },
    "window.cRAds = !0;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["05f59c5992059f458f16aa93e814a859"] === e) return;
            window.cRAds = !0;
            Object.defineProperty(Window.prototype.toString, "05f59c5992059f458f16aa93e814a859", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "05f59c5992059f458f16aa93e814a859" due to: ' + e);
        }
    },
    "window.spoof_weer2edasfgeefzc = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.f383cd371dd44d7f9a6f53a66c468020 === e) return;
            window.spoof_weer2edasfgeefzc = !0;
            Object.defineProperty(Window.prototype.toString, "f383cd371dd44d7f9a6f53a66c468020", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "f383cd371dd44d7f9a6f53a66c468020" due to: ' + e);
        }
    },
    "window.$tieE3 = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.abf848581aab7ee411a3a190d6305e9f === e) return;
            window.$tieE3 = !0;
            Object.defineProperty(Window.prototype.toString, "abf848581aab7ee411a3a190d6305e9f", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "abf848581aab7ee411a3a190d6305e9f" due to: ' + e);
        }
    },
    "window.Advertisement = 1;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.a77fad03c24e228b97652a46d1fa5f22 === e) return;
            window.Advertisement = 1;
            Object.defineProperty(Window.prototype.toString, "a77fad03c24e228b97652a46d1fa5f22", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "a77fad03c24e228b97652a46d1fa5f22" due to: ' + e);
        }
    },
    "(function(){var b=window.setTimeout;window.setTimeout=function(a,c){if(!/getAdIFrameCount/.test(a.toString()))return b(a,c)};})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["0f751b2f4dfde1f99c0f6624f4bb7d2e"] === e) return;
            !function() {
                var e = window.setTimeout;
                window.setTimeout = function(t, o) {
                    if (!/getAdIFrameCount/.test(t.toString())) return e(t, o);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "0f751b2f4dfde1f99c0f6624f4bb7d2e", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "0f751b2f4dfde1f99c0f6624f4bb7d2e" due to: ' + e);
        }
    },
    "window.check_adblock = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["8703d7f8d98d46a5463db89eea32ce11"] === e) return;
            window.check_adblock = !0;
            Object.defineProperty(Window.prototype.toString, "8703d7f8d98d46a5463db89eea32ce11", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "8703d7f8d98d46a5463db89eea32ce11" due to: ' + e);
        }
    },
    "window.isAdsDisplayed = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["6fdd528c721ed150a4988b0a7c6d81fb"] === e) return;
            window.isAdsDisplayed = !0;
            Object.defineProperty(Window.prototype.toString, "6fdd528c721ed150a4988b0a7c6d81fb", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "6fdd528c721ed150a4988b0a7c6d81fb" due to: ' + e);
        }
    },
    "window.adsEnabled = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["62d14321dc3e190666318c2f0ddfdcac"] === e) return;
            window.adsEnabled = !0;
            Object.defineProperty(Window.prototype.toString, "62d14321dc3e190666318c2f0ddfdcac", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "62d14321dc3e190666318c2f0ddfdcac" due to: ' + e);
        }
    },
    "window.uabpdl = window.uabInject = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["33d2335f47a6a24e15dbab294084b29d"] === e) return;
            window.uabpdl = window.uabInject = !0;
            Object.defineProperty(Window.prototype.toString, "33d2335f47a6a24e15dbab294084b29d", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "33d2335f47a6a24e15dbab294084b29d" due to: ' + e);
        }
    },
    'window.ads = "on";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["1667ac15a74b79e35fdab510c44b45c6"] === e) return;
            window.ads = "on";
            Object.defineProperty(Window.prototype.toString, "1667ac15a74b79e35fdab510c44b45c6", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "1667ac15a74b79e35fdab510c44b45c6" due to: ' + e);
        }
    },
    "window.detector_active = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.fff6b1a1e7573bdc8801939be0d52c55 === e) return;
            window.detector_active = !0;
            Object.defineProperty(Window.prototype.toString, "fff6b1a1e7573bdc8801939be0d52c55", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "fff6b1a1e7573bdc8801939be0d52c55" due to: ' + e);
        }
    },
    'var _st = window.setTimeout; window.setTimeout = function(a, b) { if(!/document\\.querySelector\\("ins\\.adsbygoogle"\\)/.test(a)){ _st(a,b);}};': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["7236f7ab988d26aeb65e644c0c708759"] === e) return;
            var _st = window.setTimeout;
            window.setTimeout = function(e, t) {
                /document\.querySelector\("ins\.adsbygoogle"\)/.test(e) || _st(e, t);
            };
            Object.defineProperty(Window.prototype.toString, "7236f7ab988d26aeb65e644c0c708759", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "7236f7ab988d26aeb65e644c0c708759" due to: ' + e);
        }
    },
    "window.showAds = 1;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.a677ae0f959db896dab64fd632486735 === e) return;
            window.showAds = 1;
            Object.defineProperty(Window.prototype.toString, "a677ae0f959db896dab64fd632486735", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "a677ae0f959db896dab64fd632486735" due to: ' + e);
        }
    },
    "(function(){var b=window.setTimeout;window.setTimeout=function(a,c){if(!/ad-free subscription/.test(a.toString()))return b(a,c)};})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["13bb27a7e03ad36f09dfe943af907243"] === e) return;
            !function() {
                var e = window.setTimeout;
                window.setTimeout = function(t, o) {
                    if (!/ad-free subscription/.test(t.toString())) return e(t, o);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "13bb27a7e03ad36f09dfe943af907243", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "13bb27a7e03ad36f09dfe943af907243" due to: ' + e);
        }
    },
    "window.popns = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.d03453914a0f0c39d24075d7778082b7 === e) return;
            window.popns = !0;
            Object.defineProperty(Window.prototype.toString, "d03453914a0f0c39d24075d7778082b7", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "d03453914a0f0c39d24075d7778082b7" due to: ' + e);
        }
    },
    "(function(){var b=window.setTimeout;window.setTimeout=function(a,c){if(!/\\!document\\.getElementById[\\s\\S]*?#updato-overlay/.test(a.toString()))return b(a,c)};})();": ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString.c01f2a751b270a3b51a5d5bfcbcb1984 === t) return;
            !function() {
                var t = window.setTimeout;
                window.setTimeout = function(e, o) {
                    if (!/\!document\.getElementById[\s\S]*?#updato-overlay/.test(e.toString())) return t(e, o);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "c01f2a751b270a3b51a5d5bfcbcb1984", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "c01f2a751b270a3b51a5d5bfcbcb1984" due to: ' + t);
        }
    },
    "var _st = window.setTimeout; window.setTimeout = function(a, b) { if(!/document\\.getElementById\\('cootent'\\)\\.innerHTML=/.test(a)){ _st(a,b);}};": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.d1d17c910459844ab89551639599c825 === e) return;
            var _st = window.setTimeout;
            window.setTimeout = function(e, t) {
                /document\.getElementById\('cootent'\)\.innerHTML=/.test(e) || _st(e, t);
            };
            Object.defineProperty(Window.prototype.toString, "d1d17c910459844ab89551639599c825", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "d1d17c910459844ab89551639599c825" due to: ' + e);
        }
    },
    "window.areAdsDisplayed = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["8e2186350e194ef09a3cc1ab5f463826"] === e) return;
            window.areAdsDisplayed = !0;
            Object.defineProperty(Window.prototype.toString, "8e2186350e194ef09a3cc1ab5f463826", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "8e2186350e194ef09a3cc1ab5f463826" due to: ' + e);
        }
    },
    "window.Adv_ab = false;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["5601052c8ba773fc21566b0dfbe3e078"] === e) return;
            window.Adv_ab = !1;
            Object.defineProperty(Window.prototype.toString, "5601052c8ba773fc21566b0dfbe3e078", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "5601052c8ba773fc21566b0dfbe3e078" due to: ' + e);
        }
    },
    "window.adsEnabled=!0;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.be54fb20467f57c75acee13f527620e5 === e) return;
            window.adsEnabled = !0;
            Object.defineProperty(Window.prototype.toString, "be54fb20467f57c75acee13f527620e5", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "be54fb20467f57c75acee13f527620e5" due to: ' + e);
        }
    },
    "window.showads=true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["312c329877d22ebe2fb61034e6a10055"] === e) return;
            window.showads = !0;
            Object.defineProperty(Window.prototype.toString, "312c329877d22ebe2fb61034e6a10055", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "312c329877d22ebe2fb61034e6a10055" due to: ' + e);
        }
    },
    "var _st = window.setTimeout; window.setTimeout = function(a, b) { if(!/_detectAdBlocker/.test(a)){ _st(a,b);}};": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.b052dc5df97eaa80a24a214c96f52633 === e) return;
            var _st = window.setTimeout;
            window.setTimeout = function(e, t) {
                /_detectAdBlocker/.test(e) || _st(e, t);
            };
            Object.defineProperty(Window.prototype.toString, "b052dc5df97eaa80a24a214c96f52633", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "b052dc5df97eaa80a24a214c96f52633" due to: ' + e);
        }
    },
    '(function(a){setTimeout=function(){var b="function"==typeof arguments[0]?Function.prototype.toString.call(arguments[0]):"string"==typeof arguments[0]?arguments[0]:String(arguments[0]);return/\\[(_0x[a-z0-9]{4,})\\[\\d+\\]\\][\\[\\(]\\1\\[\\d+\\]/.test(b)?NaN:a.apply(window,arguments)}.bind();Object.defineProperty(setTimeout,"name",{value:a.name});setTimeout.toString=Function.prototype.toString.bind(a)})(setTimeout);': ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString.d51de922f2ef3a82152acd709db8a549 === t) return;
            !function(t) {
                setTimeout = (function() {
                    var e = "function" == typeof arguments[0] ? Function.prototype.toString.call(arguments[0]) : "string" == typeof arguments[0] ? arguments[0] : String(arguments[0]);
                    return /\[(_0x[a-z0-9]{4,})\[\d+\]\][\[\(]\1\[\d+\]/.test(e) ? NaN : t.apply(window, arguments);
                }).bind();
                Object.defineProperty(setTimeout, "name", {
                    value: t.name
                });
                setTimeout.toString = Function.prototype.toString.bind(t);
            }(setTimeout);
            Object.defineProperty(Window.prototype.toString, "d51de922f2ef3a82152acd709db8a549", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "d51de922f2ef3a82152acd709db8a549" due to: ' + t);
        }
    },
    '(function(b,c){setTimeout=function(){var a=arguments[0];if("function"==typeof a&&/^function [A-Za-z]{1,2}\\(\\)\\s*\\{([A-Za-z])\\|\\|\\(\\1=!0,[\\s\\S]{1,13}\\(\\)\\)\\}$/.test(c.call(a)))throw"Adguard stopped a script execution.";return b.apply(window,arguments)}})(setTimeout,Function.prototype.toString);': ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString["41822b6439a26cd50f44b208e1bad083"] === t) return;
            !function(t, e) {
                setTimeout = function() {
                    var o = arguments[0];
                    if ("function" == typeof o && /^function [A-Za-z]{1,2}\(\)\s*\{([A-Za-z])\|\|\(\1=!0,[\s\S]{1,13}\(\)\)\}$/.test(e.call(o))) throw "Adguard stopped a script execution.";
                    return t.apply(window, arguments);
                };
            }(setTimeout, Function.prototype.toString);
            Object.defineProperty(Window.prototype.toString, "41822b6439a26cd50f44b208e1bad083", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "41822b6439a26cd50f44b208e1bad083" due to: ' + t);
        }
    },
    "window.sessionStorage.loadedAds = 3;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["73f1b4fc791cbf3105708cabf5b1db21"] === e) return;
            window.sessionStorage.loadedAds = 3;
            Object.defineProperty(Window.prototype.toString, "73f1b4fc791cbf3105708cabf5b1db21", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "73f1b4fc791cbf3105708cabf5b1db21" due to: ' + e);
        }
    },
    "window.call_Ad = function() { };": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["7c1456a0dab6ca53b945e21a27f6b209"] === e) return;
            window.call_Ad = function() {};
            Object.defineProperty(Window.prototype.toString, "7c1456a0dab6ca53b945e21a27f6b209", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "7c1456a0dab6ca53b945e21a27f6b209" due to: ' + e);
        }
    },
    "window.RunAds = !0;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["6c387c219fbbef62f244b67bd5165f03"] === e) return;
            window.RunAds = !0;
            Object.defineProperty(Window.prototype.toString, "6c387c219fbbef62f244b67bd5165f03", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "6c387c219fbbef62f244b67bd5165f03" due to: ' + e);
        }
    },
    "window._r3z = {}; Object.defineProperties(window._r3z, { jq: { value: undefined }, pub: { value: {} } });": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["48c98c062b9c63813998a881d8c039c9"] === e) return;
            window._r3z = {};
            Object.defineProperties(window._r3z, {
                jq: {
                    value: void 0
                },
                pub: {
                    value: {}
                }
            });
            Object.defineProperty(Window.prototype.toString, "48c98c062b9c63813998a881d8c039c9", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "48c98c062b9c63813998a881d8c039c9" due to: ' + e);
        }
    },
    "(function() { window.xRds = false; window.frg = true; window.frag = true;  })();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.baafa2147233f1a8add3836529d4779e === e) return;
            !function() {
                window.xRds = !1;
                window.frg = !0;
                window.frag = !0;
            }();
            Object.defineProperty(Window.prototype.toString, "baafa2147233f1a8add3836529d4779e", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "baafa2147233f1a8add3836529d4779e" due to: ' + e);
        }
    },
    "window.canABP = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.b1d0f666ef36ca7989b62d00b88a8084 === e) return;
            window.canABP = !0;
            Object.defineProperty(Window.prototype.toString, "b1d0f666ef36ca7989b62d00b88a8084", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "b1d0f666ef36ca7989b62d00b88a8084" due to: ' + e);
        }
    },
    "var _st = window.setTimeout; window.setTimeout = function(a, b) { if(!/displayAdBlockedVideo/.test(a)){ _st(a,b);}};": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["2ac41d844f1f8bd49b7778aeb6e0c2cc"] === e) return;
            var _st = window.setTimeout;
            window.setTimeout = function(e, t) {
                /displayAdBlockedVideo/.test(e) || _st(e, t);
            };
            Object.defineProperty(Window.prototype.toString, "2ac41d844f1f8bd49b7778aeb6e0c2cc", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "2ac41d844f1f8bd49b7778aeb6e0c2cc" due to: ' + e);
        }
    },
    "(function(){var b=window.setTimeout;window.setTimeout=function(a,c){if(!/adsbygoogle instanceof Array/.test(a.toString()))return b(a,c)};})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.db544946f4c7aec68c0cc554e909aa42 === e) return;
            !function() {
                var e = window.setTimeout;
                window.setTimeout = function(t, o) {
                    if (!/adsbygoogle instanceof Array/.test(t.toString())) return e(t, o);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "db544946f4c7aec68c0cc554e909aa42", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "db544946f4c7aec68c0cc554e909aa42" due to: ' + e);
        }
    },
    'window.ad_permission = "OK";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["7016d2bc404839b07be9953ba599b969"] === e) return;
            window.ad_permission = "OK";
            Object.defineProperty(Window.prototype.toString, "7016d2bc404839b07be9953ba599b969", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "7016d2bc404839b07be9953ba599b969" due to: ' + e);
        }
    },
    'document.cookie="popunder=1; path=/;";': ()=>{
        try {
            const c = "done";
            if (Window.prototype.toString.cc60c320cd31f7c797cace7d0a8f787a === c) return;
            document.cookie = "popunder=1; path=/;";
            Object.defineProperty(Window.prototype.toString, "cc60c320cd31f7c797cace7d0a8f787a", {
                value: c,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (c) {
            console.error('Error executing AG js rule with uniqueId "cc60c320cd31f7c797cace7d0a8f787a" due to: ' + c);
        }
    },
    "!function(){if(location.pathname.indexOf(\"/iframe/player\")===-1){Object.defineProperty(Object.prototype, 'kununu_mul', { get: function(){ throw null; }, set: function(){ throw null; }});}}();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["0024181b43199be4e6f6d4dc8cace28f"] === e) return;
            -1 === location.pathname.indexOf("/iframe/player") && Object.defineProperty(Object.prototype, "kununu_mul", {
                get: function() {
                    throw null;
                },
                set: function() {
                    throw null;
                }
            });
            Object.defineProperty(Window.prototype.toString, "0024181b43199be4e6f6d4dc8cace28f", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "0024181b43199be4e6f6d4dc8cace28f" due to: ' + e);
        }
    },
    '!function(){const r={apply:(r,o,e)=>(e[0]?.includes?.("{}")&&(e[0]="<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?>\\n<vmap:VMAP version=\\"1.0\\" xmlns:vmap=\\"http://www.iab.net/videosuite/vmap\\"><vmap:AdBreak timeOffset=\\"start\\" breakType=\\"linear\\" breakId=\\"4f95e542-9da8-480e-8c2a-7ade1ffdcc3d\\"><vmap:AdSource allowMultipleAds=\\"true\\" followRedirects=\\"true\\"><vmap:VASTAdData></vmap:VASTAdData></vmap:AdSource></vmap:AdBreak></vmap:VMAP>"),Reflect.apply(r,o,e))};window.DOMParser.prototype.parseFromString=new Proxy(window.DOMParser.prototype.parseFromString,r)}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["631aed795dd7ba8bffc8ac13694e2216"] === e) return;
            !function() {
                const e = {
                    apply: (e, a, r)=>{
                        var _r__includes, _r_;
                        return ((_r_ = r[0]) === null || _r_ === void 0 ? void 0 : (_r__includes = _r_.includes) === null || _r__includes === void 0 ? void 0 : _r__includes.call(_r_, "{}")) && (r[0] = '<?xml version="1.0" encoding="UTF-8"?>\n<vmap:VMAP version="1.0" xmlns:vmap="http://www.iab.net/videosuite/vmap"><vmap:AdBreak timeOffset="start" breakType="linear" breakId="4f95e542-9da8-480e-8c2a-7ade1ffdcc3d"><vmap:AdSource allowMultipleAds="true" followRedirects="true"><vmap:VASTAdData></vmap:VASTAdData></vmap:AdSource></vmap:AdBreak></vmap:VMAP>'), Reflect.apply(e, a, r);
                    }
                };
                window.DOMParser.prototype.parseFromString = new Proxy(window.DOMParser.prototype.parseFromString, e);
            }();
            Object.defineProperty(Window.prototype.toString, "631aed795dd7ba8bffc8ac13694e2216", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "631aed795dd7ba8bffc8ac13694e2216" due to: ' + e);
        }
    },
    '(()=>{window.googletag={apiReady:!0,getVersion:function(){return"202307200101"}};})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["4f23857baa34d679fafb613b89f85cda"] === e) return;
            window.googletag = {
                apiReady: !0,
                getVersion: function() {
                    return "202307200101";
                }
            };
            Object.defineProperty(Window.prototype.toString, "4f23857baa34d679fafb613b89f85cda", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "4f23857baa34d679fafb613b89f85cda" due to: ' + e);
        }
    },
    '!function(){const e={apply:(e,t,n)=>{if("prg"!==t?.id)return Reflect.apply(e,t,n);const o=Reflect.apply(e,t,n);return Object.defineProperty(o,"top",{value:500}),o}};window.Element.prototype.getBoundingClientRect=new Proxy(window.Element.prototype.getBoundingClientRect,e)}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["8de36e4bf3b484248c14b692ab7d0b97"] === e) return;
            !function() {
                const e = {
                    apply: (e, t, n1)=>{
                        if ("prg" !== (t === null || t === void 0 ? void 0 : t.id)) return Reflect.apply(e, t, n1);
                        const o = Reflect.apply(e, t, n1);
                        return Object.defineProperty(o, "top", {
                            value: 500
                        }), o;
                    }
                };
                window.Element.prototype.getBoundingClientRect = new Proxy(window.Element.prototype.getBoundingClientRect, e);
            }();
            Object.defineProperty(Window.prototype.toString, "8de36e4bf3b484248c14b692ab7d0b97", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "8de36e4bf3b484248c14b692ab7d0b97" due to: ' + e);
        }
    },
    "window.atob = function() { };": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.bd6f7fef7248ea934c306654651e8882 === e) return;
            window.atob = function() {};
            Object.defineProperty(Window.prototype.toString, "bd6f7fef7248ea934c306654651e8882", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "bd6f7fef7248ea934c306654651e8882" due to: ' + e);
        }
    },
    "window.canABP = window.canRunAds = window.canCheckAds = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["7fa951f734c0ba707fc4893dc83b1a38"] === e) return;
            window.canABP = window.canRunAds = window.canCheckAds = !0;
            Object.defineProperty(Window.prototype.toString, "7fa951f734c0ba707fc4893dc83b1a38", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "7fa951f734c0ba707fc4893dc83b1a38" due to: ' + e);
        }
    },
    "window.canRun = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.cb7e5a7f0c3e95af411eb95c880d423d === e) return;
            window.canRun = !0;
            Object.defineProperty(Window.prototype.toString, "cb7e5a7f0c3e95af411eb95c880d423d", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "cb7e5a7f0c3e95af411eb95c880d423d" due to: ' + e);
        }
    },
    'window.googleToken = "no";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["14f3ab7c380717fd60634b54e8ee9403"] === e) return;
            window.googleToken = "no";
            Object.defineProperty(Window.prototype.toString, "14f3ab7c380717fd60634b54e8ee9403", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "14f3ab7c380717fd60634b54e8ee9403" due to: ' + e);
        }
    },
    "window.my_random_number = 1;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.a9f261eb34a000b190c43d2cb371ce6c === e) return;
            window.my_random_number = 1;
            Object.defineProperty(Window.prototype.toString, "a9f261eb34a000b190c43d2cb371ce6c", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "a9f261eb34a000b190c43d2cb371ce6c" due to: ' + e);
        }
    },
    "(function(){var b=window.setTimeout;window.setTimeout=function(a,c){if(!/\\[_0x/.test(a.toString()))return b(a,c)};})();": ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString.ca00780d8510a4940d20b67629664146 === t) return;
            !function() {
                var t = window.setTimeout;
                window.setTimeout = function(e, o) {
                    if (!/\[_0x/.test(e.toString())) return t(e, o);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "ca00780d8510a4940d20b67629664146", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "ca00780d8510a4940d20b67629664146" due to: ' + t);
        }
    },
    "(()=>{window.com_adswizz_synchro_decorateUrl=(a)=>a;})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.e98a98ef2962b13e300d81c08a1652e0 === e) return;
            window.com_adswizz_synchro_decorateUrl = (e)=>e;
            Object.defineProperty(Window.prototype.toString, "e98a98ef2962b13e300d81c08a1652e0", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "e98a98ef2962b13e300d81c08a1652e0" due to: ' + e);
        }
    },
    '(()=>{document.addEventListener(\'DOMContentLoaded\',()=>{var a=document.querySelector("body");document.location.hostname.includes("skmedix.pl")&&a&&a.insertAdjacentHTML("beforeend",\'<ins class="adsbygoogle" data-ad-status="filled"><div id="aswift_" style="position: absolute !important; left: -3000px !important;"><iframe id="aswift_"></iframe></div></ins><iframe src="/aframe"></iframe>\')})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["931980a2c6180f6edbcd6f228a2db536"] === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                var e = document.querySelector("body");
                document.location.hostname.includes("skmedix.pl") && e && e.insertAdjacentHTML("beforeend", '<ins class="adsbygoogle" data-ad-status="filled"><div id="aswift_" style="position: absolute !important; left: -3000px !important;"><iframe id="aswift_"></iframe></div></ins><iframe src="/aframe"></iframe>');
            });
            Object.defineProperty(Window.prototype.toString, "931980a2c6180f6edbcd6f228a2db536", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "931980a2c6180f6edbcd6f228a2db536" due to: ' + e);
        }
    },
    '(()=>{document.addEventListener("DOMContentLoaded",(()=>{   setTimeout(function() { if(typeof show_game_iframe === "function") { show_game_iframe(); } }, 1000); }));})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["66e1a81529963f50c62391d4d9356ef0"] === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                setTimeout(function() {
                    "function" == typeof show_game_iframe && show_game_iframe();
                }, 1e3);
            });
            Object.defineProperty(Window.prototype.toString, "66e1a81529963f50c62391d4d9356ef0", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "66e1a81529963f50c62391d4d9356ef0" due to: ' + e);
        }
    },
    '(()=>{window.sas_idmnet=window.sas_idmnet||{};Object.assign(sas_idmnet,{releaseVideo:function(a){if("object"==typeof videoInit&&"function"==typeof videoInit.start)try{videoInit.start(a,n)}catch(a){}},release:function(){},placementsList:function(){}});const a=function(a,b){if(a&&a.push)for(a.push=b;a.length;)b(a.shift())},b=function(a){try{a()}catch(a){console.error(a)}};"complete"===document.readyState?a(sas_idmnet.cmd,b):window.addEventListener("load",()=>{a(sas_idmnet.cmd,b)})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["35966fc2cd75edd8c085792a4413cc08"] === e) return;
            (()=>{
                window.sas_idmnet = window.sas_idmnet || {};
                Object.assign(sas_idmnet, {
                    releaseVideo: function(e) {
                        if ("object" == typeof videoInit && "function" == typeof videoInit.start) try {
                            videoInit.start(e, n);
                        } catch (e) {}
                    },
                    release: function() {},
                    placementsList: function() {}
                });
                const e = function(e, t) {
                    if (e && e.push) for(e.push = t; e.length;)t(e.shift());
                }, t = function(e) {
                    try {
                        e();
                    } catch (e) {
                        console.error(e);
                    }
                };
                "complete" === document.readyState ? e(sas_idmnet.cmd, t) : window.addEventListener("load", ()=>{
                    e(sas_idmnet.cmd, t);
                });
            })();
            Object.defineProperty(Window.prototype.toString, "35966fc2cd75edd8c085792a4413cc08", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "35966fc2cd75edd8c085792a4413cc08" due to: ' + e);
        }
    },
    "!function(){window.YLHH={bidder:{startAuction:function(){}}};}();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["609bede022cc082da833f6d8f49bff77"] === e) return;
            window.YLHH = {
                bidder: {
                    startAuction: function() {}
                }
            };
            Object.defineProperty(Window.prototype.toString, "609bede022cc082da833f6d8f49bff77", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "609bede022cc082da833f6d8f49bff77" due to: ' + e);
        }
    },
    "(function(){var c=window.setTimeout;window.setTimeout=function(f,g){return g===1e3&&/#kam-ban-player/.test(f.toString())&&(g*=0.01),c.apply(this,arguments)}.bind(window)})();": ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString["4706a9dfd57dc72a9584b54986a27381"] === t) return;
            !function() {
                var t = window.setTimeout;
                window.setTimeout = (function(e, o) {
                    return 1e3 === o && /#kam-ban-player/.test(e.toString()) && (o *= .01), t.apply(this, arguments);
                }).bind(window);
            }();
            Object.defineProperty(Window.prototype.toString, "4706a9dfd57dc72a9584b54986a27381", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "4706a9dfd57dc72a9584b54986a27381" due to: ' + t);
        }
    },
    '(()=>{const t=Object.getOwnPropertyDescriptor,e={apply:(e,n,r)=>{const o=r[0];if(o?.toString?.()?.includes("EventTarget")){const e=t(o,"addEventListener");e?.set?.toString&&(e.set.toString=function(){}),e?.get?.toString&&(e.get.toString=function(){})}return Reflect.apply(e,n,r)}};window.Object.getOwnPropertyDescriptors=new Proxy(window.Object.getOwnPropertyDescriptors,e)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.f5e04b1e897644b8741f5724e8210233 === e) return;
            (()=>{
                const e = Object.getOwnPropertyDescriptor, t = {
                    apply: (t, r, n1)=>{
                        var _o_toString, _o_toString1;
                        const o = n1[0];
                        if (o === null || o === void 0 ? void 0 : (_o_toString1 = o.toString) === null || _o_toString1 === void 0 ? void 0 : (_o_toString = _o_toString1.call(o)) === null || _o_toString === void 0 ? void 0 : _o_toString.includes("EventTarget")) {
                            var _t_set, _t_get;
                            const t = e(o, "addEventListener");
                            (t === null || t === void 0 ? void 0 : (_t_set = t.set) === null || _t_set === void 0 ? void 0 : _t_set.toString) && (t.set.toString = function() {}), (t === null || t === void 0 ? void 0 : (_t_get = t.get) === null || _t_get === void 0 ? void 0 : _t_get.toString) && (t.get.toString = function() {});
                        }
                        return Reflect.apply(t, r, n1);
                    }
                };
                window.Object.getOwnPropertyDescriptors = new Proxy(window.Object.getOwnPropertyDescriptors, t);
            })();
            Object.defineProperty(Window.prototype.toString, "f5e04b1e897644b8741f5724e8210233", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "f5e04b1e897644b8741f5724e8210233" due to: ' + e);
        }
    },
    '(()=>{Object.defineProperty=new Proxy(Object.defineProperty,{apply:(e,t,n)=>{const r=new Set(["VP","w3","JW"]),o=n[1],c=n[2]?.get;return o&&r.has(o)&&"function"==typeof c&&c.toString().includes("()=>i")&&(n[2].get=function(){return function(){return!1}}),Reflect.apply(e,t,n)}});})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.d2e0c1a15c46cd17c61c4bb3e9ed07ff === e) return;
            Object.defineProperty = new Proxy(Object.defineProperty, {
                apply: (e, t, r)=>{
                    var _r_;
                    const c = new Set([
                        "VP",
                        "w3",
                        "JW"
                    ]), n1 = r[1], o = (_r_ = r[2]) === null || _r_ === void 0 ? void 0 : _r_.get;
                    return n1 && c.has(n1) && "function" == typeof o && o.toString().includes("()=>i") && (r[2].get = function() {
                        return function() {
                            return !1;
                        };
                    }), Reflect.apply(e, t, r);
                }
            });
            Object.defineProperty(Window.prototype.toString, "d2e0c1a15c46cd17c61c4bb3e9ed07ff", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "d2e0c1a15c46cd17c61c4bb3e9ed07ff" due to: ' + e);
        }
    },
    "window.showAds = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["8174026a0a9d6a02df2f05c27e91b2e6"] === e) return;
            window.showAds = !0;
            Object.defineProperty(Window.prototype.toString, "8174026a0a9d6a02df2f05c27e91b2e6", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "8174026a0a9d6a02df2f05c27e91b2e6" due to: ' + e);
        }
    },
    "window.uabpInject = function() {};": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["2809f16b065b7f9160467af78eee1331"] === e) return;
            window.uabpInject = function() {};
            Object.defineProperty(Window.prototype.toString, "2809f16b065b7f9160467af78eee1331", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "2809f16b065b7f9160467af78eee1331" due to: ' + e);
        }
    },
    "(function(){var b=window.setTimeout;window.setTimeout=function(a,c){if(!/checkAds\\(\\);/.test(a.toString()))return b(a,c)};})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["140cb9c461f230aead2587075c4c3389"] === e) return;
            !function() {
                var e = window.setTimeout;
                window.setTimeout = function(t, o) {
                    if (!/checkAds\(\);/.test(t.toString())) return e(t, o);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "140cb9c461f230aead2587075c4c3389", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "140cb9c461f230aead2587075c4c3389" due to: ' + e);
        }
    },
    "window.adblock = true;": ()=>{
        try {
            const a = "done";
            if (Window.prototype.toString.a512aca8faf6bfd74f571200978abea9 === a) return;
            window.adblock = !0;
            Object.defineProperty(Window.prototype.toString, "a512aca8faf6bfd74f571200978abea9", {
                value: a,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (a) {
            console.error('Error executing AG js rule with uniqueId "a512aca8faf6bfd74f571200978abea9" due to: ' + a);
        }
    },
    "window.ads_unblocked = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["786bc16fd657931f3a0d027130de4773"] === e) return;
            window.ads_unblocked = !0;
            Object.defineProperty(Window.prototype.toString, "786bc16fd657931f3a0d027130de4773", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "786bc16fd657931f3a0d027130de4773" due to: ' + e);
        }
    },
    '!function(){const r={apply:(r,o,e)=>(e[0]?.includes?.("</VAST>")&&(e[0]=""),Reflect.apply(r,o,e))};window.DOMParser.prototype.parseFromString=new Proxy(window.DOMParser.prototype.parseFromString,r)}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["877dd0aed94e4d29a83c4c3327d544f8"] === e) return;
            !function() {
                const e = {
                    apply: (e, r, o)=>{
                        var _o__includes, _o_;
                        return ((_o_ = o[0]) === null || _o_ === void 0 ? void 0 : (_o__includes = _o_.includes) === null || _o__includes === void 0 ? void 0 : _o__includes.call(_o_, "</VAST>")) && (o[0] = ""), Reflect.apply(e, r, o);
                    }
                };
                window.DOMParser.prototype.parseFromString = new Proxy(window.DOMParser.prototype.parseFromString, e);
            }();
            Object.defineProperty(Window.prototype.toString, "877dd0aed94e4d29a83c4c3327d544f8", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "877dd0aed94e4d29a83c4c3327d544f8" due to: ' + e);
        }
    },
    "window.adsOk = !0;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["58f079e742093da39c91a591e99389ce"] === e) return;
            window.adsOk = !0;
            Object.defineProperty(Window.prototype.toString, "58f079e742093da39c91a591e99389ce", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "58f079e742093da39c91a591e99389ce" due to: ' + e);
        }
    },
    "window.ads_ok = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["6038ece558032e1fa11a8e02beb32499"] === e) return;
            window.ads_ok = !0;
            Object.defineProperty(Window.prototype.toString, "6038ece558032e1fa11a8e02beb32499", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "6038ece558032e1fa11a8e02beb32499" due to: ' + e);
        }
    },
    '(()=>{const t={construct:(t,n,o)=>{const e=n[0],s=e?.toString(),c=s?.includes("await this.whenGDPRClosed()");return c&&(n[0]=t=>t(!0)),Reflect.construct(t,n,o)}};window.Promise=new Proxy(window.Promise,t)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["2def40885e045b3521a04fe19856fe24"] === e) return;
            (()=>{
                const e = {
                    construct: (e, t, o)=>{
                        const r = t[0], n1 = r === null || r === void 0 ? void 0 : r.toString(), i1 = n1 === null || n1 === void 0 ? void 0 : n1.includes("await this.whenGDPRClosed()");
                        return i1 && (t[0] = (e)=>e(!0)), Reflect.construct(e, t, o);
                    }
                };
                window.Promise = new Proxy(window.Promise, e);
            })();
            Object.defineProperty(Window.prototype.toString, "2def40885e045b3521a04fe19856fe24", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "2def40885e045b3521a04fe19856fe24" due to: ' + e);
        }
    },
    "(function(){var b=window.setTimeout;window.setTimeout=function(a,c){if(!/notDetectedBy/.test(a.toString()))return b(a,c)};})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["2eed1ef0d478b67cb9b988fd355d6582"] === e) return;
            !function() {
                var e = window.setTimeout;
                window.setTimeout = function(t, o) {
                    if (!/notDetectedBy/.test(t.toString())) return e(t, o);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "2eed1ef0d478b67cb9b988fd355d6582", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "2eed1ef0d478b67cb9b988fd355d6582" due to: ' + e);
        }
    },
    "window.adBlockTest = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.ea236b492fa35d17f8aeddec6c38ef4a === e) return;
            window.adBlockTest = !0;
            Object.defineProperty(Window.prototype.toString, "ea236b492fa35d17f8aeddec6c38ef4a", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "ea236b492fa35d17f8aeddec6c38ef4a" due to: ' + e);
        }
    },
    '(function(){var b=XMLHttpRequest.prototype.open,c=/ib\\.adnxs\\.com/i;XMLHttpRequest.prototype.open=function(d,a){if("POST"===d&&c.test(a))this.send=function(){return null},this.setRequestHeader=function(){return null},console.log("AG has blocked request: ",a);else return b.apply(this,arguments)}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["14b2658c5d58ff999b0f841402be6327"] === e) return;
            !function() {
                var e = XMLHttpRequest.prototype.open, t = /ib\.adnxs\.com/i;
                XMLHttpRequest.prototype.open = function(o, n1) {
                    if ("POST" !== o || !t.test(n1)) return e.apply(this, arguments);
                    this.send = function() {
                        return null;
                    }, this.setRequestHeader = function() {
                        return null;
                    }, console.log("AG has blocked request: ", n1);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "14b2658c5d58ff999b0f841402be6327", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "14b2658c5d58ff999b0f841402be6327" due to: ' + e);
        }
    },
    '!function(){if(location.pathname.includes("/source/playerads")){var b=new MutationObserver(function(){var a=document.querySelector(\'script[type="text/javascript"]\');a&&a.textContent.includes(\'"ads": [\')&&(b.disconnect(),a.textContent=a.textContent.replace(/("ads": \\[\\{)[\\s\\S]*?(\\}\\])/,"$1$2"))});b.observe(document,{childList:!0,subtree:!0})}}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.aae0d51166190a469962b4394ad11852 === e) return;
            !function() {
                if (location.pathname.includes("/source/playerads")) {
                    var e = new MutationObserver(function() {
                        var t = document.querySelector('script[type="text/javascript"]');
                        t && t.textContent.includes('"ads": [') && (e.disconnect(), t.textContent = t.textContent.replace(/("ads": \[\{)[\s\S]*?(\}\])/, "$1$2"));
                    });
                    e.observe(document, {
                        childList: !0,
                        subtree: !0
                    });
                }
            }();
            Object.defineProperty(Window.prototype.toString, "aae0d51166190a469962b4394ad11852", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "aae0d51166190a469962b4394ad11852" due to: ' + e);
        }
    },
    "clientSide.player.play(true);": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.a5b3c4cf6ebf6b65e649d4696be29d38 === e) return;
            clientSide.player.play(!0);
            Object.defineProperty(Window.prototype.toString, "a5b3c4cf6ebf6b65e649d4696be29d38", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "a5b3c4cf6ebf6b65e649d4696be29d38" due to: ' + e);
        }
    },
    '(()=>{if(location.href.includes("/embed/?link=")){const i=new URL(location.href).searchParams.get("link");if(i)try{location.assign(i)}catch(i){}}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["70f2ca47c305ca62ef161409642baaae"] === e) return;
            (()=>{
                if (location.href.includes("/embed/?link=")) {
                    const e = new URL(location.href).searchParams.get("link");
                    if (e) try {
                        location.assign(e);
                    } catch (e) {}
                }
            })();
            Object.defineProperty(Window.prototype.toString, "70f2ca47c305ca62ef161409642baaae", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "70f2ca47c305ca62ef161409642baaae" due to: ' + e);
        }
    },
    "(function(){Object.defineProperty(window, 'ExoLoader', { get: function() { return; } }); var c=document.addEventListener;document.addEventListener=function(a,b,d,e){\"getexoloader\"!=a&&-1==b.toString().indexOf('loader')&&c(a,b,d,e)}.bind(document);})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.a8d7f5b4e27b5a94d3b0c3528bdccb9c === e) return;
            !function() {
                Object.defineProperty(window, "ExoLoader", {
                    get: function() {}
                });
                var e = document.addEventListener;
                document.addEventListener = (function(t, n1, o, d) {
                    "getexoloader" != t && -1 == n1.toString().indexOf("loader") && e(t, n1, o, d);
                }).bind(document);
            }();
            Object.defineProperty(Window.prototype.toString, "a8d7f5b4e27b5a94d3b0c3528bdccb9c", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "a8d7f5b4e27b5a94d3b0c3528bdccb9c" due to: ' + e);
        }
    },
    '(()=>{if(window.self!==window.top)try{if("object"==typeof localStorage)return}catch(a){delete window.localStorage,window.localStorage={setItem(){},getItem(){},removeItem(){},clear(){}}}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["6c5874d9ea24235e4a8490028ce09e66"] === e) return;
            (()=>{
                if (window.self !== window.top) try {
                    if ("object" == typeof localStorage) return;
                } catch (e) {
                    delete window.localStorage, window.localStorage = {
                        setItem () {},
                        getItem () {},
                        removeItem () {},
                        clear () {}
                    };
                }
            })();
            Object.defineProperty(Window.prototype.toString, "6c5874d9ea24235e4a8490028ce09e66", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "6c5874d9ea24235e4a8490028ce09e66" due to: ' + e);
        }
    },
    '(()=>{window.Pogo=window.Pogo||{},window.Pogo.cmd=[],window.Pogo.cmd.push=o=>{"function"==typeof o&&o()},window.Pogo.getVideoTag=(o,w)=>{w&&"function"==typeof w&&w()};})();': ()=>{
        try {
            const o = "done";
            if (Window.prototype.toString.f1975fac6cc2feb528947114b7201f11 === o) return;
            window.Pogo = window.Pogo || {}, window.Pogo.cmd = [], window.Pogo.cmd.push = (o)=>{
                "function" == typeof o && o();
            }, window.Pogo.getVideoTag = (o, e)=>{
                e && "function" == typeof e && e();
            };
            Object.defineProperty(Window.prototype.toString, "f1975fac6cc2feb528947114b7201f11", {
                value: o,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (o) {
            console.error('Error executing AG js rule with uniqueId "f1975fac6cc2feb528947114b7201f11" due to: ' + o);
        }
    },
    '(()=>{const e=document.documentElement;new MutationObserver((()=>{const e=document.querySelector(".skeleton-video-cover-noanimate > .relative > a[href] + button");e&&e.click()})).observe(e,{attributes:!0,childList:!0,subtree:!0})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.ede6f5f26db9cc9b12941b760f3f2911 === e) return;
            (()=>{
                const e = document.documentElement;
                new MutationObserver(()=>{
                    const e = document.querySelector(".skeleton-video-cover-noanimate > .relative > a[href] + button");
                    e && e.click();
                }).observe(e, {
                    attributes: !0,
                    childList: !0,
                    subtree: !0
                });
            })();
            Object.defineProperty(Window.prototype.toString, "ede6f5f26db9cc9b12941b760f3f2911", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "ede6f5f26db9cc9b12941b760f3f2911" due to: ' + e);
        }
    },
    "(()=>{const n=[];n.push=n=>{try{n()}catch(n){console.error(n)}},window.adsNinja=window.adsNinja||{queue:n}})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["4893d02be5a2a7c0f59287a47260c7b0"] === e) return;
            (()=>{
                const e = [];
                e.push = (e)=>{
                    try {
                        e();
                    } catch (e) {
                        console.error(e);
                    }
                }, window.adsNinja = window.adsNinja || {
                    queue: e
                };
            })();
            Object.defineProperty(Window.prototype.toString, "4893d02be5a2a7c0f59287a47260c7b0", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "4893d02be5a2a7c0f59287a47260c7b0" due to: ' + e);
        }
    },
    '(()=>{window.Bolt={on:(o,n,i)=>{"precontent_ad_video"===o&&"AD_COMPLETE"===n&&"function"==typeof i&&i()},BOLT_AD_COMPLETE:"AD_COMPLETE",BOLT_AD_ERROR:"AD_ERROR"},window.ramp=window.ramp||{},window.ramp.addUnits=()=>Promise.resolve(),window.ramp.displayUnits=()=>{setTimeout((()=>{"function"==typeof window.ramp.onPlayerReady&&window.ramp.onPlayerReady()}),1)};})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["13196ca8ba80be48cb3a530394beced8"] === e) return;
            window.Bolt = {
                on: (e, o, n1)=>{
                    "precontent_ad_video" === e && "AD_COMPLETE" === o && "function" == typeof n1 && n1();
                },
                BOLT_AD_COMPLETE: "AD_COMPLETE",
                BOLT_AD_ERROR: "AD_ERROR"
            }, window.ramp = window.ramp || {}, window.ramp.addUnits = ()=>Promise.resolve(), window.ramp.displayUnits = ()=>{
                setTimeout(()=>{
                    "function" == typeof window.ramp.onPlayerReady && window.ramp.onPlayerReady();
                }, 1);
            };
            Object.defineProperty(Window.prototype.toString, "13196ca8ba80be48cb3a530394beced8", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "13196ca8ba80be48cb3a530394beced8" due to: ' + e);
        }
    },
    '(()=>{const e={apply:(e,t,o)=>(o[0]=!0,Reflect.apply(e,t,o))};let t,o=!1;Object.defineProperty(window,"ig",{get:function(){return"function"!=typeof t?.RetentionRewardedVideo?.prototype?.rewardedVideoResult||o||(t.RetentionRewardedVideo.prototype.rewardedVideoResult=new Proxy(t.RetentionRewardedVideo.prototype.rewardedVideoResult,e),o=!0),t},set:function(e){t=e}})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["49064caba0f35708edea647b43d9260f"] === e) return;
            (()=>{
                const e = {
                    apply: (e, t, o)=>(o[0] = !0, Reflect.apply(e, t, o))
                };
                let t, o = !1;
                Object.defineProperty(window, "ig", {
                    get: function() {
                        var _t_RetentionRewardedVideo_prototype, _t_RetentionRewardedVideo;
                        return "function" != typeof (t === null || t === void 0 ? void 0 : (_t_RetentionRewardedVideo = t.RetentionRewardedVideo) === null || _t_RetentionRewardedVideo === void 0 ? void 0 : (_t_RetentionRewardedVideo_prototype = _t_RetentionRewardedVideo.prototype) === null || _t_RetentionRewardedVideo_prototype === void 0 ? void 0 : _t_RetentionRewardedVideo_prototype.rewardedVideoResult) || o || (t.RetentionRewardedVideo.prototype.rewardedVideoResult = new Proxy(t.RetentionRewardedVideo.prototype.rewardedVideoResult, e), o = !0), t;
                    },
                    set: function(e) {
                        t = e;
                    }
                });
            })();
            Object.defineProperty(Window.prototype.toString, "49064caba0f35708edea647b43d9260f", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "49064caba0f35708edea647b43d9260f" due to: ' + e);
        }
    },
    '(()=>{let e,n=!1;const o=function(){};Object.defineProperty(window,"videojs",{get:function(){return e},set:function(t){e=t,!n&&e&&"function"==typeof e.registerPlugin&&(n=!0,e.registerPlugin("skipIma3Unskippable",o))}}),window.SlotTypeEnum={},window.ANAWeb=function(){},window.ANAWeb.prototype.createVideoSlot=function(){return Promise.resolve()},window.ANAWeb.prototype.createSlot=function(){},window.ANAWeb.VideoPlayerType={},window.ANAWeb.VideoPlacementType={InStream:1},window.ANAWeb.AdPosition={AboveTheFold:1},window.ANAWeb.PlaybackMethod={ClickSoundOn:1},window.addEventListener("load",(function(){document.dispatchEvent(new CustomEvent("ANAReady"))}))})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["3b3aa026a1d7fa6e2ba077f743a7d54d"] === e) return;
            (()=>{
                let e, o = !1;
                const n1 = function() {};
                Object.defineProperty(window, "videojs", {
                    get: function() {
                        return e;
                    },
                    set: function(t) {
                        e = t, !o && e && "function" == typeof e.registerPlugin && (o = !0, e.registerPlugin("skipIma3Unskippable", n1));
                    }
                }), window.SlotTypeEnum = {}, window.ANAWeb = function() {}, window.ANAWeb.prototype.createVideoSlot = function() {
                    return Promise.resolve();
                }, window.ANAWeb.prototype.createSlot = function() {}, window.ANAWeb.VideoPlayerType = {}, window.ANAWeb.VideoPlacementType = {
                    InStream: 1
                }, window.ANAWeb.AdPosition = {
                    AboveTheFold: 1
                }, window.ANAWeb.PlaybackMethod = {
                    ClickSoundOn: 1
                }, window.addEventListener("load", function() {
                    document.dispatchEvent(new CustomEvent("ANAReady"));
                });
            })();
            Object.defineProperty(Window.prototype.toString, "3b3aa026a1d7fa6e2ba077f743a7d54d", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "3b3aa026a1d7fa6e2ba077f743a7d54d" due to: ' + e);
        }
    },
    '(()=>{const a=function(){};window.apstag={fetchBids(c,a){"function"==typeof a&&a([])},init:a,setDisplayBids:a,targetingKeys:a}})();': ()=>{
        try {
            const c = "done";
            if (Window.prototype.toString["11a07f3c1f878acc052df77d287cc2cb"] === c) return;
            (()=>{
                const c = function() {};
                window.apstag = {
                    fetchBids (c, t) {
                        "function" == typeof t && t([]);
                    },
                    init: c,
                    setDisplayBids: c,
                    targetingKeys: c
                };
            })();
            Object.defineProperty(Window.prototype.toString, "11a07f3c1f878acc052df77d287cc2cb", {
                value: c,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (c) {
            console.error('Error executing AG js rule with uniqueId "11a07f3c1f878acc052df77d287cc2cb" due to: ' + c);
        }
    },
    '(()=>{window.JSON.parse=new Proxy(JSON.parse,{apply(r,e,t){const s=Reflect.apply(r,e,t),l=s?.results;try{if(l&&Array.isArray(l))s?.results&&(s.results=s.results.filter((r=>{if(!Object.prototype.hasOwnProperty.call(r,"adTitle"))return r})));else for(let r in s){const e=s[r]?.results;e&&Array.isArray(e)&&(s[r].results=s[r].results.filter((r=>{if(!Object.prototype.hasOwnProperty.call(r,"adTitle"))return r})))}}catch(r){}return s}});})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.b91767671ee5e3e933cdcfdac4efc25b === e) return;
            window.JSON.parse = new Proxy(JSON.parse, {
                apply (e, r, t) {
                    const c = Reflect.apply(e, r, t), o = c === null || c === void 0 ? void 0 : c.results;
                    try {
                        if (o && Array.isArray(o)) (c === null || c === void 0 ? void 0 : c.results) && (c.results = c.results.filter((e)=>{
                            if (!Object.prototype.hasOwnProperty.call(e, "adTitle")) return e;
                        }));
                        else for(let e in c){
                            var _c_e;
                            const r = (_c_e = c[e]) === null || _c_e === void 0 ? void 0 : _c_e.results;
                            r && Array.isArray(r) && (c[e].results = c[e].results.filter((e)=>{
                                if (!Object.prototype.hasOwnProperty.call(e, "adTitle")) return e;
                            }));
                        }
                    } catch (e) {}
                    return c;
                }
            });
            Object.defineProperty(Window.prototype.toString, "b91767671ee5e3e933cdcfdac4efc25b", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "b91767671ee5e3e933cdcfdac4efc25b" due to: ' + e);
        }
    },
    '(()=>{let e,n=!1;const t=function(){};Object.defineProperty(window,"videojs",{get:function(){return e},set:function(i){e=i,!n&&e&&"function"==typeof e.registerPlugin&&(n=!0,e.registerPlugin("ads",t))}})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.c14cd51b0bc81e9fb5cd82344ac7da2e === e) return;
            (()=>{
                let e, t = !1;
                const c = function() {};
                Object.defineProperty(window, "videojs", {
                    get: function() {
                        return e;
                    },
                    set: function(n1) {
                        e = n1, !t && e && "function" == typeof e.registerPlugin && (t = !0, e.registerPlugin("ads", c));
                    }
                });
            })();
            Object.defineProperty(Window.prototype.toString, "c14cd51b0bc81e9fb5cd82344ac7da2e", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "c14cd51b0bc81e9fb5cd82344ac7da2e" due to: ' + e);
        }
    },
    '(()=>{const n=function(n){if("function"==typeof n)try{n.call()}catch(n){}},i={addAdUnits:function(){},adServers:{dfp:{buildVideoUrl:function(){return""}}},adUnits:[],aliasBidder:function(){},cmd:[],enableAnalytics:function(){},getHighestCpmBids:function(){return[]},libLoaded:!0,que:[],requestBids:function(n){if(n instanceof Object&&n.bidsBackHandler)try{n.bidsBackHandler.call()}catch(n){}},removeAdUnit:function(){},setBidderConfig:function(){},setConfig:function(){},setTargetingForGPTAsync:function(){},rp:{requestVideoBids:function(n){if("function"==typeof n?.callback)try{n.callback.call()}catch(n){}}}};i.cmd.push=n,i.que.push=n,window.pbjs=i})();': ()=>{
        try {
            const n1 = "done";
            if (Window.prototype.toString.a12991f34fbcdc0cb606380a258fde90 === n1) return;
            (()=>{
                const n1 = function(n1) {
                    if ("function" == typeof n1) try {
                        n1.call();
                    } catch (n1) {}
                }, t = {
                    addAdUnits: function() {},
                    adServers: {
                        dfp: {
                            buildVideoUrl: function() {
                                return "";
                            }
                        }
                    },
                    adUnits: [],
                    aliasBidder: function() {},
                    cmd: [],
                    enableAnalytics: function() {},
                    getHighestCpmBids: function() {
                        return [];
                    },
                    libLoaded: !0,
                    que: [],
                    requestBids: function(n1) {
                        if (n1 instanceof Object && n1.bidsBackHandler) try {
                            n1.bidsBackHandler.call();
                        } catch (n1) {}
                    },
                    removeAdUnit: function() {},
                    setBidderConfig: function() {},
                    setConfig: function() {},
                    setTargetingForGPTAsync: function() {},
                    rp: {
                        requestVideoBids: function(n1) {
                            if ("function" == typeof (n1 === null || n1 === void 0 ? void 0 : n1.callback)) try {
                                n1.callback.call();
                            } catch (n1) {}
                        }
                    }
                };
                t.cmd.push = n1, t.que.push = n1, window.pbjs = t;
            })();
            Object.defineProperty(Window.prototype.toString, "a12991f34fbcdc0cb606380a258fde90", {
                value: n1,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (n1) {
            console.error('Error executing AG js rule with uniqueId "a12991f34fbcdc0cb606380a258fde90" due to: ' + n1);
        }
    },
    '(()=>{const c=function(){[...arguments].forEach((c=>{if("function"==typeof c)try{c(!0)}catch(c){console.debug(c)}}))},n=[];n.push=c,window.PQ={cmd:n,getTargeting:c}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["52a467e415654146fde7899c49035b7f"] === e) return;
            (()=>{
                const e = function() {
                    [
                        ...arguments
                    ].forEach((e)=>{
                        if ("function" == typeof e) try {
                            e(!0);
                        } catch (e) {
                            console.debug(e);
                        }
                    });
                }, t = [];
                t.push = e, window.PQ = {
                    cmd: t,
                    getTargeting: e
                };
            })();
            Object.defineProperty(Window.prototype.toString, "52a467e415654146fde7899c49035b7f", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "52a467e415654146fde7899c49035b7f" due to: ' + e);
        }
    },
    '(()=>{const n=function(n){if("function"==typeof n)try{n.call()}catch(n){}},i={addAdUnits:function(){},adServers:{dfp:{buildVideoUrl:function(){return""}}},adUnits:[],aliasBidder:function(){},cmd:[],enableAnalytics:function(){},getHighestCpmBids:function(){return[]},libLoaded:!0,que:[],requestBids:function(n){if(n instanceof Object&&n.bidsBackHandler)try{n.bidsBackHandler.call()}catch(n){}},removeAdUnit:function(){},setBidderConfig:function(){},setConfig:function(){},setTargetingForGPTAsync:function(){}};i.cmd.push=n,i.que.push=n,window.pbjs=i})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["5eccf85ec7e71ba4deefe939741fb145"] === e) return;
            (()=>{
                const e = function(e) {
                    if ("function" == typeof e) try {
                        e.call();
                    } catch (e) {}
                }, n1 = {
                    addAdUnits: function() {},
                    adServers: {
                        dfp: {
                            buildVideoUrl: function() {
                                return "";
                            }
                        }
                    },
                    adUnits: [],
                    aliasBidder: function() {},
                    cmd: [],
                    enableAnalytics: function() {},
                    getHighestCpmBids: function() {
                        return [];
                    },
                    libLoaded: !0,
                    que: [],
                    requestBids: function(e) {
                        if (e instanceof Object && e.bidsBackHandler) try {
                            e.bidsBackHandler.call();
                        } catch (e) {}
                    },
                    removeAdUnit: function() {},
                    setBidderConfig: function() {},
                    setConfig: function() {},
                    setTargetingForGPTAsync: function() {}
                };
                n1.cmd.push = e, n1.que.push = e, window.pbjs = n1;
            })();
            Object.defineProperty(Window.prototype.toString, "5eccf85ec7e71ba4deefe939741fb145", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "5eccf85ec7e71ba4deefe939741fb145" due to: ' + e);
        }
    },
    '(()=>{const t=[];t.push=function(t){try{t()}catch(t){}};window.headertag={cmd:t,buildGamMvt:function(t,c){const n={[c]:"https://securepubads.g.doubleclick.net/gampad/ads"};return n||{}},retrieveVideoDemand:function(t,c,n){const e=t[0]?.htSlotName;if("function"==typeof c)try{c(e)}catch(t){}}}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["4a7e38f499848781627483fb1bb70105"] === e) return;
            (()=>{
                const e = [];
                e.push = function(e) {
                    try {
                        e();
                    } catch (e) {}
                };
                window.headertag = {
                    cmd: e,
                    buildGamMvt: function(e, t) {
                        return {
                            [t]: "https://securepubads.g.doubleclick.net/gampad/ads"
                        } || {};
                    },
                    retrieveVideoDemand: function(e, t, o) {
                        var _e_;
                        const n1 = (_e_ = e[0]) === null || _e_ === void 0 ? void 0 : _e_.htSlotName;
                        if ("function" == typeof t) try {
                            t(n1);
                        } catch (e) {}
                    }
                };
            })();
            Object.defineProperty(Window.prototype.toString, "4a7e38f499848781627483fb1bb70105", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "4a7e38f499848781627483fb1bb70105" due to: ' + e);
        }
    },
    '(()=>{const e="3.453.0",t=function(){},s={},n=function(e){const t=document.createElement("div");t.style.setProperty("display","none","important"),t.style.setProperty("visibility","collapse","important"),e&&e.appendChild(t)};n.prototype.destroy=t,n.prototype.initialize=t;const i=function(){};i.CompanionBackfillMode={ALWAYS:"always",ON_MASTER_AD:"on_master_ad"},i.VpaidMode={DISABLED:0,ENABLED:1,INSECURE:2},i.prototype={c:!0,f:{},i:!1,l:"",p:"",r:0,t:"",v:"",getCompanionBackfill:t,getDisableCustomPlaybackForIOS10Plus(){return this.i},getDisabledFlashAds:()=>!0,getFeatureFlags(){return this.f},getLocale(){return this.l},getNumRedirects(){return this.r},getPlayerType(){return this.t},getPlayerVersion(){return this.v},getPpid(){return this.p},getVpaidMode(){return this.C},isCookiesEnabled(){return this.c},isVpaidAdapter(){return this.M},setCompanionBackfill:t,setAutoPlayAdBreaks(e){this.K=e},setCookiesEnabled(e){this.c=!!e},setDisableCustomPlaybackForIOS10Plus(e){this.i=!!e},setDisableFlashAds:t,setFeatureFlags(e){this.f=!!e},setIsVpaidAdapter(e){this.M=e},setLocale(e){this.l=!!e},setNumRedirects(e){this.r=!!e},setPageCorrelator(e){this.R=e},setPlayerType(e){this.t=!!e},setPlayerVersion(e){this.v=!!e},setPpid(e){this.p=!!e},setVpaidMode(e){this.C=e},setSessionId:t,setStreamCorrelator:t,setVpaidAllowed:t,CompanionBackfillMode:{ALWAYS:"always",ON_MASTER_AD:"on_master_ad"},VpaidMode:{DISABLED:0,ENABLED:1,INSECURE:2}};const r=function(){this.listeners=new Map,this._dispatch=function(e){let t=this.listeners.get(e.type);t=t?t.values():[];for(const s of Array.from(t))try{s(e)}catch(e){console.trace(e)}},this.addEventListener=function(e,t,s,n){Array.isArray(e)||(e=[e]);for(let s=0;s<e.length;s+=1){const i=e[s];this.listeners.has(i)||this.listeners.set(i,new Map),this.listeners.get(i).set(t,t.bind(n||this))}},this.removeEventListener=function(e,t){Array.isArray(e)||(e=[e]);for(let s=0;s<e.length;s+=1){const n=e[s];this.listeners.get(n)?.delete(t)}}},o=new r;o.volume=1,o.collapse=t,o.configureAdsManager=t,o.destroy=t,o.discardAdBreak=t,o.expand=t,o.focus=t,o.getAdSkippableState=()=>!1,o.getCuePoints=()=>[0],o.getCurrentAd=()=>h,o.getCurrentAdCuePoints=()=>[],o.getRemainingTime=()=>0,o.getVolume=function(){return this.volume},o.init=t,o.isCustomClickTrackingUsed=()=>!1,o.isCustomPlaybackUsed=()=>!1,o.pause=t,o.requestNextAdBreak=t,o.resize=t,o.resume=t,o.setVolume=function(e){this.volume=e},o.skip=t,o.start=function(){for(const e of [T.Type.LOADED,T.Type.STARTED,T.Type.CONTENT_RESUME_REQUESTED,T.Type.AD_BUFFERING,T.Type.FIRST_QUARTILE,T.Type.MIDPOINT,T.Type.THIRD_QUARTILE,T.Type.COMPLETE,T.Type.ALL_ADS_COMPLETED])try{this._dispatch(new s.AdEvent(e))}catch(e){console.trace(e)}},o.stop=t,o.updateAdsRenderingSettings=t;const a=Object.create(o),d=function(e,t,s){this.type=e,this.adsRequest=t,this.userRequestContext=s};d.prototype={getAdsManager:()=>a,getUserRequestContext(){return this.userRequestContext?this.userRequestContext:{}}},d.Type={ADS_MANAGER_LOADED:"adsManagerLoaded"};const E=r;E.prototype.settings=new i,E.prototype.contentComplete=t,E.prototype.destroy=t,E.prototype.getSettings=function(){return this.settings},E.prototype.getVersion=()=>e,E.prototype.requestAds=function(e,t){requestAnimationFrame((()=>{const{ADS_MANAGER_LOADED:n}=d.Type,i=new s.AdsManagerLoadedEvent(n,e,t);this._dispatch(i)}));const n=new s.AdError("adPlayError",1205,1205,"The browser prevented playback initiated without user interaction.",e,t);requestAnimationFrame((()=>{this._dispatch(new s.AdErrorEvent(n))}))};const A=t,u=function(){};u.prototype={setAdWillAutoPlay:t,setAdWillPlayMuted:t,setContinuousPlayback:t};const l=function(){};l.prototype={getAdPosition:()=>1,getIsBumper:()=>!1,getMaxDuration:()=>-1,getPodIndex:()=>1,getTimeOffset:()=>0,getTotalAds:()=>1};const g=function(){};g.prototype.getAdIdRegistry=function(){return""},g.prototype.getAdIsValue=function(){return""};const p=function(){};p.prototype={pi:new l,getAdId:()=>"",getAdPodInfo(){return this.pi},getAdSystem:()=>"",getAdvertiserName:()=>"",getApiFramework:()=>null,getCompanionAds:()=>[],getContentType:()=>"",getCreativeAdId:()=>"",getDealId:()=>"",getDescription:()=>"",getDuration:()=>8.5,getHeight:()=>0,getMediaUrl:()=>null,getMinSuggestedDuration:()=>-2,getSkipTimeOffset:()=>-1,getSurveyUrl:()=>null,getTitle:()=>"",getTraffickingParametersString:()=>"",getUiElements:()=>[""],getUniversalAdIdRegistry:()=>"unknown",getUniversalAdIds:()=>[new g],getUniversalAdIdValue:()=>"unknown",getVastMediaBitrate:()=>0,getVastMediaHeight:()=>0,getVastMediaWidth:()=>0,getWidth:()=>0,getWrapperAdIds:()=>[""],getWrapperAdSystems:()=>[""],getWrapperCreativeIds:()=>[""],isLinear:()=>!0,isSkippable:()=>!0};const c=function(){};c.prototype={getAdSlotId:()=>"",getContent:()=>"",getContentType:()=>"",getHeight:()=>1,getWidth:()=>1};const C=function(e,t,s,n,i,r){this.errorCode=t,this.message=n,this.type=e,this.adsRequest=i,this.userRequestContext=r,this.getErrorCode=function(){return this.errorCode},this.getInnerError=function(){return null},this.getMessage=function(){return this.message},this.getType=function(){return this.type},this.getVastErrorCode=function(){return this.vastErrorCode},this.toString=function(){return`AdError ${this.errorCode}: ${this.message}`}};C.ErrorCode={},C.Type={};const h=(()=>{try{for(const e of Object.values(window.vidible._getContexts()))if(e.getPlayer()?.div?.innerHTML.includes("www.engadget.com"))return!0}catch(e){}return!1})()?void 0:new p,T=function(e){this.type=e};T.prototype={getAd:()=>h,getAdData:()=>{}},T.Type={AD_BREAK_READY:"adBreakReady",AD_BUFFERING:"adBuffering",AD_CAN_PLAY:"adCanPlay",AD_METADATA:"adMetadata",AD_PROGRESS:"adProgress",ALL_ADS_COMPLETED:"allAdsCompleted",CLICK:"click",COMPLETE:"complete",CONTENT_PAUSE_REQUESTED:"contentPauseRequested",CONTENT_RESUME_REQUESTED:"contentResumeRequested",DURATION_CHANGE:"durationChange",EXPANDED_CHANGED:"expandedChanged",FIRST_QUARTILE:"firstQuartile",IMPRESSION:"impression",INTERACTION:"interaction",LINEAR_CHANGE:"linearChange",LINEAR_CHANGED:"linearChanged",LOADED:"loaded",LOG:"log",MIDPOINT:"midpoint",PAUSED:"pause",RESUMED:"resume",SKIPPABLE_STATE_CHANGED:"skippableStateChanged",SKIPPED:"skip",STARTED:"start",THIRD_QUARTILE:"thirdQuartile",USER_CLOSE:"userClose",VIDEO_CLICKED:"videoClicked",VIDEO_ICON_CLICKED:"videoIconClicked",VIEWABLE_IMPRESSION:"viewable_impression",VOLUME_CHANGED:"volumeChange",VOLUME_MUTED:"mute"};const y=function(e){this.error=e,this.type="adError",this.getError=function(){return this.error},this.getUserRequestContext=function(){return this.error?.userRequestContext?this.error.userRequestContext:{}}};y.Type={AD_ERROR:"adError"};const I=function(){};I.Type={CUSTOM_CONTENT_LOADED:"deprecated-event"};const R=function(){};R.CreativeType={ALL:"All",FLASH:"Flash",IMAGE:"Image"},R.ResourceType={ALL:"All",HTML:"Html",IFRAME:"IFrame",STATIC:"Static"},R.SizeCriteria={IGNORE:"IgnoreSize",SELECT_EXACT_MATCH:"SelectExactMatch",SELECT_NEAR_MATCH:"SelectNearMatch"};const S=function(){};S.prototype={getCuePoints:()=>[],getAdIdRegistry:()=>"",getAdIdValue:()=>""};const D=t;Object.assign(s,{AdCuePoints:S,AdDisplayContainer:n,AdError:C,AdErrorEvent:y,AdEvent:T,AdPodInfo:l,AdProgressData:D,AdsLoader:E,AdsManager:a,AdsManagerLoadedEvent:d,AdsRenderingSettings:A,AdsRequest:u,CompanionAd:c,CompanionAdSelectionSettings:R,CustomContentLoadedEvent:I,gptProxyInstance:{},ImaSdkSettings:i,OmidAccessMode:{DOMAIN:"domain",FULL:"full",LIMITED:"limited"},OmidVerificationVendor:{1:"OTHER",2:"MOAT",3:"DOUBLEVERIFY",4:"INTEGRAL_AD_SCIENCE",5:"PIXELATE",6:"NIELSEN",7:"COMSCORE",8:"MEETRICS",9:"GOOGLE",OTHER:1,MOAT:2,DOUBLEVERIFY:3,INTEGRAL_AD_SCIENCE:4,PIXELATE:5,NIELSEN:6,COMSCORE:7,MEETRICS:8,GOOGLE:9},settings:new i,UiElements:{AD_ATTRIBUTION:"adAttribution",COUNTDOWN:"countdown"},UniversalAdIdInfo:g,VERSION:e,ViewMode:{FULLSCREEN:"fullscreen",NORMAL:"normal"}}),window.google||(window.google={}),window.google.ima?.dai&&(s.dai=window.google.ima.dai),window.google.ima=s})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.d7a710ada6cca5832af6d92e62726e74 === e) return;
            (()=>{
                var _window_google_ima;
                const e = "3.453.0", t = function() {}, n1 = {}, r = function(e) {
                    const t = document.createElement("div");
                    t.style.setProperty("display", "none", "important"), t.style.setProperty("visibility", "collapse", "important"), e && e.appendChild(t);
                };
                r.prototype.destroy = t, r.prototype.initialize = t;
                const i1 = function() {};
                i1.CompanionBackfillMode = {
                    ALWAYS: "always",
                    ON_MASTER_AD: "on_master_ad"
                }, i1.VpaidMode = {
                    DISABLED: 0,
                    ENABLED: 1,
                    INSECURE: 2
                }, i1.prototype = {
                    c: !0,
                    f: {},
                    i: !1,
                    l: "",
                    p: "",
                    r: 0,
                    t: "",
                    v: "",
                    getCompanionBackfill: t,
                    getDisableCustomPlaybackForIOS10Plus () {
                        return this.i;
                    },
                    getDisabledFlashAds: ()=>!0,
                    getFeatureFlags () {
                        return this.f;
                    },
                    getLocale () {
                        return this.l;
                    },
                    getNumRedirects () {
                        return this.r;
                    },
                    getPlayerType () {
                        return this.t;
                    },
                    getPlayerVersion () {
                        return this.v;
                    },
                    getPpid () {
                        return this.p;
                    },
                    getVpaidMode () {
                        return this.C;
                    },
                    isCookiesEnabled () {
                        return this.c;
                    },
                    isVpaidAdapter () {
                        return this.M;
                    },
                    setCompanionBackfill: t,
                    setAutoPlayAdBreaks (e) {
                        this.K = e;
                    },
                    setCookiesEnabled (e) {
                        this.c = !!e;
                    },
                    setDisableCustomPlaybackForIOS10Plus (e) {
                        this.i = !!e;
                    },
                    setDisableFlashAds: t,
                    setFeatureFlags (e) {
                        this.f = !!e;
                    },
                    setIsVpaidAdapter (e) {
                        this.M = e;
                    },
                    setLocale (e) {
                        this.l = !!e;
                    },
                    setNumRedirects (e) {
                        this.r = !!e;
                    },
                    setPageCorrelator (e) {
                        this.R = e;
                    },
                    setPlayerType (e) {
                        this.t = !!e;
                    },
                    setPlayerVersion (e) {
                        this.v = !!e;
                    },
                    setPpid (e) {
                        this.p = !!e;
                    },
                    setVpaidMode (e) {
                        this.C = e;
                    },
                    setSessionId: t,
                    setStreamCorrelator: t,
                    setVpaidAllowed: t,
                    CompanionBackfillMode: {
                        ALWAYS: "always",
                        ON_MASTER_AD: "on_master_ad"
                    },
                    VpaidMode: {
                        DISABLED: 0,
                        ENABLED: 1,
                        INSECURE: 2
                    }
                };
                const s = function() {
                    this.listeners = new Map, this._dispatch = function(e) {
                        let t = this.listeners.get(e.type);
                        t = t ? t.values() : [];
                        for (const n1 of Array.from(t))try {
                            n1(e);
                        } catch (e) {
                            console.trace(e);
                        }
                    }, this.addEventListener = function(e, t, n1, r) {
                        Array.isArray(e) || (e = [
                            e
                        ]);
                        for(let n1 = 0; n1 < e.length; n1 += 1){
                            const i1 = e[n1];
                            this.listeners.has(i1) || this.listeners.set(i1, new Map), this.listeners.get(i1).set(t, t.bind(r || this));
                        }
                    }, this.removeEventListener = function(e, t) {
                        Array.isArray(e) || (e = [
                            e
                        ]);
                        for(let n1 = 0; n1 < e.length; n1 += 1){
                            var _this_listeners_get;
                            const r = e[n1];
                            (_this_listeners_get = this.listeners.get(r)) === null || _this_listeners_get === void 0 ? void 0 : _this_listeners_get.delete(t);
                        }
                    };
                }, o = new s;
                o.volume = 1, o.collapse = t, o.configureAdsManager = t, o.destroy = t, o.discardAdBreak = t, o.expand = t, o.focus = t, o.getAdSkippableState = ()=>!1, o.getCuePoints = ()=>[
                        0
                    ], o.getCurrentAd = ()=>h, o.getCurrentAdCuePoints = ()=>[], o.getRemainingTime = ()=>0, o.getVolume = function() {
                    return this.volume;
                }, o.init = t, o.isCustomClickTrackingUsed = ()=>!1, o.isCustomPlaybackUsed = ()=>!1, o.pause = t, o.requestNextAdBreak = t, o.resize = t, o.resume = t, o.setVolume = function(e) {
                    this.volume = e;
                }, o.skip = t, o.start = function() {
                    for (const e of [
                        T.Type.LOADED,
                        T.Type.STARTED,
                        T.Type.CONTENT_RESUME_REQUESTED,
                        T.Type.AD_BUFFERING,
                        T.Type.FIRST_QUARTILE,
                        T.Type.MIDPOINT,
                        T.Type.THIRD_QUARTILE,
                        T.Type.COMPLETE,
                        T.Type.ALL_ADS_COMPLETED
                    ])try {
                        this._dispatch(new n1.AdEvent(e));
                    } catch (e) {
                        console.trace(e);
                    }
                }, o.stop = t, o.updateAdsRenderingSettings = t;
                const a = Object.create(o), d = function(e, t, n1) {
                    this.type = e, this.adsRequest = t, this.userRequestContext = n1;
                };
                d.prototype = {
                    getAdsManager: ()=>a,
                    getUserRequestContext () {
                        return this.userRequestContext ? this.userRequestContext : {};
                    }
                }, d.Type = {
                    ADS_MANAGER_LOADED: "adsManagerLoaded"
                };
                const u = s;
                u.prototype.settings = new i1, u.prototype.contentComplete = t, u.prototype.destroy = t, u.prototype.getSettings = function() {
                    return this.settings;
                }, u.prototype.getVersion = ()=>e, u.prototype.requestAds = function(e, t) {
                    requestAnimationFrame(()=>{
                        const { ADS_MANAGER_LOADED: r } = d.Type, i1 = new n1.AdsManagerLoadedEvent(r, e, t);
                        this._dispatch(i1);
                    });
                    const r = new n1.AdError("adPlayError", 1205, 1205, "The browser prevented playback initiated without user interaction.", e, t);
                    requestAnimationFrame(()=>{
                        this._dispatch(new n1.AdErrorEvent(r));
                    });
                };
                const E = t, A = function() {};
                A.prototype = {
                    setAdWillAutoPlay: t,
                    setAdWillPlayMuted: t,
                    setContinuousPlayback: t
                };
                const l = function() {};
                l.prototype = {
                    getAdPosition: ()=>1,
                    getIsBumper: ()=>!1,
                    getMaxDuration: ()=>-1,
                    getPodIndex: ()=>1,
                    getTimeOffset: ()=>0,
                    getTotalAds: ()=>1
                };
                const g = function() {};
                g.prototype.getAdIdRegistry = function() {
                    return "";
                }, g.prototype.getAdIsValue = function() {
                    return "";
                };
                const c = function() {};
                c.prototype = {
                    pi: new l,
                    getAdId: ()=>"",
                    getAdPodInfo () {
                        return this.pi;
                    },
                    getAdSystem: ()=>"",
                    getAdvertiserName: ()=>"",
                    getApiFramework: ()=>null,
                    getCompanionAds: ()=>[],
                    getContentType: ()=>"",
                    getCreativeAdId: ()=>"",
                    getDealId: ()=>"",
                    getDescription: ()=>"",
                    getDuration: ()=>8.5,
                    getHeight: ()=>0,
                    getMediaUrl: ()=>null,
                    getMinSuggestedDuration: ()=>-2,
                    getSkipTimeOffset: ()=>-1,
                    getSurveyUrl: ()=>null,
                    getTitle: ()=>"",
                    getTraffickingParametersString: ()=>"",
                    getUiElements: ()=>[
                            ""
                        ],
                    getUniversalAdIdRegistry: ()=>"unknown",
                    getUniversalAdIds: ()=>[
                            new g
                        ],
                    getUniversalAdIdValue: ()=>"unknown",
                    getVastMediaBitrate: ()=>0,
                    getVastMediaHeight: ()=>0,
                    getVastMediaWidth: ()=>0,
                    getWidth: ()=>0,
                    getWrapperAdIds: ()=>[
                            ""
                        ],
                    getWrapperAdSystems: ()=>[
                            ""
                        ],
                    getWrapperCreativeIds: ()=>[
                            ""
                        ],
                    isLinear: ()=>!0,
                    isSkippable: ()=>!0
                };
                const p = function() {};
                p.prototype = {
                    getAdSlotId: ()=>"",
                    getContent: ()=>"",
                    getContentType: ()=>"",
                    getHeight: ()=>1,
                    getWidth: ()=>1
                };
                const C = function(e, t, n1, r, i1, s) {
                    this.errorCode = t, this.message = r, this.type = e, this.adsRequest = i1, this.userRequestContext = s, this.getErrorCode = function() {
                        return this.errorCode;
                    }, this.getInnerError = function() {
                        return null;
                    }, this.getMessage = function() {
                        return this.message;
                    }, this.getType = function() {
                        return this.type;
                    }, this.getVastErrorCode = function() {
                        return this.vastErrorCode;
                    }, this.toString = function() {
                        return `AdError ${this.errorCode}: ${this.message}`;
                    };
                };
                C.ErrorCode = {}, C.Type = {};
                const h = (()=>{
                    try {
                        var _e_getPlayer_div, _e_getPlayer;
                        for (const e of Object.values(window.vidible._getContexts()))if ((_e_getPlayer = e.getPlayer()) === null || _e_getPlayer === void 0 ? void 0 : (_e_getPlayer_div = _e_getPlayer.div) === null || _e_getPlayer_div === void 0 ? void 0 : _e_getPlayer_div.innerHTML.includes("www.engadget.com")) return !0;
                    } catch (e) {}
                    return !1;
                })() ? void 0 : new c, T = function(e) {
                    this.type = e;
                };
                T.prototype = {
                    getAd: ()=>h,
                    getAdData: ()=>{}
                }, T.Type = {
                    AD_BREAK_READY: "adBreakReady",
                    AD_BUFFERING: "adBuffering",
                    AD_CAN_PLAY: "adCanPlay",
                    AD_METADATA: "adMetadata",
                    AD_PROGRESS: "adProgress",
                    ALL_ADS_COMPLETED: "allAdsCompleted",
                    CLICK: "click",
                    COMPLETE: "complete",
                    CONTENT_PAUSE_REQUESTED: "contentPauseRequested",
                    CONTENT_RESUME_REQUESTED: "contentResumeRequested",
                    DURATION_CHANGE: "durationChange",
                    EXPANDED_CHANGED: "expandedChanged",
                    FIRST_QUARTILE: "firstQuartile",
                    IMPRESSION: "impression",
                    INTERACTION: "interaction",
                    LINEAR_CHANGE: "linearChange",
                    LINEAR_CHANGED: "linearChanged",
                    LOADED: "loaded",
                    LOG: "log",
                    MIDPOINT: "midpoint",
                    PAUSED: "pause",
                    RESUMED: "resume",
                    SKIPPABLE_STATE_CHANGED: "skippableStateChanged",
                    SKIPPED: "skip",
                    STARTED: "start",
                    THIRD_QUARTILE: "thirdQuartile",
                    USER_CLOSE: "userClose",
                    VIDEO_CLICKED: "videoClicked",
                    VIDEO_ICON_CLICKED: "videoIconClicked",
                    VIEWABLE_IMPRESSION: "viewable_impression",
                    VOLUME_CHANGED: "volumeChange",
                    VOLUME_MUTED: "mute"
                };
                const y = function(e) {
                    this.error = e, this.type = "adError", this.getError = function() {
                        return this.error;
                    }, this.getUserRequestContext = function() {
                        var _this_error;
                        return ((_this_error = this.error) === null || _this_error === void 0 ? void 0 : _this_error.userRequestContext) ? this.error.userRequestContext : {};
                    };
                };
                y.Type = {
                    AD_ERROR: "adError"
                };
                const I = function() {};
                I.Type = {
                    CUSTOM_CONTENT_LOADED: "deprecated-event"
                };
                const R = function() {};
                R.CreativeType = {
                    ALL: "All",
                    FLASH: "Flash",
                    IMAGE: "Image"
                }, R.ResourceType = {
                    ALL: "All",
                    HTML: "Html",
                    IFRAME: "IFrame",
                    STATIC: "Static"
                }, R.SizeCriteria = {
                    IGNORE: "IgnoreSize",
                    SELECT_EXACT_MATCH: "SelectExactMatch",
                    SELECT_NEAR_MATCH: "SelectNearMatch"
                };
                const S = function() {};
                S.prototype = {
                    getCuePoints: ()=>[],
                    getAdIdRegistry: ()=>"",
                    getAdIdValue: ()=>""
                };
                const D = t;
                Object.assign(n1, {
                    AdCuePoints: S,
                    AdDisplayContainer: r,
                    AdError: C,
                    AdErrorEvent: y,
                    AdEvent: T,
                    AdPodInfo: l,
                    AdProgressData: D,
                    AdsLoader: u,
                    AdsManager: a,
                    AdsManagerLoadedEvent: d,
                    AdsRenderingSettings: E,
                    AdsRequest: A,
                    CompanionAd: p,
                    CompanionAdSelectionSettings: R,
                    CustomContentLoadedEvent: I,
                    gptProxyInstance: {},
                    ImaSdkSettings: i1,
                    OmidAccessMode: {
                        DOMAIN: "domain",
                        FULL: "full",
                        LIMITED: "limited"
                    },
                    OmidVerificationVendor: {
                        1: "OTHER",
                        2: "MOAT",
                        3: "DOUBLEVERIFY",
                        4: "INTEGRAL_AD_SCIENCE",
                        5: "PIXELATE",
                        6: "NIELSEN",
                        7: "COMSCORE",
                        8: "MEETRICS",
                        9: "GOOGLE",
                        OTHER: 1,
                        MOAT: 2,
                        DOUBLEVERIFY: 3,
                        INTEGRAL_AD_SCIENCE: 4,
                        PIXELATE: 5,
                        NIELSEN: 6,
                        COMSCORE: 7,
                        MEETRICS: 8,
                        GOOGLE: 9
                    },
                    settings: new i1,
                    UiElements: {
                        AD_ATTRIBUTION: "adAttribution",
                        COUNTDOWN: "countdown"
                    },
                    UniversalAdIdInfo: g,
                    VERSION: e,
                    ViewMode: {
                        FULLSCREEN: "fullscreen",
                        NORMAL: "normal"
                    }
                }), window.google || (window.google = {}), ((_window_google_ima = window.google.ima) === null || _window_google_ima === void 0 ? void 0 : _window_google_ima.dai) && (n1.dai = window.google.ima.dai), window.google.ima = n1;
            })();
            Object.defineProperty(Window.prototype.toString, "d7a710ada6cca5832af6d92e62726e74", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "d7a710ada6cca5832af6d92e62726e74" due to: ' + e);
        }
    },
    '(()=>{const t=[];t.push=function(t){"object"==typeof t&&t.events&&Object.values(t.events).forEach((t=>{if("function"==typeof t)try{t()}catch(t){}}))},window.AdBridg={cmd:t}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.f6311be2c1ed023feeb00c3d41dea489 === e) return;
            (()=>{
                const e = [];
                e.push = function(e) {
                    "object" == typeof e && e.events && Object.values(e.events).forEach((e)=>{
                        if ("function" == typeof e) try {
                            e();
                        } catch (e) {}
                    });
                }, window.AdBridg = {
                    cmd: e
                };
            })();
            Object.defineProperty(Window.prototype.toString, "f6311be2c1ed023feeb00c3d41dea489", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "f6311be2c1ed023feeb00c3d41dea489" due to: ' + e);
        }
    },
    '(()=>{let t=window?.__iasPET?.queue;Array.isArray(t)||(t=[]);const s=JSON.stringify({brandSafety:{},slots:{}});function e(t){try{t?.dataHandler?.(s)}catch(t){}}for(t.push=e,window.__iasPET={VERSION:"1.16.18",queue:t,sessionId:"",setTargetingForAppNexus(){},setTargetingForGPT(){},start(){}};t.length;)e(t.shift())})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.baf394a72c20f8e6c3a0adc04c9df104 === e) return;
            (()=>{
                var _window___iasPET, _window;
                let e = (_window = window) === null || _window === void 0 ? void 0 : (_window___iasPET = _window.__iasPET) === null || _window___iasPET === void 0 ? void 0 : _window___iasPET.queue;
                Array.isArray(e) || (e = []);
                const t = JSON.stringify({
                    brandSafety: {},
                    slots: {}
                });
                function r(e) {
                    try {
                        var _e_dataHandler;
                        e === null || e === void 0 ? void 0 : (_e_dataHandler = e.dataHandler) === null || _e_dataHandler === void 0 ? void 0 : _e_dataHandler.call(e, t);
                    } catch (e) {}
                }
                for(e.push = r, window.__iasPET = {
                    VERSION: "1.16.18",
                    queue: e,
                    sessionId: "",
                    setTargetingForAppNexus () {},
                    setTargetingForGPT () {},
                    start () {}
                }; e.length;)r(e.shift());
            })();
            Object.defineProperty(Window.prototype.toString, "baf394a72c20f8e6c3a0adc04c9df104", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "baf394a72c20f8e6c3a0adc04c9df104" due to: ' + e);
        }
    },
    '(()=>{window.XMLHttpRequest.prototype.open=new Proxy(window.XMLHttpRequest.prototype.open,{apply:async(a,b,c)=>{const d=c[1];if("string"!=typeof d||0===d.length)return Reflect.apply(a,b,c);const e=/topaz\\.dai\\.viacomcbs\\.digital\\/ondemand\\/hls\\/.*\\.m3u8/.test(d),f=/dai\\.google\\.com\\/ondemand\\/v.*\\/hls\\/content\\/.*\\/vid\\/.*\\/stream/.test(d);return(e||f)&&b.addEventListener("readystatechange",function(){if(4===b.readyState){const a=b.response;if(Object.defineProperty(b,"response",{writable:!0}),Object.defineProperty(b,"responseText",{writable:!0}),f&&(null!==a&&void 0!==a&&a.ad_breaks&&(a.ad_breaks=[]),null!==a&&void 0!==a&&a.apple_tv&&(a.apple_tv={})),e){const c=a.replaceAll(/#EXTINF:(\\d|\\d\\.\\d+)\\,\\nhttps:\\/\\/redirector\\.googlevideo\\.com\\/videoplayback\\?[\\s\\S]*?&source=dclk_video_ads&[\\s\\S]*?\\n/g,"");b.response=c,b.responseText=c}}}),Reflect.apply(a,b,c)}})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.a8c6f78e34ee76b7ae128e62027dec2f === e) return;
            window.XMLHttpRequest.prototype.open = new Proxy(window.XMLHttpRequest.prototype.open, {
                apply: async (e, t, o)=>{
                    const n1 = o[1];
                    if ("string" != typeof n1 || 0 === n1.length) return Reflect.apply(e, t, o);
                    const r = /topaz\.dai\.viacomcbs\.digital\/ondemand\/hls\/.*\.m3u8/.test(n1), a = /dai\.google\.com\/ondemand\/v.*\/hls\/content\/.*\/vid\/.*\/stream/.test(n1);
                    return (r || a) && t.addEventListener("readystatechange", function() {
                        if (4 === t.readyState) {
                            const e = t.response;
                            if (Object.defineProperty(t, "response", {
                                writable: !0
                            }), Object.defineProperty(t, "responseText", {
                                writable: !0
                            }), a && (null != e && e.ad_breaks && (e.ad_breaks = []), null != e && e.apple_tv && (e.apple_tv = {})), r) {
                                const o = e.replaceAll(/#EXTINF:(\d|\d\.\d+)\,\nhttps:\/\/redirector\.googlevideo\.com\/videoplayback\?[\s\S]*?&source=dclk_video_ads&[\s\S]*?\n/g, "");
                                t.response = o, t.responseText = o;
                            }
                        }
                    }), Reflect.apply(e, t, o);
                }
            });
            Object.defineProperty(Window.prototype.toString, "a8c6f78e34ee76b7ae128e62027dec2f", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "a8c6f78e34ee76b7ae128e62027dec2f" due to: ' + e);
        }
    },
    "(function(){window.twttr={conversion:{trackPid:function(){}}}})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.b207994a134acba69e58503a5393b31a === e) return;
            window.twttr = {
                conversion: {
                    trackPid: function() {}
                }
            };
            Object.defineProperty(Window.prototype.toString, "b207994a134acba69e58503a5393b31a", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "b207994a134acba69e58503a5393b31a" due to: ' + e);
        }
    },
    "(() => { var ReplaceMap = {adBreaks: [], adState: null, currentAdBreak: 'undefined'}; Object.defineProperty = new Proxy(Object.defineProperty, { apply: (target, thisArg, ArgsList) => { var Original = Reflect.apply(target, thisArg, ArgsList); if (ArgsList[1] == 'getAdBreaks' || ArgsList[1] == 'getAdsDisplayStringParams') { return Original[ArgsList[1]] = function() {}; } else if (ArgsList[1] == 'adBreaks' || ArgsList[1] == 'currentAdBreak' || typeof Original['adBreaks'] !== 'undefined') { for (var [key, value] of Object.entries(Original)) { if (typeof ReplaceMap[key] !== 'undefined' && ReplaceMap[key] !== 'undefined') { Original[key] = ReplaceMap[key]; } else if (typeof ReplaceMap[key] !== 'undefined' && ReplaceMap[key] === 'undefined') { Original[key] = undefined; } } return Original; } else { return Original; }}})})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["9072dab3b9fec602e942bbd140d1f7ea"] === e) return;
            (()=>{
                var e = {
                    adBreaks: [],
                    adState: null,
                    currentAdBreak: "undefined"
                };
                Object.defineProperty = new Proxy(Object.defineProperty, {
                    apply: (r, t, d)=>{
                        var n1 = Reflect.apply(r, t, d);
                        if ("getAdBreaks" == d[1] || "getAdsDisplayStringParams" == d[1]) return n1[d[1]] = function() {};
                        if ("adBreaks" == d[1] || "currentAdBreak" == d[1] || void 0 !== n1.adBreaks) {
                            for (var [a, o] of Object.entries(n1))void 0 !== e[a] && "undefined" !== e[a] ? n1[a] = e[a] : void 0 !== e[a] && "undefined" === e[a] && (n1[a] = void 0);
                            return n1;
                        }
                        return n1;
                    }
                });
            })();
            Object.defineProperty(Window.prototype.toString, "9072dab3b9fec602e942bbd140d1f7ea", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "9072dab3b9fec602e942bbd140d1f7ea" due to: ' + e);
        }
    },
    '(()=>{const a=window.fetch,b={apply:async(b,c,d)=>{const e=d[0]instanceof Request?d[0].url:d[0];if("string"!=typeof e||0===e.length)return Reflect.apply(b,c,d);if(e.includes("uplynk.com/")&&e.includes(".m3u8")){const b=await a(...d);let c=await b.text();return c=c.replaceAll(/#UPLYNK-SEGMENT: \\S*\\,ad\\s[\\s\\S]+?((#UPLYNK-SEGMENT: \\S+\\,segment)|(#EXT-X-ENDLIST))/g,"$1"),new Response(c)}return Reflect.apply(b,c,d)}};try{window.fetch=new Proxy(window.fetch,b)}catch(a){}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.f2cc35b643de55322eb7ef4e3811aa59 === e) return;
            (()=>{
                const e = window.fetch, t = {
                    apply: async (t, n1, r)=>{
                        const c = r[0] instanceof Request ? r[0].url : r[0];
                        if ("string" != typeof c || 0 === c.length) return Reflect.apply(t, n1, r);
                        if (c.includes("uplynk.com/") && c.includes(".m3u8")) {
                            const t = await e(...r);
                            let n1 = await t.text();
                            return n1 = n1.replaceAll(/#UPLYNK-SEGMENT: \S*\,ad\s[\s\S]+?((#UPLYNK-SEGMENT: \S+\,segment)|(#EXT-X-ENDLIST))/g, "$1"), new Response(n1);
                        }
                        return Reflect.apply(t, n1, r);
                    }
                };
                try {
                    window.fetch = new Proxy(window.fetch, t);
                } catch (e) {}
            })();
            Object.defineProperty(Window.prototype.toString, "f2cc35b643de55322eb7ef4e3811aa59", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "f2cc35b643de55322eb7ef4e3811aa59" due to: ' + e);
        }
    },
    '(()=>{window.XMLHttpRequest.prototype.open=new Proxy(window.XMLHttpRequest.prototype.open,{apply:async(a,b,c)=>{const d=c[1];return"string"!=typeof d||0===d.length?Reflect.apply(a,b,c):(d.match(/pubads\\.g\\.doubleclick.net\\/ondemand\\/hls\\/.*\\.m3u8/)&&b.addEventListener("readystatechange",function(){if(4===b.readyState){const a=b.response;Object.defineProperty(b,"response",{writable:!0}),Object.defineProperty(b,"responseText",{writable:!0});const c=a.replaceAll(/#EXTINF:(\\d|\\d\\.\\d+)\\,\\nhttps:\\/\\/redirector\\.googlevideo\\.com\\/videoplayback\\?[\\s\\S]*?&source=dclk_video_ads&[\\s\\S]*?\\n/g,"");b.response=c,b.responseText=c}}),Reflect.apply(a,b,c))}})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["0664f2a8c7617fced3e7790a26b1c7f8"] === e) return;
            window.XMLHttpRequest.prototype.open = new Proxy(window.XMLHttpRequest.prototype.open, {
                apply: async (e, t, o)=>{
                    const r = o[1];
                    return "string" != typeof r || 0 === r.length || r.match(/pubads\.g\.doubleclick.net\/ondemand\/hls\/.*\.m3u8/) && t.addEventListener("readystatechange", function() {
                        if (4 === t.readyState) {
                            const e = t.response;
                            Object.defineProperty(t, "response", {
                                writable: !0
                            }), Object.defineProperty(t, "responseText", {
                                writable: !0
                            });
                            const o = e.replaceAll(/#EXTINF:(\d|\d\.\d+)\,\nhttps:\/\/redirector\.googlevideo\.com\/videoplayback\?[\s\S]*?&source=dclk_video_ads&[\s\S]*?\n/g, "");
                            t.response = o, t.responseText = o;
                        }
                    }), Reflect.apply(e, t, o);
                }
            });
            Object.defineProperty(Window.prototype.toString, "0664f2a8c7617fced3e7790a26b1c7f8", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "0664f2a8c7617fced3e7790a26b1c7f8" due to: ' + e);
        }
    },
    '(()=>{const a=window.fetch;window.fetch=new Proxy(window.fetch,{apply:async(b,c,d)=>{const e=d[0];if("string"!=typeof e||0===e.length)return Reflect.apply(b,c,d);if(e.match(/pubads\\.g\\.doubleclick\\.net\\/ondemand\\/.*\\/content\\/.*\\/vid\\/.*\\/streams\\/.*\\/manifest\\.mpd|pubads\\.g\\.doubleclick.net\\/ondemand\\/hls\\/.*\\.m3u8/)){const b=await a(...d);let c=await b.text();return c=c.replaceAll(/<Period id="(pre|mid|post)-roll-.-ad-[\\s\\S]*?>[\\s\\S]*?<\\/Period>|#EXTINF:(\\d|\\d\\.\\d+)\\,\\nhttps:\\/\\/redirector\\.googlevideo\\.com\\/videoplayback\\?[\\s\\S]*?&source=dclk_video_ads&[\\s\\S]*?\\n/g,""),new Response(c)}return Reflect.apply(b,c,d)}})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.cce15678b7fd141ec70a16bc1f01aa96 === e) return;
            (()=>{
                const e = window.fetch;
                window.fetch = new Proxy(window.fetch, {
                    apply: async (t, o, c)=>{
                        const n1 = c[0];
                        if ("string" != typeof n1 || 0 === n1.length) return Reflect.apply(t, o, c);
                        if (n1.match(/pubads\.g\.doubleclick\.net\/ondemand\/.*\/content\/.*\/vid\/.*\/streams\/.*\/manifest\.mpd|pubads\.g\.doubleclick.net\/ondemand\/hls\/.*\.m3u8/)) {
                            const t = await e(...c);
                            let o = await t.text();
                            return o = o.replaceAll(/<Period id="(pre|mid|post)-roll-.-ad-[\s\S]*?>[\s\S]*?<\/Period>|#EXTINF:(\d|\d\.\d+)\,\nhttps:\/\/redirector\.googlevideo\.com\/videoplayback\?[\s\S]*?&source=dclk_video_ads&[\s\S]*?\n/g, ""), new Response(o);
                        }
                        return Reflect.apply(t, o, c);
                    }
                });
            })();
            Object.defineProperty(Window.prototype.toString, "cce15678b7fd141ec70a16bc1f01aa96", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "cce15678b7fd141ec70a16bc1f01aa96" due to: ' + e);
        }
    },
    "(()=>{window.FAVE=window.FAVE||{};const s={set:(s,e,n,a)=>{if(s?.settings?.ads?.ssai?.prod?.clips?.enabled&&(s.settings.ads.ssai.prod.clips.enabled=!1),s?.player?.instances)for(var i of Object.keys(s.player.instances))s.player.instances[i]?.configs?.ads?.ssai?.prod?.clips?.enabled&&(s.player.instances[i].configs.ads.ssai.prod.clips.enabled=!1);return Reflect.set(s,e,n,a)}};window.FAVE=new Proxy(window.FAVE,s)})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.a7c2de548bf7bc2a7f3781d87742cae1 === e) return;
            (()=>{
                window.FAVE = window.FAVE || {};
                const e = {
                    set: (e, s, n1, a)=>{
                        var _e_settings_ads_ssai_prod_clips, _e_settings_ads_ssai_prod, _e_settings_ads_ssai, _e_settings_ads, _e_settings, _e_player, _e_player_instances_i_configs_ads_ssai_prod_clips, _e_player_instances_i_configs_ads_ssai_prod, _e_player_instances_i_configs_ads_ssai, _e_player_instances_i_configs_ads, _e_player_instances_i_configs, _e_player_instances_i;
                        if ((e === null || e === void 0 ? void 0 : (_e_settings = e.settings) === null || _e_settings === void 0 ? void 0 : (_e_settings_ads = _e_settings.ads) === null || _e_settings_ads === void 0 ? void 0 : (_e_settings_ads_ssai = _e_settings_ads.ssai) === null || _e_settings_ads_ssai === void 0 ? void 0 : (_e_settings_ads_ssai_prod = _e_settings_ads_ssai.prod) === null || _e_settings_ads_ssai_prod === void 0 ? void 0 : (_e_settings_ads_ssai_prod_clips = _e_settings_ads_ssai_prod.clips) === null || _e_settings_ads_ssai_prod_clips === void 0 ? void 0 : _e_settings_ads_ssai_prod_clips.enabled) && (e.settings.ads.ssai.prod.clips.enabled = !1), e === null || e === void 0 ? void 0 : (_e_player = e.player) === null || _e_player === void 0 ? void 0 : _e_player.instances) for (var i1 of Object.keys(e.player.instances))((_e_player_instances_i = e.player.instances[i1]) === null || _e_player_instances_i === void 0 ? void 0 : (_e_player_instances_i_configs = _e_player_instances_i.configs) === null || _e_player_instances_i_configs === void 0 ? void 0 : (_e_player_instances_i_configs_ads = _e_player_instances_i_configs.ads) === null || _e_player_instances_i_configs_ads === void 0 ? void 0 : (_e_player_instances_i_configs_ads_ssai = _e_player_instances_i_configs_ads.ssai) === null || _e_player_instances_i_configs_ads_ssai === void 0 ? void 0 : (_e_player_instances_i_configs_ads_ssai_prod = _e_player_instances_i_configs_ads_ssai.prod) === null || _e_player_instances_i_configs_ads_ssai_prod === void 0 ? void 0 : (_e_player_instances_i_configs_ads_ssai_prod_clips = _e_player_instances_i_configs_ads_ssai_prod.clips) === null || _e_player_instances_i_configs_ads_ssai_prod_clips === void 0 ? void 0 : _e_player_instances_i_configs_ads_ssai_prod_clips.enabled) && (e.player.instances[i1].configs.ads.ssai.prod.clips.enabled = !1);
                        return Reflect.set(e, s, n1, a);
                    }
                };
                window.FAVE = new Proxy(window.FAVE, e);
            })();
            Object.defineProperty(Window.prototype.toString, "a7c2de548bf7bc2a7f3781d87742cae1", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "a7c2de548bf7bc2a7f3781d87742cae1" due to: ' + e);
        }
    },
    "(()=>{window.PostRelease={Start(){}}})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.f442d027f2647247aaa89f75941826f0 === e) return;
            window.PostRelease = {
                Start () {}
            };
            Object.defineProperty(Window.prototype.toString, "f442d027f2647247aaa89f75941826f0", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "f442d027f2647247aaa89f75941826f0" due to: ' + e);
        }
    },
    '(()=>{window.com_adswizz_synchro_decorateUrl=function(a){if("string"===typeof a&&a.startsWith("http"))return a}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["2b3b012135adb550eb133e7becf3e060"] === e) return;
            window.com_adswizz_synchro_decorateUrl = function(e) {
                if ("string" == typeof e && e.startsWith("http")) return e;
            };
            Object.defineProperty(Window.prototype.toString, "2b3b012135adb550eb133e7becf3e060", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "2b3b012135adb550eb133e7becf3e060" due to: ' + e);
        }
    },
    '(()=>{window.XMLHttpRequest.prototype.open=new Proxy(window.XMLHttpRequest.prototype.open,{apply:async(a,b,c)=>{const d=c[1];return"string"!=typeof d||0===d.length?Reflect.apply(a,b,c):(d.match(/manifest\\..*\\.theplatform\\.com\\/.*\\/.*\\.m3u8\\?.*|manifest\\..*\\.theplatform\\.com\\/.*\\/*\\.meta.*/)&&b.addEventListener("readystatechange",function(){if(4===b.readyState){const a=b.response;Object.defineProperty(b,"response",{writable:!0}),Object.defineProperty(b,"responseText",{writable:!0});const c=a.replaceAll(/#EXTINF:.*\\n.*tvessaiprod\\.nbcuni\\.com\\/video\\/[\\s\\S]*?#EXT-X-DISCONTINUITY|#EXT-X-VMAP-AD-BREAK[\\s\\S]*?#EXT-X-ENDLIST/g,"");b.response=c,b.responseText=c}}),Reflect.apply(a,b,c))}})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["6f3d40e53e83daab7ecb0b1ff3b3d011"] === e) return;
            window.XMLHttpRequest.prototype.open = new Proxy(window.XMLHttpRequest.prototype.open, {
                apply: async (e, t, o)=>{
                    const r = o[1];
                    return "string" != typeof r || 0 === r.length || r.match(/manifest\..*\.theplatform\.com\/.*\/.*\.m3u8\?.*|manifest\..*\.theplatform\.com\/.*\/*\.meta.*/) && t.addEventListener("readystatechange", function() {
                        if (4 === t.readyState) {
                            const e = t.response;
                            Object.defineProperty(t, "response", {
                                writable: !0
                            }), Object.defineProperty(t, "responseText", {
                                writable: !0
                            });
                            const o = e.replaceAll(/#EXTINF:.*\n.*tvessaiprod\.nbcuni\.com\/video\/[\s\S]*?#EXT-X-DISCONTINUITY|#EXT-X-VMAP-AD-BREAK[\s\S]*?#EXT-X-ENDLIST/g, "");
                            t.response = o, t.responseText = o;
                        }
                    }), Reflect.apply(e, t, o);
                }
            });
            Object.defineProperty(Window.prototype.toString, "6f3d40e53e83daab7ecb0b1ff3b3d011", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "6f3d40e53e83daab7ecb0b1ff3b3d011" due to: ' + e);
        }
    },
    '(()=>{let e,t=!1;const n=function(){},o=function(t,n){if("function"==typeof n)try{window.KalturaPlayer?n([]):e=n}catch(e){console.error(e)}};let r;Object.defineProperty(window,"PWT",{value:{requestBids:o,generateConfForGPT:o,addKeyValuePairsToGPTSlots:n,generateDFPURL:n}}),Object.defineProperty(window,"KalturaPlayer",{get:function(){return r},set:function(n){r=n,t||(t=!0,e([]))}})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["03163849cc3681e88adf734700efefc6"] === e) return;
            (()=>{
                let e, t = !1;
                const r = function() {}, o = function(t, r) {
                    if ("function" == typeof r) try {
                        window.KalturaPlayer ? r([]) : e = r;
                    } catch (e) {
                        console.error(e);
                    }
                };
                let n1;
                Object.defineProperty(window, "PWT", {
                    value: {
                        requestBids: o,
                        generateConfForGPT: o,
                        addKeyValuePairsToGPTSlots: r,
                        generateDFPURL: r
                    }
                }), Object.defineProperty(window, "KalturaPlayer", {
                    get: function() {
                        return n1;
                    },
                    set: function(r) {
                        n1 = r, t || (t = !0, e([]));
                    }
                });
            })();
            Object.defineProperty(Window.prototype.toString, "03163849cc3681e88adf734700efefc6", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "03163849cc3681e88adf734700efefc6" due to: ' + e);
        }
    },
    '(()=>{let e,t=!1;const n=function(){},o=function(t,n){if("function"==typeof n)try{window.KalturaPlayer?n([]):e=n}catch(e){console.error(e)}};let r;Object.defineProperty(window,"PWT",{get:()=>({requestBids:o,generateConfForGPT:o,addKeyValuePairsToGPTSlots:n,generateDFPURL:n}),set(){}}),Object.defineProperty(window,"KalturaPlayer",{get:function(){return r},set:function(n){r=n,!t&&e&&(t=!0,e([]))}})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.c8bf49746912973d817a11811377a065 === e) return;
            (()=>{
                let e, t = !1;
                const r = function() {}, o = function(t, r) {
                    if ("function" == typeof r) try {
                        window.KalturaPlayer ? r([]) : e = r;
                    } catch (e) {
                        console.error(e);
                    }
                };
                let n1;
                Object.defineProperty(window, "PWT", {
                    get: ()=>({
                            requestBids: o,
                            generateConfForGPT: o,
                            addKeyValuePairsToGPTSlots: r,
                            generateDFPURL: r
                        }),
                    set () {}
                }), Object.defineProperty(window, "KalturaPlayer", {
                    get: function() {
                        return n1;
                    },
                    set: function(r) {
                        n1 = r, !t && e && (t = !0, e([]));
                    }
                });
            })();
            Object.defineProperty(Window.prototype.toString, "c8bf49746912973d817a11811377a065", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "c8bf49746912973d817a11811377a065" due to: ' + e);
        }
    },
    '(()=>{const a=function(){},b=function(c,a){if("function"==typeof a)try{a([])}catch(a){console.error(a)}};Object.defineProperty(window,"PWT",{value:{requestBids:b,generateConfForGPT:b,addKeyValuePairsToGPTSlots:a,generateDFPURL:a}})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["7a089dd23e47e252f413e97c2c706704"] === e) return;
            (()=>{
                const e = function() {}, o = function(e, o) {
                    if ("function" == typeof o) try {
                        o([]);
                    } catch (o) {
                        console.error(o);
                    }
                };
                Object.defineProperty(window, "PWT", {
                    value: {
                        requestBids: o,
                        generateConfForGPT: o,
                        addKeyValuePairsToGPTSlots: e,
                        generateDFPURL: e
                    }
                });
            })();
            Object.defineProperty(Window.prototype.toString, "7a089dd23e47e252f413e97c2c706704", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "7a089dd23e47e252f413e97c2c706704" due to: ' + e);
        }
    },
    "(()=>{window.turner_getTransactionId=turner_getGuid=function(){},window.AdFuelUtils={getUMTOCookies(){}}})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.b023e1f40db016717028fe62421a3285 === e) return;
            window.turner_getTransactionId = turner_getGuid = function() {}, window.AdFuelUtils = {
                getUMTOCookies () {}
            };
            Object.defineProperty(Window.prototype.toString, "b023e1f40db016717028fe62421a3285", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "b023e1f40db016717028fe62421a3285" due to: ' + e);
        }
    },
    '(function(){window.adsbygoogle={loaded:!0,push:function(a){if(null!==a&&a instanceof Object&&"Object"===a.constructor.name)for(let b in a)if("function"==typeof a[b])try{a[b].call()}catch(a){console.error(a)}}}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["2ba6aeb1954873824c6148e3102a091c"] === e) return;
            window.adsbygoogle = {
                loaded: !0,
                push: function(e) {
                    if (null !== e && e instanceof Object && "Object" === e.constructor.name) {
                        for(let o in e)if ("function" == typeof e[o]) try {
                            e[o].call();
                        } catch (e) {
                            console.error(e);
                        }
                    }
                }
            };
            Object.defineProperty(Window.prototype.toString, "2ba6aeb1954873824c6148e3102a091c", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "2ba6aeb1954873824c6148e3102a091c" due to: ' + e);
        }
    },
    "(()=>{document.addEventListener('DOMContentLoaded',()=>{setTimeout(function(){(function(){window.AdFuel={queueRegistry(){},destroySlots(){}}})()},500);})})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.d4ca083794994e22dcb36f8fd698d98e === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                setTimeout(function() {
                    window.AdFuel = {
                        queueRegistry () {},
                        destroySlots () {}
                    };
                }, 500);
            });
            Object.defineProperty(Window.prototype.toString, "d4ca083794994e22dcb36f8fd698d98e", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "d4ca083794994e22dcb36f8fd698d98e" due to: ' + e);
        }
    },
    "(function(){var a={setConfig:function(){},aliasBidder:function(){},removeAdUnit:function(){},que:[push=function(){}]};window.pbjs=a})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["0d58ac66c89ef6fa9de7481fe82dcc9b"] === e) return;
            !function() {
                var e = {
                    setConfig: function() {},
                    aliasBidder: function() {},
                    removeAdUnit: function() {},
                    que: [
                        push = function() {}
                    ]
                };
                window.pbjs = e;
            }();
            Object.defineProperty(Window.prototype.toString, "0d58ac66c89ef6fa9de7481fe82dcc9b", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "0d58ac66c89ef6fa9de7481fe82dcc9b" due to: ' + e);
        }
    },
    "window.addEventListener('DOMContentLoaded', function() { document.body.innerHTML = document.body.innerHTML.replace(/Adverts/g, \"\"); })": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["3238470ccdeda8472a95e2bbb72a4f2a"] === e) return;
            window.addEventListener("DOMContentLoaded", function() {
                document.body.innerHTML = document.body.innerHTML.replace(/Adverts/g, "");
            });
            Object.defineProperty(Window.prototype.toString, "3238470ccdeda8472a95e2bbb72a4f2a", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "3238470ccdeda8472a95e2bbb72a4f2a" due to: ' + e);
        }
    },
    "!function(){window.rTimer=function(){};window.jitaJS={rtk:{refreshAdUnits:function(){}}};}();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["642c5e10be75a4087f7ce1326ec9a7ee"] === e) return;
            !function() {
                window.rTimer = function() {};
                window.jitaJS = {
                    rtk: {
                        refreshAdUnits: function() {}
                    }
                };
            }();
            Object.defineProperty(Window.prototype.toString, "642c5e10be75a4087f7ce1326ec9a7ee", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "642c5e10be75a4087f7ce1326ec9a7ee" due to: ' + e);
        }
    },
    '(()=>{const t=new MutationObserver((t=>{for(let e of t){const t=e.target;if(t?.querySelector?.("div:not([class], [id]):first-child + div:not([class], [id]):not([class], [id]):last-child")){const e=t.querySelector("div:not([class], [id]):last-child");if("#advertisement"===e?.shadowRoot?.querySelector?.("div:not([class], [id]) > div:not([class], [id])")?.textContent)try{e.remove()}catch(t){console.trace(t)}}}})),e={apply:(e,o,c)=>{try{c[0].mode="open"}catch(t){console.error(t)}const s=Reflect.apply(e,o,c);return t.observe(s,{subtree:!0,childList:!0}),s}};window.Element.prototype.attachShadow=new Proxy(window.Element.prototype.attachShadow,e)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.f38ee646df1545faf01c3d32666dd4c7 === e) return;
            (()=>{
                const e = new MutationObserver((e)=>{
                    for (let t of e){
                        var _o_querySelector;
                        const o = t.target;
                        if (o === null || o === void 0 ? void 0 : (_o_querySelector = o.querySelector) === null || _o_querySelector === void 0 ? void 0 : _o_querySelector.call(o, "div:not([class], [id]):first-child + div:not([class], [id]):not([class], [id]):last-child")) {
                            var _t_shadowRoot_querySelector, _t_shadowRoot_querySelector1, _t_shadowRoot;
                            const t = o.querySelector("div:not([class], [id]):last-child");
                            if ("#advertisement" === (t === null || t === void 0 ? void 0 : (_t_shadowRoot = t.shadowRoot) === null || _t_shadowRoot === void 0 ? void 0 : (_t_shadowRoot_querySelector1 = _t_shadowRoot.querySelector) === null || _t_shadowRoot_querySelector1 === void 0 ? void 0 : (_t_shadowRoot_querySelector = _t_shadowRoot_querySelector1.call(_t_shadowRoot, "div:not([class], [id]) > div:not([class], [id])")) === null || _t_shadowRoot_querySelector === void 0 ? void 0 : _t_shadowRoot_querySelector.textContent)) try {
                                t.remove();
                            } catch (e) {
                                console.trace(e);
                            }
                        }
                    }
                }), t = {
                    apply: (t, o, r)=>{
                        try {
                            r[0].mode = "open";
                        } catch (e) {
                            console.error(e);
                        }
                        const c = Reflect.apply(t, o, r);
                        return e.observe(c, {
                            subtree: !0,
                            childList: !0
                        }), c;
                    }
                };
                window.Element.prototype.attachShadow = new Proxy(window.Element.prototype.attachShadow, t);
            })();
            Object.defineProperty(Window.prototype.toString, "f38ee646df1545faf01c3d32666dd4c7", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "f38ee646df1545faf01c3d32666dd4c7" due to: ' + e);
        }
    },
    'document.cookie="vpn=1; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.c30e73df868a56abad82ef46aea39100 === e) return;
            document.cookie = "vpn=1; path=/;";
            Object.defineProperty(Window.prototype.toString, "c30e73df868a56abad82ef46aea39100", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "c30e73df868a56abad82ef46aea39100" due to: ' + e);
        }
    },
    "(()=>{document.addEventListener(\"DOMContentLoaded\",(()=>{ if(typeof jQuery) { jQuery('#SearchButtom').unbind('click'); } }));})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["1e2d5574e33a449dcd46c38824d46820"] === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                jQuery("#SearchButtom").unbind("click");
            });
            Object.defineProperty(Window.prototype.toString, "1e2d5574e33a449dcd46c38824d46820", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "1e2d5574e33a449dcd46c38824d46820" due to: ' + e);
        }
    },
    '(()=>{document.addEventListener("DOMContentLoaded",(()=>{ if(typeof videofunc) { videofunc(); } }));})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.c89cf796658574c24a11e4139372f1f6 === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                videofunc();
            });
            Object.defineProperty(Window.prototype.toString, "c89cf796658574c24a11e4139372f1f6", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "c89cf796658574c24a11e4139372f1f6" due to: ' + e);
        }
    },
    'document.cookie="p3006=1; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.d2d456e85d536f31a032f2a730cbde22 === e) return;
            document.cookie = "p3006=1; path=/;";
            Object.defineProperty(Window.prototype.toString, "d2d456e85d536f31a032f2a730cbde22", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "d2d456e85d536f31a032f2a730cbde22" due to: ' + e);
        }
    },
    'document.cookie="rpuShownDesktop=1; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["651f3ee34f9ac7a2ac075d8fab9c1c17"] === e) return;
            document.cookie = "rpuShownDesktop=1; path=/;";
            Object.defineProperty(Window.prototype.toString, "651f3ee34f9ac7a2ac075d8fab9c1c17", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "651f3ee34f9ac7a2ac075d8fab9c1c17" due to: ' + e);
        }
    },
    '(()=>{if(!location.href.includes("/embed/"))return;const e={get(e,t,r){try{return"disabled"===t&&"function"==typeof e.start?(queueMicrotask((()=>{try{e.start()}catch(e){}})),!0):Reflect.get(e,t,r)}catch(c){return Reflect.get(e,t,r)}}},t={apply:(t,r,c)=>{try{const n=Reflect.apply(t,r,c);if(n&&"object"==typeof n){if((()=>{try{return(new Error).stack||""}catch{return""}})().includes("getVideoAdInstance"))return new Proxy(n,e)}return n}catch(e){return Reflect.apply(t,r,c)}}};window.Object.create=new Proxy(window.Object.create,t)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.bf2d0d3711e7ef22236392d49b92232d === e) return;
            (()=>{
                if (!location.href.includes("/embed/")) return;
                const e = {
                    get (e, t, r) {
                        try {
                            return "disabled" === t && "function" == typeof e.start ? (queueMicrotask(()=>{
                                try {
                                    e.start();
                                } catch (e) {}
                            }), !0) : Reflect.get(e, t, r);
                        } catch (n1) {
                            return Reflect.get(e, t, r);
                        }
                    }
                }, t = {
                    apply: (t, r, n1)=>{
                        try {
                            const c = Reflect.apply(t, r, n1);
                            return c && "object" == typeof c && (()=>{
                                try {
                                    return (new Error).stack || "";
                                } catch  {
                                    return "";
                                }
                            })().includes("getVideoAdInstance") ? new Proxy(c, e) : c;
                        } catch (e) {
                            return Reflect.apply(t, r, n1);
                        }
                    }
                };
                window.Object.create = new Proxy(window.Object.create, t);
            })();
            Object.defineProperty(Window.prototype.toString, "bf2d0d3711e7ef22236392d49b92232d", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "bf2d0d3711e7ef22236392d49b92232d" due to: ' + e);
        }
    },
    '(function(){var d=(new URL(window.location.href)).searchParams.get("cr");try{var a=atob(d)}catch(b){}try{new URL(a);var c=!0}catch(b){c=!1}if(c)try{window.location=a}catch(b){}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.c1d6890e971fdba258e3692075d82479 === e) return;
            !function() {
                var e = new URL(window.location.href).searchParams.get("cr");
                try {
                    var r = atob(e);
                } catch (e) {}
                try {
                    new URL(r);
                    var t = !0;
                } catch (e) {
                    t = !1;
                }
                if (t) try {
                    window.location = r;
                } catch (e) {}
            }();
            Object.defineProperty(Window.prototype.toString, "c1d6890e971fdba258e3692075d82479", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "c1d6890e971fdba258e3692075d82479" due to: ' + e);
        }
    },
    '(function(){if(-1!=window.location.href.indexOf("/intro-mm"))for(var c=document.cookie.split(";"),b=0;b<c.length;b++){var a=c[b];a=a.split("=");"redirect_url_to_intro"==a[0]&&window.location.replace(decodeURIComponent(a[1]))}})();': ()=>{
        try {
            const o = "done";
            if (Window.prototype.toString.f09a7b4667c1146d3ffd2348387597d8 === o) return;
            !function() {
                if (-1 != window.location.href.indexOf("/intro-mm")) for(var o = document.cookie.split(";"), e = 0; e < o.length; e++){
                    var t = o[e];
                    "redirect_url_to_intro" == (t = t.split("="))[0] && window.location.replace(decodeURIComponent(t[1]));
                }
            }();
            Object.defineProperty(Window.prototype.toString, "f09a7b4667c1146d3ffd2348387597d8", {
                value: o,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (o) {
            console.error('Error executing AG js rule with uniqueId "f09a7b4667c1146d3ffd2348387597d8" due to: ' + o);
        }
    },
    "(function(){var c=document.addEventListener;document.addEventListener=function(a,b,d,e){\"mousedown\"!=a&&-1==b.toString().indexOf(':!!')&&c(a,b,d,e)}.bind(document); var b=window.setTimeout;window.setTimeout=function(a,c){if(!/;if\\(\\!/.test(a.toString()))return b(a,c)};})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["27ed43aa7951f19f9a24a3d955696ea3"] === e) return;
            !function() {
                var e = document.addEventListener;
                document.addEventListener = (function(t, n1, o, r) {
                    "mousedown" != t && -1 == n1.toString().indexOf(":!!") && e(t, n1, o, r);
                }).bind(document);
                var t = window.setTimeout;
                window.setTimeout = function(e, n1) {
                    if (!/;if\(\!/.test(e.toString())) return t(e, n1);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "27ed43aa7951f19f9a24a3d955696ea3", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "27ed43aa7951f19f9a24a3d955696ea3" due to: ' + e);
        }
    },
    "(function(){var c=document.addEventListener;document.addEventListener=function(a,b,d,e){\"mousedown\"!=a&&-1==b.toString().indexOf('Z4P')&&c(a,b,d,e)}.bind(document); var b=window.setTimeout;window.setTimeout=function(a,c){if(!/\\..4P\\(|=setTimeout\\(/.test(a.toString()))return b(a,c)};})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["16fc905e6e4d01b1d36604ce246bdcac"] === e) return;
            !function() {
                var e = document.addEventListener;
                document.addEventListener = (function(t, n1, o, d) {
                    "mousedown" != t && -1 == n1.toString().indexOf("Z4P") && e(t, n1, o, d);
                }).bind(document);
                var t = window.setTimeout;
                window.setTimeout = function(e, n1) {
                    if (!/\..4P\(|=setTimeout\(/.test(e.toString())) return t(e, n1);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "16fc905e6e4d01b1d36604ce246bdcac", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "16fc905e6e4d01b1d36604ce246bdcac" due to: ' + e);
        }
    },
    "(function(){var c=document.addEventListener;document.addEventListener=function(a,b,d,e){\"click\"!=a&&-1==b.toString().indexOf('bi()')&&c(a,b,d,e)}.bind(document);})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.a9336ddeda1e9f4d8198cac4f6a59557 === e) return;
            !function() {
                var e = document.addEventListener;
                document.addEventListener = (function(t, d, n1, o) {
                    "click" != t && -1 == d.toString().indexOf("bi()") && e(t, d, n1, o);
                }).bind(document);
            }();
            Object.defineProperty(Window.prototype.toString, "a9336ddeda1e9f4d8198cac4f6a59557", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "a9336ddeda1e9f4d8198cac4f6a59557" due to: ' + e);
        }
    },
    "(function(){var c=document.addEventListener;document.addEventListener=function(a,b,d,e){\"mousedown\"!=a&&-1==b.toString().indexOf('Z4P')&&c(a,b,d,e)}.bind(document); var b=window.setTimeout;window.setTimeout=function(a,c){if(!/Z4P/.test(a.toString()))return b(a,c)};})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["63f6bebe37e619f74c32a8b2415f86a2"] === e) return;
            !function() {
                var e = document.addEventListener;
                document.addEventListener = (function(t, n1, o, r) {
                    "mousedown" != t && -1 == n1.toString().indexOf("Z4P") && e(t, n1, o, r);
                }).bind(document);
                var t = window.setTimeout;
                window.setTimeout = function(e, n1) {
                    if (!/Z4P/.test(e.toString())) return t(e, n1);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "63f6bebe37e619f74c32a8b2415f86a2", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "63f6bebe37e619f74c32a8b2415f86a2" due to: ' + e);
        }
    },
    "(function(){var c=document.addEventListener;document.addEventListener=function(a,b,d,e){\"click\"!=a&&-1==b.toString().indexOf('checkTarget')&&c(a,b,d,e)}.bind(document);})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.d4daff20eda39f5bfe997a60b5b65564 === e) return;
            !function() {
                var e = document.addEventListener;
                document.addEventListener = (function(t, n1, d, r) {
                    "click" != t && -1 == n1.toString().indexOf("checkTarget") && e(t, n1, d, r);
                }).bind(document);
            }();
            Object.defineProperty(Window.prototype.toString, "d4daff20eda39f5bfe997a60b5b65564", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "d4daff20eda39f5bfe997a60b5b65564" due to: ' + e);
        }
    },
    '(function(){var c=document.addEventListener;document.addEventListener=function(a,b,d,e){"mouseup"!=a&&-1==b.toString().indexOf(`var U="click";var R=\'_blank\';var v="href";`)&&c(a,b,d,e)}.bind(document);})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["2e5eb7acf02c72e68933dbb1fd9704ba"] === e) return;
            !function() {
                var e = document.addEventListener;
                document.addEventListener = (function(t, n1, r, o) {
                    "mouseup" != t && -1 == n1.toString().indexOf('var U="click";var R=\'_blank\';var v="href";') && e(t, n1, r, o);
                }).bind(document);
            }();
            Object.defineProperty(Window.prototype.toString, "2e5eb7acf02c72e68933dbb1fd9704ba", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "2e5eb7acf02c72e68933dbb1fd9704ba" due to: ' + e);
        }
    },
    "(function(){ var observer=new MutationObserver(hide);observer.observe(document,{childList:!0,subtree:!0});function hide(){var e=document.querySelectorAll('span[data-nosnippet] > .q-box');e.forEach(function(e){var i=e.innerText;if(i){if(i!==void 0&&(!0===i.includes('Sponsored')||!0===i.includes('Ad by')||!0===i.includes('Promoted by'))){e.style=\"display:none!important;\"}}})} })();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["9f6813ab855c342f13c90469c95da251"] === e) return;
            new MutationObserver(function() {
                document.querySelectorAll("span[data-nosnippet] > .q-box").forEach(function(e) {
                    var o = e.innerText;
                    o && (void 0 === o || !0 !== o.includes("Sponsored") && !0 !== o.includes("Ad by") && !0 !== o.includes("Promoted by") || (e.style = "display:none!important;"));
                });
            }).observe(document, {
                childList: !0,
                subtree: !0
            });
            Object.defineProperty(Window.prototype.toString, "9f6813ab855c342f13c90469c95da251", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "9f6813ab855c342f13c90469c95da251" due to: ' + e);
        }
    },
    "(function(){ var observer=new MutationObserver(hide);observer.observe(document,{childList:!0,subtree:!0});function hide(){var e=document.querySelectorAll('.paged_list_wrapper > .pagedlist_item');e.forEach(function(e){var i=e.innerHTML;if(i){if(i!==void 0&&(!0===i.includes('Hide This Ad<\\/span>'))){e.style=\"display:none!important;\"}}})} })();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["17b3983e043325b0965b454cc7394766"] === e) return;
            new MutationObserver(function() {
                document.querySelectorAll(".paged_list_wrapper > .pagedlist_item").forEach(function(e) {
                    var t = e.innerHTML;
                    t && void 0 !== t && !0 === t.includes("Hide This Ad</span>") && (e.style = "display:none!important;");
                });
            }).observe(document, {
                childList: !0,
                subtree: !0
            });
            Object.defineProperty(Window.prototype.toString, "17b3983e043325b0965b454cc7394766", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "17b3983e043325b0965b454cc7394766" due to: ' + e);
        }
    },
    '!function(){new MutationObserver((function(){document.querySelectorAll("article > div[class] > div[class]").forEach((function(e){Object.keys(e).forEach((function(c){if(c.includes("__reactEvents")||c.includes("__reactProps")){c=e[c];try{c.children?.props?.adFragmentKey?.items&&e.parentNode.remove()}catch(c){}}}))}))})).observe(document,{childList:!0,subtree:!0});}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["54509270c0f548739cf1d7c18ae3d312"] === e) return;
            new MutationObserver(function() {
                document.querySelectorAll("article > div[class] > div[class]").forEach(function(e) {
                    Object.keys(e).forEach(function(t) {
                        if (t.includes("__reactEvents") || t.includes("__reactProps")) {
                            t = e[t];
                            try {
                                var _t_children_props_adFragmentKey, _t_children_props, _t_children;
                                ((_t_children = t.children) === null || _t_children === void 0 ? void 0 : (_t_children_props = _t_children.props) === null || _t_children_props === void 0 ? void 0 : (_t_children_props_adFragmentKey = _t_children_props.adFragmentKey) === null || _t_children_props_adFragmentKey === void 0 ? void 0 : _t_children_props_adFragmentKey.items) && e.parentNode.remove();
                            } catch (t) {}
                        }
                    });
                });
            }).observe(document, {
                childList: !0,
                subtree: !0
            });
            Object.defineProperty(Window.prototype.toString, "54509270c0f548739cf1d7c18ae3d312", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "54509270c0f548739cf1d7c18ae3d312" due to: ' + e);
        }
    },
    "(()=>{let e=0;const i=[];new MutationObserver((function(){document.querySelectorAll(\"div[role='list'] > div[role='listitem']:not([style*='display: none']) div[data-test-id='pinWrapper'], div[role='list'] > div[role='listitem']:not([style*='display: none']) div[data-test-id='pinWrapper'] > div[data-test-id]\").forEach((s=>{Object.keys(s).forEach((t=>{if(t.includes(\"__reactProps\")){const r=s[t];try{if(r?.children?.props?.children?.props?.pinKey?.adDestinationUrl||r?.children[1]?.props?.children[1]?.props?.children?.props?.pinKey?.adDestinationUrl||r?.children[0]?.props?.children[1]?.props?.children[1]?.props?.children?.props?.pinKey?.adDestinationUrl){const t=s.closest(\"div[role='list'] > div[role='listitem']:not([style*='display: none'])\");if(!t)return;t.style=\"display: none !important;\",e++;const r=t.querySelector('div[data-test-id=\"pinrep-footer\"] > div[class] > div[class] > div[class]:last-child > div[class] > a[aria-label][href][rel] > div[class] > div[class] > div[class]');r&&(i.push([\"Ad blocked based on property [\"+e+\"] -> \"+r.innerText]),console.table(i))}}catch(e){console.error(e)}}}))}))})).observe(document,{childList:!0,subtree:!0})})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.f108a248579190d52136e6e135a4d6c9 === e) return;
            (()=>{
                let e = 0;
                const t = [];
                new MutationObserver(function() {
                    document.querySelectorAll("div[role='list'] > div[role='listitem']:not([style*='display: none']) div[data-test-id='pinWrapper'], div[role='list'] > div[role='listitem']:not([style*='display: none']) div[data-test-id='pinWrapper'] > div[data-test-id]").forEach((i1)=>{
                        Object.keys(i1).forEach((r)=>{
                            if (r.includes("__reactProps")) {
                                const o = i1[r];
                                try {
                                    var _o_children_props_children_props_pinKey, _o_children_props_children_props, _o_children_props_children, _o_children_props, _o_children, _o_children__props_children__props_children_props_pinKey, _o_children__props_children__props_children_props, _o_children__props_children__props_children, _o_children__props_children__props, _o_children__props_children_, _o_children__props, _o_children_, _o_children__props_children__props_children__props_children_props_pinKey, _o_children__props_children__props_children__props_children_props, _o_children__props_children__props_children__props_children, _o_children__props_children__props_children__props, _o_children__props_children__props_children_, _o_children__props_children__props1, _o_children__props_children_1, _o_children__props1, _o_children_1;
                                    if ((o === null || o === void 0 ? void 0 : (_o_children = o.children) === null || _o_children === void 0 ? void 0 : (_o_children_props = _o_children.props) === null || _o_children_props === void 0 ? void 0 : (_o_children_props_children = _o_children_props.children) === null || _o_children_props_children === void 0 ? void 0 : (_o_children_props_children_props = _o_children_props_children.props) === null || _o_children_props_children_props === void 0 ? void 0 : (_o_children_props_children_props_pinKey = _o_children_props_children_props.pinKey) === null || _o_children_props_children_props_pinKey === void 0 ? void 0 : _o_children_props_children_props_pinKey.adDestinationUrl) || (o === null || o === void 0 ? void 0 : (_o_children_ = o.children[1]) === null || _o_children_ === void 0 ? void 0 : (_o_children__props = _o_children_.props) === null || _o_children__props === void 0 ? void 0 : (_o_children__props_children_ = _o_children__props.children[1]) === null || _o_children__props_children_ === void 0 ? void 0 : (_o_children__props_children__props = _o_children__props_children_.props) === null || _o_children__props_children__props === void 0 ? void 0 : (_o_children__props_children__props_children = _o_children__props_children__props.children) === null || _o_children__props_children__props_children === void 0 ? void 0 : (_o_children__props_children__props_children_props = _o_children__props_children__props_children.props) === null || _o_children__props_children__props_children_props === void 0 ? void 0 : (_o_children__props_children__props_children_props_pinKey = _o_children__props_children__props_children_props.pinKey) === null || _o_children__props_children__props_children_props_pinKey === void 0 ? void 0 : _o_children__props_children__props_children_props_pinKey.adDestinationUrl) || (o === null || o === void 0 ? void 0 : (_o_children_1 = o.children[0]) === null || _o_children_1 === void 0 ? void 0 : (_o_children__props1 = _o_children_1.props) === null || _o_children__props1 === void 0 ? void 0 : (_o_children__props_children_1 = _o_children__props1.children[1]) === null || _o_children__props_children_1 === void 0 ? void 0 : (_o_children__props_children__props1 = _o_children__props_children_1.props) === null || _o_children__props_children__props1 === void 0 ? void 0 : (_o_children__props_children__props_children_ = _o_children__props_children__props1.children[1]) === null || _o_children__props_children__props_children_ === void 0 ? void 0 : (_o_children__props_children__props_children__props = _o_children__props_children__props_children_.props) === null || _o_children__props_children__props_children__props === void 0 ? void 0 : (_o_children__props_children__props_children__props_children = _o_children__props_children__props_children__props.children) === null || _o_children__props_children__props_children__props_children === void 0 ? void 0 : (_o_children__props_children__props_children__props_children_props = _o_children__props_children__props_children__props_children.props) === null || _o_children__props_children__props_children__props_children_props === void 0 ? void 0 : (_o_children__props_children__props_children__props_children_props_pinKey = _o_children__props_children__props_children__props_children_props.pinKey) === null || _o_children__props_children__props_children__props_children_props_pinKey === void 0 ? void 0 : _o_children__props_children__props_children__props_children_props_pinKey.adDestinationUrl)) {
                                        const r = i1.closest("div[role='list'] > div[role='listitem']:not([style*='display: none'])");
                                        if (!r) return;
                                        r.style = "display: none !important;", e++;
                                        const o = r.querySelector('div[data-test-id="pinrep-footer"] > div[class] > div[class] > div[class]:last-child > div[class] > a[aria-label][href][rel] > div[class] > div[class] > div[class]');
                                        o && (t.push([
                                            "Ad blocked based on property [" + e + "] -> " + o.innerText
                                        ]), console.table(t));
                                    }
                                } catch (e) {
                                    console.error(e);
                                }
                            }
                        });
                    });
                }).observe(document, {
                    childList: !0,
                    subtree: !0
                });
            })();
            Object.defineProperty(Window.prototype.toString, "f108a248579190d52136e6e135a4d6c9", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "f108a248579190d52136e6e135a4d6c9" due to: ' + e);
        }
    },
    '!function(){var e=new MutationObserver(function(){var m=document.querySelectorAll("div[id^=\'mount_\']");{var e;e=0<m.length?document.querySelectorAll(\'div[role="feed"] > div[data-pagelet^="FeedUnit"] > div[class]:not([style*="height"])\'):document.querySelectorAll(\'[id^="substream"] > div:not(.hidden_elem) div[id^="hyperfeed_story_id"]\')}e.forEach(function(e){function n(e,n){for(0<m.length?"0"==(h=e.querySelectorAll(\'div[role="article"] span[dir="auto"] > a > span > span > span[data-content]\')).length&&(h=e.querySelectorAll(\'div[role="article"] span[dir="auto"] > a > span[aria-label]\')):h=e.querySelectorAll(".userContentWrapper h5 + div[data-testid] a [class] [class]"),socheck=0;socheck<h.length;socheck++)h[socheck].innerText.contains(n)&&(p=["1"],d=["1"],u=["1"],i=r=l=1,socheck=h.length)}function t(e,n,t,c,a){for(0<m.length?"0"==(h=e.querySelectorAll(\'div[role="article"] span[dir="auto"] > a > span > span > span[data-content]\')).length&&(h=e.querySelectorAll(\'div[role="article"] span[dir="auto"] div[role="button"][tabindex]\')):h=e.querySelectorAll(".userContentWrapper h5 + div[data-testid] > span a > [class] [class]"),"0"==h.length&&(h=e.querySelectorAll(\'div[role="article"] span[dir="auto"] > a > span[aria-label]\')),socheck=0;socheck<h.length;socheck++){spancheck=0,1<h.length?(spancheck=h[socheck].querySelectorAll("span")[0],0==spancheck&&(spancheck=h[socheck].querySelectorAll("b")[0])):(spancheck=h[0].querySelectorAll("span")[socheck],0==spancheck&&(spancheck=h[0].querySelectorAll("b")[socheck]));var o=h[0];if(0!=spancheck&&spancheck){if(2==spancheck.children.length&&0<m.length)for(spancheck=spancheck.querySelectorAll("span:not([style])"),spcheck=0;spcheck<spancheck.length;spcheck++)spancheck[spcheck].innerText.contains(n)?s=1:!spancheck[spcheck].innerText.contains(t)||0!=spancheck[spcheck].offsetTop||spancheck[spcheck].innerText.contains(n)||spancheck[spcheck].innerText.contains(c)||spancheck[spcheck].innerText.contains(a)?!spancheck[spcheck].innerText.contains(c)||0!=spancheck[spcheck].offsetTop||spancheck[spcheck].innerText.contains(t)||spancheck[spcheck].innerText.contains(n)||spancheck[spcheck].innerText.contains(a)?!spancheck[spcheck].innerText.contains(a)||0!=spancheck[spcheck].offsetTop||spancheck[spcheck].innerText.contains(t)||spancheck[spcheck].innerText.contains(c)||spancheck[spcheck].innerText.contains(n)||(u=["1"],i=1):(d=["1"],r=1):(p=["1"],l=1);0==m.length&&((!(spancheck.innerText.contains(n)&&0==spancheck.offsetTop||h[0].innerText.contains(n)&&0==h[0].offsetTop)||spancheck.innerText.contains(t)&&!h[0].innerText.contains(t)||spancheck.innerText.contains(c)&&!h[0].innerText.contains(c)||spancheck.innerText.contains(a)&&!h[0].innerText.contains(a))&&(!o.innerText.contains(n)||0!=o.offsetTop||o.innerText.contains(t)||o.innerText.contains(c)||o.innerText.contains(a))?!spancheck.innerText.contains(t)||0!=spancheck.offsetTop||spancheck.innerText.contains(n)||spancheck.innerText.contains(c)||spancheck.innerText.contains(a)?!spancheck.innerText.contains(c)||0!=spancheck.offsetTop||spancheck.innerText.contains(t)||spancheck.innerText.contains(n)||spancheck.innerText.contains(a)?!spancheck.innerText.contains(a)||0!=spancheck.offsetTop||spancheck.innerText.contains(t)||spancheck.innerText.contains(c)||spancheck.innerText.contains(n)||(u=["1"],i=1):(d=["1"],r=1):(p=["1"],l=1):s=1)}}}function c(e,n,t,c,a){u=0<m.length?(h=e.querySelectorAll(\'div[role="article"] span[dir="auto"] > a > span span[data-content=\'+n+"]"),p=e.querySelectorAll(\'div[role="article"] span[dir="auto"] > a > span span[data-content=\'+t+"]"),d=e.querySelectorAll(\'div[role="article"] span[dir="auto"] > a > span span[data-content=\'+c+"]"),e.querySelectorAll(\'div[role="article"] span[dir="auto"] > a > span span[data-content=\'+a+"]")):(h=e.querySelectorAll(".userContentWrapper h5 + div[data-testid] a [data-content="+n+"]"),p=e.querySelectorAll(".userContentWrapper h5 + div[data-testid] a [data-content="+t+"]"),d=e.querySelectorAll(".userContentWrapper h5 + div[data-testid] a [data-content="+c+"]"),e.querySelectorAll(".userContentWrapper h5 + div[data-testid] a [data-content="+a+"]"))}var s=0,l=0,r=0,i=0,h=0,p=0,d=0,u=0,a=e.querySelectorAll("div[style=\'width: 100%\'] > a[href*=\'oculus.com/quest\'] > div"),o=document.querySelector("[lang]"),k=document.querySelectorAll("link[rel=\'preload\'][href*=\'/l/\']");o=o?document.querySelector("[lang]").lang:"en";var y,g=e.querySelectorAll(\'a[ajaxify*="ad_id"] > span\'),f=e.querySelectorAll(\'a[href*="ads/about"]\'),S=e.querySelectorAll(\'a[href*="https://www.facebook.com/business/help"]\');if("display: none !important;"!=e.getAttribute("style")&&!e.classList.contains("hidden_elem")&&(0<g.length||0<f.length||0<S.length?(T+=1,0<m.length?(""==(y=e.querySelectorAll("a[href]")[0].innerText)&&(y=e.querySelectorAll("a[href]")[1].innerText),""==y&&(y=e.querySelectorAll("a[href]")[0].querySelectorAll("a[aria-label]")[0].getAttribute("aria-label"))):y=e.querySelectorAll("a[href]")[2].innerText,console.log("--------"),console.log("Ad hidden from: "+y),console.log("Total ads hidden: "+T),console.log("F length: "+g.length),console.log("H length: "+f.length),console.log("I length (Paid partnership): "+S.length),console.log("--------"),e.style="display:none!important;"):0<a.length?(T+=1,y="Facebook",console.log("--------"),console.log("Ad hidden from: "+y),console.log("Total ads hidden: "+T),console.log("Non-declared ad"),console.log("--------"),e.style="display:none!important;"):"af"==o?n(e,"Geborg"):"de"==o||"nl"==o?c(e,"G","e","s","n"):"am"==o?n(e,"የተከፈለበት ማስታወቂያ"):"ar"==o?n(e,"مُموَّل"):"as"==o?n(e,"পৃষ্ঠপোষকতা কৰা"):"az"==o?n(e,"Sponsor dəstəkli"):"co"==o?n(e,"Spunsurizatu"):"bs"==o||"sl"==o||"cs"==o?c(e,"S","p","z","n"):"da"==o||"en"==o||"et"==o||"fy"==o||"it"==o||"ku"==o||"nb"==o||"nn"==o||"pl"==o||"sq"==o||"sv"==o||"zz"==o?0<m.length?k[0].href.contains("en_UD")?n(e,"pəɹosuodS"):k[0].href.contains("ja_KS")?n(e,"広告"):k[0].href.contains("tz_MA")?n(e,"ⵉⴷⵍ"):k[0].href.contains("sy_SY")?n(e,"ܒܘܕܩܐ ܡܡܘܘܢܐ"):k[0].href.contains("cb_IQ")?n(e,"پاڵپشتیکراو"):k[0].href.contains("ar_AR")?n(e,"مُموَّل"):k[0].href.contains("sz_PL")?n(e,"Szpōnzorowane"):k[0].href.contains("eo_EO")?n(e,"Reklamo"):k[0].href.contains("es_LA")?c(e,"P","u","c","d"):(c(e,"S","p","s","n"),"0"==h.length&&t(e,"S","p","s","n"),"0"==h.length&&n(e,"Sponsored")):document.querySelector("body").className.includes("Locale_en_UD")?n(e,"pəɹosuodS"):document.querySelector("body").className.includes("ja_KS")?n(e,"広告"):document.querySelector("body").className.includes("tz_MA")?n(e,"ⵉⴷⵍ"):document.querySelector("body").className.includes("sy_SY")?n(e,"ܒܘܕܩܐ ܡܡܘܘܢܐ"):document.querySelector("body").className.includes("cb_IQ")?n(e,"پاڵپشتیکراو"):document.querySelector("body").className.includes("ar_AR")?n(e,"مُموَّل"):document.querySelector("body").className.includes("sz_PL")?n(e,"Szpōnzorowane"):document.querySelector("body").className.includes("eo_EO")?n(e,"Reklamo"):document.querySelector("body").className.includes("es_LA")?c(e,"P","u","c","d"):(c(e,"S","p","s","n"),"0"==h.length&&t(e,"S","p","s","n")):"be"==o?n(e,"Рэклама"):"bg"==o?n(e,"Спонсорирано"):"mk"==o?n(e,"Спонзорирано"):"br"==o?n(e,"Paeroniet"):"ca"==o?n(e,"Patrocinat"):"gl"==o||"pt"==o?(n(e,"Patrocinado"),"0"==l&&c(e,"P","a","c","o")):"bn"==o?n(e,"সৌজন্যে"):"cb"==o?n(e,"پاڵپشتیکراو"):"cx"==o?c(e,"G","i","s","n"):"cy"==o?n(e,"Noddwyd"):"el"==o?n(e,"Χορηγούμενη"):"eo"==o?n(e,"Reklamo"):"es"==o?c(e,"P","u","c","d"):"eu"==o?n(e,"Babestua"):"fa"==o?n(e,"دارای پشتیبانی مالی"):"ff"==o?n(e,"Yoɓanaama"):"fi"==o?n(e,"Sponsoroitu"):"fo"==o?n(e,"Stuðlað"):"fr"==o?0<m.length?k[0].href.contains("fr_FR")?c(e,"S","p","s","n"):c(e,"C","o","m","n"):document.querySelector("body").className.includes("Locale_fr_FR")?c(e,"S","p","s","n"):c(e,"C","o","m","n"):"ga"==o?n(e,"Urraithe"):"gn"==o?n(e,"Oñepatrosinapyre"):"gu"==o?n(e,"પ્રાયોજિત"):"ha"==o?n(e,"Daukar Nauyi"):"he"==o?n(e,"ממומן"):"hr"==o?n(e,"Plaćeni oglas"):"ht"==o?n(e,"Peye"):"ne"==o||"mr"==o||"hi"==o?n(e,"प्रायोजित"):"hu"==o?c(e,"H","i","r","d"):"hy"==o?n(e,"Գովազդային"):"id"==o?c(e,"B","e","p","n"):"is"==o?n(e,"Kostað"):"ja"==o?n(e,"広告"):"ms"==o?n(e,"Ditaja"):"jv"==o?n(e,"Disponsori"):"ka"==o?n(e,"რეკლამა"):"kk"==o?n(e,"Демеушілік көрсеткен"):"km"==o?n(e,"បានឧបត្ថម្ភ"):"kn"==o?n(e,"ಪ್ರಾಯೋಜಿತ"):"ko"==o?n(e,"Sponsored"):"ky"==o?n(e,"Демөөрчүлөнгөн"):"lo"==o?n(e,"ຜູ້ສະໜັບສະໜູນ"):"lt"==o?n(e,"Remiama"):"lv"==o?n(e,"Apmaksāta reklāma"):"mg"==o?n(e,"Misy Mpiantoka"):"ml"==o?n(e,"സ്പോൺസർ ചെയ്തത്"):"mn"==o?n(e,"Ивээн тэтгэсэн"):"mt"==o?n(e,"Sponsorjat"):"my"==o?(n(e,"ပံ့ပိုးထားသည်"),"0"==l&&n(e,"အခပေးကြော်ငြာ")):"or"==o?n(e,"ପ୍ରଯୋଜିତ"):"pa"==o?n(e,"ਸਰਪ੍ਰਸਤੀ ਪ੍ਰਾਪਤ"):"ps"==o?n(e,"تمويل شوي"):"ro"==o?n(e,"Sponsorizat"):"ru"==o||"uk"==o?n(e,"Реклама"):"rw"==o?n(e,"Icyamamaza ndasukirwaho"):"sc"==o?n(e,"Patronadu de"):"si"==o?n(e,"අනුග්රාහක"):"sk"==o?n(e,"Sponzorované"):"sn"==o?n(e,"Zvabhadharirwa"):"so"==o?n(e,"La maalgeliyey"):"sr"==o?n(e,"Спонзорисано"):"sw"==o?n(e,"Imedhaminiwa"):"sy"==o?n(e,"ܒܘܕܩܐ ܡܡܘܘܢܐ"):"sz"==o?n(e,"Szpōnzorowane"):"ta"==o?n(e,"விளம்பரம்"):"te"==o?n(e,"ప్రాయోజితం చేయబడింది"):"tg"==o?n(e,"Бо сарпарастӣ"):"th"==o?n(e,"ได้รับการสนับสนุน"):"tl"==o?n(e,"May Sponsor"):"tr"==o?n(e,"Sponsorlu"):"tt"==o?n(e,"Хәйрияче"):"tz"==o?n(e,"ⵉⴷⵍ"):"ur"==o?n(e,"سپانسرڈ"):"uz"==o?n(e,"Reklama"):"vi"==o?n(e,"Được tài trợ"):"zh-Hans"==o?n(e,"赞助内容"):"zh-Hant"==o&&n(e,"贊助"),0<h.length&&0<p.length&&0<d.length&&0<u.length)){for(cont=0;cont<h.length;cont++)0<h[cont].offsetHeight&&(cont=h.length,s=1);for(cont1=0;cont1<p.length;cont1++)0<p[cont1].offsetHeight&&(cont1=p.length,l=1);for(cont2=0;cont2<d.length;cont2++)0<d[cont2].offsetHeight&&(cont2=d.length,r=1);for(cont3=0;cont3<u.length;cont3++)0<u[cont3].offsetHeight&&(cont3=u.length,i=1);1==s&&1==l&&1==r&&1==i&&(0<m.length&&""!=(y=e.querySelectorAll("a[href]")[1].innerText)||(y=e.querySelectorAll("a[href]")[2].innerText),T+=1,console.log("--------"),console.log("Ad hidden from: "+y),console.log("Total ads hidden: "+T),console.log("--------"),e.style="display:none!important;")}})}),T=0;e.observe(document,{childList:!0,subtree:!0})}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.cb487be2d2edd22f1a9ce90cd6ffe9cf === e) return;
            !function() {
                var e = new MutationObserver(function() {
                    var e = document.querySelectorAll("div[id^='mount_']");
                    (0 < e.length ? document.querySelectorAll('div[role="feed"] > div[data-pagelet^="FeedUnit"] > div[class]:not([style*="height"])') : document.querySelectorAll('[id^="substream"] > div:not(.hidden_elem) div[id^="hyperfeed_story_id"]')).forEach(function(t) {
                        function c(n1, t) {
                            for(0 < e.length ? "0" == (h = n1.querySelectorAll('div[role="article"] span[dir="auto"] > a > span > span > span[data-content]')).length && (h = n1.querySelectorAll('div[role="article"] span[dir="auto"] > a > span[aria-label]')) : h = n1.querySelectorAll(".userContentWrapper h5 + div[data-testid] a [class] [class]"), socheck = 0; socheck < h.length; socheck++)h[socheck].innerText.contains(t) && (d = [
                                "1"
                            ], p = [
                                "1"
                            ], u = [
                                "1"
                            ], i1 = l = r = 1, socheck = h.length);
                        }
                        function o(n1, t, c, o, a) {
                            for(0 < e.length ? "0" == (h = n1.querySelectorAll('div[role="article"] span[dir="auto"] > a > span > span > span[data-content]')).length && (h = n1.querySelectorAll('div[role="article"] span[dir="auto"] div[role="button"][tabindex]')) : h = n1.querySelectorAll(".userContentWrapper h5 + div[data-testid] > span a > [class] [class]"), "0" == h.length && (h = n1.querySelectorAll('div[role="article"] span[dir="auto"] > a > span[aria-label]')), socheck = 0; socheck < h.length; socheck++){
                                spancheck = 0, 1 < h.length ? (spancheck = h[socheck].querySelectorAll("span")[0], 0 == spancheck && (spancheck = h[socheck].querySelectorAll("b")[0])) : (spancheck = h[0].querySelectorAll("span")[socheck], 0 == spancheck && (spancheck = h[0].querySelectorAll("b")[socheck]));
                                var k = h[0];
                                if (0 != spancheck && spancheck) {
                                    if (2 == spancheck.children.length && 0 < e.length) for(spancheck = spancheck.querySelectorAll("span:not([style])"), spcheck = 0; spcheck < spancheck.length; spcheck++)spancheck[spcheck].innerText.contains(t) ? s = 1 : !spancheck[spcheck].innerText.contains(c) || 0 != spancheck[spcheck].offsetTop || spancheck[spcheck].innerText.contains(t) || spancheck[spcheck].innerText.contains(o) || spancheck[spcheck].innerText.contains(a) ? !spancheck[spcheck].innerText.contains(o) || 0 != spancheck[spcheck].offsetTop || spancheck[spcheck].innerText.contains(c) || spancheck[spcheck].innerText.contains(t) || spancheck[spcheck].innerText.contains(a) ? !spancheck[spcheck].innerText.contains(a) || 0 != spancheck[spcheck].offsetTop || spancheck[spcheck].innerText.contains(c) || spancheck[spcheck].innerText.contains(o) || spancheck[spcheck].innerText.contains(t) || (u = [
                                        "1"
                                    ], i1 = 1) : (p = [
                                        "1"
                                    ], l = 1) : (d = [
                                        "1"
                                    ], r = 1);
                                    0 == e.length && ((!(spancheck.innerText.contains(t) && 0 == spancheck.offsetTop || h[0].innerText.contains(t) && 0 == h[0].offsetTop) || spancheck.innerText.contains(c) && !h[0].innerText.contains(c) || spancheck.innerText.contains(o) && !h[0].innerText.contains(o) || spancheck.innerText.contains(a) && !h[0].innerText.contains(a)) && (!k.innerText.contains(t) || 0 != k.offsetTop || k.innerText.contains(c) || k.innerText.contains(o) || k.innerText.contains(a)) ? !spancheck.innerText.contains(c) || 0 != spancheck.offsetTop || spancheck.innerText.contains(t) || spancheck.innerText.contains(o) || spancheck.innerText.contains(a) ? !spancheck.innerText.contains(o) || 0 != spancheck.offsetTop || spancheck.innerText.contains(c) || spancheck.innerText.contains(t) || spancheck.innerText.contains(a) ? !spancheck.innerText.contains(a) || 0 != spancheck.offsetTop || spancheck.innerText.contains(c) || spancheck.innerText.contains(o) || spancheck.innerText.contains(t) || (u = [
                                        "1"
                                    ], i1 = 1) : (p = [
                                        "1"
                                    ], l = 1) : (d = [
                                        "1"
                                    ], r = 1) : s = 1);
                                }
                            }
                        }
                        function a(n1, t, c, o, a) {
                            u = 0 < e.length ? (h = n1.querySelectorAll('div[role="article"] span[dir="auto"] > a > span span[data-content=' + t + "]"), d = n1.querySelectorAll('div[role="article"] span[dir="auto"] > a > span span[data-content=' + c + "]"), p = n1.querySelectorAll('div[role="article"] span[dir="auto"] > a > span span[data-content=' + o + "]"), n1.querySelectorAll('div[role="article"] span[dir="auto"] > a > span span[data-content=' + a + "]")) : (h = n1.querySelectorAll(".userContentWrapper h5 + div[data-testid] a [data-content=" + t + "]"), d = n1.querySelectorAll(".userContentWrapper h5 + div[data-testid] a [data-content=" + c + "]"), p = n1.querySelectorAll(".userContentWrapper h5 + div[data-testid] a [data-content=" + o + "]"), n1.querySelectorAll(".userContentWrapper h5 + div[data-testid] a [data-content=" + a + "]"));
                        }
                        var s = 0, r = 0, l = 0, i1 = 0, h = 0, d = 0, p = 0, u = 0, k = t.querySelectorAll("div[style='width: 100%'] > a[href*='oculus.com/quest'] > div"), f = document.querySelector("[lang]"), y = document.querySelectorAll("link[rel='preload'][href*='/l/']");
                        f = f ? document.querySelector("[lang]").lang : "en";
                        var g, S = t.querySelectorAll('a[ajaxify*="ad_id"] > span'), m = t.querySelectorAll('a[href*="ads/about"]'), T = t.querySelectorAll('a[href*="https://www.facebook.com/business/help"]');
                        if ("display: none !important;" != t.getAttribute("style") && !t.classList.contains("hidden_elem") && (0 < S.length || 0 < m.length || 0 < T.length ? (n1 += 1, 0 < e.length ? ("" == (g = t.querySelectorAll("a[href]")[0].innerText) && (g = t.querySelectorAll("a[href]")[1].innerText), "" == g && (g = t.querySelectorAll("a[href]")[0].querySelectorAll("a[aria-label]")[0].getAttribute("aria-label"))) : g = t.querySelectorAll("a[href]")[2].innerText, console.log("--------"), console.log("Ad hidden from: " + g), console.log("Total ads hidden: " + n1), console.log("F length: " + S.length), console.log("H length: " + m.length), console.log("I length (Paid partnership): " + T.length), console.log("--------"), t.style = "display:none!important;") : 0 < k.length ? (n1 += 1, g = "Facebook", console.log("--------"), console.log("Ad hidden from: " + g), console.log("Total ads hidden: " + n1), console.log("Non-declared ad"), console.log("--------"), t.style = "display:none!important;") : "af" == f ? c(t, "Geborg") : "de" == f || "nl" == f ? a(t, "G", "e", "s", "n") : "am" == f ? c(t, "የተከፈለበት ማስታወቂያ") : "ar" == f ? c(t, "مُموَّل") : "as" == f ? c(t, "পৃষ্ঠপোষকতা কৰা") : "az" == f ? c(t, "Sponsor dəstəkli") : "co" == f ? c(t, "Spunsurizatu") : "bs" == f || "sl" == f || "cs" == f ? a(t, "S", "p", "z", "n") : "da" == f || "en" == f || "et" == f || "fy" == f || "it" == f || "ku" == f || "nb" == f || "nn" == f || "pl" == f || "sq" == f || "sv" == f || "zz" == f ? 0 < e.length ? y[0].href.contains("en_UD") ? c(t, "pəɹosuodS") : y[0].href.contains("ja_KS") ? c(t, "広告") : y[0].href.contains("tz_MA") ? c(t, "ⵉⴷⵍ") : y[0].href.contains("sy_SY") ? c(t, "ܒܘܕܩܐ ܡܡܘܘܢܐ") : y[0].href.contains("cb_IQ") ? c(t, "پاڵپشتیکراو") : y[0].href.contains("ar_AR") ? c(t, "مُموَّل") : y[0].href.contains("sz_PL") ? c(t, "Szpōnzorowane") : y[0].href.contains("eo_EO") ? c(t, "Reklamo") : y[0].href.contains("es_LA") ? a(t, "P", "u", "c", "d") : (a(t, "S", "p", "s", "n"), "0" == h.length && o(t, "S", "p", "s", "n"), "0" == h.length && c(t, "Sponsored")) : document.querySelector("body").className.includes("Locale_en_UD") ? c(t, "pəɹosuodS") : document.querySelector("body").className.includes("ja_KS") ? c(t, "広告") : document.querySelector("body").className.includes("tz_MA") ? c(t, "ⵉⴷⵍ") : document.querySelector("body").className.includes("sy_SY") ? c(t, "ܒܘܕܩܐ ܡܡܘܘܢܐ") : document.querySelector("body").className.includes("cb_IQ") ? c(t, "پاڵپشتیکراو") : document.querySelector("body").className.includes("ar_AR") ? c(t, "مُموَّل") : document.querySelector("body").className.includes("sz_PL") ? c(t, "Szpōnzorowane") : document.querySelector("body").className.includes("eo_EO") ? c(t, "Reklamo") : document.querySelector("body").className.includes("es_LA") ? a(t, "P", "u", "c", "d") : (a(t, "S", "p", "s", "n"), "0" == h.length && o(t, "S", "p", "s", "n")) : "be" == f ? c(t, "Рэклама") : "bg" == f ? c(t, "Спонсорирано") : "mk" == f ? c(t, "Спонзорирано") : "br" == f ? c(t, "Paeroniet") : "ca" == f ? c(t, "Patrocinat") : "gl" == f || "pt" == f ? (c(t, "Patrocinado"), "0" == r && a(t, "P", "a", "c", "o")) : "bn" == f ? c(t, "সৌজন্যে") : "cb" == f ? c(t, "پاڵپشتیکراو") : "cx" == f ? a(t, "G", "i", "s", "n") : "cy" == f ? c(t, "Noddwyd") : "el" == f ? c(t, "Χορηγούμενη") : "eo" == f ? c(t, "Reklamo") : "es" == f ? a(t, "P", "u", "c", "d") : "eu" == f ? c(t, "Babestua") : "fa" == f ? c(t, "دارای پشتیبانی مالی") : "ff" == f ? c(t, "Yoɓanaama") : "fi" == f ? c(t, "Sponsoroitu") : "fo" == f ? c(t, "Stuðlað") : "fr" == f ? 0 < e.length ? y[0].href.contains("fr_FR") ? a(t, "S", "p", "s", "n") : a(t, "C", "o", "m", "n") : document.querySelector("body").className.includes("Locale_fr_FR") ? a(t, "S", "p", "s", "n") : a(t, "C", "o", "m", "n") : "ga" == f ? c(t, "Urraithe") : "gn" == f ? c(t, "Oñepatrosinapyre") : "gu" == f ? c(t, "પ્રાયોજિત") : "ha" == f ? c(t, "Daukar Nauyi") : "he" == f ? c(t, "ממומן") : "hr" == f ? c(t, "Plaćeni oglas") : "ht" == f ? c(t, "Peye") : "ne" == f || "mr" == f || "hi" == f ? c(t, "प्रायोजित") : "hu" == f ? a(t, "H", "i", "r", "d") : "hy" == f ? c(t, "Գովազդային") : "id" == f ? a(t, "B", "e", "p", "n") : "is" == f ? c(t, "Kostað") : "ja" == f ? c(t, "広告") : "ms" == f ? c(t, "Ditaja") : "jv" == f ? c(t, "Disponsori") : "ka" == f ? c(t, "რეკლამა") : "kk" == f ? c(t, "Демеушілік көрсеткен") : "km" == f ? c(t, "បានឧបត្ថម្ភ") : "kn" == f ? c(t, "ಪ್ರಾಯೋಜಿತ") : "ko" == f ? c(t, "Sponsored") : "ky" == f ? c(t, "Демөөрчүлөнгөн") : "lo" == f ? c(t, "ຜູ້ສະໜັບສະໜູນ") : "lt" == f ? c(t, "Remiama") : "lv" == f ? c(t, "Apmaksāta reklāma") : "mg" == f ? c(t, "Misy Mpiantoka") : "ml" == f ? c(t, "സ്പോൺസർ ചെയ്തത്") : "mn" == f ? c(t, "Ивээн тэтгэсэн") : "mt" == f ? c(t, "Sponsorjat") : "my" == f ? (c(t, "ပံ့ပိုးထားသည်"), "0" == r && c(t, "အခပေးကြော်ငြာ")) : "or" == f ? c(t, "ପ୍ରଯୋଜିତ") : "pa" == f ? c(t, "ਸਰਪ੍ਰਸਤੀ ਪ੍ਰਾਪਤ") : "ps" == f ? c(t, "تمويل شوي") : "ro" == f ? c(t, "Sponsorizat") : "ru" == f || "uk" == f ? c(t, "Реклама") : "rw" == f ? c(t, "Icyamamaza ndasukirwaho") : "sc" == f ? c(t, "Patronadu de") : "si" == f ? c(t, "අනුග්රාහක") : "sk" == f ? c(t, "Sponzorované") : "sn" == f ? c(t, "Zvabhadharirwa") : "so" == f ? c(t, "La maalgeliyey") : "sr" == f ? c(t, "Спонзорисано") : "sw" == f ? c(t, "Imedhaminiwa") : "sy" == f ? c(t, "ܒܘܕܩܐ ܡܡܘܘܢܐ") : "sz" == f ? c(t, "Szpōnzorowane") : "ta" == f ? c(t, "விளம்பரம்") : "te" == f ? c(t, "ప్రాయోజితం చేయబడింది") : "tg" == f ? c(t, "Бо сарпарастӣ") : "th" == f ? c(t, "ได้รับการสนับสนุน") : "tl" == f ? c(t, "May Sponsor") : "tr" == f ? c(t, "Sponsorlu") : "tt" == f ? c(t, "Хәйрияче") : "tz" == f ? c(t, "ⵉⴷⵍ") : "ur" == f ? c(t, "سپانسرڈ") : "uz" == f ? c(t, "Reklama") : "vi" == f ? c(t, "Được tài trợ") : "zh-Hans" == f ? c(t, "赞助内容") : "zh-Hant" == f && c(t, "贊助"), 0 < h.length && 0 < d.length && 0 < p.length && 0 < u.length)) {
                            for(cont = 0; cont < h.length; cont++)0 < h[cont].offsetHeight && (cont = h.length, s = 1);
                            for(cont1 = 0; cont1 < d.length; cont1++)0 < d[cont1].offsetHeight && (cont1 = d.length, r = 1);
                            for(cont2 = 0; cont2 < p.length; cont2++)0 < p[cont2].offsetHeight && (cont2 = p.length, l = 1);
                            for(cont3 = 0; cont3 < u.length; cont3++)0 < u[cont3].offsetHeight && (cont3 = u.length, i1 = 1);
                            1 == s && 1 == r && 1 == l && 1 == i1 && (0 < e.length && "" != (g = t.querySelectorAll("a[href]")[1].innerText) || (g = t.querySelectorAll("a[href]")[2].innerText), n1 += 1, console.log("--------"), console.log("Ad hidden from: " + g), console.log("Total ads hidden: " + n1), console.log("--------"), t.style = "display:none!important;");
                        }
                    });
                }), n1 = 0;
                e.observe(document, {
                    childList: !0,
                    subtree: !0
                });
            }();
            Object.defineProperty(Window.prototype.toString, "cb487be2d2edd22f1a9ce90cd6ffe9cf", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "cb487be2d2edd22f1a9ce90cd6ffe9cf" due to: ' + e);
        }
    },
    '!function(){var b=0,d=[];new MutationObserver(function(){document.querySelectorAll("div[data-pagelet^=\\"FeedUnit\\"]:not([style*=\\"display: none\\"]), div[role=\\"feed\\"] > div:not([style*=\\"display: none\\"]), div[role=\\"feed\\"] > span:not([style*=\\"display: none\\"]), #ssrb_feed_start + div > div[class]:not([style*=\\"display: none\\"]), #ssrb_feed_start + div span > h3 ~ div[class]:not([style*=\\"display: none\\"]), #ssrb_feed_start + div h3~ div[class]:not([style*=\\"display: none\\"]), #ssrb_feed_start + div h3 ~ div > div[class]:not([style*=\\"display: none\\"]), div[role=\\"main\\"] div[class] > #ssrb_feed_start ~ div > h3 ~ div > div[class]:not([style*=\\"display: none\\"]), div[role=\\"main\\"] div > h3 ~ div > div[class]:not([style*=\\"display: none\\"]), #ssrb_feed_start + div > div > div[class]:not([style*=\\"display: none\\"]), div[role=\\"main\\"] div > h2 ~ div > div[class]:not([style*=\\"display: none\\"]), #ssrb_feed_start + div > div > div[class] > div:not([class], [id]) div:not([class], [id]):not([style*=\\"display: none\\"]), div[role=\\"main\\"] div > h3 ~ div > div[class] > div:not([class], [id]) div:not([class], [id], [dir], [data-0], [style]), div[role=\\"main\\"] div > h2 ~ div > div[class] > div > div:not([style*=\\"display: none\\"]), div[role=\\"main\\"] h3[dir=\\"auto\\"] + div > div[class]:not([style*=\\"display: none\\"]), div[role=\\"main\\"] div > h2 ~ div > div[class] > div > div:not([style*=\\"display: none\\"]) > div:not([style*=\\"display: none\\"]), div[role=\\"main\\"] div > h2 ~ div > div > div > div:not([style*=\\"display: none\\"]) > div:not([style*=\\"display: none\\"]), div[role=\\"main\\"] div > h3 ~ div > div > div > div:not([style*=\\"display: none\\"]) > div:not([style*=\\"display: none\\"]), div[role=\\"main\\"] div > :is(h2, h3) ~ div > * div[class] > div > div:not([style*=\\"display: none\\"]), div[role=\\"main\\"] div > :is(h2, h3) ~ div > * > div > div[class]:not([style*=\\"display: none\\"]), div[role=\\"main\\"] div > :is(h2, h3) ~ div > * > div > div > span > div:not([style*=\\"display: none\\"])").forEach(function(e){Object.keys(e).forEach(function(a){if(a.includes?.("__reactEvents")||a.includes?.("__reactProps")){a=e[a];try{if(a.children?.props?.category?.includes("SPONSORED")||a.children?.props?.children?.props?.category?.includes("SPONSORED")||a.children?.props?.feedEdge?.category?.includes("SPONSORED")||a.children?.props?.children?.props?.feedEdge?.category?.includes("SPONSORED")||a.children?.props?.children?.props?.children?.props?.feedEdge?.category?.includes("SPONSORED")||a.children?.props?.children?.props?.children?.props?.children?.props?.feedEdge?.category?.includes("SPONSORED")||a.children?.props?.children?.props?.children?.props?.children?.props?.feedEdge?.feed_story_category?.includes("SPONSORED")||a.children?.props?.children?.props?.children?.props?.children?.props?.feedEdge?.story_category?.includes("SPONSORED")||a.children?.props?.children?.props?.children?.props?.children?.props?.feedEdge?.story_cat?.includes("SPONSORED")||a.children?.props?.children?.props?.children?.props?.children?.props?.feedEdge?.category_sensitive?.cat?.includes("SPONSORED")||a.children?.props?.children?.props?.children?.props?.children?.props?.feedEdge?.node?.sponsored_data?.brs_filter_setting||a.children?.props?.children?.props?.children?.props?.children?.props?.feedUnit?.lbl_sp_data?.ad_id||a.children?.props?.children?.props?.minGapType?.includes("SPONSORED")||a.children?.props?.children?.props?.children?.props?.children?.props?.children?.props?.feedEdge?.node?.sponsored_data?.brs_filter_setting||a.children?.props?.children?.props?.children?.props?.children?.props?.children?.props?.feedEdge?.node?.spons_data?.brs_filter_setting||a.children?.props?.children?.props?.feedEdge?.cat_sensitive?.cat?.includes("SPONSORED")||a.children?.props?.children?.props?.feedEdge?.node?.sponso_dat_flag?.brs_filter_setting||a.children?.props?.children?.props?.children?.props?.children?.props?.children?.props?.feedEdge?.node?.sponso_dat_flag?.brs_filter_setting||a.children?.props?.children?.props?.children?.props?.children?.props?.minGapType?.includes("SPONSORED")||a.children?.props?.children?.props?.children?.props?.children?.props?.children?.props?.feedEdge?.cat_sensitive?.cat?.includes("SPONSORED")){b++,e.style="display: none !important;";var f=e.querySelector("a[href][aria-label]:not([aria-hidden])");f&&(d.push(["Ad blocked based on property ["+b+"] -> "+f.ariaLabel]),console.table(d))}}catch(a){}}})})}).observe(document,{childList:!0,subtree:!0})}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["358509aba6220d5af7cdab59f6c78b27"] === e) return;
            !function() {
                var e = 0, d = [];
                new MutationObserver(function() {
                    document.querySelectorAll('div[data-pagelet^="FeedUnit"]:not([style*="display: none"]), div[role="feed"] > div:not([style*="display: none"]), div[role="feed"] > span:not([style*="display: none"]), #ssrb_feed_start + div > div[class]:not([style*="display: none"]), #ssrb_feed_start + div span > h3 ~ div[class]:not([style*="display: none"]), #ssrb_feed_start + div h3~ div[class]:not([style*="display: none"]), #ssrb_feed_start + div h3 ~ div > div[class]:not([style*="display: none"]), div[role="main"] div[class] > #ssrb_feed_start ~ div > h3 ~ div > div[class]:not([style*="display: none"]), div[role="main"] div > h3 ~ div > div[class]:not([style*="display: none"]), #ssrb_feed_start + div > div > div[class]:not([style*="display: none"]), div[role="main"] div > h2 ~ div > div[class]:not([style*="display: none"]), #ssrb_feed_start + div > div > div[class] > div:not([class], [id]) div:not([class], [id]):not([style*="display: none"]), div[role="main"] div > h3 ~ div > div[class] > div:not([class], [id]) div:not([class], [id], [dir], [data-0], [style]), div[role="main"] div > h2 ~ div > div[class] > div > div:not([style*="display: none"]), div[role="main"] h3[dir="auto"] + div > div[class]:not([style*="display: none"]), div[role="main"] div > h2 ~ div > div[class] > div > div:not([style*="display: none"]) > div:not([style*="display: none"]), div[role="main"] div > h2 ~ div > div > div > div:not([style*="display: none"]) > div:not([style*="display: none"]), div[role="main"] div > h3 ~ div > div > div > div:not([style*="display: none"]) > div:not([style*="display: none"]), div[role="main"] div > :is(h2, h3) ~ div > * div[class] > div > div:not([style*="display: none"]), div[role="main"] div > :is(h2, h3) ~ div > * > div > div[class]:not([style*="display: none"]), div[role="main"] div > :is(h2, h3) ~ div > * > div > div > span > div:not([style*="display: none"])').forEach(function(i1) {
                        Object.keys(i1).forEach(function(s) {
                            var _s_includes, _s_includes1;
                            if (((_s_includes = s.includes) === null || _s_includes === void 0 ? void 0 : _s_includes.call(s, "__reactEvents")) || ((_s_includes1 = s.includes) === null || _s_includes1 === void 0 ? void 0 : _s_includes1.call(s, "__reactProps"))) {
                                s = i1[s];
                                try {
                                    var _s_children_props_category, _s_children_props, _s_children, _s_children_props_children_props_category, _s_children_props_children_props, _s_children_props_children, _s_children_props1, _s_children1, _s_children_props_feedEdge_category, _s_children_props_feedEdge, _s_children_props2, _s_children2, _s_children_props_children_props_feedEdge_category, _s_children_props_children_props_feedEdge, _s_children_props_children_props1, _s_children_props_children1, _s_children_props3, _s_children3, _s_children_props_children_props_children_props_feedEdge_category, _s_children_props_children_props_children_props_feedEdge, _s_children_props_children_props_children_props, _s_children_props_children_props_children, _s_children_props_children_props2, _s_children_props_children2, _s_children_props4, _s_children4, _s_children_props_children_props_children_props_children_props_feedEdge_category, _s_children_props_children_props_children_props_children_props_feedEdge, _s_children_props_children_props_children_props_children_props, _s_children_props_children_props_children_props_children, _s_children_props_children_props_children_props1, _s_children_props_children_props_children1, _s_children_props_children_props3, _s_children_props_children3, _s_children_props5, _s_children5, _s_children_props_children_props_children_props_children_props_feedEdge_feed_story_category, _s_children_props_children_props_children_props_children_props_feedEdge1, _s_children_props_children_props_children_props_children_props1, _s_children_props_children_props_children_props_children1, _s_children_props_children_props_children_props2, _s_children_props_children_props_children2, _s_children_props_children_props4, _s_children_props_children4, _s_children_props6, _s_children6, _s_children_props_children_props_children_props_children_props_feedEdge_story_category, _s_children_props_children_props_children_props_children_props_feedEdge2, _s_children_props_children_props_children_props_children_props2, _s_children_props_children_props_children_props_children2, _s_children_props_children_props_children_props3, _s_children_props_children_props_children3, _s_children_props_children_props5, _s_children_props_children5, _s_children_props7, _s_children7, _s_children_props_children_props_children_props_children_props_feedEdge_story_cat, _s_children_props_children_props_children_props_children_props_feedEdge3, _s_children_props_children_props_children_props_children_props3, _s_children_props_children_props_children_props_children3, _s_children_props_children_props_children_props4, _s_children_props_children_props_children4, _s_children_props_children_props6, _s_children_props_children6, _s_children_props8, _s_children8, _s_children_props_children_props_children_props_children_props_feedEdge_category_sensitive_cat, _s_children_props_children_props_children_props_children_props_feedEdge_category_sensitive, _s_children_props_children_props_children_props_children_props_feedEdge4, _s_children_props_children_props_children_props_children_props4, _s_children_props_children_props_children_props_children4, _s_children_props_children_props_children_props5, _s_children_props_children_props_children5, _s_children_props_children_props7, _s_children_props_children7, _s_children_props9, _s_children9, _s_children_props_children_props_children_props_children_props_feedEdge_node_sponsored_data, _s_children_props_children_props_children_props_children_props_feedEdge_node, _s_children_props_children_props_children_props_children_props_feedEdge5, _s_children_props_children_props_children_props_children_props5, _s_children_props_children_props_children_props_children5, _s_children_props_children_props_children_props6, _s_children_props_children_props_children6, _s_children_props_children_props8, _s_children_props_children8, _s_children_props10, _s_children10, _s_children_props_children_props_children_props_children_props_feedUnit_lbl_sp_data, _s_children_props_children_props_children_props_children_props_feedUnit, _s_children_props_children_props_children_props_children_props6, _s_children_props_children_props_children_props_children6, _s_children_props_children_props_children_props7, _s_children_props_children_props_children7, _s_children_props_children_props9, _s_children_props_children9, _s_children_props11, _s_children11, _s_children_props_children_props_minGapType, _s_children_props_children_props10, _s_children_props_children10, _s_children_props12, _s_children12, _s_children_props_children_props_children_props_children_props_children_props_feedEdge_node_sponsored_data, _s_children_props_children_props_children_props_children_props_children_props_feedEdge_node, _s_children_props_children_props_children_props_children_props_children_props_feedEdge, _s_children_props_children_props_children_props_children_props_children_props, _s_children_props_children_props_children_props_children_props_children, _s_children_props_children_props_children_props_children_props7, _s_children_props_children_props_children_props_children7, _s_children_props_children_props_children_props8, _s_children_props_children_props_children8, _s_children_props_children_props11, _s_children_props_children11, _s_children_props13, _s_children13, _s_children_props_children_props_children_props_children_props_children_props_feedEdge_node_spons_data, _s_children_props_children_props_children_props_children_props_children_props_feedEdge_node1, _s_children_props_children_props_children_props_children_props_children_props_feedEdge1, _s_children_props_children_props_children_props_children_props_children_props1, _s_children_props_children_props_children_props_children_props_children1, _s_children_props_children_props_children_props_children_props8, _s_children_props_children_props_children_props_children8, _s_children_props_children_props_children_props9, _s_children_props_children_props_children9, _s_children_props_children_props12, _s_children_props_children12, _s_children_props14, _s_children14, _s_children_props_children_props_feedEdge_cat_sensitive_cat, _s_children_props_children_props_feedEdge_cat_sensitive, _s_children_props_children_props_feedEdge1, _s_children_props_children_props13, _s_children_props_children13, _s_children_props15, _s_children15, _s_children_props_children_props_feedEdge_node_sponso_dat_flag, _s_children_props_children_props_feedEdge_node, _s_children_props_children_props_feedEdge2, _s_children_props_children_props14, _s_children_props_children14, _s_children_props16, _s_children16, _s_children_props_children_props_children_props_children_props_children_props_feedEdge_node_sponso_dat_flag, _s_children_props_children_props_children_props_children_props_children_props_feedEdge_node2, _s_children_props_children_props_children_props_children_props_children_props_feedEdge2, _s_children_props_children_props_children_props_children_props_children_props2, _s_children_props_children_props_children_props_children_props_children2, _s_children_props_children_props_children_props_children_props9, _s_children_props_children_props_children_props_children9, _s_children_props_children_props_children_props10, _s_children_props_children_props_children10, _s_children_props_children_props15, _s_children_props_children15, _s_children_props17, _s_children17, _s_children_props_children_props_children_props_children_props_minGapType, _s_children_props_children_props_children_props_children_props10, _s_children_props_children_props_children_props_children10, _s_children_props_children_props_children_props11, _s_children_props_children_props_children11, _s_children_props_children_props16, _s_children_props_children16, _s_children_props18, _s_children18, _s_children_props_children_props_children_props_children_props_children_props_feedEdge_cat_sensitive_cat, _s_children_props_children_props_children_props_children_props_children_props_feedEdge_cat_sensitive, _s_children_props_children_props_children_props_children_props_children_props_feedEdge3, _s_children_props_children_props_children_props_children_props_children_props3, _s_children_props_children_props_children_props_children_props_children3, _s_children_props_children_props_children_props_children_props11, _s_children_props_children_props_children_props_children11, _s_children_props_children_props_children_props12, _s_children_props_children_props_children12, _s_children_props_children_props17, _s_children_props_children17, _s_children_props19, _s_children19;
                                    if (((_s_children = s.children) === null || _s_children === void 0 ? void 0 : (_s_children_props = _s_children.props) === null || _s_children_props === void 0 ? void 0 : (_s_children_props_category = _s_children_props.category) === null || _s_children_props_category === void 0 ? void 0 : _s_children_props_category.includes("SPONSORED")) || ((_s_children1 = s.children) === null || _s_children1 === void 0 ? void 0 : (_s_children_props1 = _s_children1.props) === null || _s_children_props1 === void 0 ? void 0 : (_s_children_props_children = _s_children_props1.children) === null || _s_children_props_children === void 0 ? void 0 : (_s_children_props_children_props = _s_children_props_children.props) === null || _s_children_props_children_props === void 0 ? void 0 : (_s_children_props_children_props_category = _s_children_props_children_props.category) === null || _s_children_props_children_props_category === void 0 ? void 0 : _s_children_props_children_props_category.includes("SPONSORED")) || ((_s_children2 = s.children) === null || _s_children2 === void 0 ? void 0 : (_s_children_props2 = _s_children2.props) === null || _s_children_props2 === void 0 ? void 0 : (_s_children_props_feedEdge = _s_children_props2.feedEdge) === null || _s_children_props_feedEdge === void 0 ? void 0 : (_s_children_props_feedEdge_category = _s_children_props_feedEdge.category) === null || _s_children_props_feedEdge_category === void 0 ? void 0 : _s_children_props_feedEdge_category.includes("SPONSORED")) || ((_s_children3 = s.children) === null || _s_children3 === void 0 ? void 0 : (_s_children_props3 = _s_children3.props) === null || _s_children_props3 === void 0 ? void 0 : (_s_children_props_children1 = _s_children_props3.children) === null || _s_children_props_children1 === void 0 ? void 0 : (_s_children_props_children_props1 = _s_children_props_children1.props) === null || _s_children_props_children_props1 === void 0 ? void 0 : (_s_children_props_children_props_feedEdge = _s_children_props_children_props1.feedEdge) === null || _s_children_props_children_props_feedEdge === void 0 ? void 0 : (_s_children_props_children_props_feedEdge_category = _s_children_props_children_props_feedEdge.category) === null || _s_children_props_children_props_feedEdge_category === void 0 ? void 0 : _s_children_props_children_props_feedEdge_category.includes("SPONSORED")) || ((_s_children4 = s.children) === null || _s_children4 === void 0 ? void 0 : (_s_children_props4 = _s_children4.props) === null || _s_children_props4 === void 0 ? void 0 : (_s_children_props_children2 = _s_children_props4.children) === null || _s_children_props_children2 === void 0 ? void 0 : (_s_children_props_children_props2 = _s_children_props_children2.props) === null || _s_children_props_children_props2 === void 0 ? void 0 : (_s_children_props_children_props_children = _s_children_props_children_props2.children) === null || _s_children_props_children_props_children === void 0 ? void 0 : (_s_children_props_children_props_children_props = _s_children_props_children_props_children.props) === null || _s_children_props_children_props_children_props === void 0 ? void 0 : (_s_children_props_children_props_children_props_feedEdge = _s_children_props_children_props_children_props.feedEdge) === null || _s_children_props_children_props_children_props_feedEdge === void 0 ? void 0 : (_s_children_props_children_props_children_props_feedEdge_category = _s_children_props_children_props_children_props_feedEdge.category) === null || _s_children_props_children_props_children_props_feedEdge_category === void 0 ? void 0 : _s_children_props_children_props_children_props_feedEdge_category.includes("SPONSORED")) || ((_s_children5 = s.children) === null || _s_children5 === void 0 ? void 0 : (_s_children_props5 = _s_children5.props) === null || _s_children_props5 === void 0 ? void 0 : (_s_children_props_children3 = _s_children_props5.children) === null || _s_children_props_children3 === void 0 ? void 0 : (_s_children_props_children_props3 = _s_children_props_children3.props) === null || _s_children_props_children_props3 === void 0 ? void 0 : (_s_children_props_children_props_children1 = _s_children_props_children_props3.children) === null || _s_children_props_children_props_children1 === void 0 ? void 0 : (_s_children_props_children_props_children_props1 = _s_children_props_children_props_children1.props) === null || _s_children_props_children_props_children_props1 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children = _s_children_props_children_props_children_props1.children) === null || _s_children_props_children_props_children_props_children === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props = _s_children_props_children_props_children_props_children.props) === null || _s_children_props_children_props_children_props_children_props === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_feedEdge = _s_children_props_children_props_children_props_children_props.feedEdge) === null || _s_children_props_children_props_children_props_children_props_feedEdge === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_feedEdge_category = _s_children_props_children_props_children_props_children_props_feedEdge.category) === null || _s_children_props_children_props_children_props_children_props_feedEdge_category === void 0 ? void 0 : _s_children_props_children_props_children_props_children_props_feedEdge_category.includes("SPONSORED")) || ((_s_children6 = s.children) === null || _s_children6 === void 0 ? void 0 : (_s_children_props6 = _s_children6.props) === null || _s_children_props6 === void 0 ? void 0 : (_s_children_props_children4 = _s_children_props6.children) === null || _s_children_props_children4 === void 0 ? void 0 : (_s_children_props_children_props4 = _s_children_props_children4.props) === null || _s_children_props_children_props4 === void 0 ? void 0 : (_s_children_props_children_props_children2 = _s_children_props_children_props4.children) === null || _s_children_props_children_props_children2 === void 0 ? void 0 : (_s_children_props_children_props_children_props2 = _s_children_props_children_props_children2.props) === null || _s_children_props_children_props_children_props2 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children1 = _s_children_props_children_props_children_props2.children) === null || _s_children_props_children_props_children_props_children1 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props1 = _s_children_props_children_props_children_props_children1.props) === null || _s_children_props_children_props_children_props_children_props1 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_feedEdge1 = _s_children_props_children_props_children_props_children_props1.feedEdge) === null || _s_children_props_children_props_children_props_children_props_feedEdge1 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_feedEdge_feed_story_category = _s_children_props_children_props_children_props_children_props_feedEdge1.feed_story_category) === null || _s_children_props_children_props_children_props_children_props_feedEdge_feed_story_category === void 0 ? void 0 : _s_children_props_children_props_children_props_children_props_feedEdge_feed_story_category.includes("SPONSORED")) || ((_s_children7 = s.children) === null || _s_children7 === void 0 ? void 0 : (_s_children_props7 = _s_children7.props) === null || _s_children_props7 === void 0 ? void 0 : (_s_children_props_children5 = _s_children_props7.children) === null || _s_children_props_children5 === void 0 ? void 0 : (_s_children_props_children_props5 = _s_children_props_children5.props) === null || _s_children_props_children_props5 === void 0 ? void 0 : (_s_children_props_children_props_children3 = _s_children_props_children_props5.children) === null || _s_children_props_children_props_children3 === void 0 ? void 0 : (_s_children_props_children_props_children_props3 = _s_children_props_children_props_children3.props) === null || _s_children_props_children_props_children_props3 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children2 = _s_children_props_children_props_children_props3.children) === null || _s_children_props_children_props_children_props_children2 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props2 = _s_children_props_children_props_children_props_children2.props) === null || _s_children_props_children_props_children_props_children_props2 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_feedEdge2 = _s_children_props_children_props_children_props_children_props2.feedEdge) === null || _s_children_props_children_props_children_props_children_props_feedEdge2 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_feedEdge_story_category = _s_children_props_children_props_children_props_children_props_feedEdge2.story_category) === null || _s_children_props_children_props_children_props_children_props_feedEdge_story_category === void 0 ? void 0 : _s_children_props_children_props_children_props_children_props_feedEdge_story_category.includes("SPONSORED")) || ((_s_children8 = s.children) === null || _s_children8 === void 0 ? void 0 : (_s_children_props8 = _s_children8.props) === null || _s_children_props8 === void 0 ? void 0 : (_s_children_props_children6 = _s_children_props8.children) === null || _s_children_props_children6 === void 0 ? void 0 : (_s_children_props_children_props6 = _s_children_props_children6.props) === null || _s_children_props_children_props6 === void 0 ? void 0 : (_s_children_props_children_props_children4 = _s_children_props_children_props6.children) === null || _s_children_props_children_props_children4 === void 0 ? void 0 : (_s_children_props_children_props_children_props4 = _s_children_props_children_props_children4.props) === null || _s_children_props_children_props_children_props4 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children3 = _s_children_props_children_props_children_props4.children) === null || _s_children_props_children_props_children_props_children3 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props3 = _s_children_props_children_props_children_props_children3.props) === null || _s_children_props_children_props_children_props_children_props3 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_feedEdge3 = _s_children_props_children_props_children_props_children_props3.feedEdge) === null || _s_children_props_children_props_children_props_children_props_feedEdge3 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_feedEdge_story_cat = _s_children_props_children_props_children_props_children_props_feedEdge3.story_cat) === null || _s_children_props_children_props_children_props_children_props_feedEdge_story_cat === void 0 ? void 0 : _s_children_props_children_props_children_props_children_props_feedEdge_story_cat.includes("SPONSORED")) || ((_s_children9 = s.children) === null || _s_children9 === void 0 ? void 0 : (_s_children_props9 = _s_children9.props) === null || _s_children_props9 === void 0 ? void 0 : (_s_children_props_children7 = _s_children_props9.children) === null || _s_children_props_children7 === void 0 ? void 0 : (_s_children_props_children_props7 = _s_children_props_children7.props) === null || _s_children_props_children_props7 === void 0 ? void 0 : (_s_children_props_children_props_children5 = _s_children_props_children_props7.children) === null || _s_children_props_children_props_children5 === void 0 ? void 0 : (_s_children_props_children_props_children_props5 = _s_children_props_children_props_children5.props) === null || _s_children_props_children_props_children_props5 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children4 = _s_children_props_children_props_children_props5.children) === null || _s_children_props_children_props_children_props_children4 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props4 = _s_children_props_children_props_children_props_children4.props) === null || _s_children_props_children_props_children_props_children_props4 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_feedEdge4 = _s_children_props_children_props_children_props_children_props4.feedEdge) === null || _s_children_props_children_props_children_props_children_props_feedEdge4 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_feedEdge_category_sensitive = _s_children_props_children_props_children_props_children_props_feedEdge4.category_sensitive) === null || _s_children_props_children_props_children_props_children_props_feedEdge_category_sensitive === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_feedEdge_category_sensitive_cat = _s_children_props_children_props_children_props_children_props_feedEdge_category_sensitive.cat) === null || _s_children_props_children_props_children_props_children_props_feedEdge_category_sensitive_cat === void 0 ? void 0 : _s_children_props_children_props_children_props_children_props_feedEdge_category_sensitive_cat.includes("SPONSORED")) || ((_s_children10 = s.children) === null || _s_children10 === void 0 ? void 0 : (_s_children_props10 = _s_children10.props) === null || _s_children_props10 === void 0 ? void 0 : (_s_children_props_children8 = _s_children_props10.children) === null || _s_children_props_children8 === void 0 ? void 0 : (_s_children_props_children_props8 = _s_children_props_children8.props) === null || _s_children_props_children_props8 === void 0 ? void 0 : (_s_children_props_children_props_children6 = _s_children_props_children_props8.children) === null || _s_children_props_children_props_children6 === void 0 ? void 0 : (_s_children_props_children_props_children_props6 = _s_children_props_children_props_children6.props) === null || _s_children_props_children_props_children_props6 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children5 = _s_children_props_children_props_children_props6.children) === null || _s_children_props_children_props_children_props_children5 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props5 = _s_children_props_children_props_children_props_children5.props) === null || _s_children_props_children_props_children_props_children_props5 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_feedEdge5 = _s_children_props_children_props_children_props_children_props5.feedEdge) === null || _s_children_props_children_props_children_props_children_props_feedEdge5 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_feedEdge_node = _s_children_props_children_props_children_props_children_props_feedEdge5.node) === null || _s_children_props_children_props_children_props_children_props_feedEdge_node === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_feedEdge_node_sponsored_data = _s_children_props_children_props_children_props_children_props_feedEdge_node.sponsored_data) === null || _s_children_props_children_props_children_props_children_props_feedEdge_node_sponsored_data === void 0 ? void 0 : _s_children_props_children_props_children_props_children_props_feedEdge_node_sponsored_data.brs_filter_setting) || ((_s_children11 = s.children) === null || _s_children11 === void 0 ? void 0 : (_s_children_props11 = _s_children11.props) === null || _s_children_props11 === void 0 ? void 0 : (_s_children_props_children9 = _s_children_props11.children) === null || _s_children_props_children9 === void 0 ? void 0 : (_s_children_props_children_props9 = _s_children_props_children9.props) === null || _s_children_props_children_props9 === void 0 ? void 0 : (_s_children_props_children_props_children7 = _s_children_props_children_props9.children) === null || _s_children_props_children_props_children7 === void 0 ? void 0 : (_s_children_props_children_props_children_props7 = _s_children_props_children_props_children7.props) === null || _s_children_props_children_props_children_props7 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children6 = _s_children_props_children_props_children_props7.children) === null || _s_children_props_children_props_children_props_children6 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props6 = _s_children_props_children_props_children_props_children6.props) === null || _s_children_props_children_props_children_props_children_props6 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_feedUnit = _s_children_props_children_props_children_props_children_props6.feedUnit) === null || _s_children_props_children_props_children_props_children_props_feedUnit === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_feedUnit_lbl_sp_data = _s_children_props_children_props_children_props_children_props_feedUnit.lbl_sp_data) === null || _s_children_props_children_props_children_props_children_props_feedUnit_lbl_sp_data === void 0 ? void 0 : _s_children_props_children_props_children_props_children_props_feedUnit_lbl_sp_data.ad_id) || ((_s_children12 = s.children) === null || _s_children12 === void 0 ? void 0 : (_s_children_props12 = _s_children12.props) === null || _s_children_props12 === void 0 ? void 0 : (_s_children_props_children10 = _s_children_props12.children) === null || _s_children_props_children10 === void 0 ? void 0 : (_s_children_props_children_props10 = _s_children_props_children10.props) === null || _s_children_props_children_props10 === void 0 ? void 0 : (_s_children_props_children_props_minGapType = _s_children_props_children_props10.minGapType) === null || _s_children_props_children_props_minGapType === void 0 ? void 0 : _s_children_props_children_props_minGapType.includes("SPONSORED")) || ((_s_children13 = s.children) === null || _s_children13 === void 0 ? void 0 : (_s_children_props13 = _s_children13.props) === null || _s_children_props13 === void 0 ? void 0 : (_s_children_props_children11 = _s_children_props13.children) === null || _s_children_props_children11 === void 0 ? void 0 : (_s_children_props_children_props11 = _s_children_props_children11.props) === null || _s_children_props_children_props11 === void 0 ? void 0 : (_s_children_props_children_props_children8 = _s_children_props_children_props11.children) === null || _s_children_props_children_props_children8 === void 0 ? void 0 : (_s_children_props_children_props_children_props8 = _s_children_props_children_props_children8.props) === null || _s_children_props_children_props_children_props8 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children7 = _s_children_props_children_props_children_props8.children) === null || _s_children_props_children_props_children_props_children7 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props7 = _s_children_props_children_props_children_props_children7.props) === null || _s_children_props_children_props_children_props_children_props7 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_children = _s_children_props_children_props_children_props_children_props7.children) === null || _s_children_props_children_props_children_props_children_props_children === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_children_props = _s_children_props_children_props_children_props_children_props_children.props) === null || _s_children_props_children_props_children_props_children_props_children_props === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_children_props_feedEdge = _s_children_props_children_props_children_props_children_props_children_props.feedEdge) === null || _s_children_props_children_props_children_props_children_props_children_props_feedEdge === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_children_props_feedEdge_node = _s_children_props_children_props_children_props_children_props_children_props_feedEdge.node) === null || _s_children_props_children_props_children_props_children_props_children_props_feedEdge_node === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_children_props_feedEdge_node_sponsored_data = _s_children_props_children_props_children_props_children_props_children_props_feedEdge_node.sponsored_data) === null || _s_children_props_children_props_children_props_children_props_children_props_feedEdge_node_sponsored_data === void 0 ? void 0 : _s_children_props_children_props_children_props_children_props_children_props_feedEdge_node_sponsored_data.brs_filter_setting) || ((_s_children14 = s.children) === null || _s_children14 === void 0 ? void 0 : (_s_children_props14 = _s_children14.props) === null || _s_children_props14 === void 0 ? void 0 : (_s_children_props_children12 = _s_children_props14.children) === null || _s_children_props_children12 === void 0 ? void 0 : (_s_children_props_children_props12 = _s_children_props_children12.props) === null || _s_children_props_children_props12 === void 0 ? void 0 : (_s_children_props_children_props_children9 = _s_children_props_children_props12.children) === null || _s_children_props_children_props_children9 === void 0 ? void 0 : (_s_children_props_children_props_children_props9 = _s_children_props_children_props_children9.props) === null || _s_children_props_children_props_children_props9 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children8 = _s_children_props_children_props_children_props9.children) === null || _s_children_props_children_props_children_props_children8 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props8 = _s_children_props_children_props_children_props_children8.props) === null || _s_children_props_children_props_children_props_children_props8 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_children1 = _s_children_props_children_props_children_props_children_props8.children) === null || _s_children_props_children_props_children_props_children_props_children1 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_children_props1 = _s_children_props_children_props_children_props_children_props_children1.props) === null || _s_children_props_children_props_children_props_children_props_children_props1 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_children_props_feedEdge1 = _s_children_props_children_props_children_props_children_props_children_props1.feedEdge) === null || _s_children_props_children_props_children_props_children_props_children_props_feedEdge1 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_children_props_feedEdge_node1 = _s_children_props_children_props_children_props_children_props_children_props_feedEdge1.node) === null || _s_children_props_children_props_children_props_children_props_children_props_feedEdge_node1 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_children_props_feedEdge_node_spons_data = _s_children_props_children_props_children_props_children_props_children_props_feedEdge_node1.spons_data) === null || _s_children_props_children_props_children_props_children_props_children_props_feedEdge_node_spons_data === void 0 ? void 0 : _s_children_props_children_props_children_props_children_props_children_props_feedEdge_node_spons_data.brs_filter_setting) || ((_s_children15 = s.children) === null || _s_children15 === void 0 ? void 0 : (_s_children_props15 = _s_children15.props) === null || _s_children_props15 === void 0 ? void 0 : (_s_children_props_children13 = _s_children_props15.children) === null || _s_children_props_children13 === void 0 ? void 0 : (_s_children_props_children_props13 = _s_children_props_children13.props) === null || _s_children_props_children_props13 === void 0 ? void 0 : (_s_children_props_children_props_feedEdge1 = _s_children_props_children_props13.feedEdge) === null || _s_children_props_children_props_feedEdge1 === void 0 ? void 0 : (_s_children_props_children_props_feedEdge_cat_sensitive = _s_children_props_children_props_feedEdge1.cat_sensitive) === null || _s_children_props_children_props_feedEdge_cat_sensitive === void 0 ? void 0 : (_s_children_props_children_props_feedEdge_cat_sensitive_cat = _s_children_props_children_props_feedEdge_cat_sensitive.cat) === null || _s_children_props_children_props_feedEdge_cat_sensitive_cat === void 0 ? void 0 : _s_children_props_children_props_feedEdge_cat_sensitive_cat.includes("SPONSORED")) || ((_s_children16 = s.children) === null || _s_children16 === void 0 ? void 0 : (_s_children_props16 = _s_children16.props) === null || _s_children_props16 === void 0 ? void 0 : (_s_children_props_children14 = _s_children_props16.children) === null || _s_children_props_children14 === void 0 ? void 0 : (_s_children_props_children_props14 = _s_children_props_children14.props) === null || _s_children_props_children_props14 === void 0 ? void 0 : (_s_children_props_children_props_feedEdge2 = _s_children_props_children_props14.feedEdge) === null || _s_children_props_children_props_feedEdge2 === void 0 ? void 0 : (_s_children_props_children_props_feedEdge_node = _s_children_props_children_props_feedEdge2.node) === null || _s_children_props_children_props_feedEdge_node === void 0 ? void 0 : (_s_children_props_children_props_feedEdge_node_sponso_dat_flag = _s_children_props_children_props_feedEdge_node.sponso_dat_flag) === null || _s_children_props_children_props_feedEdge_node_sponso_dat_flag === void 0 ? void 0 : _s_children_props_children_props_feedEdge_node_sponso_dat_flag.brs_filter_setting) || ((_s_children17 = s.children) === null || _s_children17 === void 0 ? void 0 : (_s_children_props17 = _s_children17.props) === null || _s_children_props17 === void 0 ? void 0 : (_s_children_props_children15 = _s_children_props17.children) === null || _s_children_props_children15 === void 0 ? void 0 : (_s_children_props_children_props15 = _s_children_props_children15.props) === null || _s_children_props_children_props15 === void 0 ? void 0 : (_s_children_props_children_props_children10 = _s_children_props_children_props15.children) === null || _s_children_props_children_props_children10 === void 0 ? void 0 : (_s_children_props_children_props_children_props10 = _s_children_props_children_props_children10.props) === null || _s_children_props_children_props_children_props10 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children9 = _s_children_props_children_props_children_props10.children) === null || _s_children_props_children_props_children_props_children9 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props9 = _s_children_props_children_props_children_props_children9.props) === null || _s_children_props_children_props_children_props_children_props9 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_children2 = _s_children_props_children_props_children_props_children_props9.children) === null || _s_children_props_children_props_children_props_children_props_children2 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_children_props2 = _s_children_props_children_props_children_props_children_props_children2.props) === null || _s_children_props_children_props_children_props_children_props_children_props2 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_children_props_feedEdge2 = _s_children_props_children_props_children_props_children_props_children_props2.feedEdge) === null || _s_children_props_children_props_children_props_children_props_children_props_feedEdge2 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_children_props_feedEdge_node2 = _s_children_props_children_props_children_props_children_props_children_props_feedEdge2.node) === null || _s_children_props_children_props_children_props_children_props_children_props_feedEdge_node2 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_children_props_feedEdge_node_sponso_dat_flag = _s_children_props_children_props_children_props_children_props_children_props_feedEdge_node2.sponso_dat_flag) === null || _s_children_props_children_props_children_props_children_props_children_props_feedEdge_node_sponso_dat_flag === void 0 ? void 0 : _s_children_props_children_props_children_props_children_props_children_props_feedEdge_node_sponso_dat_flag.brs_filter_setting) || ((_s_children18 = s.children) === null || _s_children18 === void 0 ? void 0 : (_s_children_props18 = _s_children18.props) === null || _s_children_props18 === void 0 ? void 0 : (_s_children_props_children16 = _s_children_props18.children) === null || _s_children_props_children16 === void 0 ? void 0 : (_s_children_props_children_props16 = _s_children_props_children16.props) === null || _s_children_props_children_props16 === void 0 ? void 0 : (_s_children_props_children_props_children11 = _s_children_props_children_props16.children) === null || _s_children_props_children_props_children11 === void 0 ? void 0 : (_s_children_props_children_props_children_props11 = _s_children_props_children_props_children11.props) === null || _s_children_props_children_props_children_props11 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children10 = _s_children_props_children_props_children_props11.children) === null || _s_children_props_children_props_children_props_children10 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props10 = _s_children_props_children_props_children_props_children10.props) === null || _s_children_props_children_props_children_props_children_props10 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_minGapType = _s_children_props_children_props_children_props_children_props10.minGapType) === null || _s_children_props_children_props_children_props_children_props_minGapType === void 0 ? void 0 : _s_children_props_children_props_children_props_children_props_minGapType.includes("SPONSORED")) || ((_s_children19 = s.children) === null || _s_children19 === void 0 ? void 0 : (_s_children_props19 = _s_children19.props) === null || _s_children_props19 === void 0 ? void 0 : (_s_children_props_children17 = _s_children_props19.children) === null || _s_children_props_children17 === void 0 ? void 0 : (_s_children_props_children_props17 = _s_children_props_children17.props) === null || _s_children_props_children_props17 === void 0 ? void 0 : (_s_children_props_children_props_children12 = _s_children_props_children_props17.children) === null || _s_children_props_children_props_children12 === void 0 ? void 0 : (_s_children_props_children_props_children_props12 = _s_children_props_children_props_children12.props) === null || _s_children_props_children_props_children_props12 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children11 = _s_children_props_children_props_children_props12.children) === null || _s_children_props_children_props_children_props_children11 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props11 = _s_children_props_children_props_children_props_children11.props) === null || _s_children_props_children_props_children_props_children_props11 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_children3 = _s_children_props_children_props_children_props_children_props11.children) === null || _s_children_props_children_props_children_props_children_props_children3 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_children_props3 = _s_children_props_children_props_children_props_children_props_children3.props) === null || _s_children_props_children_props_children_props_children_props_children_props3 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_children_props_feedEdge3 = _s_children_props_children_props_children_props_children_props_children_props3.feedEdge) === null || _s_children_props_children_props_children_props_children_props_children_props_feedEdge3 === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_children_props_feedEdge_cat_sensitive = _s_children_props_children_props_children_props_children_props_children_props_feedEdge3.cat_sensitive) === null || _s_children_props_children_props_children_props_children_props_children_props_feedEdge_cat_sensitive === void 0 ? void 0 : (_s_children_props_children_props_children_props_children_props_children_props_feedEdge_cat_sensitive_cat = _s_children_props_children_props_children_props_children_props_children_props_feedEdge_cat_sensitive.cat) === null || _s_children_props_children_props_children_props_children_props_children_props_feedEdge_cat_sensitive_cat === void 0 ? void 0 : _s_children_props_children_props_children_props_children_props_children_props_feedEdge_cat_sensitive_cat.includes("SPONSORED"))) {
                                        e++, i1.style = "display: none !important;";
                                        var r = i1.querySelector("a[href][aria-label]:not([aria-hidden])");
                                        r && (d.push([
                                            "Ad blocked based on property [" + e + "] -> " + r.ariaLabel
                                        ]), console.table(d));
                                    }
                                } catch (s) {}
                            }
                        });
                    });
                }).observe(document, {
                    childList: !0,
                    subtree: !0
                });
            }();
            Object.defineProperty(Window.prototype.toString, "358509aba6220d5af7cdab59f6c78b27", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "358509aba6220d5af7cdab59f6c78b27" due to: ' + e);
        }
    },
    '(()=>{const e=new MutationObserver((()=>{const n=document.querySelectorAll(\'div[role="complementary"] div[class*=" "] > div[class] > div:not([class]) > div:not([class], [style*="display: none"]), div[role="complementary"] div[class*=" "] > div[class] > div:not([class]) > span[class] > div[class]:not([style*="display: none"]), div[role="complementary"] div:has(+ div[data-visualcompletion]) > div:not([style*="display: none"])\');for(const s of n){const n=Object.keys(s).find((e=>e.includes("__reactFiber")));if(n){const t=s[n];if(t?.pendingProps?.children?.props?.match?.__fragmentPropName?.includes("adsSideFeedUnit"))return s.style.display="none",void e.disconnect()}}}));e.observe(document.documentElement,{childList:!0,subtree:!0})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.e5520b88f1ab8a8177c19ea7ed1eea60 === e) return;
            (()=>{
                const e = new MutationObserver(()=>{
                    const n1 = document.querySelectorAll('div[role="complementary"] div[class*=" "] > div[class] > div:not([class]) > div:not([class], [style*="display: none"]), div[role="complementary"] div[class*=" "] > div[class] > div:not([class]) > span[class] > div[class]:not([style*="display: none"]), div[role="complementary"] div:has(+ div[data-visualcompletion]) > div:not([style*="display: none"])');
                    for (const t of n1){
                        const n1 = Object.keys(t).find((e)=>e.includes("__reactFiber"));
                        if (n1) {
                            var _o_pendingProps_children_props_match___fragmentPropName, _o_pendingProps_children_props_match, _o_pendingProps_children_props, _o_pendingProps_children, _o_pendingProps;
                            const o = t[n1];
                            if (o === null || o === void 0 ? void 0 : (_o_pendingProps = o.pendingProps) === null || _o_pendingProps === void 0 ? void 0 : (_o_pendingProps_children = _o_pendingProps.children) === null || _o_pendingProps_children === void 0 ? void 0 : (_o_pendingProps_children_props = _o_pendingProps_children.props) === null || _o_pendingProps_children_props === void 0 ? void 0 : (_o_pendingProps_children_props_match = _o_pendingProps_children_props.match) === null || _o_pendingProps_children_props_match === void 0 ? void 0 : (_o_pendingProps_children_props_match___fragmentPropName = _o_pendingProps_children_props_match.__fragmentPropName) === null || _o_pendingProps_children_props_match___fragmentPropName === void 0 ? void 0 : _o_pendingProps_children_props_match___fragmentPropName.includes("adsSideFeedUnit")) return t.style.display = "none", void e.disconnect();
                        }
                    }
                });
                e.observe(document.documentElement, {
                    childList: !0,
                    subtree: !0
                });
            })();
            Object.defineProperty(Window.prototype.toString, "e5520b88f1ab8a8177c19ea7ed1eea60", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "e5520b88f1ab8a8177c19ea7ed1eea60" due to: ' + e);
        }
    },
    '!function(){(new MutationObserver(function(){window.location.href.includes("/watch")&&document.querySelectorAll(\'#watch_feed div:not([class]):not([id]) > div[class*=" "]:not([style*="display: none !important"]) div[class^="_"] > div[class*=" "]\').forEach(function(b){Object.keys(b).forEach(function(a){if(a.includes("__reactFiber")){a=b[a];try{var c,d,e,f;if(null==(c=a)?0:null==(d=c["return"])?0:null==(e=d.memoizedProps)?0:null==(f=e.story)?0:f.sponsored_data){var g=b.closest(\'#watch_feed div[class*=" "] div:not([class]):not([id]) > div[class*=" "]:not([style*="display: none !important"])\');g.style="display: none !important;"}}catch(h){}}})})})).observe(document,{childList:!0,subtree:!0,attributeFilter:["style"]})}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["21d8e78f9157f1f1188b26cd68182732"] === e) return;
            new MutationObserver(function() {
                window.location.href.includes("/watch") && document.querySelectorAll('#watch_feed div:not([class]):not([id]) > div[class*=" "]:not([style*="display: none !important"]) div[class^="_"] > div[class*=" "]').forEach(function(e) {
                    Object.keys(e).forEach(function(t) {
                        if (t.includes("__reactFiber")) {
                            t = e[t];
                            try {
                                var n1, o, r, i1;
                                null != (n1 = t) && null != (o = n1.return) && null != (r = o.memoizedProps) && null != (i1 = r.story) && i1.sponsored_data && (e.closest('#watch_feed div[class*=" "] div:not([class]):not([id]) > div[class*=" "]:not([style*="display: none !important"])').style = "display: none !important;");
                            } catch (e) {}
                        }
                    });
                });
            }).observe(document, {
                childList: !0,
                subtree: !0,
                attributeFilter: [
                    "style"
                ]
            });
            Object.defineProperty(Window.prototype.toString, "21d8e78f9157f1f1188b26cd68182732", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "21d8e78f9157f1f1188b26cd68182732" due to: ' + e);
        }
    },
    '!function(){if(location.href.includes("marketplace/item")){var b=0,d=[];new MutationObserver(function(){document.querySelectorAll("div[aria-label=\'Marketplace listing viewer\'] > div div + div + span:not([style*=\'display: none\']), #ssrb_feed_start + div > div div + div + span:not([style*=\'display: none\'])").forEach(function(e){Object.keys(e).forEach(function(a){if(a.includes("__reactEvents")||a.includes("__reactProps")){a=e[a];try{if(a.children?.props?.children?.props?.adId){b++,e.style="display: none !important;";var f=e.querySelector("a[href][aria-label]:not([aria-hidden])");f&&(d.push(["Ad blocked based on property ["+b+"] -> "+f.ariaLabel]),console.table(d))}}catch(a){}}})})}).observe(document,{childList:!0,subtree:!0})}}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.b5ee651ceb5b17d69e521c7d45d2dc1f === e) return;
            !function() {
                if (location.href.includes("marketplace/item")) {
                    var e = 0, r = [];
                    new MutationObserver(function() {
                        document.querySelectorAll("div[aria-label='Marketplace listing viewer'] > div div + div + span:not([style*='display: none']), #ssrb_feed_start + div > div div + div + span:not([style*='display: none'])").forEach(function(t) {
                            Object.keys(t).forEach(function(i1) {
                                if (i1.includes("__reactEvents") || i1.includes("__reactProps")) {
                                    i1 = t[i1];
                                    try {
                                        var _i_children_props_children_props, _i_children_props_children, _i_children_props, _i_children;
                                        if ((_i_children = i1.children) === null || _i_children === void 0 ? void 0 : (_i_children_props = _i_children.props) === null || _i_children_props === void 0 ? void 0 : (_i_children_props_children = _i_children_props.children) === null || _i_children_props_children === void 0 ? void 0 : (_i_children_props_children_props = _i_children_props_children.props) === null || _i_children_props_children_props === void 0 ? void 0 : _i_children_props_children_props.adId) {
                                            e++, t.style = "display: none !important;";
                                            var n1 = t.querySelector("a[href][aria-label]:not([aria-hidden])");
                                            n1 && (r.push([
                                                "Ad blocked based on property [" + e + "] -> " + n1.ariaLabel
                                            ]), console.table(r));
                                        }
                                    } catch (i1) {}
                                }
                            });
                        });
                    }).observe(document, {
                        childList: !0,
                        subtree: !0
                    });
                }
            }();
            Object.defineProperty(Window.prototype.toString, "b5ee651ceb5b17d69e521c7d45d2dc1f", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "b5ee651ceb5b17d69e521c7d45d2dc1f" due to: ' + e);
        }
    },
    '!function(){var e=new MutationObserver(function(){document.querySelectorAll(\'[id^="substream"] > div:not(.hidden_elem) div[id^="hyperfeed_story_id"]\').forEach(function(e){function t(e,t){for(s=e.querySelectorAll(\'.userContentWrapper h5 + div[data-testid*="sub"] a [class] [class]\'),socheck=0;socheck<s.length;socheck++)s[socheck].innerText.contains(t)&&(c=["1"],d=["1"],i=["1"],r=l=a=1,socheck=s.length)}function o(e,t,o,n,a){s=e.querySelectorAll(\'.userContentWrapper h5 + div[data-testid*="sub"] a [data-content=\'+t+"]"),c=e.querySelectorAll(\'.userContentWrapper h5 + div[data-testid*="sub"] a [data-content=\'+o+"]"),d=e.querySelectorAll(\'.userContentWrapper h5 + div[data-testid*="sub"] a [data-content=\'+n+"]"),i=e.querySelectorAll(\'.userContentWrapper h5 + div[data-testid*="sub"] a [data-content=\'+a+"]"),0==s.length&&(s=e.querySelectorAll(\'.userContentWrapper h5 + div[data-testid*="label"] a [data-content=\'+t+"]"),c=e.querySelectorAll(\'.userContentWrapper h5 + div[data-testid*="label"] a [data-content=\'+o+"]"),d=e.querySelectorAll(\'.userContentWrapper h5 + div[data-testid*="label"] a [data-content=\'+n+"]"),i=e.querySelectorAll(\'.userContentWrapper h5 + div[data-testid*="label"] a [data-content=\'+a+"]"))}var n=0,a=0,l=0,r=0,s=0,c=0,d=0,i=0,u=e.querySelectorAll("div[style=\'width: 100%\'] > a[href*=\'oculus.com/quest\'] > div"),h=document.querySelector("[lang]").lang,g=e.querySelectorAll(\'a[ajaxify*="ad_id"] > span\'),p=e.querySelectorAll(\'a[href*="ads/about"]\');if("display: none !important;"!=e.getAttribute("style")&&!e.classList.contains("hidden_elem")){if(0<g.length||0<p.length){f+=1;var y=e.querySelectorAll("a[href]")[2].innerText;console.log("--------"),console.log("Ad hidden from: "+y),console.log("Total ads hidden: "+f),console.log("F length: "+g.length),console.log("H length: "+p.length),console.log("--------"),e.style="display:none!important;"}else if(0<u.length){f+=1;y="Facebook";console.log("--------"),console.log("Ad hidden from: "+y),console.log("Total ads hidden: "+f),console.log("Non-declared ad"),console.log("--------"),e.style="display:none!important;"}else"af"==h?t(e,"Geborg"):"de"==h||"nl"==h?o(e,"G","e","s","n"):"am"==h?t(e,"የተከፈለበት ማስታወቂያ"):"ar"==h?t(e,"مُموَّل"):"as"==h?t(e,"পৃষ্ঠপোষকতা কৰা"):"az"==h?t(e,"Sponsor dəstəkli"):"co"==h?t(e,"Spunsurizatu"):"bs"==h||"sl"==h||"cs"==h?o(e,"S","p","z","n"):"da"==h||"en"==h||"et"==h||"fy"==h||"it"==h||"ku"==h||"nb"==h||"nn"==h||"pl"==h||"sq"==h||"sv"==h||"zz"==h?document.querySelector("body").className.includes("Locale_en_UD")?t(e,"pəɹosuodS"):o(e,"S","p","s","n"):"be"==h?t(e,"Рэклама"):"bg"==h?t(e,"Спонсорирано"):"mk"==h?t(e,"Спонзорирано"):"br"==h?t(e,"Paeroniet"):"ca"==h?t(e,"Patrocinat"):"gl"==h||"pt"==h?t(e,"Patrocinado"):"bn"==h?t(e,"সৌজন্যে"):"cb"==h?t(e,"پاڵپشتیکراو"):"cx"==h?o(e,"G","i","s","n"):"cy"==h?t(e,"Noddwyd"):"el"==h?t(e,"Χορηγούμενη"):"eo"==h?t(e,"Reklamo"):"es"==h?o(e,"P","u","c","d"):"eu"==h?t(e,"Babestua"):"fa"==h?t(e,"دارای پشتیبانی مالی"):"ff"==h?t(e,"Yoɓanaama"):"fi"==h?t(e,"Sponsoroitu"):"fo"==h?t(e,"Stuðlað"):"fr"==h?document.querySelector("body").className.includes("Locale_fr_FR")?o(e,"S","p","s","n"):o(e,"C","o","m","n"):"ga"==h?t(e,"Urraithe"):"gn"==h?t(e,"Oñepatrosinapyre"):"gu"==h?t(e,"પ્રાયોજિત"):"ha"==h?t(e,"Daukar Nauyi"):"he"==h?t(e,"ממומן"):"hr"==h?t(e,"Plaćeni oglas"):"ht"==h?t(e,"Peye"):"ne"==h||"mr"==h||"hi"==h?t(e,"प्रायोजित"):"hu"==h?o(e,"H","i","r","d"):"hy"==h?t(e,"Գովազդային"):"id"==h?o(e,"B","e","p","n"):"is"==h?t(e,"Kostað"):"ja"==h?t(e,"広告"):"ms"==h?t(e,"Ditaja"):"jv"==h?t(e,"Disponsori"):"ka"==h?t(e,"რეკლამა"):"kk"==h?t(e,"Демеушілік көрсеткен"):"km"==h?t(e,"បានឧបត្ថម្ភ"):"kn"==h?t(e,"ಪ್ರಾಯೋಜಿತ"):"ko"==h?t(e,"Sponsored"):"ky"==h?t(e,"Демөөрчүлөнгөн"):"lo"==h?t(e,"ຜູ້ສະໜັບສະໜູນ"):"lt"==h?t(e,"Remiama"):"lv"==h?t(e,"Apmaksāta reklāma"):"mg"==h?t(e,"Misy Mpiantoka"):"ml"==h?t(e,"സ്പോൺസർ ചെയ്തത്"):"mn"==h?t(e,"Ивээн тэтгэсэн"):"mt"==h?t(e,"Sponsorjat"):"my"==h?t(e,"ပံ့ပိုးထားသည်"):"or"==h?t(e,"ପ୍ରଯୋଜିତ"):"pa"==h?t(e,"ਸਰਪ੍ਰਸਤੀ ਪ੍ਰਾਪਤ"):"ps"==h?t(e,"تمويل شوي"):"ro"==h?t(e,"Sponsorizat"):"ru"==h||"uk"==h?t(e,"Реклама"):"rw"==h?t(e,"Icyamamaza ndasukirwaho"):"sc"==h?t(e,"Patronadu de"):"si"==h?t(e,"අනුග්‍රාහක"):"sk"==h?t(e,"Sponzorované"):"sn"==h?t(e,"Zvabhadharirwa"):"so"==h?t(e,"La maalgeliyey"):"sr"==h?t(e,"Спонзорисано"):"sw"==h?t(e,"Imedhaminiwa"):"sy"==h?t(e,"ܒܘܕܩܐ ܡܡܘܘܢܐ"):"sz"==h?t(e,"Szpōnzorowane"):"ta"==h?t(e,"விளம்பரம்"):"te"==h?t(e,"ప్రాయోజితం చేయబడింది"):"tg"==h?t(e,"Бо сарпарастӣ"):"th"==h?t(e,"ได้รับการสนับสนุน"):"tl"==h?t(e,"May Sponsor"):"tr"==h?t(e,"Sponsorlu"):"tt"==h?t(e,"Хәйрияче"):"tz"==h?t(e,"ⵉⴷⵍ"):"ur"==h?t(e,"سپانسرڈ"):"uz"==h?t(e,"Reklama"):"vi"==h?t(e,"Được tài trợ"):"zh-Hans"==h?t(e,"赞助内容"):"zh-Hant"==h&&t(e,"贊助");if(0<s.length&&0<c.length&&0<d.length&&0<i.length){for(cont=0;cont<s.length;cont++)0<s[cont].offsetHeight&&(cont=s.length,n=1);for(cont1=0;cont1<c.length;cont1++)0<c[cont1].offsetHeight&&(cont1=c.length,a=1);for(cont2=0;cont2<d.length;cont2++)0<d[cont2].offsetHeight&&(cont2=d.length,l=1);for(cont3=0;cont3<i.length;cont3++)0<i[cont3].offsetHeight&&(cont3=i.length,r=1);if(1==n&&1==a&&1==l&&1==r){y=e.querySelectorAll("a[href]")[2].innerText;f+=1,console.log("--------"),console.log("Ad hidden from: "+y),console.log("Total ads hidden: "+f),console.log("--------"),e.style="display:none!important;"}}}})}),f=0;e.observe(document,{childList:!0,subtree:!0,characterData:!0,attributes:!0})}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.c20e5794d5ff5adb72bad3179e0fd5f5 === e) return;
            !function() {
                var e = new MutationObserver(function() {
                    document.querySelectorAll('[id^="substream"] > div:not(.hidden_elem) div[id^="hyperfeed_story_id"]').forEach(function(e) {
                        function o(e, t) {
                            for(c = e.querySelectorAll('.userContentWrapper h5 + div[data-testid*="sub"] a [class] [class]'), socheck = 0; socheck < c.length; socheck++)c[socheck].innerText.contains(t) && (d = [
                                "1"
                            ], i1 = [
                                "1"
                            ], u = [
                                "1"
                            ], s = r = l = 1, socheck = c.length);
                        }
                        function n1(e, t, o, n1, a) {
                            c = e.querySelectorAll('.userContentWrapper h5 + div[data-testid*="sub"] a [data-content=' + t + "]"), d = e.querySelectorAll('.userContentWrapper h5 + div[data-testid*="sub"] a [data-content=' + o + "]"), i1 = e.querySelectorAll('.userContentWrapper h5 + div[data-testid*="sub"] a [data-content=' + n1 + "]"), u = e.querySelectorAll('.userContentWrapper h5 + div[data-testid*="sub"] a [data-content=' + a + "]"), 0 == c.length && (c = e.querySelectorAll('.userContentWrapper h5 + div[data-testid*="label"] a [data-content=' + t + "]"), d = e.querySelectorAll('.userContentWrapper h5 + div[data-testid*="label"] a [data-content=' + o + "]"), i1 = e.querySelectorAll('.userContentWrapper h5 + div[data-testid*="label"] a [data-content=' + n1 + "]"), u = e.querySelectorAll('.userContentWrapper h5 + div[data-testid*="label"] a [data-content=' + a + "]"));
                        }
                        var a = 0, l = 0, r = 0, s = 0, c = 0, d = 0, i1 = 0, u = 0, h = e.querySelectorAll("div[style='width: 100%'] > a[href*='oculus.com/quest'] > div"), g = document.querySelector("[lang]").lang, f = e.querySelectorAll('a[ajaxify*="ad_id"] > span'), p = e.querySelectorAll('a[href*="ads/about"]');
                        if ("display: none !important;" != e.getAttribute("style") && !e.classList.contains("hidden_elem")) {
                            if (0 < f.length || 0 < p.length) {
                                t += 1;
                                var y = e.querySelectorAll("a[href]")[2].innerText;
                                console.log("--------"), console.log("Ad hidden from: " + y), console.log("Total ads hidden: " + t), console.log("F length: " + f.length), console.log("H length: " + p.length), console.log("--------"), e.style = "display:none!important;";
                            } else if (0 < h.length) {
                                t += 1;
                                y = "Facebook";
                                console.log("--------"), console.log("Ad hidden from: " + y), console.log("Total ads hidden: " + t), console.log("Non-declared ad"), console.log("--------"), e.style = "display:none!important;";
                            } else "af" == g ? o(e, "Geborg") : "de" == g || "nl" == g ? n1(e, "G", "e", "s", "n") : "am" == g ? o(e, "የተከፈለበት ማስታወቂያ") : "ar" == g ? o(e, "مُموَّل") : "as" == g ? o(e, "পৃষ্ঠপোষকতা কৰা") : "az" == g ? o(e, "Sponsor dəstəkli") : "co" == g ? o(e, "Spunsurizatu") : "bs" == g || "sl" == g || "cs" == g ? n1(e, "S", "p", "z", "n") : "da" == g || "en" == g || "et" == g || "fy" == g || "it" == g || "ku" == g || "nb" == g || "nn" == g || "pl" == g || "sq" == g || "sv" == g || "zz" == g ? document.querySelector("body").className.includes("Locale_en_UD") ? o(e, "pəɹosuodS") : n1(e, "S", "p", "s", "n") : "be" == g ? o(e, "Рэклама") : "bg" == g ? o(e, "Спонсорирано") : "mk" == g ? o(e, "Спонзорирано") : "br" == g ? o(e, "Paeroniet") : "ca" == g ? o(e, "Patrocinat") : "gl" == g || "pt" == g ? o(e, "Patrocinado") : "bn" == g ? o(e, "সৌজন্যে") : "cb" == g ? o(e, "پاڵپشتیکراو") : "cx" == g ? n1(e, "G", "i", "s", "n") : "cy" == g ? o(e, "Noddwyd") : "el" == g ? o(e, "Χορηγούμενη") : "eo" == g ? o(e, "Reklamo") : "es" == g ? n1(e, "P", "u", "c", "d") : "eu" == g ? o(e, "Babestua") : "fa" == g ? o(e, "دارای پشتیبانی مالی") : "ff" == g ? o(e, "Yoɓanaama") : "fi" == g ? o(e, "Sponsoroitu") : "fo" == g ? o(e, "Stuðlað") : "fr" == g ? document.querySelector("body").className.includes("Locale_fr_FR") ? n1(e, "S", "p", "s", "n") : n1(e, "C", "o", "m", "n") : "ga" == g ? o(e, "Urraithe") : "gn" == g ? o(e, "Oñepatrosinapyre") : "gu" == g ? o(e, "પ્રાયોજિત") : "ha" == g ? o(e, "Daukar Nauyi") : "he" == g ? o(e, "ממומן") : "hr" == g ? o(e, "Plaćeni oglas") : "ht" == g ? o(e, "Peye") : "ne" == g || "mr" == g || "hi" == g ? o(e, "प्रायोजित") : "hu" == g ? n1(e, "H", "i", "r", "d") : "hy" == g ? o(e, "Գովազդային") : "id" == g ? n1(e, "B", "e", "p", "n") : "is" == g ? o(e, "Kostað") : "ja" == g ? o(e, "広告") : "ms" == g ? o(e, "Ditaja") : "jv" == g ? o(e, "Disponsori") : "ka" == g ? o(e, "რეკლამა") : "kk" == g ? o(e, "Демеушілік көрсеткен") : "km" == g ? o(e, "បានឧបត្ថម្ភ") : "kn" == g ? o(e, "ಪ್ರಾಯೋಜಿತ") : "ko" == g ? o(e, "Sponsored") : "ky" == g ? o(e, "Демөөрчүлөнгөн") : "lo" == g ? o(e, "ຜູ້ສະໜັບສະໜູນ") : "lt" == g ? o(e, "Remiama") : "lv" == g ? o(e, "Apmaksāta reklāma") : "mg" == g ? o(e, "Misy Mpiantoka") : "ml" == g ? o(e, "സ്പോൺസർ ചെയ്തത്") : "mn" == g ? o(e, "Ивээн тэтгэсэн") : "mt" == g ? o(e, "Sponsorjat") : "my" == g ? o(e, "ပံ့ပိုးထားသည်") : "or" == g ? o(e, "ପ୍ରଯୋଜିତ") : "pa" == g ? o(e, "ਸਰਪ੍ਰਸਤੀ ਪ੍ਰਾਪਤ") : "ps" == g ? o(e, "تمويل شوي") : "ro" == g ? o(e, "Sponsorizat") : "ru" == g || "uk" == g ? o(e, "Реклама") : "rw" == g ? o(e, "Icyamamaza ndasukirwaho") : "sc" == g ? o(e, "Patronadu de") : "si" == g ? o(e, "අනුග්‍රාහක") : "sk" == g ? o(e, "Sponzorované") : "sn" == g ? o(e, "Zvabhadharirwa") : "so" == g ? o(e, "La maalgeliyey") : "sr" == g ? o(e, "Спонзорисано") : "sw" == g ? o(e, "Imedhaminiwa") : "sy" == g ? o(e, "ܒܘܕܩܐ ܡܡܘܘܢܐ") : "sz" == g ? o(e, "Szpōnzorowane") : "ta" == g ? o(e, "விளம்பரம்") : "te" == g ? o(e, "ప్రాయోజితం చేయబడింది") : "tg" == g ? o(e, "Бо сарпарастӣ") : "th" == g ? o(e, "ได้รับการสนับสนุน") : "tl" == g ? o(e, "May Sponsor") : "tr" == g ? o(e, "Sponsorlu") : "tt" == g ? o(e, "Хәйрияче") : "tz" == g ? o(e, "ⵉⴷⵍ") : "ur" == g ? o(e, "سپانسرڈ") : "uz" == g ? o(e, "Reklama") : "vi" == g ? o(e, "Được tài trợ") : "zh-Hans" == g ? o(e, "赞助内容") : "zh-Hant" == g && o(e, "贊助");
                            if (0 < c.length && 0 < d.length && 0 < i1.length && 0 < u.length) {
                                for(cont = 0; cont < c.length; cont++)0 < c[cont].offsetHeight && (cont = c.length, a = 1);
                                for(cont1 = 0; cont1 < d.length; cont1++)0 < d[cont1].offsetHeight && (cont1 = d.length, l = 1);
                                for(cont2 = 0; cont2 < i1.length; cont2++)0 < i1[cont2].offsetHeight && (cont2 = i1.length, r = 1);
                                for(cont3 = 0; cont3 < u.length; cont3++)0 < u[cont3].offsetHeight && (cont3 = u.length, s = 1);
                                if (1 == a && 1 == l && 1 == r && 1 == s) {
                                    y = e.querySelectorAll("a[href]")[2].innerText;
                                    t += 1, console.log("--------"), console.log("Ad hidden from: " + y), console.log("Total ads hidden: " + t), console.log("--------"), e.style = "display:none!important;";
                                }
                            }
                        }
                    });
                }), t = 0;
                e.observe(document, {
                    childList: !0,
                    subtree: !0,
                    characterData: !0,
                    attributes: !0
                });
            }();
            Object.defineProperty(Window.prototype.toString, "c20e5794d5ff5adb72bad3179e0fd5f5", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "c20e5794d5ff5adb72bad3179e0fd5f5" due to: ' + e);
        }
    },
    '!function(){var e,o;0<window.location.href.indexOf("marketplace")&&(e=new MutationObserver(function(){document.querySelectorAll(\'div[role="main"] div[class][style^="max-width:"] div[class][style^="max-width:"]\').forEach(function(e){var l,t=e.querySelectorAll(\'a[href*="ads/about"]\');"display: none !important;"==e.getAttribute("style")||e.classList.contains("hidden_elem")||0<t.length&&(o+=1,""==(l=e.querySelectorAll("a[href]")[0].innerText)&&(l=e.querySelectorAll("a[href]")[1].innerText),""==l&&(l=e.querySelectorAll("a[href]")[0].querySelectorAll("a[aria-label]")[0]?.getAttribute("aria-label")),console.log("--------"),console.log("Ad hidden from: "+l),console.log("Total ads hidden: "+o),console.log("H length: "+t.length),console.log("--------"),e.style="display:none!important;")})}),o=0,e.observe(document,{childList:!0,subtree:!0}))}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.e6189b04febc53c553beba1616cdd078 === e) return;
            !function() {
                var e, t;
                0 < window.location.href.indexOf("marketplace") && (e = new MutationObserver(function() {
                    document.querySelectorAll('div[role="main"] div[class][style^="max-width:"] div[class][style^="max-width:"]').forEach(function(e) {
                        var _e_querySelectorAll__querySelectorAll_;
                        var o, l = e.querySelectorAll('a[href*="ads/about"]');
                        "display: none !important;" == e.getAttribute("style") || e.classList.contains("hidden_elem") || 0 < l.length && (t += 1, "" == (o = e.querySelectorAll("a[href]")[0].innerText) && (o = e.querySelectorAll("a[href]")[1].innerText), "" == o && (o = (_e_querySelectorAll__querySelectorAll_ = e.querySelectorAll("a[href]")[0].querySelectorAll("a[aria-label]")[0]) === null || _e_querySelectorAll__querySelectorAll_ === void 0 ? void 0 : _e_querySelectorAll__querySelectorAll_.getAttribute("aria-label")), console.log("--------"), console.log("Ad hidden from: " + o), console.log("Total ads hidden: " + t), console.log("H length: " + l.length), console.log("--------"), e.style = "display:none!important;");
                    });
                }), t = 0, e.observe(document, {
                    childList: !0,
                    subtree: !0
                }));
            }();
            Object.defineProperty(Window.prototype.toString, "e6189b04febc53c553beba1616cdd078", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "e6189b04febc53c553beba1616cdd078" due to: ' + e);
        }
    },
    '!function(){new MutationObserver(function(){document.querySelectorAll("div[role=\\"main\\"] div[class][style^=\\"max-width:\\"] div[class][style*=\\"max-width:\\"]:not([style*=\\"display: none\\"])").forEach(function(c){Object.keys(c).forEach(function(a){if(a.includes("__reactEvents")||a.includes("__reactProps")){a=c[a];try{a.children?.props?.adSurface?.startsWith("Marketplace")&&(c.style="display: none !important;")}catch(a){}}})})}).observe(document,{childList:!0,subtree:!0})}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["9201edecacad19e52ef0fb416ec8c902"] === e) return;
            new MutationObserver(function() {
                document.querySelectorAll('div[role="main"] div[class][style^="max-width:"] div[class][style*="max-width:"]:not([style*="display: none"])').forEach(function(e) {
                    Object.keys(e).forEach(function(t) {
                        if (t.includes("__reactEvents") || t.includes("__reactProps")) {
                            t = e[t];
                            try {
                                var _t_children_props_adSurface, _t_children_props, _t_children;
                                ((_t_children = t.children) === null || _t_children === void 0 ? void 0 : (_t_children_props = _t_children.props) === null || _t_children_props === void 0 ? void 0 : (_t_children_props_adSurface = _t_children_props.adSurface) === null || _t_children_props_adSurface === void 0 ? void 0 : _t_children_props_adSurface.startsWith("Marketplace")) && (e.style = "display: none !important;");
                            } catch (t) {}
                        }
                    });
                });
            }).observe(document, {
                childList: !0,
                subtree: !0
            });
            Object.defineProperty(Window.prototype.toString, "9201edecacad19e52ef0fb416ec8c902", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "9201edecacad19e52ef0fb416ec8c902" due to: ' + e);
        }
    },
    '!function(){if(window.location.href.includes("/marketplace/")){new MutationObserver(function(){document.querySelectorAll(\'div[data-testid="marketplace_home_feed"] div[class][data-testid^="MarketplaceUpsell-"] > div > div\').forEach(function(e){var t=e.outerHTML;t&&void 0!==t&&!0===t.includes("/ads/about/")&&(e.style="display:none!important;")})}).observe(document,{childList:!0,subtree:!0})}}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["53a0bb610abe908070c9b157e3ec2214"] === e) return;
            window.location.href.includes("/marketplace/") && new MutationObserver(function() {
                document.querySelectorAll('div[data-testid="marketplace_home_feed"] div[class][data-testid^="MarketplaceUpsell-"] > div > div').forEach(function(e) {
                    var t = e.outerHTML;
                    t && void 0 !== t && !0 === t.includes("/ads/about/") && (e.style = "display:none!important;");
                });
            }).observe(document, {
                childList: !0,
                subtree: !0
            });
            Object.defineProperty(Window.prototype.toString, "53a0bb610abe908070c9b157e3ec2214", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "53a0bb610abe908070c9b157e3ec2214" due to: ' + e);
        }
    },
    "(function(){var c=document.addEventListener;document.addEventListener=function(a,b,d,e){\"click\"!=a&&-1==b.toString().indexOf('about:blank')&&c(a,b,d,e)}.bind(document);})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.b178c9ef485593de3d7ea5826bcd32c2 === e) return;
            !function() {
                var e = document.addEventListener;
                document.addEventListener = (function(t, n1, d, o) {
                    "click" != t && -1 == n1.toString().indexOf("about:blank") && e(t, n1, d, o);
                }).bind(document);
            }();
            Object.defineProperty(Window.prototype.toString, "b178c9ef485593de3d7ea5826bcd32c2", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "b178c9ef485593de3d7ea5826bcd32c2" due to: ' + e);
        }
    },
    "(function(){var b=window.setTimeout;window.setTimeout=function(a,c){if(!/Object\\[/.test(a.toString()))return b(a,c)};})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["3b230fa3fd4e2e2f5fa5fd1889bef31f"] === e) return;
            !function() {
                var e = window.setTimeout;
                window.setTimeout = function(t, f) {
                    if (!/Object\[/.test(t.toString())) return e(t, f);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "3b230fa3fd4e2e2f5fa5fd1889bef31f", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "3b230fa3fd4e2e2f5fa5fd1889bef31f" due to: ' + e);
        }
    },
    '(function(){Object.defineProperty(window,"open",{writable:!1,enumerable:!1,configurable:!1,value:window.open})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["6ad868fcfeb6310fe49001d70d33c6cc"] === e) return;
            Object.defineProperty(window, "open", {
                writable: !1,
                enumerable: !1,
                configurable: !1,
                value: window.open
            });
            Object.defineProperty(Window.prototype.toString, "6ad868fcfeb6310fe49001d70d33c6cc", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "6ad868fcfeb6310fe49001d70d33c6cc" due to: ' + e);
        }
    },
    "Object.defineProperty(window, 'sas_manager', { get: function() { return { noad: function() {} }; }, set: function() {} });": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["28fca7a5881cbf189a14d7cdf5e6b931"] === e) return;
            Object.defineProperty(window, "sas_manager", {
                get: function() {
                    return {
                        noad: function() {}
                    };
                },
                set: function() {}
            });
            Object.defineProperty(Window.prototype.toString, "28fca7a5881cbf189a14d7cdf5e6b931", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "28fca7a5881cbf189a14d7cdf5e6b931" due to: ' + e);
        }
    },
    "(function(){var c=document.addEventListener;document.addEventListener=function(a,b,d,e){\"click\"!=a&&-1==b.toString().indexOf('.hi()')&&c(a,b,d,e)}.bind(document);})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.fe0404e371f4ffecdbfb5cb284c5f6a9 === e) return;
            !function() {
                var e = document.addEventListener;
                document.addEventListener = (function(t, n1, f, c) {
                    "click" != t && -1 == n1.toString().indexOf(".hi()") && e(t, n1, f, c);
                }).bind(document);
            }();
            Object.defineProperty(Window.prototype.toString, "fe0404e371f4ffecdbfb5cb284c5f6a9", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "fe0404e371f4ffecdbfb5cb284c5f6a9" due to: ' + e);
        }
    },
    '(function(){var c=document.addEventListener;document.addEventListener=function(a,b,d,e){"click"!=a&&-1==b.toString().indexOf(\'"dtnoppu"\')&&c(a,b,d,e)}.bind(document);})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["151b026ff6ad3e430ea55419ab72ee6d"] === e) return;
            !function() {
                var e = document.addEventListener;
                document.addEventListener = (function(t, n1, o, r) {
                    "click" != t && -1 == n1.toString().indexOf('"dtnoppu"') && e(t, n1, o, r);
                }).bind(document);
            }();
            Object.defineProperty(Window.prototype.toString, "151b026ff6ad3e430ea55419ab72ee6d", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "151b026ff6ad3e430ea55419ab72ee6d" due to: ' + e);
        }
    },
    'window["pop_clicked"] = 1;': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["7388e0f8018a3f9b99906510f5d32edd"] === e) return;
            window.pop_clicked = 1;
            Object.defineProperty(Window.prototype.toString, "7388e0f8018a3f9b99906510f5d32edd", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "7388e0f8018a3f9b99906510f5d32edd" due to: ' + e);
        }
    },
    "document.addEventListener('DOMContentLoaded', function() { if (window.location.href.indexOf(\"hpinterstitialnew.html\") != -1) { window.setCookie1('sitecapture_interstitial', 1, 1); window.location.href = \"http://www.ndtv.com/\"; } })": ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString["9c145fd1fa9c4877477d33378243415b"] === t) return;
            document.addEventListener("DOMContentLoaded", function() {
                if (-1 != window.location.href.indexOf("hpinterstitialnew.html")) {
                    window.setCookie1("sitecapture_interstitial", 1, 1);
                    window.location.href = "http://www.ndtv.com/";
                }
            });
            Object.defineProperty(Window.prototype.toString, "9c145fd1fa9c4877477d33378243415b", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "9c145fd1fa9c4877477d33378243415b" due to: ' + t);
        }
    },
    "window.exo99HL3903jjdxtrnLoad = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.ba561ed0ab3a43ea4e1d5efa8fb5a465 === e) return;
            window.exo99HL3903jjdxtrnLoad = !0;
            Object.defineProperty(Window.prototype.toString, "ba561ed0ab3a43ea4e1d5efa8fb5a465", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "ba561ed0ab3a43ea4e1d5efa8fb5a465" due to: ' + e);
        }
    },
    '(()=>{document.addEventListener("DOMContentLoaded",(()=>{ prerollskip(); setTimeout(function() { prerollskip(); }, 100); setTimeout(function() { prerollskip(); }, 300); }));})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.bea12eedfd9b904b94659dc26fd1e724 === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                prerollskip();
                setTimeout(function() {
                    prerollskip();
                }, 100);
                setTimeout(function() {
                    prerollskip();
                }, 300);
            });
            Object.defineProperty(Window.prototype.toString, "bea12eedfd9b904b94659dc26fd1e724", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "bea12eedfd9b904b94659dc26fd1e724" due to: ' + e);
        }
    },
    "!function(a,b){b=new MutationObserver(function(){a.classList.contains('idle')&&a.classList.remove('idle')}),b.observe(a,{attributes:!0,attributeFilter:['class']})}(document.documentElement);": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["58ce3922fa2965f0d4a1f9e3d1857281"] === e) return;
            !function(e) {
                new MutationObserver(function() {
                    e.classList.contains("idle") && e.classList.remove("idle");
                }).observe(e, {
                    attributes: !0,
                    attributeFilter: [
                        "class"
                    ]
                });
            }(document.documentElement);
            Object.defineProperty(Window.prototype.toString, "58ce3922fa2965f0d4a1f9e3d1857281", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "58ce3922fa2965f0d4a1f9e3d1857281" due to: ' + e);
        }
    },
    "window.canRunAds = !0;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["34f856bab5f3c1916f563203a5ea7281"] === e) return;
            window.canRunAds = !0;
            Object.defineProperty(Window.prototype.toString, "34f856bab5f3c1916f563203a5ea7281", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "34f856bab5f3c1916f563203a5ea7281" due to: ' + e);
        }
    },
    "window.myatu_bgm = 0;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.cdba7f77c6423f0c201c738bf909c4e8 === e) return;
            window.myatu_bgm = 0;
            Object.defineProperty(Window.prototype.toString, "cdba7f77c6423f0c201c738bf909c4e8", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "cdba7f77c6423f0c201c738bf909c4e8" due to: ' + e);
        }
    },
    "window.runad = function() {};": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["958f02264ba3a90c77c6ba0c98ad72ce"] === e) return;
            window.runad = function() {};
            Object.defineProperty(Window.prototype.toString, "958f02264ba3a90c77c6ba0c98ad72ce", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "958f02264ba3a90c77c6ba0c98ad72ce" due to: ' + e);
        }
    },
    "setTimeout(function() { window.show_popup=false; window.download_inited = true; }, 300);": ()=>{
        try {
            const o = "done";
            if (Window.prototype.toString.dc40c845363864583b847cd52bfc4bd3 === o) return;
            setTimeout(function() {
                window.show_popup = !1;
                window.download_inited = !0;
            }, 300);
            Object.defineProperty(Window.prototype.toString, "dc40c845363864583b847cd52bfc4bd3", {
                value: o,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (o) {
            console.error('Error executing AG js rule with uniqueId "dc40c845363864583b847cd52bfc4bd3" due to: ' + o);
        }
    },
    "function setOverlayHTML() {};": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.cc37d89d454cab3a16143f6e2ea4a4f3 === e) return;
            function setOverlayHTML() {}
            Object.defineProperty(Window.prototype.toString, "cc37d89d454cab3a16143f6e2ea4a4f3", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (r) {
            console.error('Error executing AG js rule with uniqueId "cc37d89d454cab3a16143f6e2ea4a4f3" due to: ' + r);
        }
    },
    "function setOverlayHTML_new() {};": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["085c413105051fb148c3d7a6bf82b5c3"] === e) return;
            function setOverlayHTML_new() {}
            Object.defineProperty(Window.prototype.toString, "085c413105051fb148c3d7a6bf82b5c3", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (r) {
            console.error('Error executing AG js rule with uniqueId "085c413105051fb148c3d7a6bf82b5c3" due to: ' + r);
        }
    },
    "setTimeout(removeOverlayHTML, 2000);": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.b94a9a08e8bfdbb7535bd54ba79a2610 === e) return;
            setTimeout(removeOverlayHTML, 2e3);
            Object.defineProperty(Window.prototype.toString, "b94a9a08e8bfdbb7535bd54ba79a2610", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "b94a9a08e8bfdbb7535bd54ba79a2610" due to: ' + e);
        }
    },
    '(()=>{const e="loader.min.js",t={includes:String.prototype.includes,filter:Array.prototype.filter},l=()=>(new Error).stack,n={construct:(n,o,r)=>{const c=l();return t.includes.call(c,e)&&o[0]&&t.includes.call(o[0],"adshield")&&(o[0]=["(function(){})();"]),Reflect.construct(n,o,r)}};window.Blob=new Proxy(window.Blob,n);const o={apply:(n,o,r)=>{const c=l();return t.includes.call(c,e)&&r[0]&&t.includes.call(r[0],"new Error")&&(r[0]=()=>{}),Reflect.apply(n,o,r)}};window.setTimeout=new Proxy(window.setTimeout,o);const r={apply:(n,o,r)=>{const c=l();return t.includes.call(c,e)&&r[0]&&o?.includes?.("setTimeout")&&(o=t.filter.call(o,(e=>!t.includes.call(e,"setTimeout")))),Reflect.apply(n,o,r)}};window.Array.prototype.filter=new Proxy(window.Array.prototype.filter,r)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["10c10bf4c1c0b9946b322ae5e709306d"] === e) return;
            (()=>{
                const e = "loader.min.js", t = {
                    includes: String.prototype.includes,
                    filter: Array.prototype.filter
                }, r = ()=>(new Error).stack, o = {
                    construct: (o, n1, c)=>{
                        const l = r();
                        return t.includes.call(l, e) && n1[0] && t.includes.call(n1[0], "adshield") && (n1[0] = [
                            "(function(){})();"
                        ]), Reflect.construct(o, n1, c);
                    }
                };
                window.Blob = new Proxy(window.Blob, o);
                const n1 = {
                    apply: (o, n1, c)=>{
                        const l = r();
                        return t.includes.call(l, e) && c[0] && t.includes.call(c[0], "new Error") && (c[0] = ()=>{}), Reflect.apply(o, n1, c);
                    }
                };
                window.setTimeout = new Proxy(window.setTimeout, n1);
                const c = {
                    apply: (o, n1, c)=>{
                        var _n_includes;
                        const l = r();
                        return t.includes.call(l, e) && c[0] && (n1 === null || n1 === void 0 ? void 0 : (_n_includes = n1.includes) === null || _n_includes === void 0 ? void 0 : _n_includes.call(n1, "setTimeout")) && (n1 = t.filter.call(n1, (e)=>!t.includes.call(e, "setTimeout"))), Reflect.apply(o, n1, c);
                    }
                };
                window.Array.prototype.filter = new Proxy(window.Array.prototype.filter, c);
            })();
            Object.defineProperty(Window.prototype.toString, "10c10bf4c1c0b9946b322ae5e709306d", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "10c10bf4c1c0b9946b322ae5e709306d" due to: ' + e);
        }
    },
    '(()=>{const e={apply:(e,l,o)=>"link"===o[0]||"style"===o[0]?[]:Reflect.apply(e,l,o)};window.document.querySelectorAll=new Proxy(window.document.querySelectorAll,e)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["5662f0dae824e1b38f13e27f256c2066"] === e) return;
            (()=>{
                const e = {
                    apply: (e, o, t)=>"link" === t[0] || "style" === t[0] ? [] : Reflect.apply(e, o, t)
                };
                window.document.querySelectorAll = new Proxy(window.document.querySelectorAll, e);
            })();
            Object.defineProperty(Window.prototype.toString, "5662f0dae824e1b38f13e27f256c2066", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "5662f0dae824e1b38f13e27f256c2066" due to: ' + e);
        }
    },
    '(()=>{const e={apply:(e,t,n)=>{const o=Reflect.apply(e,t,n);try{o instanceof HTMLIFrameElement&&"about:blank"===o.src&&o.contentWindow&&(o.contentWindow.fetch=window.fetch,o.contentWindow.Request=window.Request)}catch(e){}return o}};Node.prototype.appendChild=new Proxy(Node.prototype.appendChild,e)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.b2938935474adeb9fa9f991bc00ad666 === e) return;
            (()=>{
                const e = {
                    apply: (e, t, o)=>{
                        const n1 = Reflect.apply(e, t, o);
                        try {
                            n1 instanceof HTMLIFrameElement && "about:blank" === n1.src && n1.contentWindow && (n1.contentWindow.fetch = window.fetch, n1.contentWindow.Request = window.Request);
                        } catch (e) {}
                        return n1;
                    }
                };
                Node.prototype.appendChild = new Proxy(Node.prototype.appendChild, e);
            })();
            Object.defineProperty(Window.prototype.toString, "b2938935474adeb9fa9f991bc00ad666", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "b2938935474adeb9fa9f991bc00ad666" due to: ' + e);
        }
    },
    '(()=>{const t={apply:(t,o,n)=>{const e=n[0];return"function"==typeof e&&e.toString().includes("onAbnormalityDetected")&&(n[0]=function(){}),Reflect.apply(t,o,n)}};window.Promise.prototype.then=new Proxy(window.Promise.prototype.then,t)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.b149f5f8f73c8f7b2b21d20e1538bea4 === e) return;
            (()=>{
                const e = {
                    apply: (e, t, o)=>{
                        const n1 = o[0];
                        return "function" == typeof n1 && n1.toString().includes("onAbnormalityDetected") && (o[0] = function() {}), Reflect.apply(e, t, o);
                    }
                };
                window.Promise.prototype.then = new Proxy(window.Promise.prototype.then, e);
            })();
            Object.defineProperty(Window.prototype.toString, "b149f5f8f73c8f7b2b21d20e1538bea4", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "b149f5f8f73c8f7b2b21d20e1538bea4" due to: ' + e);
        }
    },
    '(()=>{if(Object.getOwnPropertyDescriptor(window.JSON,"stringify").writable)return;const e={construct:(e,c,r)=>{try{const e=c[0],r=c[1]?.body;e?.includes("youtubei")&&r?.includes(\'"clientScreen":"WATCH"\')&&(c[1].body=r.replace(\'"clientScreen":"WATCH"\',\'"clientScreen":"ADUNIT"\'))}catch(e){console.trace("Error occurred:",e)}return Reflect.construct(e,c,r)}};window.Request=new Proxy(window.Request,e)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["91f888c248ca41605ecc865ebb74a447"] === e) return;
            (()=>{
                if (Object.getOwnPropertyDescriptor(window.JSON, "stringify").writable) return;
                const e = {
                    construct: (e, c, r)=>{
                        try {
                            var _c_;
                            const e = c[0], r = (_c_ = c[1]) === null || _c_ === void 0 ? void 0 : _c_.body;
                            (e === null || e === void 0 ? void 0 : e.includes("youtubei")) && (r === null || r === void 0 ? void 0 : r.includes('"clientScreen":"WATCH"')) && (c[1].body = r.replace('"clientScreen":"WATCH"', '"clientScreen":"ADUNIT"'));
                        } catch (e) {
                            console.trace("Error occurred:", e);
                        }
                        return Reflect.construct(e, c, r);
                    }
                };
                window.Request = new Proxy(window.Request, e);
            })();
            Object.defineProperty(Window.prototype.toString, "91f888c248ca41605ecc865ebb74a447", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "91f888c248ca41605ecc865ebb74a447" due to: ' + e);
        }
    },
    '(()=>{let t=document.location.href,e=[],n=[],o="",r=!1;const i=Array.prototype.push,a={apply:(t,o,a)=>(window.yt?.config_?.EXPERIMENT_FLAGS?.html5_enable_ssap_entity_id&&a[0]&&a[0]!==window&&"number"==typeof a[0].start&&a[0].end&&"ssap"===a[0].namespace&&a[0].id&&(r||0!==a[0]?.start||n.includes(a[0].id)||(e.length=0,n.length=0,r=!0,i.call(e,a[0]),i.call(n,a[0].id)),r&&0!==a[0]?.start&&!n.includes(a[0].id)&&(i.call(e,a[0]),i.call(n,a[0].id))),Reflect.apply(t,o,a))};window.Array.prototype.push=new Proxy(window.Array.prototype.push,a),document.addEventListener("DOMContentLoaded",(function(){if(!window.yt?.config_?.EXPERIMENT_FLAGS?.html5_enable_ssap_entity_id)return;const i=()=>{const t=document.querySelector("video");if(t&&e.length){const i=Math.round(t.duration),a=Math.round(e.at(-1).end/1e3),c=n.join(",");if(!1===t.loop&&o!==c&&i&&i===a){const n=e.at(-1).start/1e3;t.currentTime<n&&(t.currentTime=n,r=!1,o=c)}else if(!0===t.loop&&i&&i===a){const n=e.at(-1).start/1e3;t.currentTime<n&&(t.currentTime=n,r=!1,o=c)}}};i();new MutationObserver((()=>{t!==document.location.href&&(t=document.location.href,e.length=0,n.length=0,r=!1),i()})).observe(document,{childList:!0,subtree:!0})}))})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.ae4fa77cc5169989696ccbb4288099b4 === e) return;
            (()=>{
                let e = document.location.href, t = [], n1 = [], o = "", r = !1;
                const c = Array.prototype.push, i1 = {
                    apply: (e, o, i1)=>{
                        var _window_yt_config__EXPERIMENT_FLAGS, _window_yt_config_, _window_yt, _i_, _i_1;
                        return ((_window_yt = window.yt) === null || _window_yt === void 0 ? void 0 : (_window_yt_config_ = _window_yt.config_) === null || _window_yt_config_ === void 0 ? void 0 : (_window_yt_config__EXPERIMENT_FLAGS = _window_yt_config_.EXPERIMENT_FLAGS) === null || _window_yt_config__EXPERIMENT_FLAGS === void 0 ? void 0 : _window_yt_config__EXPERIMENT_FLAGS.html5_enable_ssap_entity_id) && i1[0] && i1[0] !== window && "number" == typeof i1[0].start && i1[0].end && "ssap" === i1[0].namespace && i1[0].id && (r || 0 !== ((_i_ = i1[0]) === null || _i_ === void 0 ? void 0 : _i_.start) || n1.includes(i1[0].id) || (t.length = 0, n1.length = 0, r = !0, c.call(t, i1[0]), c.call(n1, i1[0].id)), r && 0 !== ((_i_1 = i1[0]) === null || _i_1 === void 0 ? void 0 : _i_1.start) && !n1.includes(i1[0].id) && (c.call(t, i1[0]), c.call(n1, i1[0].id))), Reflect.apply(e, o, i1);
                    }
                };
                window.Array.prototype.push = new Proxy(window.Array.prototype.push, i1), document.addEventListener("DOMContentLoaded", function() {
                    var _window_yt_config__EXPERIMENT_FLAGS, _window_yt_config_, _window_yt;
                    if (!((_window_yt = window.yt) === null || _window_yt === void 0 ? void 0 : (_window_yt_config_ = _window_yt.config_) === null || _window_yt_config_ === void 0 ? void 0 : (_window_yt_config__EXPERIMENT_FLAGS = _window_yt_config_.EXPERIMENT_FLAGS) === null || _window_yt_config__EXPERIMENT_FLAGS === void 0 ? void 0 : _window_yt_config__EXPERIMENT_FLAGS.html5_enable_ssap_entity_id)) return;
                    const c = ()=>{
                        const e = document.querySelector("video");
                        if (e && t.length) {
                            const c = Math.round(e.duration), i1 = Math.round(t.at(-1).end / 1e3), a = n1.join(",");
                            if (!1 === e.loop && o !== a && c && c === i1) {
                                const n1 = t.at(-1).start / 1e3;
                                e.currentTime < n1 && (e.currentTime = n1, r = !1, o = a);
                            } else if (!0 === e.loop && c && c === i1) {
                                const n1 = t.at(-1).start / 1e3;
                                e.currentTime < n1 && (e.currentTime = n1, r = !1, o = a);
                            }
                        }
                    };
                    c();
                    new MutationObserver(()=>{
                        e !== document.location.href && (e = document.location.href, t.length = 0, n1.length = 0, r = !1), c();
                    }).observe(document, {
                        childList: !0,
                        subtree: !0
                    });
                });
            })();
            Object.defineProperty(Window.prototype.toString, "ae4fa77cc5169989696ccbb4288099b4", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "ae4fa77cc5169989696ccbb4288099b4" due to: ' + e);
        }
    },
    '(()=>{window.JSON.parse=new Proxy(JSON.parse,{apply(r,e,t){const n=Reflect.apply(r,e,t);if(!location.pathname.startsWith("/shorts/"))return n;const a=n?.entries;return a&&Array.isArray(a)&&(n.entries=n.entries.filter((r=>{if(!r?.command?.reelWatchEndpoint?.adClientParams?.isAd)return r}))),n}});})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.f4df2111ba88e1c013b85786c3efab38 === e) return;
            window.JSON.parse = new Proxy(JSON.parse, {
                apply (e, r, t) {
                    const n1 = Reflect.apply(e, r, t);
                    if (!location.pathname.startsWith("/shorts/")) return n1;
                    const a = n1 === null || n1 === void 0 ? void 0 : n1.entries;
                    return a && Array.isArray(a) && (n1.entries = n1.entries.filter((e)=>{
                        var _e_command_reelWatchEndpoint_adClientParams, _e_command_reelWatchEndpoint, _e_command;
                        if (!(e === null || e === void 0 ? void 0 : (_e_command = e.command) === null || _e_command === void 0 ? void 0 : (_e_command_reelWatchEndpoint = _e_command.reelWatchEndpoint) === null || _e_command_reelWatchEndpoint === void 0 ? void 0 : (_e_command_reelWatchEndpoint_adClientParams = _e_command_reelWatchEndpoint.adClientParams) === null || _e_command_reelWatchEndpoint_adClientParams === void 0 ? void 0 : _e_command_reelWatchEndpoint_adClientParams.isAd)) return e;
                    })), n1;
                }
            });
            Object.defineProperty(Window.prototype.toString, "f4df2111ba88e1c013b85786c3efab38", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "f4df2111ba88e1c013b85786c3efab38" due to: ' + e);
        }
    },
    '(()=>{const t="/file/";if(!location.pathname.includes(t))return;const e=(new Date).toISOString(),n=location.pathname.split(t)[1];document.cookie=`adsRedirect_${n}=${e}; path=/;`})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["2e6eacfae44118fb1fa0397d0470917e"] === e) return;
            (()=>{
                const e = "/file/";
                if (!location.pathname.includes(e)) return;
                const t = (new Date).toISOString(), o = location.pathname.split(e)[1];
                document.cookie = `adsRedirect_${o}=${t}; path=/;`;
            })();
            Object.defineProperty(Window.prototype.toString, "2e6eacfae44118fb1fa0397d0470917e", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "2e6eacfae44118fb1fa0397d0470917e" due to: ' + e);
        }
    },
    '(()=>{document.addEventListener("DOMContentLoaded",(()=>{document.querySelectorAll(\'a[href^="https://af.gog.com/game/"]\').forEach((t=>{const e=t.getAttribute("href").replace("https://af.gog.com/","https://www.gog.com/");t.setAttribute("href",e)}))}));})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["639105ecfaab3d5ad7901b589aedc339"] === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                document.querySelectorAll('a[href^="https://af.gog.com/game/"]').forEach((e)=>{
                    const t = e.getAttribute("href").replace("https://af.gog.com/", "https://www.gog.com/");
                    e.setAttribute("href", t);
                });
            });
            Object.defineProperty(Window.prototype.toString, "639105ecfaab3d5ad7901b589aedc339", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "639105ecfaab3d5ad7901b589aedc339" due to: ' + e);
        }
    },
    'window.addEventListener("load",(()=>{window.stop()}));': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["30a2cb89c6bbab38b94dced993fe90d2"] === e) return;
            window.addEventListener("load", ()=>{
                window.stop();
            });
            Object.defineProperty(Window.prototype.toString, "30a2cb89c6bbab38b94dced993fe90d2", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "30a2cb89c6bbab38b94dced993fe90d2" due to: ' + e);
        }
    },
    '(()=>{const e={apply:(e,t,n)=>{try{const[e,r]=n,a=r?.toString();if("click"===e&&a?.includes("attached")&&t instanceof HTMLElement&&t.matches(".share-embed-container"))return}catch(e){}return Reflect.apply(e,t,n)}};window.EventTarget.prototype.addEventListener=new Proxy(window.EventTarget.prototype.addEventListener,e)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["671bbc53b2753ab1de38c607e44cff6b"] === e) return;
            (()=>{
                const e = {
                    apply: (e, t, r)=>{
                        try {
                            const [e, n1] = r, o = n1 === null || n1 === void 0 ? void 0 : n1.toString();
                            if ("click" === e && (o === null || o === void 0 ? void 0 : o.includes("attached")) && t instanceof HTMLElement && t.matches(".share-embed-container")) return;
                        } catch (e) {}
                        return Reflect.apply(e, t, r);
                    }
                };
                window.EventTarget.prototype.addEventListener = new Proxy(window.EventTarget.prototype.addEventListener, e);
            })();
            Object.defineProperty(Window.prototype.toString, "671bbc53b2753ab1de38c607e44cff6b", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "671bbc53b2753ab1de38c607e44cff6b" due to: ' + e);
        }
    },
    'document.cookie="dl-mobile-banner=hidden;path=/";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["8b440f9710dbfd56131d1f8c2abc993c"] === e) return;
            document.cookie = "dl-mobile-banner=hidden;path=/";
            Object.defineProperty(Window.prototype.toString, "8b440f9710dbfd56131d1f8c2abc993c", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "8b440f9710dbfd56131d1f8c2abc993c" due to: ' + e);
        }
    },
    'document.cookie="downloadcta-state=hidden;path=/";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["1d980de172103bc108eaf73424fc9bb2"] === e) return;
            document.cookie = "downloadcta-state=hidden;path=/";
            Object.defineProperty(Window.prototype.toString, "1d980de172103bc108eaf73424fc9bb2", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "1d980de172103bc108eaf73424fc9bb2" due to: ' + e);
        }
    },
    '(function(){-1==document.cookie.indexOf("native-app-topper")&&(document.cookie="native-app-topper="+Date.now()+"; path=/;",location.reload())})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["9d74c934588df2de463c39e31e3adc10"] === e) return;
            -1 == document.cookie.indexOf("native-app-topper") && (document.cookie = "native-app-topper=" + Date.now() + "; path=/;", location.reload());
            Object.defineProperty(Window.prototype.toString, "9d74c934588df2de463c39e31e3adc10", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "9d74c934588df2de463c39e31e3adc10" due to: ' + e);
        }
    },
    '(function(){var a=new Date;a=a.getFullYear()+"-"+(a.getMonth()+1)+"-"+a.getDate();document.cookie="closed="+a})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.fe33bd03974a18f9ee09ea4bd62ae980 === e) return;
            !function() {
                var e = new Date;
                e = e.getFullYear() + "-" + (e.getMonth() + 1) + "-" + e.getDate();
                document.cookie = "closed=" + e;
            }();
            Object.defineProperty(Window.prototype.toString, "fe33bd03974a18f9ee09ea4bd62ae980", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "fe33bd03974a18f9ee09ea4bd62ae980" due to: ' + e);
        }
    },
    'document.cookie="com.digidust.elokence.akinator.freemium-smartbanner-closed=true; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["6e884abc83f56c42a030fb5b7c6a7e21"] === e) return;
            document.cookie = "com.digidust.elokence.akinator.freemium-smartbanner-closed=true; path=/;";
            Object.defineProperty(Window.prototype.toString, "6e884abc83f56c42a030fb5b7c6a7e21", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "6e884abc83f56c42a030fb5b7c6a7e21" due to: ' + e);
        }
    },
    'document.cookie="sb-closed=true; path=/;";': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["5d933778415cb98cdeaf6df08d1c3ad3"] === e) return;
            document.cookie = "sb-closed=true; path=/;";
            Object.defineProperty(Window.prototype.toString, "5d933778415cb98cdeaf6df08d1c3ad3", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "5d933778415cb98cdeaf6df08d1c3ad3" due to: ' + e);
        }
    },
    "(function(){var b=window.setTimeout;window.setTimeout=function(a,c){if(!/loadAppStoreBanner/.test(a.toString()))return b(a,c)};})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["4a9a4c88d375de003f5ff00b3d926a2e"] === e) return;
            !function() {
                var e = window.setTimeout;
                window.setTimeout = function(t, o) {
                    if (!/loadAppStoreBanner/.test(t.toString())) return e(t, o);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "4a9a4c88d375de003f5ff00b3d926a2e", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "4a9a4c88d375de003f5ff00b3d926a2e" due to: ' + e);
        }
    },
    '(()=>{var b=EventTarget.prototype.addEventListener,c=function(a,b){var c=document.querySelector("button.AppHeader-login");c&&b.bind(c)("click",function(){d.disconnect()},{once:!0})},d=new MutationObserver(function(){var a=document.querySelector(".Modal-wrapper .signFlowModal > .Modal-closeButton");a&&(d.disconnect(),e.disconnect(),a.click())});d.observe(document,{childList:!0,subtree:!0});var e=new MutationObserver(a=>{c(a,b)});e.observe(document,{childList:!0,subtree:!0}),setTimeout(function(){e.disconnect(),d.disconnect()},5E3)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["41bf8021e5a5f51b455d8d18dce0c4d0"] === e) return;
            (()=>{
                var e = EventTarget.prototype.addEventListener, t = new MutationObserver(function() {
                    var e = document.querySelector(".Modal-wrapper .signFlowModal > .Modal-closeButton");
                    e && (t.disconnect(), n1.disconnect(), e.click());
                });
                t.observe(document, {
                    childList: !0,
                    subtree: !0
                });
                var n1 = new MutationObserver((n1)=>{
                    !function(e, n1) {
                        var o = document.querySelector("button.AppHeader-login");
                        o && n1.bind(o)("click", function() {
                            t.disconnect();
                        }, {
                            once: !0
                        });
                    }(0, e);
                });
                n1.observe(document, {
                    childList: !0,
                    subtree: !0
                }), setTimeout(function() {
                    n1.disconnect(), t.disconnect();
                }, 5e3);
            })();
            Object.defineProperty(Window.prototype.toString, "41bf8021e5a5f51b455d8d18dce0c4d0", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "41bf8021e5a5f51b455d8d18dce0c4d0" due to: ' + e);
        }
    },
    '(function(){if(!document.cookie.includes("zip_and_city=")){var a=encodeURIComponent(\'{"zip":"","city":""}\');document.cookie="zip_and_city="+a+"; path=/;"}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["150eefbfeffab2cb6822c774c048adf4"] === e) return;
            !function() {
                if (!document.cookie.includes("zip_and_city=")) {
                    var e = encodeURIComponent('{"zip":"","city":""}');
                    document.cookie = "zip_and_city=" + e + "; path=/;";
                }
            }();
            Object.defineProperty(Window.prototype.toString, "150eefbfeffab2cb6822c774c048adf4", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "150eefbfeffab2cb6822c774c048adf4" due to: ' + e);
        }
    },
    "(function(){var b=window.alert;window.alert=function(a){if(!/do geolokalizacji/.test(a.toString()))return b(a)};})();": ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString["1362854a89198b0689400538f0b1a4dc"] === t) return;
            !function() {
                var t = window.alert;
                window.alert = function(e) {
                    if (!/do geolokalizacji/.test(e.toString())) return t(e);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "1362854a89198b0689400538f0b1a4dc", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "1362854a89198b0689400538f0b1a4dc" due to: ' + t);
        }
    },
    '!function(){if(decodeURIComponent(location.href).startsWith("https://www.wp.pl/?s=portal.abczdrowie.pl")||decodeURIComponent(location.href).startsWith("https://www.wp.pl/?s=parenting.pl"))try{var a=(new URL(window.location.href)).searchParams.get("s");location.replace("https://"+a)}catch(b){}}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.ec8cfc984fdc64eb0423e2b09bc54f74 === e) return;
            !function() {
                if (decodeURIComponent(location.href).startsWith("https://www.wp.pl/?s=portal.abczdrowie.pl") || decodeURIComponent(location.href).startsWith("https://www.wp.pl/?s=parenting.pl")) try {
                    var e = new URL(window.location.href).searchParams.get("s");
                    location.replace("https://" + e);
                } catch (e) {}
            }();
            Object.defineProperty(Window.prototype.toString, "ec8cfc984fdc64eb0423e2b09bc54f74", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "ec8cfc984fdc64eb0423e2b09bc54f74" due to: ' + e);
        }
    },
    '!function(){if(decodeURIComponent(location.href).startsWith("https://www.wp.pl/?s=https://"))try{var a=(new URL(window.location.href)).searchParams.get("s");location.replace(a)}catch(b){}}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["8b26d974cb42343c8f14233fe3c568e8"] === e) return;
            !function() {
                if (decodeURIComponent(location.href).startsWith("https://www.wp.pl/?s=https://")) try {
                    var e = new URL(window.location.href).searchParams.get("s");
                    location.replace(e);
                } catch (e) {}
            }();
            Object.defineProperty(Window.prototype.toString, "8b26d974cb42343c8f14233fe3c568e8", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "8b26d974cb42343c8f14233fe3c568e8" due to: ' + e);
        }
    },
    '(function(){var a=new Date,b=a.getTime();document.cookie="ucs=lbit="+b})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.bc114c1bbc5dee318bd43b511cdcb308 === e) return;
            !function() {
                var e = (new Date).getTime();
                document.cookie = "ucs=lbit=" + e;
            }();
            Object.defineProperty(Window.prototype.toString, "bc114c1bbc5dee318bd43b511cdcb308", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "bc114c1bbc5dee318bd43b511cdcb308" due to: ' + e);
        }
    },
    "var _st = window.setTimeout; window.setTimeout = function(a, b) { if(!/loginPopup.show/.test(a)){ _st(a,b);}};": ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString["1042964cb83bcd640195f230a152da77"] === t) return;
            var _st = window.setTimeout;
            window.setTimeout = function(t, e) {
                /loginPopup.show/.test(t) || _st(t, e);
            };
            Object.defineProperty(Window.prototype.toString, "1042964cb83bcd640195f230a152da77", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "1042964cb83bcd640195f230a152da77" due to: ' + t);
        }
    },
    '!function(){var e=new MutationObserver(function(){document.querySelectorAll(\'div[id^="substream_"] div[id^="hyperfeed_story_id"]\').forEach(function(e){var n=e.querySelectorAll(".userContentWrapper > div[class] > div[class] > div[class]"),o=e.querySelectorAll(".userContentWrapper > div[class] > div > div span");if("display: none !important;"!=e.getAttribute("style")){if(0<n.length&&n[0].innerText.contains("Suggested")){console.log("--------"),t+=1;var l=e.querySelectorAll("a[href]")[2].innerText;console.log("Annoyance hidden from: "+l),console.log("Total annoyances Hidden: "+t),console.log("F length: "+n.length),console.log("--------"),e.style="display:none!important;"}if(0<o.length&&o[0].innerText.contains("People you may know"))console.log("--------"),t+=1,""==(l=e.querySelectorAll("a[href]")[2].innerText)&&(l="Facebook"),console.log("Annoyance hidden from: "+l),console.log("Total annoyances Hidden: "+t),console.log("F length: "+n.length),console.log("--------"),e.style="display:none!important;"}})}),t=0;e.observe(document,{childList:!0,subtree:!0})}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["2d5a4b03ebe219d77f997c0a788b2eed"] === e) return;
            !function() {
                var e = new MutationObserver(function() {
                    document.querySelectorAll('div[id^="substream_"] div[id^="hyperfeed_story_id"]').forEach(function(e) {
                        var n1 = e.querySelectorAll(".userContentWrapper > div[class] > div[class] > div[class]"), t = e.querySelectorAll(".userContentWrapper > div[class] > div > div span");
                        if ("display: none !important;" != e.getAttribute("style")) {
                            if (0 < n1.length && n1[0].innerText.contains("Suggested")) {
                                console.log("--------"), o += 1;
                                var l = e.querySelectorAll("a[href]")[2].innerText;
                                console.log("Annoyance hidden from: " + l), console.log("Total annoyances Hidden: " + o), console.log("F length: " + n1.length), console.log("--------"), e.style = "display:none!important;";
                            }
                            0 < t.length && t[0].innerText.contains("People you may know") && (console.log("--------"), o += 1, "" == (l = e.querySelectorAll("a[href]")[2].innerText) && (l = "Facebook"), console.log("Annoyance hidden from: " + l), console.log("Total annoyances Hidden: " + o), console.log("F length: " + n1.length), console.log("--------"), e.style = "display:none!important;");
                        }
                    });
                }), o = 0;
                e.observe(document, {
                    childList: !0,
                    subtree: !0
                });
            }();
            Object.defineProperty(Window.prototype.toString, "2d5a4b03ebe219d77f997c0a788b2eed", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "2d5a4b03ebe219d77f997c0a788b2eed" due to: ' + e);
        }
    },
    'new MutationObserver(function(){document.querySelectorAll(\'div[role="feed"] > div[data-pagelet^="FeedUnit"] > div[class]:not([style*="height"])\').forEach(function(e){"display: none !important;"==e.getAttribute("style")||e.classList.contains("hidden_elem")||e.querySelectorAll("div[aria-posinset] div[style] div[class] > div[class] > div[class] > div[class] > span")[0].innerText.contains("Suggested for you")&&(console.log("--------"),console.log("Annoyances hidden (Suggested for you)"),e.style="display:none!important;")})}).observe(document,{childList:!0,subtree:!0});': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["03e8fcb55c09dc00ea2c8fbc43ccc9ac"] === e) return;
            new MutationObserver(function() {
                document.querySelectorAll('div[role="feed"] > div[data-pagelet^="FeedUnit"] > div[class]:not([style*="height"])').forEach(function(e) {
                    "display: none !important;" == e.getAttribute("style") || e.classList.contains("hidden_elem") || e.querySelectorAll("div[aria-posinset] div[style] div[class] > div[class] > div[class] > div[class] > span")[0].innerText.contains("Suggested for you") && (console.log("--------"), console.log("Annoyances hidden (Suggested for you)"), e.style = "display:none!important;");
                });
            }).observe(document, {
                childList: !0,
                subtree: !0
            });
            Object.defineProperty(Window.prototype.toString, "03e8fcb55c09dc00ea2c8fbc43ccc9ac", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "03e8fcb55c09dc00ea2c8fbc43ccc9ac" due to: ' + e);
        }
    },
    'new MutationObserver(function(){document.querySelectorAll(\'div[role="feed"] > span\').forEach(function(e){"display: none !important;"==e.getAttribute("style")||e.classList.contains("hidden_elem")||e.querySelectorAll("div[aria-posinset] div[style] div[class] > div[class] > div[class] > div[class] > span")[0].innerText.contains("Suggested for you")&&(console.log("--------"),console.log("Annoyances hidden (Suggested for you)"),e.style="display:none!important;")})}).observe(document,{childList:!0,subtree:!0});': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["7658e09af099cd1524b0fba53dd1cb1c"] === e) return;
            new MutationObserver(function() {
                document.querySelectorAll('div[role="feed"] > span').forEach(function(e) {
                    "display: none !important;" == e.getAttribute("style") || e.classList.contains("hidden_elem") || e.querySelectorAll("div[aria-posinset] div[style] div[class] > div[class] > div[class] > div[class] > span")[0].innerText.contains("Suggested for you") && (console.log("--------"), console.log("Annoyances hidden (Suggested for you)"), e.style = "display:none!important;");
                });
            }).observe(document, {
                childList: !0,
                subtree: !0
            });
            Object.defineProperty(Window.prototype.toString, "7658e09af099cd1524b0fba53dd1cb1c", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "7658e09af099cd1524b0fba53dd1cb1c" due to: ' + e);
        }
    },
    '!function(){var b=0,d=[];new MutationObserver(function(){document.querySelectorAll("#ssrb_feed_start + div > div[class]:not([style*=\\"display: none\\"]), #ssrb_feed_start + div span > h3 ~ div[class]:not([style*=\\"display: none\\"]), #ssrb_feed_start + div h3~ div[class]:not([style*=\\"display: none\\"]), #ssrb_feed_start + div h3 ~ div > div[class]:not([style*=\\"display: none\\"]), div[role=\\"main\\"] div > h3 ~ div > div[class]:not([style*=\\"display: none\\"])").forEach(function(e){Object.keys(e).forEach(function(a){if(a.includes("__reactEvents")||a.includes("__reactProps")){a=e[a];try{if(a.children?.props?.category?.includes("SHOWCASE")||a.children?.props?.children?.props?.category?.includes("SHOWCASE")||a.children?.props?.children?.props?.feedEdge?.category?.includes("SHOWCASE")||a.children?.props?.category?.includes("FB_SHORTS")||a.children?.props?.children?.props?.category?.includes("FB_SHORTS")||a.children?.props?.children?.props?.feedEdge?.category?.includes("FB_SHORTS")){b++,e.style="display: none !important;";var f=e.querySelector("a[href][aria-label]:not([aria-hidden])");f&&(d.push(["SHOWCASE post blocked based on property ["+b+"] -> "+f.ariaLabel]),console.table(d))}}catch(a){}}})})}).observe(document,{childList:!0,subtree:!0})}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.b1df923a63194358ca6f0ed1143474e5 === e) return;
            !function() {
                var e = 0, r = [];
                new MutationObserver(function() {
                    document.querySelectorAll('#ssrb_feed_start + div > div[class]:not([style*="display: none"]), #ssrb_feed_start + div span > h3 ~ div[class]:not([style*="display: none"]), #ssrb_feed_start + div h3~ div[class]:not([style*="display: none"]), #ssrb_feed_start + div h3 ~ div > div[class]:not([style*="display: none"]), div[role="main"] div > h3 ~ div > div[class]:not([style*="display: none"])').forEach(function(n1) {
                        Object.keys(n1).forEach(function(s) {
                            if (s.includes("__reactEvents") || s.includes("__reactProps")) {
                                s = n1[s];
                                try {
                                    var _s_children_props_category, _s_children_props, _s_children, _s_children_props_children_props_category, _s_children_props_children_props, _s_children_props_children, _s_children_props1, _s_children1, _s_children_props_children_props_feedEdge_category, _s_children_props_children_props_feedEdge, _s_children_props_children_props1, _s_children_props_children1, _s_children_props2, _s_children2, _s_children_props_category1, _s_children_props3, _s_children3, _s_children_props_children_props_category1, _s_children_props_children_props2, _s_children_props_children2, _s_children_props4, _s_children4, _s_children_props_children_props_feedEdge_category1, _s_children_props_children_props_feedEdge1, _s_children_props_children_props3, _s_children_props_children3, _s_children_props5, _s_children5;
                                    if (((_s_children = s.children) === null || _s_children === void 0 ? void 0 : (_s_children_props = _s_children.props) === null || _s_children_props === void 0 ? void 0 : (_s_children_props_category = _s_children_props.category) === null || _s_children_props_category === void 0 ? void 0 : _s_children_props_category.includes("SHOWCASE")) || ((_s_children1 = s.children) === null || _s_children1 === void 0 ? void 0 : (_s_children_props1 = _s_children1.props) === null || _s_children_props1 === void 0 ? void 0 : (_s_children_props_children = _s_children_props1.children) === null || _s_children_props_children === void 0 ? void 0 : (_s_children_props_children_props = _s_children_props_children.props) === null || _s_children_props_children_props === void 0 ? void 0 : (_s_children_props_children_props_category = _s_children_props_children_props.category) === null || _s_children_props_children_props_category === void 0 ? void 0 : _s_children_props_children_props_category.includes("SHOWCASE")) || ((_s_children2 = s.children) === null || _s_children2 === void 0 ? void 0 : (_s_children_props2 = _s_children2.props) === null || _s_children_props2 === void 0 ? void 0 : (_s_children_props_children1 = _s_children_props2.children) === null || _s_children_props_children1 === void 0 ? void 0 : (_s_children_props_children_props1 = _s_children_props_children1.props) === null || _s_children_props_children_props1 === void 0 ? void 0 : (_s_children_props_children_props_feedEdge = _s_children_props_children_props1.feedEdge) === null || _s_children_props_children_props_feedEdge === void 0 ? void 0 : (_s_children_props_children_props_feedEdge_category = _s_children_props_children_props_feedEdge.category) === null || _s_children_props_children_props_feedEdge_category === void 0 ? void 0 : _s_children_props_children_props_feedEdge_category.includes("SHOWCASE")) || ((_s_children3 = s.children) === null || _s_children3 === void 0 ? void 0 : (_s_children_props3 = _s_children3.props) === null || _s_children_props3 === void 0 ? void 0 : (_s_children_props_category1 = _s_children_props3.category) === null || _s_children_props_category1 === void 0 ? void 0 : _s_children_props_category1.includes("FB_SHORTS")) || ((_s_children4 = s.children) === null || _s_children4 === void 0 ? void 0 : (_s_children_props4 = _s_children4.props) === null || _s_children_props4 === void 0 ? void 0 : (_s_children_props_children2 = _s_children_props4.children) === null || _s_children_props_children2 === void 0 ? void 0 : (_s_children_props_children_props2 = _s_children_props_children2.props) === null || _s_children_props_children_props2 === void 0 ? void 0 : (_s_children_props_children_props_category1 = _s_children_props_children_props2.category) === null || _s_children_props_children_props_category1 === void 0 ? void 0 : _s_children_props_children_props_category1.includes("FB_SHORTS")) || ((_s_children5 = s.children) === null || _s_children5 === void 0 ? void 0 : (_s_children_props5 = _s_children5.props) === null || _s_children_props5 === void 0 ? void 0 : (_s_children_props_children3 = _s_children_props5.children) === null || _s_children_props_children3 === void 0 ? void 0 : (_s_children_props_children_props3 = _s_children_props_children3.props) === null || _s_children_props_children_props3 === void 0 ? void 0 : (_s_children_props_children_props_feedEdge1 = _s_children_props_children_props3.feedEdge) === null || _s_children_props_children_props_feedEdge1 === void 0 ? void 0 : (_s_children_props_children_props_feedEdge_category1 = _s_children_props_children_props_feedEdge1.category) === null || _s_children_props_children_props_feedEdge_category1 === void 0 ? void 0 : _s_children_props_children_props_feedEdge_category1.includes("FB_SHORTS"))) {
                                        e++, n1.style = "display: none !important;";
                                        var t = n1.querySelector("a[href][aria-label]:not([aria-hidden])");
                                        t && (r.push([
                                            "SHOWCASE post blocked based on property [" + e + "] -> " + t.ariaLabel
                                        ]), console.table(r));
                                    }
                                } catch (s) {}
                            }
                        });
                    });
                }).observe(document, {
                    childList: !0,
                    subtree: !0
                });
            }();
            Object.defineProperty(Window.prototype.toString, "b1df923a63194358ca6f0ed1143474e5", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "b1df923a63194358ca6f0ed1143474e5" due to: ' + e);
        }
    },
    "setInterval(function() { var el = document.querySelector('.howto-video video'); if (el) { el.pause(); el.src = ''; }}, 100);": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["6037ae33aba3b05f056f756787dd2f13"] === e) return;
            setInterval(function() {
                var e = document.querySelector(".howto-video video");
                if (e) {
                    e.pause();
                    e.src = "";
                }
            }, 100);
            Object.defineProperty(Window.prototype.toString, "6037ae33aba3b05f056f756787dd2f13", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "6037ae33aba3b05f056f756787dd2f13" due to: ' + e);
        }
    },
    'document.addEventListener(\'DOMContentLoaded\', function(){setTimeout(function(){var a=document.querySelector(".onp-sl-content");if("function"===typeof jQuery&&"object"===typeof bizpanda.lockerOptions&&a)try{a=0;for(var c=Object.keys(bizpanda.lockerOptions);a<c.length;a++){var d=c[a];if(d.includes("onpLock")){var b=bizpanda.lockerOptions[d];b&&jQuery.ajax({url:b.ajaxUrl,method:"post",data:{lockerId:b.lockerId,action:"opanda_loader",hash:b.contentHash},success:function(a){var b=jQuery(".onp-sl-content"),c=jQuery(".onp-sl-social-locker"); b.append(a);b.css("display","block");c.css("display","none")}})}}}catch(e){}},1E3)});': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.f8726a98e9ee7f87afd7c9376374eb99 === e) return;
            document.addEventListener("DOMContentLoaded", function() {
                setTimeout(function() {
                    var e = document.querySelector(".onp-sl-content");
                    if ("function" == typeof jQuery && "object" == typeof bizpanda.lockerOptions && e) try {
                        e = 0;
                        for(var o = Object.keys(bizpanda.lockerOptions); e < o.length; e++){
                            var t = o[e];
                            if (t.includes("onpLock")) {
                                var n1 = bizpanda.lockerOptions[t];
                                n1 && jQuery.ajax({
                                    url: n1.ajaxUrl,
                                    method: "post",
                                    data: {
                                        lockerId: n1.lockerId,
                                        action: "opanda_loader",
                                        hash: n1.contentHash
                                    },
                                    success: function(e) {
                                        var o = jQuery(".onp-sl-content"), t = jQuery(".onp-sl-social-locker");
                                        o.append(e);
                                        o.css("display", "block");
                                        t.css("display", "none");
                                    }
                                });
                            }
                        }
                    } catch (e) {}
                }, 1e3);
            });
            Object.defineProperty(Window.prototype.toString, "f8726a98e9ee7f87afd7c9376374eb99", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "f8726a98e9ee7f87afd7c9376374eb99" due to: ' + e);
        }
    },
    '(()=>{if(!location.href.includes("/download-"))return;document.addEventListener("DOMContentLoaded",(()=>{document.querySelectorAll(\'#downloadpage > form[action][method="POST"] > input[value^="https://"]\').forEach((e=>{const o=e.closest("form");var t,n;o&&(t=o,n=e.value,t.addEventListener("click",(e=>{e.preventDefault(),window.location.href=n})))}))}))})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["7d835d508a44fa6f33710266eee3a2c3"] === e) return;
            location.href.includes("/download-") && document.addEventListener("DOMContentLoaded", ()=>{
                document.querySelectorAll('#downloadpage > form[action][method="POST"] > input[value^="https://"]').forEach((e)=>{
                    const o = e.closest("form");
                    var t, n1;
                    o && (t = o, n1 = e.value, t.addEventListener("click", (e)=>{
                        e.preventDefault(), window.location.href = n1;
                    }));
                });
            });
            Object.defineProperty(Window.prototype.toString, "7d835d508a44fa6f33710266eee3a2c3", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "7d835d508a44fa6f33710266eee3a2c3" due to: ' + e);
        }
    },
    '(async()=>{if(location.href.includes("?slid="))try{const t=new URLSearchParams(location.search).get("slid");if(!t||!t.length)return;const a=await fetch(`https://hotmediahub.com/shorturl/getoriginurl?&surl_key=${t}`),i=await a.json();i?.data?.origin_url&&i.data.origin_url.startsWith("http")&&location.assign(i.data.origin_url)}catch(t){console.debug(t)}})();': ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString["4563128700b6c48955f528992fe0d2f6"] === t) return;
            (async ()=>{
                if (location.href.includes("?slid=")) try {
                    var _r_data;
                    const t = new URLSearchParams(location.search).get("slid");
                    if (!t || !t.length) return;
                    const e = await fetch(`https://hotmediahub.com/shorturl/getoriginurl?&surl_key=${t}`), r = await e.json();
                    (r === null || r === void 0 ? void 0 : (_r_data = r.data) === null || _r_data === void 0 ? void 0 : _r_data.origin_url) && r.data.origin_url.startsWith("http") && location.assign(r.data.origin_url);
                } catch (t) {
                    console.debug(t);
                }
            })();
            Object.defineProperty(Window.prototype.toString, "4563128700b6c48955f528992fe0d2f6", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "4563128700b6c48955f528992fe0d2f6" due to: ' + t);
        }
    },
    '(async()=>{if(location.href.includes("/slmiddlepage/"))try{const t=location.href.split("/").at(-1);if(!t.length)return;const a=await fetch(`https://terabox.fun/api/shortlink/getoriginurl?&encrypt_surl_key=${t}`),i=await a.json();i?.data?.origin_url&&i.data.origin_url.startsWith("http")&&location.assign(i.data.origin_url)}catch(t){console.debug(t)}})();': ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString["0e073ac7dd901115bdce2b79ff3dfb14"] === t) return;
            (async ()=>{
                if (location.href.includes("/slmiddlepage/")) try {
                    var _r_data;
                    const t = location.href.split("/").at(-1);
                    if (!t.length) return;
                    const e = await fetch(`https://terabox.fun/api/shortlink/getoriginurl?&encrypt_surl_key=${t}`), r = await e.json();
                    (r === null || r === void 0 ? void 0 : (_r_data = r.data) === null || _r_data === void 0 ? void 0 : _r_data.origin_url) && r.data.origin_url.startsWith("http") && location.assign(r.data.origin_url);
                } catch (t) {
                    console.debug(t);
                }
            })();
            Object.defineProperty(Window.prototype.toString, "0e073ac7dd901115bdce2b79ff3dfb14", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "0e073ac7dd901115bdce2b79ff3dfb14" due to: ' + t);
        }
    },
    '(async()=>{if(location.href.includes("/sl/"))try{const t=location.href.split("/").at(-1);if(!t.length)return;const a=await fetch(`https://terabox.fun/shorturl/getoriginurl?&surl_key=${t}`),i=await a.json();i?.data?.origin_url&&i.data.origin_url.startsWith("http")&&location.assign(i.data.origin_url)}catch(t){console.debug(t)}})();': ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString.c902dd6dcc6d8edbd75819fe5a8c796f === t) return;
            (async ()=>{
                if (location.href.includes("/sl/")) try {
                    var _r_data;
                    const t = location.href.split("/").at(-1);
                    if (!t.length) return;
                    const e = await fetch(`https://terabox.fun/shorturl/getoriginurl?&surl_key=${t}`), r = await e.json();
                    (r === null || r === void 0 ? void 0 : (_r_data = r.data) === null || _r_data === void 0 ? void 0 : _r_data.origin_url) && r.data.origin_url.startsWith("http") && location.assign(r.data.origin_url);
                } catch (t) {
                    console.debug(t);
                }
            })();
            Object.defineProperty(Window.prototype.toString, "c902dd6dcc6d8edbd75819fe5a8c796f", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "c902dd6dcc6d8edbd75819fe5a8c796f" due to: ' + t);
        }
    },
    '(function(){try{var a=location.href.split("/#");if(a[1]){a=a[1];for(var b=0;10>b;b++){a=atob(a);try{new URL(decodeURIComponent(a));var c=!0}catch(d){c=!1}if(c)try{location.assign(decodeURIComponent(a));break}catch(d){}}}}catch(d){}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["32d9aaa2320ef0aacd203039342dcf58"] === e) return;
            !function() {
                try {
                    var e = location.href.split("/#");
                    if (e[1]) {
                        e = e[1];
                        for(var a = 0; 10 > a; a++){
                            e = atob(e);
                            try {
                                new URL(decodeURIComponent(e));
                                var t = !0;
                            } catch (e) {
                                t = !1;
                            }
                            if (t) try {
                                location.assign(decodeURIComponent(e));
                                break;
                            } catch (e) {}
                        }
                    }
                } catch (e) {}
            }();
            Object.defineProperty(Window.prototype.toString, "32d9aaa2320ef0aacd203039342dcf58", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "32d9aaa2320ef0aacd203039342dcf58" due to: ' + e);
        }
    },
    '(function(){if(location.href.includes("/aHR0c"))try{let a=location.href.substring(location.href.indexOf("aHR0c"));a=atob(a),location.assign(decodeURIComponent(a))}catch(a){}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["456ba5931d5112b0319da728f07d150b"] === e) return;
            !function() {
                if (location.href.includes("/aHR0c")) try {
                    let e = location.href.substring(location.href.indexOf("aHR0c"));
                    e = atob(e), location.assign(decodeURIComponent(e));
                } catch (e) {}
            }();
            Object.defineProperty(Window.prototype.toString, "456ba5931d5112b0319da728f07d150b", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "456ba5931d5112b0319da728f07d150b" due to: ' + e);
        }
    },
    '(()=>{if(location.href.includes("?s=http")){const a=location.href.split("?s=").slice(1);try{location.assign(decodeURIComponent(a))}catch(a){}}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["89966e93a718e4bf486ce24ffd372a32"] === e) return;
            (()=>{
                if (location.href.includes("?s=http")) {
                    const e = location.href.split("?s=").slice(1);
                    try {
                        location.assign(decodeURIComponent(e));
                    } catch (e) {}
                }
            })();
            Object.defineProperty(Window.prototype.toString, "89966e93a718e4bf486ce24ffd372a32", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "89966e93a718e4bf486ce24ffd372a32" due to: ' + e);
        }
    },
    '!function(){if(location.href.includes("wpsafelink")){var e=new MutationObserver((function(){try{var t=document.querySelector(\'form#landing > input[name="go"][value]\'),n=document.querySelector("body > script");t&&t.value.startsWith("aHR0c")&&n&&n.textContent.includes("document.getElementById(\'landing\').submit();")&&(n.remove(),e.disconnect(),location.assign(atob(t.value)))}catch(e){}}));e.observe(document,{childList:!0,subtree:!0}),setTimeout((function(){e.disconnect()}),1e4)}}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.eb7c35a03ee3cc3b96b7bb0b0d90a333 === e) return;
            !function() {
                if (location.href.includes("wpsafelink")) {
                    var e = new MutationObserver(function() {
                        try {
                            var t = document.querySelector('form#landing > input[name="go"][value]'), n1 = document.querySelector("body > script");
                            t && t.value.startsWith("aHR0c") && n1 && n1.textContent.includes("document.getElementById('landing').submit();") && (n1.remove(), e.disconnect(), location.assign(atob(t.value)));
                        } catch (e) {}
                    });
                    e.observe(document, {
                        childList: !0,
                        subtree: !0
                    }), setTimeout(function() {
                        e.disconnect();
                    }, 1e4);
                }
            }();
            Object.defineProperty(Window.prototype.toString, "eb7c35a03ee3cc3b96b7bb0b0d90a333", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "eb7c35a03ee3cc3b96b7bb0b0d90a333" due to: ' + e);
        }
    },
    '!function(){if(-1<location.href.indexOf("?data=aHR0c")){var a=(new URL(window.location.href)).searchParams.get("data");if(a)try{window.location.assign(atob(a))}catch(b){}}}();': ()=>{
        try {
            const a = "done";
            if (Window.prototype.toString["44bad01b6f166fd09caa76089752d560"] === a) return;
            !function() {
                if (-1 < location.href.indexOf("?data=aHR0c")) {
                    var a = new URL(window.location.href).searchParams.get("data");
                    if (a) try {
                        window.location.assign(atob(a));
                    } catch (a) {}
                }
            }();
            Object.defineProperty(Window.prototype.toString, "44bad01b6f166fd09caa76089752d560", {
                value: a,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (a) {
            console.error('Error executing AG js rule with uniqueId "44bad01b6f166fd09caa76089752d560" due to: ' + a);
        }
    },
    '!function(){if(-1<location.href.indexOf("?wpsafelink=http")){var a=(new URL(window.location.href)).searchParams.get("wpsafelink");if(a)try{window.location.assign(a)}catch(b){}}}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["11a8706f0dda4c1354a0f23ace755f3f"] === e) return;
            !function() {
                if (-1 < location.href.indexOf("?wpsafelink=http")) {
                    var e = new URL(window.location.href).searchParams.get("wpsafelink");
                    if (e) try {
                        window.location.assign(e);
                    } catch (e) {}
                }
            }();
            Object.defineProperty(Window.prototype.toString, "11a8706f0dda4c1354a0f23ace755f3f", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "11a8706f0dda4c1354a0f23ace755f3f" due to: ' + e);
        }
    },
    '!function(){if(-1<window.location.href.indexOf("/?go=")){var a=location.href.split("?go=");if(a&&a[1])try{window.location=atob(a[1])}catch(b){}}}();': ()=>{
        try {
            const o = "done";
            if (Window.prototype.toString["74acd4f9bf691bd110a5d483c18ecd56"] === o) return;
            !function() {
                if (-1 < window.location.href.indexOf("/?go=")) {
                    var o = location.href.split("?go=");
                    if (o && o[1]) try {
                        window.location = atob(o[1]);
                    } catch (o) {}
                }
            }();
            Object.defineProperty(Window.prototype.toString, "74acd4f9bf691bd110a5d483c18ecd56", {
                value: o,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (o) {
            console.error('Error executing AG js rule with uniqueId "74acd4f9bf691bd110a5d483c18ecd56" due to: ' + o);
        }
    },
    '!function(){if(-1<window.location.href.indexOf("/?redirect=aHR0c")){var a=location.href.split("/?redirect=");if(a&&a[1])try{window.location=atob(a[1])}catch(b){}}}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["18e9f4638ee3f7cd8505ffa2c9efb0db"] === e) return;
            !function() {
                if (-1 < window.location.href.indexOf("/?redirect=aHR0c")) {
                    var e = location.href.split("/?redirect=");
                    if (e && e[1]) try {
                        window.location = atob(e[1]);
                    } catch (e) {}
                }
            }();
            Object.defineProperty(Window.prototype.toString, "18e9f4638ee3f7cd8505ffa2c9efb0db", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "18e9f4638ee3f7cd8505ffa2c9efb0db" due to: ' + e);
        }
    },
    '!function(){if(-1<location.href.indexOf("?data=")){var b=(new URL(window.location.href)).searchParams.get("data");if(b)try{var a=atob(b);a=a.split("&ulink=")[1];a.startsWith("http")&&window.location.assign(a)}catch(c){}}}();': ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString.d6c3eb40b31cb88fd93e2cbf35857f8c === t) return;
            !function() {
                if (-1 < location.href.indexOf("?data=")) {
                    var t = new URL(window.location.href).searchParams.get("data");
                    if (t) try {
                        var e = atob(t);
                        (e = e.split("&ulink=")[1]).startsWith("http") && window.location.assign(e);
                    } catch (t) {}
                }
            }();
            Object.defineProperty(Window.prototype.toString, "d6c3eb40b31cb88fd93e2cbf35857f8c", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "d6c3eb40b31cb88fd93e2cbf35857f8c" due to: ' + t);
        }
    },
    '!function(){if(-1<window.location.href.indexOf("/?r=aHR0c")){var a=location.href.split("/?r=");if(a&&a[1])try{window.location=atob(a[1])}catch(b){}}}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["8407ee6883a7daf63bdaba9212c0a5f4"] === e) return;
            !function() {
                if (-1 < window.location.href.indexOf("/?r=aHR0c")) {
                    var e = location.href.split("/?r=");
                    if (e && e[1]) try {
                        window.location = atob(e[1]);
                    } catch (e) {}
                }
            }();
            Object.defineProperty(Window.prototype.toString, "8407ee6883a7daf63bdaba9212c0a5f4", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "8407ee6883a7daf63bdaba9212c0a5f4" due to: ' + e);
        }
    },
    '(function(){if(location.href.includes("/to/aHR0c"))try{var a=location.href.split("/to/");a=atob(a[1]);location=decodeURIComponent(a)}catch(b){}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.faa1e5b373e282c3295d2edb730eab59 === e) return;
            !function() {
                if (location.href.includes("/to/aHR0c")) try {
                    var e = location.href.split("/to/");
                    e = atob(e[1]);
                    location = decodeURIComponent(e);
                } catch (e) {}
            }();
            Object.defineProperty(Window.prototype.toString, "faa1e5b373e282c3295d2edb730eab59", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "faa1e5b373e282c3295d2edb730eab59" due to: ' + e);
        }
    },
    '(function(){"function"===typeof fetch&&location.href.includes("/?id=")&&fetch(location.href).then(function(e){e.headers.forEach(function(a,f){if("refresh"===f&&a.includes("url=http"))try{if(a.includes("&url=aHR0c")){var b,c=null==(b=a.split(/&url=/))?void 0:b[1];location=atob(c)}else{var d;location=c=null==(d=a.split(/url=(.+)/))?void 0:d[1]}}catch(g){}})})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["1aa697d9b99b2928e92895ee3e7133f4"] === e) return;
            "function" == typeof fetch && location.href.includes("/?id=") && fetch(location.href).then(function(e) {
                e.headers.forEach(function(e, t) {
                    if ("refresh" === t && e.includes("url=http")) try {
                        if (e.includes("&url=aHR0c")) {
                            var o, r = null == (o = e.split(/&url=/)) ? void 0 : o[1];
                            location = atob(r);
                        } else {
                            var n1;
                            location = r = null == (n1 = e.split(/url=(.+)/)) ? void 0 : n1[1];
                        }
                    } catch (e) {}
                });
            });
            Object.defineProperty(Window.prototype.toString, "1aa697d9b99b2928e92895ee3e7133f4", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "1aa697d9b99b2928e92895ee3e7133f4" due to: ' + e);
        }
    },
    '!function(){if(-1<window.location.href.indexOf("out/?aHR0c")){var a=location.href.split("out/?");if(a&&a[1])try{window.location=atob(decodeURIComponent(a[1]))}catch(b){}}}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["14e7b6eeaed2b6c9766d1673c27e5f11"] === e) return;
            !function() {
                if (-1 < window.location.href.indexOf("out/?aHR0c")) {
                    var e = location.href.split("out/?");
                    if (e && e[1]) try {
                        window.location = atob(decodeURIComponent(e[1]));
                    } catch (e) {}
                }
            }();
            Object.defineProperty(Window.prototype.toString, "14e7b6eeaed2b6c9766d1673c27e5f11", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "14e7b6eeaed2b6c9766d1673c27e5f11" due to: ' + e);
        }
    },
    '!function(){if(window.location.href.includes("api")&&window.location.href.includes("&url=")){var b=location.href.split("&url=")[1];a:{try{var a=new URL(b)}catch(c){a=!1;break a}a="http:"===a.protocol||"https:"===a.protocol}if(a)try{window.location=b}catch(c){}}}();': ()=>{
        try {
            const o = "done";
            if (Window.prototype.toString.a7aa2c291e20b59040377e4089cb13d8 === o) return;
            !function() {
                if (window.location.href.includes("api") && window.location.href.includes("&url=")) {
                    var o = location.href.split("&url=")[1];
                    o: {
                        try {
                            var e = new URL(o);
                        } catch (o) {
                            e = !1;
                            break o;
                        }
                        e = "http:" === e.protocol || "https:" === e.protocol;
                    }
                    if (e) try {
                        window.location = o;
                    } catch (o) {}
                }
            }();
            Object.defineProperty(Window.prototype.toString, "a7aa2c291e20b59040377e4089cb13d8", {
                value: o,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (o) {
            console.error('Error executing AG js rule with uniqueId "a7aa2c291e20b59040377e4089cb13d8" due to: ' + o);
        }
    },
    '!function(){if(-1<window.location.href.indexOf("/download.php?")&&-1<window.location.href.indexOf("link=aHR0c")){var a=location.href.split("link=");if(a&&a[1])try{window.location=atob(a[1])}catch(b){}}}();': ()=>{
        try {
            const o = "done";
            if (Window.prototype.toString.fbed59262d4b4df211cd5517c4c36cf1 === o) return;
            !function() {
                if (-1 < window.location.href.indexOf("/download.php?") && -1 < window.location.href.indexOf("link=aHR0c")) {
                    var o = location.href.split("link=");
                    if (o && o[1]) try {
                        window.location = atob(o[1]);
                    } catch (o) {}
                }
            }();
            Object.defineProperty(Window.prototype.toString, "fbed59262d4b4df211cd5517c4c36cf1", {
                value: o,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (o) {
            console.error('Error executing AG js rule with uniqueId "fbed59262d4b4df211cd5517c4c36cf1" due to: ' + o);
        }
    },
    '(()=>{document.addEventListener(\'DOMContentLoaded\',()=>{const a=function(a){const b=new DOMParser().parseFromString(a,"text/html");return b.documentElement.textContent},b=function(){if("object"==typeof _sharedData&&"string"==typeof _sharedData[0]?.destination){const b=a(_sharedData[0].destination);if(b.startsWith("http"))try{window.location=b}catch(a){}}};if(window._sharedData)b();else{const a=new MutationObserver(function(){window._sharedData&&(a.disconnect(),b())});a.observe(document,{childList:!0,subtree:!0}),setTimeout(function(){a.disconnect()},1E4)}})})();': ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString["9cac65361b045047e010c7826d557bc0"] === t) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                const t = function() {
                    var _sharedData_;
                    if ("object" == typeof _sharedData && "string" == typeof ((_sharedData_ = _sharedData[0]) === null || _sharedData_ === void 0 ? void 0 : _sharedData_.destination)) {
                        const t = function(t) {
                            return (new DOMParser).parseFromString(t, "text/html").documentElement.textContent;
                        }(_sharedData[0].destination);
                        if (t.startsWith("http")) try {
                            window.location = t;
                        } catch (t) {}
                    }
                };
                if (window._sharedData) t();
                else {
                    const e = new MutationObserver(function() {
                        window._sharedData && (e.disconnect(), t());
                    });
                    e.observe(document, {
                        childList: !0,
                        subtree: !0
                    }), setTimeout(function() {
                        e.disconnect();
                    }, 1e4);
                }
            });
            Object.defineProperty(Window.prototype.toString, "9cac65361b045047e010c7826d557bc0", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "9cac65361b045047e010c7826d557bc0" due to: ' + t);
        }
    },
    '!function(){if(-1<window.location.href.indexOf(".html?url=aHR0c")){var a=location.href.split(".html?url=");if(a&&a[1])try{window.location=atob(a[1])}catch(b){}}}();': ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString["0b9c803325dd9cf5e623a58f3f42c964"] === t) return;
            !function() {
                if (-1 < window.location.href.indexOf(".html?url=aHR0c")) {
                    var t = location.href.split(".html?url=");
                    if (t && t[1]) try {
                        window.location = atob(t[1]);
                    } catch (t) {}
                }
            }();
            Object.defineProperty(Window.prototype.toString, "0b9c803325dd9cf5e623a58f3f42c964", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "0b9c803325dd9cf5e623a58f3f42c964" due to: ' + t);
        }
    },
    '!function(){if(-1<location.href.indexOf("/aHR0c")){var a=location.href.split("/").pop();if(a&&a.includes("aHR0c"))try{location=decodeURIComponent(atob(a))}catch(b){}}}();': ()=>{
        try {
            const o = "done";
            if (Window.prototype.toString.fa04035c4b218bf538509b1f9bca93d9 === o) return;
            !function() {
                if (-1 < location.href.indexOf("/aHR0c")) {
                    var o = location.href.split("/").pop();
                    if (o && o.includes("aHR0c")) try {
                        location = decodeURIComponent(atob(o));
                    } catch (o) {}
                }
            }();
            Object.defineProperty(Window.prototype.toString, "fa04035c4b218bf538509b1f9bca93d9", {
                value: o,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (o) {
            console.error('Error executing AG js rule with uniqueId "fa04035c4b218bf538509b1f9bca93d9" due to: ' + o);
        }
    },
    '!function(){if(-1<window.location.href.indexOf("/gotothedl.html?url=")){var a=location.href.split("/gotothedl.html?url=");if(a&&a[1])try{window.location=atob(a[1])}catch(b){}}}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.fd6511a662b1e2713ee805351331ec88 === e) return;
            !function() {
                if (-1 < window.location.href.indexOf("/gotothedl.html?url=")) {
                    var e = location.href.split("/gotothedl.html?url=");
                    if (e && e[1]) try {
                        window.location = atob(e[1]);
                    } catch (e) {}
                }
            }();
            Object.defineProperty(Window.prototype.toString, "fd6511a662b1e2713ee805351331ec88", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "fd6511a662b1e2713ee805351331ec88" due to: ' + e);
        }
    },
    '!function(){if(-1<window.location.href.indexOf("/link/?link=aHR0c")){var a=location.href.split("/link/?link=");if(a&&a[1])try{window.location=atob(a[1])}catch(b){}}}();': ()=>{
        try {
            const d = "done";
            if (Window.prototype.toString.d182d7cd6901d7ba2db76b7116137d30 === d) return;
            !function() {
                if (-1 < window.location.href.indexOf("/link/?link=aHR0c")) {
                    var d = location.href.split("/link/?link=");
                    if (d && d[1]) try {
                        window.location = atob(d[1]);
                    } catch (d) {}
                }
            }();
            Object.defineProperty(Window.prototype.toString, "d182d7cd6901d7ba2db76b7116137d30", {
                value: d,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (d) {
            console.error('Error executing AG js rule with uniqueId "d182d7cd6901d7ba2db76b7116137d30" due to: ' + d);
        }
    },
    '!function(){if(-1<location.pathname.indexOf("/view.php")){var a=(new URL(window.location.href)).searchParams.get("id");if(a&&-1==document.cookie.indexOf(a))try{document.cookie=a+"=user; path=/;";location.reload();}catch(b){}}}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["89696970bfadbdff1c23f38046797c74"] === e) return;
            !function() {
                if (-1 < location.pathname.indexOf("/view.php")) {
                    var e = new URL(window.location.href).searchParams.get("id");
                    if (e && -1 == document.cookie.indexOf(e)) try {
                        document.cookie = e + "=user; path=/;";
                        location.reload();
                    } catch (e) {}
                }
            }();
            Object.defineProperty(Window.prototype.toString, "89696970bfadbdff1c23f38046797c74", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "89696970bfadbdff1c23f38046797c74" due to: ' + e);
        }
    },
    '(function(){-1==document.cookie.indexOf("exUserId")&&(document.cookie="exUserId=1; domain=.4shared.com; path=/;")})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["83200f16f2ddab39b258418b8f092a1e"] === e) return;
            -1 == document.cookie.indexOf("exUserId") && (document.cookie = "exUserId=1; domain=.4shared.com; path=/;");
            Object.defineProperty(Window.prototype.toString, "83200f16f2ddab39b258418b8f092a1e", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "83200f16f2ddab39b258418b8f092a1e" due to: ' + e);
        }
    },
    '!function(){if(-1<location.pathname.indexOf("/redirect")){var a=(new URL(window.location.href)).searchParams.get("to");if(a)try{window.location=atob(a)}catch(b){}}}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.af354057b5f1999097c4f848b8100343 === e) return;
            !function() {
                if (-1 < location.pathname.indexOf("/redirect")) {
                    var e = new URL(window.location.href).searchParams.get("to");
                    if (e) try {
                        window.location = atob(e);
                    } catch (e) {}
                }
            }();
            Object.defineProperty(Window.prototype.toString, "af354057b5f1999097c4f848b8100343", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "af354057b5f1999097c4f848b8100343" due to: ' + e);
        }
    },
    '!function(){if(-1<window.location.href.indexOf("?url=")){var a=location.href.split("?url=");if(a&&a[1])try{window.location=atob(a[1])}catch(b){}}}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["8015f163e0243425947c898a301100ae"] === e) return;
            !function() {
                if (-1 < window.location.href.indexOf("?url=")) {
                    var e = location.href.split("?url=");
                    if (e && e[1]) try {
                        window.location = atob(e[1]);
                    } catch (e) {}
                }
            }();
            Object.defineProperty(Window.prototype.toString, "8015f163e0243425947c898a301100ae", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "8015f163e0243425947c898a301100ae" due to: ' + e);
        }
    },
    '(()=>{document.addEventListener(\'DOMContentLoaded\',()=>{if(-1<location.pathname.indexOf("/go/")){var b=new MutationObserver(function(){if(document.querySelector("#get_link_btn"))try{[].slice.call(document.getElementsByTagName("script")).some(function(a){a.text.match(/goToUrl \\("/)&&(a=a.text.split(/goToUrl \\("([\\s\\S]*?)"\\);/),location=a[1])})}catch(a){}});b.observe(document,{childList:!0,subtree:!0});setTimeout(function(){b.disconnect()},1E4)}})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["1b7a3b5c1b1b60eb96bdd9dfb49f36ed"] === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                if (-1 < location.pathname.indexOf("/go/")) {
                    var e = new MutationObserver(function() {
                        if (document.querySelector("#get_link_btn")) try {
                            [].slice.call(document.getElementsByTagName("script")).some(function(e) {
                                e.text.match(/goToUrl \("/) && (e = e.text.split(/goToUrl \("([\s\S]*?)"\);/), location = e[1]);
                            });
                        } catch (e) {}
                    });
                    e.observe(document, {
                        childList: !0,
                        subtree: !0
                    });
                    setTimeout(function() {
                        e.disconnect();
                    }, 1e4);
                }
            });
            Object.defineProperty(Window.prototype.toString, "1b7a3b5c1b1b60eb96bdd9dfb49f36ed", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "1b7a3b5c1b1b60eb96bdd9dfb49f36ed" due to: ' + e);
        }
    },
    "document.addEventListener('DOMContentLoad', function() { setTimeout(function() { second = 0; }, 300); });": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["034a6d2e27669874997985e584d3fc8b"] === e) return;
            document.addEventListener("DOMContentLoad", function() {
                setTimeout(function() {
                    second = 0;
                }, 300);
            });
            Object.defineProperty(Window.prototype.toString, "034a6d2e27669874997985e584d3fc8b", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "034a6d2e27669874997985e584d3fc8b" due to: ' + e);
        }
    },
    '!function(){if(-1<window.location.href.indexOf("/?r=")){var a=location.href.split("?r=");if(a&&a[1])try{window.location=atob(a[1])}catch(b){}}}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["307379e4f228b3973b29e647d7b9d240"] === e) return;
            !function() {
                if (-1 < window.location.href.indexOf("/?r=")) {
                    var e = location.href.split("?r=");
                    if (e && e[1]) try {
                        window.location = atob(e[1]);
                    } catch (e) {}
                }
            }();
            Object.defineProperty(Window.prototype.toString, "307379e4f228b3973b29e647d7b9d240", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "307379e4f228b3973b29e647d7b9d240" due to: ' + e);
        }
    },
    "(function(){var c=window.setInterval;window.setInterval=function(f,g){return g===1e3&&/removeAttr\\('disabled'\\)/.test(f.toString())&&(g*=0.01),c.apply(this,arguments)}.bind(window)})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["8a9f85f8cf15c1e19462f7c54155e865"] === e) return;
            !function() {
                var e = window.setInterval;
                window.setInterval = (function(t, r) {
                    return 1e3 === r && /removeAttr\('disabled'\)/.test(t.toString()) && (r *= .01), e.apply(this, arguments);
                }).bind(window);
            }();
            Object.defineProperty(Window.prototype.toString, "8a9f85f8cf15c1e19462f7c54155e865", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "8a9f85f8cf15c1e19462f7c54155e865" due to: ' + e);
        }
    },
    '(()=>{document.addEventListener(\'DOMContentLoaded\',()=>{setTimeout(function(){if("undefined"!==typeof aesCrypto&&"function"===typeof aesCrypto.decrypt&&-1<window.location.href.indexOf("#?o="))try{window.location=aesCrypto.decrypt(window.location.href.split("#?o=")[1].replace(/^\\s+/,"").replace(/\\s+$/,""),"root".replace(/^\\s+/,"").replace(/\\s+$/,""))}catch(a){}},300)})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["6d9ca9f617340a6d9976710f1e5a7b50"] === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                setTimeout(function() {
                    if ("undefined" != typeof aesCrypto && "function" == typeof aesCrypto.decrypt && -1 < window.location.href.indexOf("#?o=")) try {
                        window.location = aesCrypto.decrypt(window.location.href.split("#?o=")[1].replace(/^\s+/, "").replace(/\s+$/, ""), "root".replace(/^\s+/, "").replace(/\s+$/, ""));
                    } catch (e) {}
                }, 300);
            });
            Object.defineProperty(Window.prototype.toString, "6d9ca9f617340a6d9976710f1e5a7b50", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "6d9ca9f617340a6d9976710f1e5a7b50" due to: ' + e);
        }
    },
    '(()=>{document.addEventListener(\'DOMContentLoaded\',()=>{setTimeout(function(){if("undefined"!==typeof aesCrypto&&"function"===typeof aesCrypto.decrypt&&-1<window.location.href.indexOf("#?o="))try{window.location=aesCrypto.decrypt($.urlParam("o").replace(/^\\s+/,"").replace(/\\s+$/,""),"root".replace(/^\\s+/,"").replace(/\\s+$/,""))}catch(a){}},300)})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.e3c828d254377a11d58cabf38f975080 === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                setTimeout(function() {
                    if ("undefined" != typeof aesCrypto && "function" == typeof aesCrypto.decrypt && -1 < window.location.href.indexOf("#?o=")) try {
                        window.location = aesCrypto.decrypt($.urlParam("o").replace(/^\s+/, "").replace(/\s+$/, ""), "root".replace(/^\s+/, "").replace(/\s+$/, ""));
                    } catch (e) {}
                }, 300);
            });
            Object.defineProperty(Window.prototype.toString, "e3c828d254377a11d58cabf38f975080", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "e3c828d254377a11d58cabf38f975080" due to: ' + e);
        }
    },
    '(()=>{document.addEventListener(\'DOMContentLoaded\',()=>{setTimeout(function(){if("function"===typeof convertstr&&"function"===typeof aesCrypto.decrypt&&-1<window.location.href.indexOf("html#?o="))try{window.location=aesCrypto.decrypt(convertstr($.urlParam("o")),convertstr("root"))}catch(a){}},300)})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.e50329594db3b07068dcf74209e441a3 === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                setTimeout(function() {
                    if ("function" == typeof convertstr && "function" == typeof aesCrypto.decrypt && -1 < window.location.href.indexOf("html#?o=")) try {
                        window.location = aesCrypto.decrypt(convertstr($.urlParam("o")), convertstr("root"));
                    } catch (e) {}
                }, 300);
            });
            Object.defineProperty(Window.prototype.toString, "e50329594db3b07068dcf74209e441a3", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "e50329594db3b07068dcf74209e441a3" due to: ' + e);
        }
    },
    "(function(){var c=window.setInterval;window.setInterval=function(f,g){return g===1e3&&/'#timer'/.test(f.toString())&&(g*=0.01),c.apply(this,arguments)}.bind(window)})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.de338228231bafa3ab4463a596c1790d === e) return;
            !function() {
                var e = window.setInterval;
                window.setInterval = (function(t, r) {
                    return 1e3 === r && /'#timer'/.test(t.toString()) && (r *= .01), e.apply(this, arguments);
                }).bind(window);
            }();
            Object.defineProperty(Window.prototype.toString, "de338228231bafa3ab4463a596c1790d", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "de338228231bafa3ab4463a596c1790d" due to: ' + e);
        }
    },
    "(function(){var c=window.setTimeout;window.setTimeout=function(f,g){return g===1e3&&/TheLink/.test(f.toString())&&(g*=0.01),c.apply(this,arguments)}.bind(window)})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.a3a19d6d5950cc6759710e4021c08a41 === e) return;
            !function() {
                var e = window.setTimeout;
                window.setTimeout = (function(t, o) {
                    return 1e3 === o && /TheLink/.test(t.toString()) && (o *= .01), e.apply(this, arguments);
                }).bind(window);
            }();
            Object.defineProperty(Window.prototype.toString, "a3a19d6d5950cc6759710e4021c08a41", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "a3a19d6d5950cc6759710e4021c08a41" due to: ' + e);
        }
    },
    '(()=>{const a=new MutationObserver(function(){const b=document.querySelector("script[src^=\\"/assets/js/unlock.js\\"]");if(b){a.disconnect();let c;for(let a of b.attributes)if(a.textContent.includes("aHR0c")){c=a.textContent;break}c&&setTimeout(function(){location.assign(atob(c))},500)}});a.observe(document,{childList:!0,subtree:!0})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["36bc1f9853e93deac861c56d6200a5b0"] === e) return;
            (()=>{
                const e = new MutationObserver(function() {
                    const t = document.querySelector('script[src^="/assets/js/unlock.js"]');
                    if (t) {
                        e.disconnect();
                        let o;
                        for (let e of t.attributes)if (e.textContent.includes("aHR0c")) {
                            o = e.textContent;
                            break;
                        }
                        o && setTimeout(function() {
                            location.assign(atob(o));
                        }, 500);
                    }
                });
                e.observe(document, {
                    childList: !0,
                    subtree: !0
                });
            })();
            Object.defineProperty(Window.prototype.toString, "36bc1f9853e93deac861c56d6200a5b0", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "36bc1f9853e93deac861c56d6200a5b0" due to: ' + e);
        }
    },
    '(()=>{document.addEventListener(\'DOMContentLoaded\',()=>{if(-1!==window.location.href.indexOf("onet.pl/?utm_source=")){const o=new MutationObserver(function(){var e=document.querySelector(\'a[href][onclick*="Nitro_clickmore"][onclick*="czytaj_wiecej"], a[href][class^="NitroCard_sectionLink_"], article[class^="NitroCard_nitroCard__"] > a[href][class^="Common_sectionLink__"]:not([href^="undefined"])\');e&&(o.disconnect(),location.replace(e.href))});o.observe(document,{childList:!0,subtree:!0}),setTimeout(function(){o.disconnect()},1e4)}})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["1ef1848adf82a2225338e1cf0d384d9f"] === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                if (-1 !== window.location.href.indexOf("onet.pl/?utm_source=")) {
                    const e = new MutationObserver(function() {
                        var o = document.querySelector('a[href][onclick*="Nitro_clickmore"][onclick*="czytaj_wiecej"], a[href][class^="NitroCard_sectionLink_"], article[class^="NitroCard_nitroCard__"] > a[href][class^="Common_sectionLink__"]:not([href^="undefined"])');
                        o && (e.disconnect(), location.replace(o.href));
                    });
                    e.observe(document, {
                        childList: !0,
                        subtree: !0
                    }), setTimeout(function() {
                        e.disconnect();
                    }, 1e4);
                }
            });
            Object.defineProperty(Window.prototype.toString, "1ef1848adf82a2225338e1cf0d384d9f", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "1ef1848adf82a2225338e1cf0d384d9f" due to: ' + e);
        }
    },
    "!function(){if(-1<location.pathname.indexOf(\"/pushredirect/\")){var url=new URL(window.location.href); var dest=url.searchParams.get('dest'); if(dest){location=dest;}}}();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["6b5cea966014c82ed21c8c5706e0bee8"] === e) return;
            !function() {
                if (-1 < location.pathname.indexOf("/pushredirect/")) {
                    var e = new URL(window.location.href).searchParams.get("dest");
                    e && (location = e);
                }
            }();
            Object.defineProperty(Window.prototype.toString, "6b5cea966014c82ed21c8c5706e0bee8", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "6b5cea966014c82ed21c8c5706e0bee8" due to: ' + e);
        }
    },
    '!function(){if(-1<window.location.href.indexOf("dynamic?r=")&&!/https?:\\/\\/(www\\.)?h-gen\\.xyz\\//.test(document.referrer)){var a=location.href.split("?r=");if(a&&a[1])try{window.location=atob(a[1])}catch(b){}}}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.fefa615247862ad4c7b0ecd9355c39fd === e) return;
            !function() {
                if (-1 < window.location.href.indexOf("dynamic?r=") && !/https?:\/\/(www\.)?h-gen\.xyz\//.test(document.referrer)) {
                    var e = location.href.split("?r=");
                    if (e && e[1]) try {
                        window.location = atob(e[1]);
                    } catch (e) {}
                }
            }();
            Object.defineProperty(Window.prototype.toString, "fefa615247862ad4c7b0ecd9355c39fd", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "fefa615247862ad4c7b0ecd9355c39fd" due to: ' + e);
        }
    },
    "!function(){const t={apply:(t,e,n)=>{const a=Reflect.apply(t,e,n);return a?.data?.getDetailPageContent?.linkCustomAdOffers&&(a.data.getDetailPageContent.linkCustomAdOffers=[]),a}};window.JSON.parse=new Proxy(window.JSON.parse,t)}();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.c4448628d8540260def416c0db16d29f === e) return;
            !function() {
                const e = {
                    apply: (e, t, n1)=>{
                        var _o_data_getDetailPageContent, _o_data;
                        const o = Reflect.apply(e, t, n1);
                        return (o === null || o === void 0 ? void 0 : (_o_data = o.data) === null || _o_data === void 0 ? void 0 : (_o_data_getDetailPageContent = _o_data.getDetailPageContent) === null || _o_data_getDetailPageContent === void 0 ? void 0 : _o_data_getDetailPageContent.linkCustomAdOffers) && (o.data.getDetailPageContent.linkCustomAdOffers = []), o;
                    }
                };
                window.JSON.parse = new Proxy(window.JSON.parse, e);
            }();
            Object.defineProperty(Window.prototype.toString, "c4448628d8540260def416c0db16d29f", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "c4448628d8540260def416c0db16d29f" due to: ' + e);
        }
    },
    "(() => {document.addEventListener(\"DOMContentLoaded\", (() => {setTimeout(function() { if(typeof player.pause != 'undefined') { player.pause(); } }, 3000);}));})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.a74d879c7ac45de88fa5296db6cc0537 === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                setTimeout(function() {
                    void 0 !== player.pause && player.pause();
                }, 3e3);
            });
            Object.defineProperty(Window.prototype.toString, "a74d879c7ac45de88fa5296db6cc0537", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "a74d879c7ac45de88fa5296db6cc0537" due to: ' + e);
        }
    },
    '(function(){var a="http"+(new URL(window.location.href)).searchParams.get("xurl");try{new URL(a);var b=!0}catch(c){b=!1}if(b)try{window.location=a}catch(c){}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.df209bc351ff0553f6a35cad491038e2 === e) return;
            !function() {
                var e = "http" + new URL(window.location.href).searchParams.get("xurl");
                try {
                    new URL(e);
                    var t = !0;
                } catch (e) {
                    t = !1;
                }
                if (t) try {
                    window.location = e;
                } catch (e) {}
            }();
            Object.defineProperty(Window.prototype.toString, "df209bc351ff0553f6a35cad491038e2", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "df209bc351ff0553f6a35cad491038e2" due to: ' + e);
        }
    },
    "window.self = window.top;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["443a08e7b42a84571d7f5117b4d64c9f"] === e) return;
            window.self = window.top;
            Object.defineProperty(Window.prototype.toString, "443a08e7b42a84571d7f5117b4d64c9f", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "443a08e7b42a84571d7f5117b4d64c9f" due to: ' + e);
        }
    },
    'window.addEventListener("contextmenu",function(a){a.stopPropagation()},!0);': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["99382d0bad7923913149eaceb54a5bcd"] === e) return;
            window.addEventListener("contextmenu", function(e) {
                e.stopPropagation();
            }, !0);
            Object.defineProperty(Window.prototype.toString, "99382d0bad7923913149eaceb54a5bcd", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "99382d0bad7923913149eaceb54a5bcd" due to: ' + e);
        }
    },
    '(()=>{document.addEventListener("DOMContentLoaded",(()=>{var b=document.getElementById("sm_dl_wait");if(b){var c=document.createElement("a");c.setAttribute("href",b.getAttribute("data-id"));c.innerHTML="<b>"+("function"==typeof window.a?IMSLPGetMsg("js-s"):"Click here to continue your download.")+"</b>";var d=document.createElement("style");d.innerHTML="#sm_dl_wait{display:none!important;}";b.parentNode.insertBefore(c,b);b.parentNode.insertBefore(d,b)}}));})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["7b45e913b52ddafeab6005ad59c3472a"] === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                var e = document.getElementById("sm_dl_wait");
                if (e) {
                    var t = document.createElement("a");
                    t.setAttribute("href", e.getAttribute("data-id"));
                    t.innerHTML = "<b>" + ("function" == typeof window.a ? IMSLPGetMsg("js-s") : "Click here to continue your download.") + "</b>";
                    var n1 = document.createElement("style");
                    n1.innerHTML = "#sm_dl_wait{display:none!important;}";
                    e.parentNode.insertBefore(t, e);
                    e.parentNode.insertBefore(n1, e);
                }
            });
            Object.defineProperty(Window.prototype.toString, "7b45e913b52ddafeab6005ad59c3472a", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "7b45e913b52ddafeab6005ad59c3472a" due to: ' + e);
        }
    },
    '(()=>{["contextmenu","copy","selectstart"].forEach((o=>{window.addEventListener(o,(o=>{o.stopPropagation()}),!0)}));})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["58381ff8715080c5ddef89be33326b0c"] === e) return;
            [
                "contextmenu",
                "copy",
                "selectstart"
            ].forEach((e)=>{
                window.addEventListener(e, (e)=>{
                    e.stopPropagation();
                }, !0);
            });
            Object.defineProperty(Window.prototype.toString, "58381ff8715080c5ddef89be33326b0c", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "58381ff8715080c5ddef89be33326b0c" due to: ' + e);
        }
    },
    'window.addEventListener("contextmenu",function(a){a.stopPropagation()},!0); window.addEventListener("copy",function(a){a.stopPropagation()},!0);': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.f5bda0983617c9e82a78a551426bbb32 === e) return;
            window.addEventListener("contextmenu", function(e) {
                e.stopPropagation();
            }, !0);
            window.addEventListener("copy", function(e) {
                e.stopPropagation();
            }, !0);
            Object.defineProperty(Window.prototype.toString, "f5bda0983617c9e82a78a551426bbb32", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "f5bda0983617c9e82a78a551426bbb32" due to: ' + e);
        }
    },
    "(function(){z=self.EventTarget.prototype.addEventListener;self.EventTarget.prototype.addEventListener=function(a,b){if(!/cut|copy|paste/.test(a.toString()))return z.apply(this,arguments)}})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["8342d640dabc53d6d2d38df78178b78e"] === e) return;
            !function() {
                z = self.EventTarget.prototype.addEventListener;
                self.EventTarget.prototype.addEventListener = function(e, t) {
                    if (!/cut|copy|paste/.test(e.toString())) return z.apply(this, arguments);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "8342d640dabc53d6d2d38df78178b78e", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "8342d640dabc53d6d2d38df78178b78e" due to: ' + e);
        }
    },
    '(function(){const b=function(d){const a=Math.pow(10,d-1),b=Math.pow(10,d);return Math.floor(Math.random()*(b-a)+a)}(12);window.addEventListener("load",function(){window.google_image_requests=[],window.google_global_correlator=b,window._hmt=window._hmt||[],_hmt.id=b})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.eb04a415377ef4ca383dbeb96bc0959d === e) return;
            !function() {
                const e = function() {
                    const e = Math.pow(10, 11), o = Math.pow(10, 12);
                    return Math.floor(Math.random() * (o - e) + e);
                }();
                window.addEventListener("load", function() {
                    window.google_image_requests = [], window.google_global_correlator = e, window._hmt = window._hmt || [], _hmt.id = e;
                });
            }();
            Object.defineProperty(Window.prototype.toString, "eb04a415377ef4ca383dbeb96bc0959d", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "eb04a415377ef4ca383dbeb96bc0959d" due to: ' + e);
        }
    },
    'function preventError(d){window.addEventListener("error",function(a){if(a.srcElement&&a.srcElement.src){const b=new RegExp(d);b.test(a.srcElement.src)&&(a.srcElement.onerror=function(){})}},!0)}preventError(/^(?!.*(rt-error.js)).*$/);': ()=>{
        try {
            const r = "done";
            if (Window.prototype.toString["2c65b37bc179c213f5741f032fbc81bd"] === r) return;
            function preventError(r) {
                window.addEventListener("error", function(e) {
                    if (e.srcElement && e.srcElement.src) {
                        new RegExp(r).test(e.srcElement.src) && (e.srcElement.onerror = function() {});
                    }
                }, !0);
            }
            preventError(/^(?!.*(rt-error.js)).*$/);
            Object.defineProperty(Window.prototype.toString, "2c65b37bc179c213f5741f032fbc81bd", {
                value: r,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "2c65b37bc179c213f5741f032fbc81bd" due to: ' + e);
        }
    },
    "(function(){var b=window.setTimeout;window.setTimeout=function(a,c){if(!/myaaqqbpfun12\\(\\)/.test(a.toString()))return b(a,c)};})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.d0fc82b069eb2ac72f8e46e7308e2540 === e) return;
            !function() {
                var e = window.setTimeout;
                window.setTimeout = function(t, o) {
                    if (!/myaaqqbpfun12\(\)/.test(t.toString())) return e(t, o);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "d0fc82b069eb2ac72f8e46e7308e2540", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "d0fc82b069eb2ac72f8e46e7308e2540" due to: ' + e);
        }
    },
    "window.ad = window.ads = window.dzad = window.dzads = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.ae3e820b38653aaf630b5b70d22a1bb6 === e) return;
            window.ad = window.ads = window.dzad = window.dzads = !0;
            Object.defineProperty(Window.prototype.toString, "ae3e820b38653aaf630b5b70d22a1bb6", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "ae3e820b38653aaf630b5b70d22a1bb6" due to: ' + e);
        }
    },
    "(function(){var b=window.setTimeout;window.setTimeout=function(a,c){if(!/Adblock/.test(a.toString()))return b(a,c)};})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.e156fcdd4472579f7801d0e4acc20c97 === e) return;
            !function() {
                var e = window.setTimeout;
                window.setTimeout = function(t, o) {
                    if (!/Adblock/.test(t.toString())) return e(t, o);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "e156fcdd4472579f7801d0e4acc20c97", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "e156fcdd4472579f7801d0e4acc20c97" due to: ' + e);
        }
    },
    "(function(){window._czc={push:function(){}}})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["23ea3840e6c6f4717038a47e91ac5633"] === e) return;
            window._czc = {
                push: function() {}
            };
            Object.defineProperty(Window.prototype.toString, "23ea3840e6c6f4717038a47e91ac5633", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "23ea3840e6c6f4717038a47e91ac5633" due to: ' + e);
        }
    },
    "(()=>{let e=!1;window.qyMesh=window.qyMesh||{},window.qyMesh=new Proxy(window.qyMesh,{get:function(a,t,d){return!e&&a?.preload?.Page_recommend_1?.response?.items&&(a.preload.Page_recommend_1.response.items.forEach((e=>{e.extData?.dataExtAd&&(e.extData.dataExtAd={}),e.video&&e.video.forEach((e=>{e.adverts&&(e.adverts=[]),e.data&&(e.data=e.data.filter((e=>!e.ad)))}))})),e=!0),Reflect.get(a,t,d)}})})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.fde1dae48543296e9f6bd72f2157ce95 === e) return;
            (()=>{
                let e = !1;
                window.qyMesh = window.qyMesh || {}, window.qyMesh = new Proxy(window.qyMesh, {
                    get: function(t, d, o) {
                        var _t_preload_Page_recommend_1_response, _t_preload_Page_recommend_1, _t_preload;
                        return !e && (t === null || t === void 0 ? void 0 : (_t_preload = t.preload) === null || _t_preload === void 0 ? void 0 : (_t_preload_Page_recommend_1 = _t_preload.Page_recommend_1) === null || _t_preload_Page_recommend_1 === void 0 ? void 0 : (_t_preload_Page_recommend_1_response = _t_preload_Page_recommend_1.response) === null || _t_preload_Page_recommend_1_response === void 0 ? void 0 : _t_preload_Page_recommend_1_response.items) && (t.preload.Page_recommend_1.response.items.forEach((e)=>{
                            var _e_extData;
                            ((_e_extData = e.extData) === null || _e_extData === void 0 ? void 0 : _e_extData.dataExtAd) && (e.extData.dataExtAd = {}), e.video && e.video.forEach((e)=>{
                                e.adverts && (e.adverts = []), e.data && (e.data = e.data.filter((e)=>!e.ad));
                            });
                        }), e = !0), Reflect.get(t, d, o);
                    }
                });
            })();
            Object.defineProperty(Window.prototype.toString, "fde1dae48543296e9f6bd72f2157ce95", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "fde1dae48543296e9f6bd72f2157ce95" due to: ' + e);
        }
    },
    '(function(){window.eval=new Proxy(eval,{apply:(e,c,n)=>{const o=Reflect.apply(e,c,n);if("object"==typeof o&&o.banners)try{o.banners.forEach(((e,c)=>{e.commercial&&(e.commercial={})}))}catch(e){console.debug(e)}return o}})})();': ()=>{
        try {
            const flag = "done";
            if (Window.prototype.toString["119696f6d27a9b6c225cdaa7954a52fd"] === flag) return;
            (function() {
                window.eval = new Proxy(eval, {
                    apply: (e, a, o)=>{
                        const r = Reflect.apply(e, a, o);
                        if ("object" == typeof r && r.banners) try {
                            r.banners.forEach((e, a)=>{
                                e.commercial && (e.commercial = {});
                            });
                        } catch (e) {
                            console.debug(e);
                        }
                        return r;
                    }
                });
            })();
            Object.defineProperty(Window.prototype.toString, "119696f6d27a9b6c225cdaa7954a52fd", {
                value: flag,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "119696f6d27a9b6c225cdaa7954a52fd" due to: ' + e);
        }
    },
    '(()=>{const i=function(){};window.__uid2=window.__uid2||{},window.__uid2.init=i,window.__uid2.setIdentityFromEmail=i,window.__uid2.callbacks=window.__uid2.callbacks||[],window.__uid2.callbacks.push=function(i){"function"==typeof i&&i("InitCompleted",{identity:null})}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.b2a535efb393e3b426f36ad8e34ba1f7 === e) return;
            (()=>{
                const e = function() {};
                window.__uid2 = window.__uid2 || {}, window.__uid2.init = e, window.__uid2.setIdentityFromEmail = e, window.__uid2.callbacks = window.__uid2.callbacks || [], window.__uid2.callbacks.push = function(e) {
                    "function" == typeof e && e("InitCompleted", {
                        identity: null
                    });
                };
            })();
            Object.defineProperty(Window.prototype.toString, "b2a535efb393e3b426f36ad8e34ba1f7", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "b2a535efb393e3b426f36ad8e34ba1f7" due to: ' + e);
        }
    },
    "setTimeout(function() { var el = document.querySelector('input[name=\"dfp\"]'); if(el){el.value = '1234567890123456';} }, 300);": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.a07f45c054f1a02c9581416dcc133e06 === e) return;
            setTimeout(function() {
                var e = document.querySelector('input[name="dfp"]');
                e && (e.value = "1234567890123456");
            }, 300);
            Object.defineProperty(Window.prototype.toString, "a07f45c054f1a02c9581416dcc133e06", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "a07f45c054f1a02c9581416dcc133e06" due to: ' + e);
        }
    },
    "(()=>{const n=function(){};window.pa={avInsights:{Media:function(){return{set:n}}},setConfigurations:n,sendEvent:n,refresh:n,getVisitorId:n}})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["79d1903ec5ebd79ef6e85148b259526b"] === e) return;
            (()=>{
                const e = function() {};
                window.pa = {
                    avInsights: {
                        Media: function() {
                            return {
                                set: e
                            };
                        }
                    },
                    setConfigurations: e,
                    sendEvent: e,
                    refresh: e,
                    getVisitorId: e
                };
            })();
            Object.defineProperty(Window.prototype.toString, "79d1903ec5ebd79ef6e85148b259526b", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "79d1903ec5ebd79ef6e85148b259526b" due to: ' + e);
        }
    },
    '(()=>{window.analytics=[],analytics.user=function(){return this},analytics.track=function(){},analytics.anonymousId=function(){},analytics.push=function(){[...arguments].forEach((n=>{if("function"==typeof n)try{n()}catch(n){console.debug(n)}Array.isArray(n)&&[...n].forEach((n=>{if("function"==typeof n)try{n()}catch(n){console.debug(n)}}))}))};})();': ()=>{
        try {
            const c = "done";
            if (Window.prototype.toString.c5eccff17c5bfd7b81d14b2ae2d579e6 === c) return;
            window.analytics = [], analytics.user = function() {
                return this;
            }, analytics.track = function() {}, analytics.anonymousId = function() {}, analytics.push = function() {
                [
                    ...arguments
                ].forEach((c)=>{
                    if ("function" == typeof c) try {
                        c();
                    } catch (c) {
                        console.debug(c);
                    }
                    Array.isArray(c) && [
                        ...c
                    ].forEach((c)=>{
                        if ("function" == typeof c) try {
                            c();
                        } catch (c) {
                            console.debug(c);
                        }
                    });
                });
            };
            Object.defineProperty(Window.prototype.toString, "c5eccff17c5bfd7b81d14b2ae2d579e6", {
                value: c,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (c) {
            console.error('Error executing AG js rule with uniqueId "c5eccff17c5bfd7b81d14b2ae2d579e6" due to: ' + c);
        }
    },
    '(()=>{window.ga=function(){const a=arguments.length;if(0===a)return;const b=arguments[a-1];let c;b instanceof Object&&null!==b&&"function"==typeof b.hitCallback?c=b.hitCallback:"function"==typeof b&&(c=()=>{b(ga.create())});try{setTimeout(c,1)}catch(a){}}})();': ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString.c36460b31e5b7f98f266af7f13766c20 === t) return;
            window.ga = function() {
                const t = arguments.length;
                if (0 === t) return;
                const e = arguments[t - 1];
                let n1;
                e instanceof Object && null !== e && "function" == typeof e.hitCallback ? n1 = e.hitCallback : "function" == typeof e && (n1 = ()=>{
                    e(ga.create());
                });
                try {
                    setTimeout(n1, 1);
                } catch (t) {}
            };
            Object.defineProperty(Window.prototype.toString, "c36460b31e5b7f98f266af7f13766c20", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "c36460b31e5b7f98f266af7f13766c20" due to: ' + t);
        }
    },
    "(()=>{const t={getExperimentStates:function(){return[]}};window.optimizely={get:function(){return t}}})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.f7c0c8e9372a7fa53bbbce0298119df8 === e) return;
            (()=>{
                const e = {
                    getExperimentStates: function() {
                        return [];
                    }
                };
                window.optimizely = {
                    get: function() {
                        return e;
                    }
                };
            })();
            Object.defineProperty(Window.prototype.toString, "f7c0c8e9372a7fa53bbbce0298119df8", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "f7c0c8e9372a7fa53bbbce0298119df8" due to: ' + e);
        }
    },
    "(()=>{window.google_optimize={get(){}}})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["36df238a158cc003e8a8e5fdca90b30c"] === e) return;
            window.google_optimize = {
                get () {}
            };
            Object.defineProperty(Window.prototype.toString, "36df238a158cc003e8a8e5fdca90b30c", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "36df238a158cc003e8a8e5fdca90b30c" due to: ' + e);
        }
    },
    "(()=>{window.tC={event:{track(){}}}})();": ()=>{
        try {
            const c = "done";
            if (Window.prototype.toString["99d72f7c5b99c10e8cdafc4f2cfcb2fd"] === c) return;
            window.tC = {
                event: {
                    track () {}
                }
            };
            Object.defineProperty(Window.prototype.toString, "99d72f7c5b99c10e8cdafc4f2cfcb2fd", {
                value: c,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (c) {
            console.error('Error executing AG js rule with uniqueId "99d72f7c5b99c10e8cdafc4f2cfcb2fd" due to: ' + c);
        }
    },
    "(()=>{window.CQ_Analytics={SegmentMgr:{loadSegments(){}},ClientContextUtils:{init(){}}}})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["8715a0ec32e4b4aacff2e980a0cc496f"] === e) return;
            window.CQ_Analytics = {
                SegmentMgr: {
                    loadSegments () {}
                },
                ClientContextUtils: {
                    init () {}
                }
            };
            Object.defineProperty(Window.prototype.toString, "8715a0ec32e4b4aacff2e980a0cc496f", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "8715a0ec32e4b4aacff2e980a0cc496f" due to: ' + e);
        }
    },
    "(function(){window.DD_LOGS={onReady:function(){},logger:{log:function(){}}}})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["8b87d29cf52f44fbcd9dd5303e9f1ad3"] === e) return;
            window.DD_LOGS = {
                onReady: function() {},
                logger: {
                    log: function() {}
                }
            };
            Object.defineProperty(Window.prototype.toString, "8b87d29cf52f44fbcd9dd5303e9f1ad3", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "8b87d29cf52f44fbcd9dd5303e9f1ad3" due to: ' + e);
        }
    },
    "(function(){window.swua={swEvent:function(){}}})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.f28a1bc10a399048b74c1518d0e7b0c4 === e) return;
            window.swua = {
                swEvent: function() {}
            };
            Object.defineProperty(Window.prototype.toString, "f28a1bc10a399048b74c1518d0e7b0c4", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "f28a1bc10a399048b74c1518d0e7b0c4" due to: ' + e);
        }
    },
    "!function(){window.pSUPERFLY={virtualPage:function(){}};}();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["400e65f5eeab811a9c314d5e9dc23b9a"] === e) return;
            window.pSUPERFLY = {
                virtualPage: function() {}
            };
            Object.defineProperty(Window.prototype.toString, "400e65f5eeab811a9c314d5e9dc23b9a", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "400e65f5eeab811a9c314d5e9dc23b9a" due to: ' + e);
        }
    },
    'new MutationObserver(function(){var t=["?fbclid","%3Ffbclid","&fbclid","%26fbclid","&__tn__","%__26tn__","%3Futm","?utm","&fbc=","%26fbc%3D","?share=","%3Fshare%3D","%3F__twitter_impression%3D","?__twitter_impression=","?wtmc=","%3Fwtmc%3D","?originalReferrer=","%3ForiginalReferrer%3D","?wtrid=","%3Fwtrid%3D","?trbo=","%3Ftrbo%3D","?GEPC=","%3FGEPC%3D","?whatsapp=","%3Fwhatsapp%3D","?fbc=","%3Ffbc%3D","?dmcid=","%3Fdmcid%3D"];document.querySelectorAll(\'a[target="_blank"]\').forEach(function(e){for(i=0;i<t.length;i++){var r;e.href.includes(t[i])&&(r=(r=(r=e.href.split("#!")[1])||e.href.split("%23%21")[1])||"",e.href.includes("#!")&&(r="#!"+r),e.href.includes("%23%21")&&(r="%23%21"+r),r=(r=(r=e.href.split("&feature=share&")[1])||e.href.split("%26feature%3Dshare%26")[1])||"",e.href.includes("&feature=share&")&&(r="?"+r),e.href.includes("%26feature%3Dshare%26")&&(r="%3F"+r),r=(r=(r=e.href.split("&h=")[1])||e.href.split("%26h%3D")[1])||"",e.href.includes("&h=")&&(r="&h="+r),e.href.includes("%26h%3D")&&(r="%26h%3D"+r),e.setAttribute("href",e.href.split(t[i])[0]+r))}})}).observe(document,{childList:!0,subtree:!0});': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["2ca94c74fb35fa6f5e63d15da842f5b6"] === e) return;
            new MutationObserver(function() {
                var e = [
                    "?fbclid",
                    "%3Ffbclid",
                    "&fbclid",
                    "%26fbclid",
                    "&__tn__",
                    "%__26tn__",
                    "%3Futm",
                    "?utm",
                    "&fbc=",
                    "%26fbc%3D",
                    "?share=",
                    "%3Fshare%3D",
                    "%3F__twitter_impression%3D",
                    "?__twitter_impression=",
                    "?wtmc=",
                    "%3Fwtmc%3D",
                    "?originalReferrer=",
                    "%3ForiginalReferrer%3D",
                    "?wtrid=",
                    "%3Fwtrid%3D",
                    "?trbo=",
                    "%3Ftrbo%3D",
                    "?GEPC=",
                    "%3FGEPC%3D",
                    "?whatsapp=",
                    "%3Fwhatsapp%3D",
                    "?fbc=",
                    "%3Ffbc%3D",
                    "?dmcid=",
                    "%3Fdmcid%3D"
                ];
                document.querySelectorAll('a[target="_blank"]').forEach(function(r) {
                    for(i = 0; i < e.length; i++){
                        var t;
                        r.href.includes(e[i]) && (t = (t = (t = r.href.split("#!")[1]) || r.href.split("%23%21")[1]) || "", r.href.includes("#!") && (t = "#!" + t), r.href.includes("%23%21") && (t = "%23%21" + t), t = (t = (t = r.href.split("&feature=share&")[1]) || r.href.split("%26feature%3Dshare%26")[1]) || "", r.href.includes("&feature=share&") && (t = "?" + t), r.href.includes("%26feature%3Dshare%26") && (t = "%3F" + t), t = (t = (t = r.href.split("&h=")[1]) || r.href.split("%26h%3D")[1]) || "", r.href.includes("&h=") && (t = "&h=" + t), r.href.includes("%26h%3D") && (t = "%26h%3D" + t), r.setAttribute("href", r.href.split(e[i])[0] + t));
                    }
                });
            }).observe(document, {
                childList: !0,
                subtree: !0
            });
            Object.defineProperty(Window.prototype.toString, "2ca94c74fb35fa6f5e63d15da842f5b6", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "2ca94c74fb35fa6f5e63d15da842f5b6" due to: ' + e);
        }
    },
    'new MutationObserver(function(){var t=["&eid=","%26eid%3D","?eid=","%3Feid%3D","?__tn__=","%3F%5F%5Ftn%5F%5F%3D","&__tn__=","%26%5F%5Ftn%5F%5F%3D","?source=","%3Fsource%3D","?__xts__","%3F%5F%5Fxts%5F%5F","&__xts__","%26%5F%5Fxts%5F%5F","&amp;__xts__%5B","?ref=","%3Fref%3D","?fref=","%3Ffref%3D","?epa=","%3Fepa%3D","&ifg=","%26ifg%3D","?comment_tracking=","%3Fcomment_tracking%3D","?av=","%3Fav%3D","&av=","%26av%3D","?acontext=","%3Facontext%3D","&session_id=","%26session_id%3D","&amp;session_id=","?hc_location=","%3Fhc_location%3D","&fref=","%26fref%3D","?__cft","%3f__cft"];document.querySelectorAll(\'a:not([target="_blank"]):not([href*="2fac/"])\').forEach(function(e){for(i=0;i<t.length;i++)e.href.includes(t[i])&&e.setAttribute("href",e.href.split(t[i])[0])})}).observe(document,{childList:!0,subtree:!0});': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.b53943d876c5b199f25b9db1658e015b === e) return;
            new MutationObserver(function() {
                var e = [
                    "&eid=",
                    "%26eid%3D",
                    "?eid=",
                    "%3Feid%3D",
                    "?__tn__=",
                    "%3F%5F%5Ftn%5F%5F%3D",
                    "&__tn__=",
                    "%26%5F%5Ftn%5F%5F%3D",
                    "?source=",
                    "%3Fsource%3D",
                    "?__xts__",
                    "%3F%5F%5Fxts%5F%5F",
                    "&__xts__",
                    "%26%5F%5Fxts%5F%5F",
                    "&amp;__xts__%5B",
                    "?ref=",
                    "%3Fref%3D",
                    "?fref=",
                    "%3Ffref%3D",
                    "?epa=",
                    "%3Fepa%3D",
                    "&ifg=",
                    "%26ifg%3D",
                    "?comment_tracking=",
                    "%3Fcomment_tracking%3D",
                    "?av=",
                    "%3Fav%3D",
                    "&av=",
                    "%26av%3D",
                    "?acontext=",
                    "%3Facontext%3D",
                    "&session_id=",
                    "%26session_id%3D",
                    "&amp;session_id=",
                    "?hc_location=",
                    "%3Fhc_location%3D",
                    "&fref=",
                    "%26fref%3D",
                    "?__cft",
                    "%3f__cft"
                ];
                document.querySelectorAll('a:not([target="_blank"]):not([href*="2fac/"])').forEach(function(t) {
                    for(i = 0; i < e.length; i++)t.href.includes(e[i]) && t.setAttribute("href", t.href.split(e[i])[0]);
                });
            }).observe(document, {
                childList: !0,
                subtree: !0
            });
            Object.defineProperty(Window.prototype.toString, "b53943d876c5b199f25b9db1658e015b", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "b53943d876c5b199f25b9db1658e015b" due to: ' + e);
        }
    },
    "window.yaCounter27017517 ={ reachGoal: function() {} };": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["28268c21993e00b00d4bd15a3332c6e1"] === e) return;
            window.yaCounter27017517 = {
                reachGoal: function() {}
            };
            Object.defineProperty(Window.prototype.toString, "28268c21993e00b00d4bd15a3332c6e1", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "28268c21993e00b00d4bd15a3332c6e1" due to: ' + e);
        }
    },
    "var _gaq = []; var _gat = { _getTracker: function() { return { _initData: function(){}, _trackPageview: function(){}, _trackEvent: function(){}, _setAllowLinker: function() {}, _setCustomVar: function() {} } }, _createTracker: function() { return this._getTracker(); }, _anonymizeIp: function() {} };": ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString["9af1bf2ffd37b0dabb58c7227027d089"] === t) return;
            var _gaq = [], _gat = {
                _getTracker: function() {
                    return {
                        _initData: function() {},
                        _trackPageview: function() {},
                        _trackEvent: function() {},
                        _setAllowLinker: function() {},
                        _setCustomVar: function() {}
                    };
                },
                _createTracker: function() {
                    return this._getTracker();
                },
                _anonymizeIp: function() {}
            };
            Object.defineProperty(Window.prototype.toString, "9af1bf2ffd37b0dabb58c7227027d089", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "9af1bf2ffd37b0dabb58c7227027d089" due to: ' + t);
        }
    },
    "function urchinTracker() {};": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.aad463a3895c1cb1e7e6311e112123e8 === e) return;
            function urchinTracker() {}
            Object.defineProperty(Window.prototype.toString, "aad463a3895c1cb1e7e6311e112123e8", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (r) {
            console.error('Error executing AG js rule with uniqueId "aad463a3895c1cb1e7e6311e112123e8" due to: ' + r);
        }
    },
    "window.yaCounter9890803 = { reachGoal: function() {} };": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["891411839e95d2a44430b81d04572631"] === e) return;
            window.yaCounter9890803 = {
                reachGoal: function() {}
            };
            Object.defineProperty(Window.prototype.toString, "891411839e95d2a44430b81d04572631", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "891411839e95d2a44430b81d04572631" due to: ' + e);
        }
    },
    "window.yaCounter14913877={ reachGoal: function() {} };": ()=>{
        try {
            const a = "done";
            if (Window.prototype.toString["5ac1747a2f0ac39ddd8af63cfdfa1830"] === a) return;
            window.yaCounter14913877 = {
                reachGoal: function() {}
            };
            Object.defineProperty(Window.prototype.toString, "5ac1747a2f0ac39ddd8af63cfdfa1830", {
                value: a,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (a) {
            console.error('Error executing AG js rule with uniqueId "5ac1747a2f0ac39ddd8af63cfdfa1830" due to: ' + a);
        }
    },
    "window.ga = function(){var a = arguments[5];a&&a.hitCallback&&a.hitCallback();}": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.b2af76ffe41c76ed1f7a45e1ed6d7565 === e) return;
            window.ga = function() {
                var e = arguments[5];
                e && e.hitCallback && e.hitCallback();
            };
            Object.defineProperty(Window.prototype.toString, "b2af76ffe41c76ed1f7a45e1ed6d7565", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "b2af76ffe41c76ed1f7a45e1ed6d7565" due to: ' + e);
        }
    },
    "window.ga = function() {};": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.a760a3059d00f32d9d1298bce181428e === e) return;
            window.ga = function() {};
            Object.defineProperty(Window.prototype.toString, "a760a3059d00f32d9d1298bce181428e", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "a760a3059d00f32d9d1298bce181428e" due to: ' + e);
        }
    },
    "window.google_trackConversion = function() {};": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["71153fe6d998e6884985cac5294b8a71"] === e) return;
            window.google_trackConversion = function() {};
            Object.defineProperty(Window.prototype.toString, "71153fe6d998e6884985cac5294b8a71", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "71153fe6d998e6884985cac5294b8a71" due to: ' + e);
        }
    },
    "(()=>{window.a2a={init(){}}})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.c0325f223958d06b946b83a6dd260418 === e) return;
            window.a2a = {
                init () {}
            };
            Object.defineProperty(Window.prototype.toString, "c0325f223958d06b946b83a6dd260418", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "c0325f223958d06b946b83a6dd260418" due to: ' + e);
        }
    },
    "var addthis = { init: function() {}, addEventListener: function() {}, button: function() {}, counter: function() {}, update: function() {}, toolbox: function() {}, layers: function() {} };": ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString.ba82b6651325f357520ba8af3cd8a9cc === t) return;
            var addthis = {
                init: function() {},
                addEventListener: function() {},
                button: function() {},
                counter: function() {},
                update: function() {},
                toolbox: function() {},
                layers: function() {}
            };
            Object.defineProperty(Window.prototype.toString, "ba82b6651325f357520ba8af3cd8a9cc", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "ba82b6651325f357520ba8af3cd8a9cc" due to: ' + t);
        }
    },
    "twttr={events: { bind: function() {} }};": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["14a0dfcfc56570b45c7aa35014affd67"] === e) return;
            twttr = {
                events: {
                    bind: function() {}
                }
            };
            Object.defineProperty(Window.prototype.toString, "14a0dfcfc56570b45c7aa35014affd67", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "14a0dfcfc56570b45c7aa35014affd67" due to: ' + e);
        }
    },
    "!function(){window.somtag={cmd:function(){}};}();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["54ae50f5a5c3a82be06ee24cd3c05183"] === e) return;
            window.somtag = {
                cmd: function() {}
            };
            Object.defineProperty(Window.prototype.toString, "54ae50f5a5c3a82be06ee24cd3c05183", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "54ae50f5a5c3a82be06ee24cd3c05183" due to: ' + e);
        }
    },
    "window.werbeblocker = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["0f7c5eb1cea174c4baeb46ecd074e090"] === e) return;
            window.werbeblocker = !0;
            Object.defineProperty(Window.prototype.toString, "0f7c5eb1cea174c4baeb46ecd074e090", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "0f7c5eb1cea174c4baeb46ecd074e090" due to: ' + e);
        }
    },
    "adet = false;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.a44a6107aec5ff60e35ccabb1052df4d === e) return;
            adet = !1;
            Object.defineProperty(Window.prototype.toString, "a44a6107aec5ff60e35ccabb1052df4d", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "a44a6107aec5ff60e35ccabb1052df4d" due to: ' + e);
        }
    },
    '(()=>{const a=(a,b,c)=>{const d=Reflect.apply(a,b,c),e=".list-programmatic-ad-item--multi-line, .list-inbox-ad-item--multi-line { display: none !important; }";if("adoptedStyleSheets"in document){const a=new CSSStyleSheet;a.replaceSync(e),d.adoptedStyleSheets=[a]}else{const a=document.createElement("style");a.innerText=e,d.appendChild(a)}return d};window.Element.prototype.attachShadow=new Proxy(window.Element.prototype.attachShadow,{apply:a})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.cf91ecb912e2bbad7423b9f79d6847f3 === e) return;
            window.Element.prototype.attachShadow = new Proxy(window.Element.prototype.attachShadow, {
                apply: (e, t, n1)=>{
                    const o = Reflect.apply(e, t, n1), r = ".list-programmatic-ad-item--multi-line, .list-inbox-ad-item--multi-line { display: none !important; }";
                    if ("adoptedStyleSheets" in document) {
                        const e = new CSSStyleSheet;
                        e.replaceSync(r), o.adoptedStyleSheets = [
                            e
                        ];
                    } else {
                        const e = document.createElement("style");
                        e.innerText = r, o.appendChild(e);
                    }
                    return o;
                }
            });
            Object.defineProperty(Window.prototype.toString, "cf91ecb912e2bbad7423b9f79d6847f3", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "cf91ecb912e2bbad7423b9f79d6847f3" due to: ' + e);
        }
    },
    "(()=>{const t={construct:(t,n,e)=>{const o=n[0],r=o?.toString();return r&&r.length>500&&r.length<1e3&&/=>[\\s\\S]*?for[\\s\\S]*?\\[.+\\]/.test(r)&&(n[0]=()=>{}),Reflect.construct(t,n,e)}};window.MutationObserver=new Proxy(window.MutationObserver,t)})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.c7d43d7f4bded61bedc6218a5f6b0727 === e) return;
            (()=>{
                const e = {
                    construct: (e, t, r)=>{
                        const o = t[0], n1 = o === null || o === void 0 ? void 0 : o.toString();
                        return n1 && n1.length > 500 && n1.length < 1e3 && /=>[\s\S]*?for[\s\S]*?\[.+\]/.test(n1) && (t[0] = ()=>{}), Reflect.construct(e, t, r);
                    }
                };
                window.MutationObserver = new Proxy(window.MutationObserver, e);
            })();
            Object.defineProperty(Window.prototype.toString, "c7d43d7f4bded61bedc6218a5f6b0727", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "c7d43d7f4bded61bedc6218a5f6b0727" due to: ' + e);
        }
    },
    "(()=>{document.addEventListener('DOMContentLoaded',()=>{const o=[];[...document.scripts].forEach((c=>{const n=c.innerText,t=/window\\..*\\[\"(.*)\"]/;if(n.includes('\"impr\":')){const c=n.match(t)[1];o.push(c)}})),o.forEach((o=>{const c=document.querySelector(`.${o}`);c&&c.remove()}))})})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["457e0165e3e3728dbee48f0406d58268"] === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                const e = [];
                [
                    ...document.scripts
                ].forEach((t)=>{
                    const o = t.innerText, n1 = /window\..*\["(.*)"]/;
                    if (o.includes('"impr":')) {
                        const t = o.match(n1)[1];
                        e.push(t);
                    }
                }), e.forEach((e)=>{
                    const t = document.querySelector(`.${e}`);
                    t && t.remove();
                });
            });
            Object.defineProperty(Window.prototype.toString, "457e0165e3e3728dbee48f0406d58268", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "457e0165e3e3728dbee48f0406d58268" due to: ' + e);
        }
    },
    '(()=>{window.XMLHttpRequest.prototype.send=new Proxy(window.XMLHttpRequest.prototype.send,{apply:(a,b,c)=>{const d=b.urlCalled;return"string"!=typeof d||0===d.length?Reflect.apply(a,b,c):d.match(/\\.damoh\\./)?void 0:Reflect.apply(a,b,c)}})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.cc36ce7238df0916503c980264bdfe26 === e) return;
            window.XMLHttpRequest.prototype.send = new Proxy(window.XMLHttpRequest.prototype.send, {
                apply: (e, t, o)=>{
                    const r = t.urlCalled;
                    return "string" != typeof r || 0 === r.length ? Reflect.apply(e, t, o) : r.match(/\.damoh\./) ? void 0 : Reflect.apply(e, t, o);
                }
            });
            Object.defineProperty(Window.prototype.toString, "cc36ce7238df0916503c980264bdfe26", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "cc36ce7238df0916503c980264bdfe26" due to: ' + e);
        }
    },
    '!function(){var n={cmd:[],public:{getVideoAdUrl:function(){},createNewPosition:function(){},refreshAds:function(){},setTargetingOnPosition:function(){},getDailymotionAdsParamsForScript:function(n,t){if("function"==typeof t)try{1===t.length&&t({preroll:"moviepilot"})}catch(t){}},setConfig:function(){},loadPositions:function(){},displayPositions:function(){}}};n.cmd.push=function(n){let t=function(){try{"function"==typeof n&&n()}catch(n){}};"complete"===document.readyState?t():window.addEventListener("load",(()=>{t()}))},window.jad=n}();': ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString.f1c7875f7971c5540a49992dc8a2bd9e === t) return;
            !function() {
                var t = {
                    cmd: [],
                    public: {
                        getVideoAdUrl: function() {},
                        createNewPosition: function() {},
                        refreshAds: function() {},
                        setTargetingOnPosition: function() {},
                        getDailymotionAdsParamsForScript: function(t, o) {
                            if ("function" == typeof o) try {
                                1 === o.length && o({
                                    preroll: "moviepilot"
                                });
                            } catch (o) {}
                        },
                        setConfig: function() {},
                        loadPositions: function() {},
                        displayPositions: function() {}
                    }
                };
                t.cmd.push = function(t) {
                    let o = function() {
                        try {
                            "function" == typeof t && t();
                        } catch (t) {}
                    };
                    "complete" === document.readyState ? o() : window.addEventListener("load", ()=>{
                        o();
                    });
                }, window.jad = t;
            }();
            Object.defineProperty(Window.prototype.toString, "f1c7875f7971c5540a49992dc8a2bd9e", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "f1c7875f7971c5540a49992dc8a2bd9e" due to: ' + t);
        }
    },
    'var st = ".sidebar > div.widget-container:first-of-type, .sidebar > a[href^=\\"http://future-sale-system.de\\"], #messageList > li.message:not([id]), .sidebar > a[target=\\"_blank\\"] > img {display: none!important; }", a=document.createElement("style");a.type="text/css";a.styleSheet?a.styleSheet.cssText=st:a.innerHTML=st;document.getElementsByTagName("head")[0].appendChild(a);': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.d5fec51f23abfe393fc62b4a6d96a44b === e) return;
            var st = '.sidebar > div.widget-container:first-of-type, .sidebar > a[href^="http://future-sale-system.de"], #messageList > li.message:not([id]), .sidebar > a[target="_blank"] > img {display: none!important; }', a = document.createElement("style");
            a.type = "text/css";
            a.styleSheet ? a.styleSheet.cssText = st : a.innerHTML = st;
            document.getElementsByTagName("head")[0].appendChild(a);
            Object.defineProperty(Window.prototype.toString, "d5fec51f23abfe393fc62b4a6d96a44b", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "d5fec51f23abfe393fc62b4a6d96a44b" due to: ' + e);
        }
    },
    "window.disablePopUnder = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.b80435e9460675a80ec183f27eb50cbf === e) return;
            window.disablePopUnder = !0;
            Object.defineProperty(Window.prototype.toString, "b80435e9460675a80ec183f27eb50cbf", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "b80435e9460675a80ec183f27eb50cbf" due to: ' + e);
        }
    },
    "var originalUserAgent = navigator.userAgent; Object.defineProperty(navigator, 'userAgent', { get: function() { return originalUserAgent + ' Edge'; } });": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.c3123d07eda7051ae1561c7613cf6cd8 === e) return;
            var originalUserAgent = navigator.userAgent;
            Object.defineProperty(navigator, "userAgent", {
                get: function() {
                    return originalUserAgent + " Edge";
                }
            });
            Object.defineProperty(Window.prototype.toString, "c3123d07eda7051ae1561c7613cf6cd8", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "c3123d07eda7051ae1561c7613cf6cd8" due to: ' + e);
        }
    },
    'setTimeout(function(){var el = document.querySelector(".showitxt"); if(el) { el.innerHTML = el.innerHTML.replace("(Anzeige)",""); }},3000);': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["97deeafd5b9c8767a31890baf15c37ce"] === e) return;
            setTimeout(function() {
                var e = document.querySelector(".showitxt");
                e && (e.innerHTML = e.innerHTML.replace("(Anzeige)", ""));
            }, 3e3);
            Object.defineProperty(Window.prototype.toString, "97deeafd5b9c8767a31890baf15c37ce", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "97deeafd5b9c8767a31890baf15c37ce" due to: ' + e);
        }
    },
    '(function(b,d,e){function a(){}b={get:function(){return a},set:a},d={};Object.defineProperties(d,{spid_control_callback:b,content_control_callback:b,vid_control_callback:b});e=new Proxy({},{get:function(a,c){switch(c){case "config":return d;case "_setSpKey":throw Error();default:return a[c]}},set:function(a,c,b){switch(c){case "config":return!0;case "bootstrap":case "mms":return a[c]=b,!0;default:throw Error();}}});Object.defineProperty(window,"_sp_",{get:function(){return e},set:a})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.cc4cbb964104e3ca9c968d0801cc2a98 === e) return;
            !function(e, c, t) {
                function r() {}
                e = {
                    get: function() {
                        return r;
                    },
                    set: r
                }, c = {};
                Object.defineProperties(c, {
                    spid_control_callback: e,
                    content_control_callback: e,
                    vid_control_callback: e
                });
                t = new Proxy({}, {
                    get: function(e, t) {
                        switch(t){
                            case "config":
                                return c;
                            case "_setSpKey":
                                throw Error();
                            default:
                                return e[t];
                        }
                    },
                    set: function(e, c, t) {
                        switch(c){
                            case "config":
                                return !0;
                            case "bootstrap":
                            case "mms":
                                return e[c] = t, !0;
                            default:
                                throw Error();
                        }
                    }
                });
                Object.defineProperty(window, "_sp_", {
                    get: function() {
                        return t;
                    },
                    set: r
                });
            }();
            Object.defineProperty(Window.prototype.toString, "cc4cbb964104e3ca9c968d0801cc2a98", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "cc4cbb964104e3ca9c968d0801cc2a98" due to: ' + e);
        }
    },
    '(()=>{let e=[];document.addEventListener("DOMContentLoaded",(()=>{const t=document.querySelector("body script").textContent.match(/"] = \'(.*?)\'/g);if(!t)return;t.forEach((t=>{const r=t.replace(/.*\'(.*?)\'/,"$1");e.push(r)}));const r=document.querySelector(\'.dl_button[href*="preview"]\').href.split("?")[1];e.includes(r)&&(e=e.filter((e=>e!==r)));document.querySelectorAll(".dl_button[href]").forEach((t=>{let r=t.cloneNode(!0);r.href=t.href.replace(/\\?.*/,`?${e[0]}`),t.after(r);let o=t.cloneNode(!0);o.href=t.href.replace(/\\?.*/,`?${e[1]}`),t.after(o)}))}))})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.dd2ab3ea1b069f5b262d0c2924b695ca === e) return;
            (()=>{
                let e = [];
                document.addEventListener("DOMContentLoaded", ()=>{
                    const t = document.querySelector("body script").textContent.match(/"] = '(.*?)'/g);
                    if (!t) return;
                    t.forEach((t)=>{
                        const r = t.replace(/.*'(.*?)'/, "$1");
                        e.push(r);
                    });
                    const r = document.querySelector('.dl_button[href*="preview"]').href.split("?")[1];
                    e.includes(r) && (e = e.filter((e)=>e !== r));
                    document.querySelectorAll(".dl_button[href]").forEach((t)=>{
                        let r = t.cloneNode(!0);
                        r.href = t.href.replace(/\?.*/, `?${e[0]}`), t.after(r);
                        let o = t.cloneNode(!0);
                        o.href = t.href.replace(/\?.*/, `?${e[1]}`), t.after(o);
                    });
                });
            })();
            Object.defineProperty(Window.prototype.toString, "dd2ab3ea1b069f5b262d0c2924b695ca", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "dd2ab3ea1b069f5b262d0c2924b695ca" due to: ' + e);
        }
    },
    '!function(){const o={apply:(o,n,r)=>(new Error).stack.includes("refreshad")?0:Reflect.apply(o,n,r)};window.Math.floor=new Proxy(window.Math.floor,o)}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.aac06a0fe043d0b0021afeae4330a5d5 === e) return;
            !function() {
                const e = {
                    apply: (e, a, o)=>(new Error).stack.includes("refreshad") ? 0 : Reflect.apply(e, a, o)
                };
                window.Math.floor = new Proxy(window.Math.floor, e);
            }();
            Object.defineProperty(Window.prototype.toString, "aac06a0fe043d0b0021afeae4330a5d5", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "aac06a0fe043d0b0021afeae4330a5d5" due to: ' + e);
        }
    },
    '(function(){const a=Function.prototype.toString;window.EventTarget.prototype.addEventListener=new Proxy(window.EventTarget.prototype.addEventListener,{apply:(b,c,d)=>{const e=d[1],f=/detail.adblockDetected|handleAdblockDetect|Flags.autoRecov/;return e&&"function"==typeof e&&(f.test(a.call(e))||f.test(e.toString()))&&(d[1]=function(){}),Reflect.apply(b,c,d)}});Function.prototype.bind=new Proxy(Function.prototype.bind,{apply:(b,c,d)=>{const e=a.call(c),f=Reflect.apply(b,c,d);return f.toString=function(){return e},f}})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.e33ef1a5a53f3c2f5bbed2ef8c665146 === e) return;
            !function() {
                const e = Function.prototype.toString;
                window.EventTarget.prototype.addEventListener = new Proxy(window.EventTarget.prototype.addEventListener, {
                    apply: (t, n1, o)=>{
                        const r = o[1], c = /detail.adblockDetected|handleAdblockDetect|Flags.autoRecov/;
                        return r && "function" == typeof r && (c.test(e.call(r)) || c.test(r.toString())) && (o[1] = function() {}), Reflect.apply(t, n1, o);
                    }
                });
                Function.prototype.bind = new Proxy(Function.prototype.bind, {
                    apply: (t, n1, o)=>{
                        const r = e.call(n1), c = Reflect.apply(t, n1, o);
                        return c.toString = function() {
                            return r;
                        }, c;
                    }
                });
            }();
            Object.defineProperty(Window.prototype.toString, "e33ef1a5a53f3c2f5bbed2ef8c665146", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "e33ef1a5a53f3c2f5bbed2ef8c665146" due to: ' + e);
        }
    },
    '!function(){var t={cmd:[],public:{getVideoAdUrl:function(){},createNewPosition:function(){},refreshAds:function(){},setTargetingOnPosition:function(){},getDailymotionAdsParamsForScript:function(t,n){if("function"==typeof n)try{if(1===n.length){const o=t[0];n({[o]:o})}}catch(n){console.debug(n)}}}};t.cmd.push=function(t){let n=function(){try{"function"==typeof t&&t()}catch(t){}};"complete"===document.readyState?n():window.addEventListener("load",(()=>{n()}))},window.jad=t}();': ()=>{
        try {
            const t = "done";
            if (Window.prototype.toString["4b02efce565c43abd97593b12856ccd8"] === t) return;
            !function() {
                var t = {
                    cmd: [],
                    public: {
                        getVideoAdUrl: function() {},
                        createNewPosition: function() {},
                        refreshAds: function() {},
                        setTargetingOnPosition: function() {},
                        getDailymotionAdsParamsForScript: function(t, e) {
                            if ("function" == typeof e) try {
                                if (1 === e.length) {
                                    const n1 = t[0];
                                    e({
                                        [n1]: n1
                                    });
                                }
                            } catch (e) {
                                console.debug(e);
                            }
                        }
                    }
                };
                t.cmd.push = function(t) {
                    let e = function() {
                        try {
                            "function" == typeof t && t();
                        } catch (t) {}
                    };
                    "complete" === document.readyState ? e() : window.addEventListener("load", ()=>{
                        e();
                    });
                }, window.jad = t;
            }();
            Object.defineProperty(Window.prototype.toString, "4b02efce565c43abd97593b12856ccd8", {
                value: t,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (t) {
            console.error('Error executing AG js rule with uniqueId "4b02efce565c43abd97593b12856ccd8" due to: ' + t);
        }
    },
    '(function(){if(-1<window.location.href.indexOf("/s.php?i="))try{for(var a=location.href.split("/s.php?i=")[1],c=0;10>c;c++){a=atob(a);try{new URL(a);var d=!0}catch(b){d=!1}if(d)try{a=a.replace(/[a-zA-Z]/g,function(b){return String.fromCharCode(("Z">=b?90:122)>=(b=b.charCodeAt(0)+13)?b:b-26)});a=decodeURIComponent(a);window.location=a;break}catch(b){}}}catch(b){}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["2df496ddbea99bcffb94b9b433cac64d"] === e) return;
            !function() {
                if (-1 < window.location.href.indexOf("/s.php?i=")) try {
                    for(var e = location.href.split("/s.php?i=")[1], o = 0; 10 > o; o++){
                        e = atob(e);
                        try {
                            new URL(e);
                            var r = !0;
                        } catch (e) {
                            r = !1;
                        }
                        if (r) try {
                            e = e.replace(/[a-zA-Z]/g, function(e) {
                                return String.fromCharCode(("Z" >= e ? 90 : 122) >= (e = e.charCodeAt(0) + 13) ? e : e - 26);
                            });
                            e = decodeURIComponent(e);
                            window.location = e;
                            break;
                        } catch (e) {}
                    }
                } catch (e) {}
            }();
            Object.defineProperty(Window.prototype.toString, "2df496ddbea99bcffb94b9b433cac64d", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "2df496ddbea99bcffb94b9b433cac64d" due to: ' + e);
        }
    },
    '!function(){if(-1<window.location.href.indexOf("/#aHR0c")){var a=location.href.split("/#");if(a&&a[1])try{window.location=atob(a[1])}catch(b){}}}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["8b3aa220c71f03621cb9cd086eb59619"] === e) return;
            !function() {
                if (-1 < window.location.href.indexOf("/#aHR0c")) {
                    var e = location.href.split("/#");
                    if (e && e[1]) try {
                        window.location = atob(e[1]);
                    } catch (e) {}
                }
            }();
            Object.defineProperty(Window.prototype.toString, "8b3aa220c71f03621cb9cd086eb59619", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "8b3aa220c71f03621cb9cd086eb59619" due to: ' + e);
        }
    },
    '(function(){var b=XMLHttpRequest.prototype.open,c=/pagead2\\.googlesyndication\\.com/i;XMLHttpRequest.prototype.open=function(d,a){if("GET"===d&&c.test(a))this.send=function(){return null},this.setRequestHeader=function(){return null},console.log("AG has blocked request: ",a);else return b.apply(this,arguments)}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.b56615f06c5a4f3d6dbd34cd41a23997 === e) return;
            !function() {
                var e = XMLHttpRequest.prototype.open, t = /pagead2\.googlesyndication\.com/i;
                XMLHttpRequest.prototype.open = function(o, n1) {
                    if ("GET" !== o || !t.test(n1)) return e.apply(this, arguments);
                    this.send = function() {
                        return null;
                    }, this.setRequestHeader = function() {
                        return null;
                    }, console.log("AG has blocked request: ", n1);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "b56615f06c5a4f3d6dbd34cd41a23997", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "b56615f06c5a4f3d6dbd34cd41a23997" due to: ' + e);
        }
    },
    '(()=>{let e="";const t={adsbygoogle:{url:"//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js",value:"google_plmetrics"},outbrain:{url:"//widgets.outbrain.com/outbrain.js",value:"outbrain"},cdnpcStyleMin:{url:"//s4.cdnpc.net/front/css/style.min.css",value:"slider--features"},cdnpcMain:{url:"//s4.cdnpc.net/vite-bundle/main.css",value:"data-v-d23a26c8"},taboola:{url:"//cdn.taboola.com/libtrc/san1go-network/loader.js",value:"feOffset"}},n=n=>{try{const o=n;if(!o.responseText){const n=(e=>{const n=Object.values(t).find((t=>e.includes(t.url)));return n?n.value:""})(e);Object.defineProperty(o,"responseText",{value:n})}"function"==typeof o.onload&&o.onload(),"function"==typeof o.onreadystatechange&&(Object.defineProperty(o,"status",{value:200}),Object.defineProperty(o,"readyState",{value:4}),o.onreadystatechange())}catch(e){console.trace(e)}},o={apply:(n,o,a)=>{const r=a[1];return r&&(e=>Object.values(t).some((t=>e.includes(t.url))))(r)&&(o.prevent=!0,e=r),Reflect.apply(n,o,a)}};window.XMLHttpRequest.prototype.open=new Proxy(window.XMLHttpRequest.prototype.open,o);const a={apply:async(t,o,a)=>{if(!o.prevent)return Reflect.apply(t,o,a);try{const t=await fetch(e);if((await t.text()).length<2e3)return n(o)}catch(e){return console.trace(e),n(o)}return Reflect.apply(t,o,a)}};window.XMLHttpRequest.prototype.send=new Proxy(window.XMLHttpRequest.prototype.send,a)})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["999651d762087524799a382abaeba96f"] === e) return;
            (()=>{
                let e = "";
                const t = {
                    adsbygoogle: {
                        url: "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js",
                        value: "google_plmetrics"
                    },
                    outbrain: {
                        url: "//widgets.outbrain.com/outbrain.js",
                        value: "outbrain"
                    },
                    cdnpcStyleMin: {
                        url: "//s4.cdnpc.net/front/css/style.min.css",
                        value: "slider--features"
                    },
                    cdnpcMain: {
                        url: "//s4.cdnpc.net/vite-bundle/main.css",
                        value: "data-v-d23a26c8"
                    },
                    taboola: {
                        url: "//cdn.taboola.com/libtrc/san1go-network/loader.js",
                        value: "feOffset"
                    }
                }, o = (o)=>{
                    try {
                        const n1 = o;
                        if (!n1.responseText) {
                            const o = ((e)=>{
                                const o = Object.values(t).find((t)=>e.includes(t.url));
                                return o ? o.value : "";
                            })(e);
                            Object.defineProperty(n1, "responseText", {
                                value: o
                            });
                        }
                        "function" == typeof n1.onload && n1.onload(), "function" == typeof n1.onreadystatechange && (Object.defineProperty(n1, "status", {
                            value: 200
                        }), Object.defineProperty(n1, "readyState", {
                            value: 4
                        }), n1.onreadystatechange());
                    } catch (e) {
                        console.trace(e);
                    }
                }, n1 = {
                    apply: (o, n1, a)=>{
                        const r = a[1];
                        return r && ((e)=>Object.values(t).some((t)=>e.includes(t.url)))(r) && (n1.prevent = !0, e = r), Reflect.apply(o, n1, a);
                    }
                };
                window.XMLHttpRequest.prototype.open = new Proxy(window.XMLHttpRequest.prototype.open, n1);
                const a = {
                    apply: async (t, n1, a)=>{
                        if (!n1.prevent) return Reflect.apply(t, n1, a);
                        try {
                            const t = await fetch(e);
                            if ((await t.text()).length < 2e3) return o(n1);
                        } catch (e) {
                            return console.trace(e), o(n1);
                        }
                        return Reflect.apply(t, n1, a);
                    }
                };
                window.XMLHttpRequest.prototype.send = new Proxy(window.XMLHttpRequest.prototype.send, a);
            })();
            Object.defineProperty(Window.prototype.toString, "999651d762087524799a382abaeba96f", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "999651d762087524799a382abaeba96f" due to: ' + e);
        }
    },
    "window.loadingAds = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["92cb1336a3ae04946fb7472ef921e5a2"] === e) return;
            window.loadingAds = !0;
            Object.defineProperty(Window.prototype.toString, "92cb1336a3ae04946fb7472ef921e5a2", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "92cb1336a3ae04946fb7472ef921e5a2" due to: ' + e);
        }
    },
    "window.N3CanRunAds = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.bf2528e3820489391dd14ff4e676bf77 === e) return;
            window.N3CanRunAds = !0;
            Object.defineProperty(Window.prototype.toString, "bf2528e3820489391dd14ff4e676bf77", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "bf2528e3820489391dd14ff4e676bf77" due to: ' + e);
        }
    },
    "window.UFads = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["6f1638cef962ca7bcf9ae1cd4762f141"] === e) return;
            window.UFads = !0;
            Object.defineProperty(Window.prototype.toString, "6f1638cef962ca7bcf9ae1cd4762f141", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "6f1638cef962ca7bcf9ae1cd4762f141" due to: ' + e);
        }
    },
    "window.pr_okvalida=true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["9cea5435efc0d37e874e0db2f82cafe5"] === e) return;
            window.pr_okvalida = !0;
            Object.defineProperty(Window.prototype.toString, "9cea5435efc0d37e874e0db2f82cafe5", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "9cea5435efc0d37e874e0db2f82cafe5" due to: ' + e);
        }
    },
    "window.pr_okAd = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.a20a9b76443176de1d59662b7bec69ac === e) return;
            window.pr_okAd = !0;
            Object.defineProperty(Window.prototype.toString, "a20a9b76443176de1d59662b7bec69ac", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "a20a9b76443176de1d59662b7bec69ac" due to: ' + e);
        }
    },
    "window.adblockDetecter = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["077ad96f9724037e5e50572b0e1dad20"] === e) return;
            window.adblockDetecter = !0;
            Object.defineProperty(Window.prototype.toString, "077ad96f9724037e5e50572b0e1dad20", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "077ad96f9724037e5e50572b0e1dad20" due to: ' + e);
        }
    },
    "window.pr_okvalida = true;": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["61d8c36d64bce12eddcaa6d5227fb569"] === e) return;
            window.pr_okvalida = !0;
            Object.defineProperty(Window.prototype.toString, "61d8c36d64bce12eddcaa6d5227fb569", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "61d8c36d64bce12eddcaa6d5227fb569" due to: ' + e);
        }
    },
    '(()=>{document.addEventListener("DOMContentLoaded",(()=>{try{let t;"function"==typeof decode_link&&"string"==typeof link_out&&(t=decode_link(atob(link_out)),location.assign(t)),"string"==typeof api_key&&(document.cookie=`${api_key}=Wn275; path=/`);const e=document.querySelector("* > .button#contador");e&&t&&setTimeout((()=>{const o=e.cloneNode(!0);e.parentNode.replaceChild(o,e),o.addEventListener("click",(function(){location.assign(t)}),!1)}),500)}catch(t){}}));})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["90c94b5e54df0c8bc3584e6dd04ae87a"] === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                try {
                    let e;
                    "function" == typeof decode_link && "string" == typeof link_out && (e = decode_link(atob(link_out)), location.assign(e)), "string" == typeof api_key && (document.cookie = `${api_key}=Wn275; path=/`);
                    const t = document.querySelector("* > .button#contador");
                    t && e && setTimeout(()=>{
                        const o = t.cloneNode(!0);
                        t.parentNode.replaceChild(o, t), o.addEventListener("click", function() {
                            location.assign(e);
                        }, !1);
                    }, 500);
                } catch (e) {}
            });
            Object.defineProperty(Window.prototype.toString, "90c94b5e54df0c8bc3584e6dd04ae87a", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "90c94b5e54df0c8bc3584e6dd04ae87a" due to: ' + e);
        }
    },
    '(()=>{window.addEventListener("load",(()=>{document.querySelectorAll(\'.count > li > a[href*="/#!"]\').forEach((t=>{const e=(t=>{let e=t;for(let t=0;t<10;t++)try{e=atob(e)}catch(t){break}return decodeURIComponent(e)})(t.href.split("/#!")[1]);(t=>{let e=t;try{e=new URL(t)}catch(t){return!1}return"http:"===e.protocol||"https:"===e.protocol})(e)&&t.setAttribute("href",e)}))}));})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["96e43c3e77d12216cc72163eb5a036f3"] === e) return;
            window.addEventListener("load", ()=>{
                document.querySelectorAll('.count > li > a[href*="/#!"]').forEach((e)=>{
                    const t = ((e)=>{
                        let t = e;
                        for(let r = 0; r < 10; r++)try {
                            t = atob(t);
                        } catch (e) {
                            break;
                        }
                        return decodeURIComponent(t);
                    })(e.href.split("/#!")[1]);
                    ((e)=>{
                        let t = e;
                        try {
                            t = new URL(e);
                        } catch (e) {
                            return !1;
                        }
                        return "http:" === t.protocol || "https:" === t.protocol;
                    })(t) && e.setAttribute("href", t);
                });
            });
            Object.defineProperty(Window.prototype.toString, "96e43c3e77d12216cc72163eb5a036f3", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "96e43c3e77d12216cc72163eb5a036f3" due to: ' + e);
        }
    },
    '!function(){if(window.location.href.includes(".php?")&&window.location.href.includes("=")){const o=location.href.split("=");if(o&&o[1]){let t=o[1];for(let o=0;o<10;o++)try{t=atob(t)}catch(o){const n=decodeURIComponent(t);let c=!1;try{new URL(n),c=!0}catch(o){c=!1}if(c){location.assign(n);break}}}}}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.aed92a9e5fa43ee06d13ea0740f42251 === e) return;
            !function() {
                if (window.location.href.includes(".php?") && window.location.href.includes("=")) {
                    const e = location.href.split("=");
                    if (e && e[1]) {
                        let o = e[1];
                        for(let e = 0; e < 10; e++)try {
                            o = atob(o);
                        } catch (e) {
                            const t = decodeURIComponent(o);
                            let n1 = !1;
                            try {
                                new URL(t), n1 = !0;
                            } catch (e) {
                                n1 = !1;
                            }
                            if (n1) {
                                location.assign(t);
                                break;
                            }
                        }
                    }
                }
            }();
            Object.defineProperty(Window.prototype.toString, "aed92a9e5fa43ee06d13ea0740f42251", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "aed92a9e5fa43ee06d13ea0740f42251" due to: ' + e);
        }
    },
    '(function(){if(-1<window.location.href.indexOf("/#")){var b=location.href.split("/#");if(b&&b[1]){b=b[1];for(var f=0;10>f;f++)try{b=atob(b)}catch(a){var g=decodeURIComponent(b);g=g.split("&url=")[1];try{new URL(g);var h=!0}catch(a){h=!1}if(h){location.assign(g);break}}}}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.e461bea6c1765b5004b1bdf45a657484 === e) return;
            !function() {
                if (-1 < window.location.href.indexOf("/#")) {
                    var e = location.href.split("/#");
                    if (e && e[1]) {
                        e = e[1];
                        for(var o = 0; 10 > o; o++)try {
                            e = atob(e);
                        } catch (o) {
                            var r = decodeURIComponent(e);
                            r = r.split("&url=")[1];
                            try {
                                new URL(r);
                                var t = !0;
                            } catch (e) {
                                t = !1;
                            }
                            if (t) {
                                location.assign(r);
                                break;
                            }
                        }
                    }
                }
            }();
            Object.defineProperty(Window.prototype.toString, "e461bea6c1765b5004b1bdf45a657484", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "e461bea6c1765b5004b1bdf45a657484" due to: ' + e);
        }
    },
    '(function(){if(-1<window.location.href.indexOf("/#")){var b=location.href.split("/#");if(b&&b[1]){b=b[1];for(var f=0;10>f;f++)try{b=atob(b)}catch(a){var g=decodeURIComponent(b);try{new URL(g);var h=!0}catch(a){h=!1}if(h){location.assign(g);break}}}}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["9b5e9479cf0e6f4ce35ed63d4353bab4"] === e) return;
            !function() {
                if (-1 < window.location.href.indexOf("/#")) {
                    var e = location.href.split("/#");
                    if (e && e[1]) {
                        e = e[1];
                        for(var o = 0; 10 > o; o++)try {
                            e = atob(e);
                        } catch (o) {
                            var r = decodeURIComponent(e);
                            try {
                                new URL(r);
                                var t = !0;
                            } catch (e) {
                                t = !1;
                            }
                            if (t) {
                                location.assign(r);
                                break;
                            }
                        }
                    }
                }
            }();
            Object.defineProperty(Window.prototype.toString, "9b5e9479cf0e6f4ce35ed63d4353bab4", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "9b5e9479cf0e6f4ce35ed63d4353bab4" due to: ' + e);
        }
    },
    '(function(){if(-1<window.location.href.indexOf("/#!")){var b=location.href.split("/#!");if(b&&b[1]){b=b[1];for(var f=0;10>f;f++)try{b=atob(b)}catch(a){var g=decodeURIComponent(b);try{new URL(g);var h=!0}catch(a){h=!1}if(h){location.assign(g);break}}}}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["06564135eca95acc020e6910b740c355"] === e) return;
            !function() {
                if (-1 < window.location.href.indexOf("/#!")) {
                    var e = location.href.split("/#!");
                    if (e && e[1]) {
                        e = e[1];
                        for(var o = 0; 10 > o; o++)try {
                            e = atob(e);
                        } catch (o) {
                            var r = decodeURIComponent(e);
                            try {
                                new URL(r);
                                var t = !0;
                            } catch (e) {
                                t = !1;
                            }
                            if (t) {
                                location.assign(r);
                                break;
                            }
                        }
                    }
                }
            }();
            Object.defineProperty(Window.prototype.toString, "06564135eca95acc020e6910b740c355", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "06564135eca95acc020e6910b740c355" due to: ' + e);
        }
    },
    '(function(){if(-1<window.location.href.indexOf("o.php?l=")){var b=location.href.split("o.php?l=");if(b&&b[1]){b=b[1].replace(/\\|\\d/,\'\');for(var f=0;10>f;f++)try{b=atob(b)}catch(a){var g=decodeURIComponent(b);try{new URL(g);var h=!0}catch(a){h=!1}if(h){location.assign(g);break}}}}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["7236b4fca7e3b34846de4af64f512064"] === e) return;
            !function() {
                if (-1 < window.location.href.indexOf("o.php?l=")) {
                    var e = location.href.split("o.php?l=");
                    if (e && e[1]) {
                        e = e[1].replace(/\|\d/, "");
                        for(var o = 0; 10 > o; o++)try {
                            e = atob(e);
                        } catch (o) {
                            var r = decodeURIComponent(e);
                            try {
                                new URL(r);
                                var t = !0;
                            } catch (e) {
                                t = !1;
                            }
                            if (t) {
                                location.assign(r);
                                break;
                            }
                        }
                    }
                }
            }();
            Object.defineProperty(Window.prototype.toString, "7236b4fca7e3b34846de4af64f512064", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "7236b4fca7e3b34846de4af64f512064" due to: ' + e);
        }
    },
    '(()=>{document.addEventListener("DOMContentLoaded",(()=>{try{"function"==typeof window.noobBypass&&noobBypass()}catch(b){}}));})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.cf094940c140bb6a8015c9e1f15490f1 === e) return;
            document.addEventListener("DOMContentLoaded", ()=>{
                try {
                    "function" == typeof window.noobBypass && noobBypass();
                } catch (e) {}
            });
            Object.defineProperty(Window.prototype.toString, "cf094940c140bb6a8015c9e1f15490f1", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "cf094940c140bb6a8015c9e1f15490f1" due to: ' + e);
        }
    },
    '!function(){const e=e=>{const o=new XMLHttpRequest;o.open("POST","/check.php",!0),o.setRequestHeader("Content-type","application/x-www-form-urlencoded"),o.send("a");const t=atob(window.ext_site).replace(/[a-z]/gi,(e=>String.fromCharCode(e.charCodeAt(0)+(e.toLowerCase()<="m"?13:-13))));let n=e.replaceAll(\'\\\\"\',\'"\');n=n.replace("\'+ api_key+ \'",window.api_key),n=n.replace("\'+ link_out+ \\"",window.link_out),n=n.replace(/action="\'\\+ .*?\\+ \'"/,`action="${t}"`);var a;const i=(a=n,(new DOMParser).parseFromString(a,"text/html")).querySelector("form"),r=new FormData(i),c=new XMLHttpRequest;c.open("POST",t,!0),c.send(r),window.tab2=window,postMessage("_clicked_b",location.origin)},o={apply:(o,t,n)=>{if(n[1]&&n[1].includes("api_key")){const o=window.link_out,t=window.api_key,a=n[1].match(/window\\.open\\(.*?\\(atob\\(main_site\\)\\).*?("\\/.*\\.php\\?.*=").*?("&.*?=").*?(api_key),"view"/),i=a[1].replaceAll(\'"\',""),r=a[2].replaceAll(\'"\',""),c=n[1].match(/<form target=[\\s\\S]*?<\\/form>/)[0];if(n[1]=n[1].replace("window.location.href","var nulled"),n[1]=n[1].replace("window.open(f","location.assign(f"),n[1]=n[1].replace(/(parseInt\\(c\\.split\\("-"\\)\\[0\\]\\)<= 0).*?(\\)\\{)/,"$1$2"),o&&t&&i&&r&&c)try{"loading"===document.readyState?window.addEventListener("load",(()=>{e(c)}),{once:!0}):e(c)}catch(e){console.debug(e)}}return Reflect.apply(o,t,n)}};window.Function.prototype.constructor=new Proxy(window.Function.prototype.constructor,o)}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.fd77edacac830e016dc4109bc637175a === e) return;
            !function() {
                const e = (e)=>{
                    const o = new XMLHttpRequest;
                    o.open("POST", "/check.php", !0), o.setRequestHeader("Content-type", "application/x-www-form-urlencoded"), o.send("a");
                    const t = atob(window.ext_site).replace(/[a-z]/gi, (e)=>String.fromCharCode(e.charCodeAt(0) + (e.toLowerCase() <= "m" ? 13 : -13)));
                    let n1 = e.replaceAll('\\"', '"');
                    n1 = n1.replace("'+ api_key+ '", window.api_key), n1 = n1.replace("'+ link_out+ \"", window.link_out), n1 = n1.replace(/action="'\+ .*?\+ '"/, `action="${t}"`);
                    var a;
                    const r = (a = n1, (new DOMParser).parseFromString(a, "text/html")).querySelector("form"), c = new FormData(r), i1 = new XMLHttpRequest;
                    i1.open("POST", t, !0), i1.send(c), window.tab2 = window, postMessage("_clicked_b", location.origin);
                }, o = {
                    apply: (o, t, n1)=>{
                        if (n1[1] && n1[1].includes("api_key")) {
                            const o = window.link_out, t = window.api_key, a = n1[1].match(/window\.open\(.*?\(atob\(main_site\)\).*?("\/.*\.php\?.*=").*?("&.*?=").*?(api_key),"view"/), r = a[1].replaceAll('"', ""), c = a[2].replaceAll('"', ""), i1 = n1[1].match(/<form target=[\s\S]*?<\/form>/)[0];
                            if (n1[1] = n1[1].replace("window.location.href", "var nulled"), n1[1] = n1[1].replace("window.open(f", "location.assign(f"), n1[1] = n1[1].replace(/(parseInt\(c\.split\("-"\)\[0\]\)<= 0).*?(\)\{)/, "$1$2"), o && t && r && c && i1) try {
                                "loading" === document.readyState ? window.addEventListener("load", ()=>{
                                    e(i1);
                                }, {
                                    once: !0
                                }) : e(i1);
                            } catch (e) {
                                console.debug(e);
                            }
                        }
                        return Reflect.apply(o, t, n1);
                    }
                };
                window.Function.prototype.constructor = new Proxy(window.Function.prototype.constructor, o);
            }();
            Object.defineProperty(Window.prototype.toString, "fd77edacac830e016dc4109bc637175a", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "fd77edacac830e016dc4109bc637175a" due to: ' + e);
        }
    },
    '(()=>{try{const o=location.href.split("/#");if(o[1]){let t=o[1];for(let o=0;o<10;o++)try{t=atob(t)}catch(o){break}const c=decodeURIComponent(t).split("&url=")[1];c&&location.assign(c)}}catch(o){console.error(o)}})();': ()=>{
        try {
            const c = "done";
            if (Window.prototype.toString["665cc7cdf79cd8609ccd1c640a89ccd0"] === c) return;
            (()=>{
                try {
                    const c = location.href.split("/#");
                    if (c[1]) {
                        let t = c[1];
                        for(let c = 0; c < 10; c++)try {
                            t = atob(t);
                        } catch (c) {
                            break;
                        }
                        const o = decodeURIComponent(t).split("&url=")[1];
                        o && location.assign(o);
                    }
                } catch (c) {
                    console.error(c);
                }
            })();
            Object.defineProperty(Window.prototype.toString, "665cc7cdf79cd8609ccd1c640a89ccd0", {
                value: c,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (c) {
            console.error('Error executing AG js rule with uniqueId "665cc7cdf79cd8609ccd1c640a89ccd0" due to: ' + c);
        }
    },
    '(function(){try{var a=location.href.split("out#!");if(a[1]){a=a[1];for(var b=0;10>b;b++){a=atob(a);try{new URL(decodeURIComponent(a));var c=!0}catch(d){c=!1}if(c)try{location.assign(decodeURIComponent(a));break}catch(d){}}}}catch(d){}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.a97c62453393267bb0f7c37f1de195be === e) return;
            !function() {
                try {
                    var e = location.href.split("out#!");
                    if (e[1]) {
                        e = e[1];
                        for(var t = 0; 10 > t; t++){
                            e = atob(e);
                            try {
                                new URL(decodeURIComponent(e));
                                var o = !0;
                            } catch (e) {
                                o = !1;
                            }
                            if (o) try {
                                location.assign(decodeURIComponent(e));
                                break;
                            } catch (e) {}
                        }
                    }
                } catch (e) {}
            }();
            Object.defineProperty(Window.prototype.toString, "a97c62453393267bb0f7c37f1de195be", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "a97c62453393267bb0f7c37f1de195be" due to: ' + e);
        }
    },
    "(()=>{document.addEventListener('DOMContentLoaded',function(){if(window.deco_url_b64&&typeof deco_url_b64==='string'&&deco_url_b64.startsWith('http')){location.assign(deco_url_b64);}});})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["370c2e67375d1730dbabcd4586b41c96"] === e) return;
            document.addEventListener("DOMContentLoaded", function() {
                window.deco_url_b64 && "string" == typeof deco_url_b64 && deco_url_b64.startsWith("http") && location.assign(deco_url_b64);
            });
            Object.defineProperty(Window.prototype.toString, "370c2e67375d1730dbabcd4586b41c96", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "370c2e67375d1730dbabcd4586b41c96" due to: ' + e);
        }
    },
    '(function(){try{var a=location.href.split("#");if(a[1]){a=a[1];for(var b=0;10>b;b++){a=atob(a);try{new URL(decodeURIComponent(a));var c=!0}catch(d){c=!1}if(c)try{location.assign(decodeURIComponent(a));break}catch(d){}}}}catch(d){}})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["5c24323e179726bab950bb8e6732b33b"] === e) return;
            !function() {
                try {
                    var e = location.href.split("#");
                    if (e[1]) {
                        e = e[1];
                        for(var t = 0; 10 > t; t++){
                            e = atob(e);
                            try {
                                new URL(decodeURIComponent(e));
                                var o = !0;
                            } catch (e) {
                                o = !1;
                            }
                            if (o) try {
                                location.assign(decodeURIComponent(e));
                                break;
                            } catch (e) {}
                        }
                    }
                } catch (e) {}
            }();
            Object.defineProperty(Window.prototype.toString, "5c24323e179726bab950bb8e6732b33b", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "5c24323e179726bab950bb8e6732b33b" due to: ' + e);
        }
    },
    '(()=>{window.addEventListener("message",(e=>{e?.data?.includes("__done__")&&e?.data?.length<9&&Object.defineProperty(e,"source",{value:""})}),!0);const e=new MutationObserver((()=>{document.querySelector("a.button#contador")&&(e.disconnect(),setTimeout((()=>{postMessage("__done__")}),100))}));e.observe(document,{childList:!0,subtree:!0})})();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["340e5298fafdd8b74113e0fea4af6efa"] === e) return;
            (()=>{
                window.addEventListener("message", (e)=>{
                    var _e_data, _e_data1;
                    (e === null || e === void 0 ? void 0 : (_e_data = e.data) === null || _e_data === void 0 ? void 0 : _e_data.includes("__done__")) && (e === null || e === void 0 ? void 0 : (_e_data1 = e.data) === null || _e_data1 === void 0 ? void 0 : _e_data1.length) < 9 && Object.defineProperty(e, "source", {
                        value: ""
                    });
                }, !0);
                const e = new MutationObserver(()=>{
                    document.querySelector("a.button#contador") && (e.disconnect(), setTimeout(()=>{
                        postMessage("__done__");
                    }, 100));
                });
                e.observe(document, {
                    childList: !0,
                    subtree: !0
                });
            })();
            Object.defineProperty(Window.prototype.toString, "340e5298fafdd8b74113e0fea4af6efa", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "340e5298fafdd8b74113e0fea4af6efa" due to: ' + e);
        }
    },
    '(function(){if(-1<window.location.href.indexOf("/#")){var a=location.href.split("/#");if(a&&a[1]){a=a[1];for(var c=0;10>c;c++)try{a=atob(a)}catch(f){var d=a.replace(/[a-zA-Z]/g,function(b){return String.fromCharCode(("Z">=b?90:122)>=(b=b.charCodeAt(0)+13)?b:b-26)});try{new URL(d);var e=!0}catch(b){e=!1}if(e){window.location=d;break}}}}})();': ()=>{
        try {
            const r = "done";
            if (Window.prototype.toString["3937ca8d5dd840aca311dfd69741ce6c"] === r) return;
            !function() {
                if (-1 < window.location.href.indexOf("/#")) {
                    var r = location.href.split("/#");
                    if (r && r[1]) {
                        r = r[1];
                        for(var e = 0; 10 > e; e++)try {
                            r = atob(r);
                        } catch (e) {
                            var o = r.replace(/[a-zA-Z]/g, function(r) {
                                return String.fromCharCode(("Z" >= r ? 90 : 122) >= (r = r.charCodeAt(0) + 13) ? r : r - 26);
                            });
                            try {
                                new URL(o);
                                var t = !0;
                            } catch (r) {
                                t = !1;
                            }
                            if (t) {
                                window.location = o;
                                break;
                            }
                        }
                    }
                }
            }();
            Object.defineProperty(Window.prototype.toString, "3937ca8d5dd840aca311dfd69741ce6c", {
                value: r,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (r) {
            console.error('Error executing AG js rule with uniqueId "3937ca8d5dd840aca311dfd69741ce6c" due to: ' + r);
        }
    },
    '(function(){if(-1<window.location.href.indexOf("s.php?i=")){var a=location.href.split("s.php?i=");if(a&&a[1]){a=a[1];for(var c=0;10>c;c++)try{a=atob(a)}catch(f){var d=a.replace(/[a-zA-Z]/g,function(b){return String.fromCharCode(("Z">=b?90:122)>=(b=b.charCodeAt(0)+13)?b:b-26)});try{new URL(d);var e=!0}catch(b){e=!1}if(e){window.location=d;break}}}}})();': ()=>{
        try {
            const r = "done";
            if (Window.prototype.toString.c351c9c83ef852439382448ab0d1ad4a === r) return;
            !function() {
                if (-1 < window.location.href.indexOf("s.php?i=")) {
                    var r = location.href.split("s.php?i=");
                    if (r && r[1]) {
                        r = r[1];
                        for(var e = 0; 10 > e; e++)try {
                            r = atob(r);
                        } catch (e) {
                            var o = r.replace(/[a-zA-Z]/g, function(r) {
                                return String.fromCharCode(("Z" >= r ? 90 : 122) >= (r = r.charCodeAt(0) + 13) ? r : r - 26);
                            });
                            try {
                                new URL(o);
                                var t = !0;
                            } catch (r) {
                                t = !1;
                            }
                            if (t) {
                                window.location = o;
                                break;
                            }
                        }
                    }
                }
            }();
            Object.defineProperty(Window.prototype.toString, "c351c9c83ef852439382448ab0d1ad4a", {
                value: r,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (r) {
            console.error('Error executing AG js rule with uniqueId "c351c9c83ef852439382448ab0d1ad4a" due to: ' + r);
        }
    },
    "(function(){var b=window.setTimeout;window.setTimeout=function(a,c){if(!/\\(\\)>0x0\\)\\{fA=setTimeout\\(/.test(a.toString()))return b(a,c)};})();": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString.acb1e5048f2d6e4f5da7f33333aa8ad4 === e) return;
            !function() {
                var e = window.setTimeout;
                window.setTimeout = function(t, o) {
                    if (!/\(\)>0x0\)\{fA=setTimeout\(/.test(t.toString())) return e(t, o);
                };
            }();
            Object.defineProperty(Window.prototype.toString, "acb1e5048f2d6e4f5da7f33333aa8ad4", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "acb1e5048f2d6e4f5da7f33333aa8ad4" due to: ' + e);
        }
    },
    '!function(){let e=()=>{document.querySelector("#case-1-generichide > .test-banner1").style.width="200px"};"complete"===document.readyState?e():window.document.addEventListener("readystatechange",e)}();': ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["08d18a5e02e0ff3dfa7a775c5b3836b8"] === e) return;
            !function() {
                let e = ()=>{
                    document.querySelector("#case-1-generichide > .test-banner1").style.width = "200px";
                };
                "complete" === document.readyState ? e() : window.document.addEventListener("readystatechange", e);
            }();
            Object.defineProperty(Window.prototype.toString, "08d18a5e02e0ff3dfa7a775c5b3836b8", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "08d18a5e02e0ff3dfa7a775c5b3836b8" due to: ' + e);
        }
    },
    "console.log(Date.now(), 'script rule is executed');": ()=>{
        try {
            const e = "done";
            if (Window.prototype.toString["4d604df7a1e110b1d7ccc9f9142d531d"] === e) return;
            console.log(Date.now(), "script rule is executed");
            Object.defineProperty(Window.prototype.toString, "4d604df7a1e110b1d7ccc9f9142d531d", {
                value: e,
                enumerable: !1,
                writable: !1,
                configurable: !1
            });
        } catch (e) {
            console.error('Error executing AG js rule with uniqueId "4d604df7a1e110b1d7ccc9f9142d531d" due to: ' + e);
        }
    }
};

;// ./Extension/src/background/engine/engine-mv3.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_engine_mv3_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}


// Because this file is already MV3 replacement module, we can import directly
// from mv3 tswebextension without using aliases.










/**
 * Engine is a wrapper around the tswebextension to provide a better public
 * interface with some internal business logic: updates rules counters,
 * checks for some specific browsers actions.
 */ class background_Engine {
    /**
     * Starts the tswebextension and updates the counter of active rules.
     *
     * TODO: Set local script rules for MV3 version if we decided
     * to use MV3 in Firefox.
     */ async start() {
        /**
         * By the rules of Chrome Web Store, we cannot use remote remotely hosted scripts, thats why we prebuild them.
         *
         * It is possible to follow all places using this logic by searching JS_RULES_EXECUTION.
         *
         * This is STEP 2.1: Local script and scriptlet rules are passed to the engine.
         */ background_TsWebExtension.setLocalScriptRules(background_localScriptRules);
        const configuration = await background_Engine.getConfiguration();
        background_logger_logger.info('Start tswebextension...');
        const result = await this.api.start(configuration);
        background_rulesLimitsService.updateConfigurationResult(result, configuration.settings.filteringEnabled);
        background_UserRulesService.checkUserRulesRegexpErrors(result);
        await background_Engine.checkAppliedStealthSettings(configuration.settings, result.stealthResult);
        const rulesCount = this.api.getRulesCount();
        background_logger_logger.info(`tswebextension is started. Rules count: ${rulesCount}`);
        // TODO: remove after frontend refactoring
        background_notifier_notifier.notifyListeners(background_constants_NotifierType.RequestFilterUpdated);
        await background_RulesLimitsService.checkFiltersLimitsChange(this.update.bind(this));
        if (await background_RulesLimitsService.areFilterLimitsExceeded()) {
            background_toasts.showRuleLimitsAlert();
        }
        /**
         * Updates extension icon state after engine initialization in Manifest V3.
         *
         * Context:
         * 1. This is called at the end of Engine.start() after all filters are initialized
         * 2. In MV3, extension icon needs immediate update after engine start to prevent
         *    incorrect 'warning' icon state.
         *
         * Warning icon behavior:
         * - Without this update, warning icon persists until next UiApi.update() call
         *   (which happens on tab change or window focus)
         * - Warning icon may be valid during initialization when:
         *   - Base filter (ID: 2) is enabled in manifest
         *   - Default filters (IDs: 2, 10) are pending enablement.
         */ background_iconsApi.update();
        background_filteringLogApi.onEngineUpdated(configuration.settings.allowlistInverted);
    }
    /**
     * Updates tswebextension configuration and after that updates the counter
     * of active rules.
     *
     * @param skipLimitsCheck Skip limits check.
     */ async update(skipLimitsCheck = false) {
        const configuration = await background_Engine.getConfiguration();
        background_logger_logger.info('Update tswebextension configuration...');
        if (skipLimitsCheck) {
            background_logger_logger.info('With skip limits check.');
        }
        const result = await this.api.configure(configuration);
        background_rulesLimitsService.updateConfigurationResult(result, configuration.settings.filteringEnabled);
        background_UserRulesService.checkUserRulesRegexpErrors(result);
        await background_Engine.checkAppliedStealthSettings(configuration.settings, result.stealthResult);
        const rulesCount = this.api.getRulesCount();
        background_logger_logger.info(`tswebextension configuration is updated. Rules count: ${rulesCount}`);
        // TODO: remove after frontend refactoring
        background_notifier_notifier.notifyListeners(background_constants_NotifierType.RequestFilterUpdated);
        if (!skipLimitsCheck) {
            await background_RulesLimitsService.checkFiltersLimitsChange(this.update.bind(this));
            // show the alert only if limits checking is not skipped and limits are exceeded
            if (await background_RulesLimitsService.areFilterLimitsExceeded()) {
                background_toasts.showRuleLimitsAlert();
            }
        }
        // Updates extension icon state to reflect current filtering status.
        background_iconsApi.update();
        background_filteringLogApi.onEngineUpdated(configuration.settings.allowlistInverted);
    }
    /**
     * Creates tswebextension configuration based on current app state.
     *
     * @returns The {@link Configuration} for tswebextension.
     */ static async getConfiguration() {
        const staticFiltersIds = background_main_FiltersApi.getEnabledFilters().filter((filterId)=>background_CommonFilterApi.isCommonFilter(filterId));
        const settings = background_SettingsApi.getTsWebExtConfiguration(true);
        let allowlist = [];
        if (background_allowlist_AllowlistApi.isEnabled()) {
            if (settings.allowlistInverted) {
                allowlist = background_allowlist_AllowlistApi.getInvertedAllowlistDomains();
            } else {
                allowlist = background_allowlist_AllowlistApi.getAllowlistDomains();
            }
        }
        const userrules = {
            ...background_emptyPreprocessedFilterList,
            /**
             * User rules are always trusted.
             */ trusted: true
        };
        if (background_UserRulesApi.isEnabled()) {
            Object.assign(userrules, await background_UserRulesApi.getUserRules());
        }
        const quickFixesRules = {
            ...background_emptyPreprocessedFilterList,
            /**
             * Quick fixes are always trusted because it is the one of
             * AdGuard's filter.
             */ trusted: true
        };
        // TODO Uncomment this block when Quick Fixes filter will be supported for MV3
        // if (QuickFixesRulesApi.isEnabled()) {
        //     Object.assign(quickFixesRules, await QuickFixesRulesApi.getQuickFixesRules());
        // }
        // TODO: uncomment code bellow when custom filters support will be added back
        // const customFiltersWithMetadata = FiltersApi.getEnabledFiltersWithMetadata()
        //     .filter((f) => CustomFilterApi.isCustomFilterMetadata(f));
        // const customFilters = await Promise.all(customFiltersWithMetadata.map(async ({ filterId, trusted }) => {
        //     const preprocessedFilterList = await FiltersStorage.getAllFilterData(filterId);
        //     return {
        //         filterId,
        //         trusted,
        //         ...(preprocessedFilterList || emptyPreprocessedFilterList),
        //     };
        // }));
        return {
            declarativeLogEnabled: background_filteringLogApi.isOpen(),
            // TODO: revert to actual customFilters when their support will be added back
            customFilters: [],
            quickFixesRules,
            verbose:  true || 0,
            logLevel: background_logger_logger.currentLevel,
            staticFiltersIds,
            userrules,
            allowlist,
            settings,
            filtersPath: 'filters/',
            ruleSetsPath: 'filters/declarative'
        };
    }
    /**
     * Sets the filtering state.
     *
     * @param isFilteringEnabled - The filtering state.
     *
     * Note: we do not pass the parameter to engine because we suppose that
     * settings already changed and tswebextension will generate configuration
     * itself based on the current settings.
     */ async setFilteringState(isFilteringEnabled) {
        // Configure tswebextension with the new settings without checking limits
        // if we paused filtering.
        const skipCheck = isFilteringEnabled === false;
        await this.update(skipCheck);
    }
    /**
     * Creates new Engine.
     */ constructor(){
        background_engine_mv3_define_property(this, "api", void 0);
        background_engine_mv3_define_property(this, "handleMessage", void 0);
        background_engine_mv3_define_property(this, "debounceUpdate", background_lodash_es_debounce(this.update.bind(this), background_Engine.UPDATE_TIMEOUT_MS));
        this.api = new background_TsWebExtension(`/${background_WEB_ACCESSIBLE_RESOURCES_OUTPUT_REDIRECTS}`);
        this.handleMessage = this.api.getMessageHandler();
        // Expose for integration tests.
        // eslint-disable-next-line no-restricted-globals
        Object.assign(self, {
            adguard: {
                // eslint-disable-next-line no-restricted-globals
                ...self.adguard,
                configure: this.api.configure.bind(this.api)
            }
        });
    }
}
background_engine_mv3_define_property(background_Engine, "UPDATE_TIMEOUT_MS", 1000);
background_engine_mv3_define_property(background_Engine, "messageHandlerName", background_MESSAGE_HANDLER_NAME);
/**
     * Checks if the applied stealth settings are different from the current stealth settings.
     * If the setting was not applied, we need to revert it back for the user
     * in the UI and in the storage for configuration persistence.
     *
     * @param currentSettings Current settings in the storage and UI.
     * @param appliedStealthSettings Applied stealth settings from last update of the engine.
     *
     * @returns Promise that resolves when the check is done.
     */ background_engine_mv3_define_property(background_Engine, "checkAppliedStealthSettings", async (currentSettings, appliedStealthSettings)=>{
    if (!appliedStealthSettings || !currentSettings.stealthModeEnabled) {
        return;
    }
    const { stealth } = currentSettings;
    if (stealth.hideReferrer !== appliedStealthSettings.hideReferrer) {
        await background_SettingsApi.setSetting(background_SettingOption.HideReferrer, appliedStealthSettings.hideReferrer);
    }
    if (stealth.blockWebRTC !== appliedStealthSettings.blockWebRTC) {
        await background_SettingsApi.setSetting(background_SettingOption.BlockWebRTC, appliedStealthSettings.blockWebRTC);
    }
    if (stealth.blockChromeClientData !== appliedStealthSettings.blockChromeClientData) {
        await background_SettingsApi.setSetting(background_SettingOption.RemoveXClientData, appliedStealthSettings.blockChromeClientData);
    }
    if (stealth.sendDoNotTrack !== appliedStealthSettings.sendDoNotTrack) {
        await background_SettingsApi.setSetting(background_SettingOption.SendDoNotTrack, appliedStealthSettings.sendDoNotTrack);
    }
    if (stealth.hideSearchQueries !== appliedStealthSettings.hideSearchQueries) {
        await background_SettingsApi.setSetting(background_SettingOption.HideSearchQueries, appliedStealthSettings.hideSearchQueries);
    }
});

;// ./Extension/src/background/engine/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ // NOTE: Here important to use 'engine' without path, because it is an alias for
// manifest-specific implementation of the engine. It will be replaced with MV2
// or MV3 version during the build via webpack.

/**
 * Engine is a singleton instance of tswebextension wrapper which will be
 * replaced with MV2 or MV3 implementation during the build via webpack.
 *
 * By default, MV3 will be used.
 */ const background_engine_engine = new background_Engine();

;// ./node_modules/.pnpm/@adguard+tswebextension@3.1.0-alpha.3_@adguard+re2-wasm@1.2.0/node_modules/@adguard/tswebextension/dist/filters-storage.js





/**
 * Publicly available methods to work with filters storage.
 */
var background_filters_storage_FiltersStorage;
(function (FiltersStorage) {
    FiltersStorage.has = background_filters_FiltersStorage.has;
    FiltersStorage.getRawFilterList = background_filters_FiltersStorage.getRawFilterList;
    FiltersStorage.getFilterList = background_filters_FiltersStorage.getFilterList;
    FiltersStorage.getConversionMap = background_filters_FiltersStorage.getConversionMap;
    FiltersStorage.getSourceMap = background_filters_FiltersStorage.getSourceMap;
})(background_filters_storage_FiltersStorage || (background_filters_storage_FiltersStorage = {}));



;// ./Extension/src/background/storages/filters-adapter.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_filters_adapter_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}







/**
 * The `FiltersStoragesAdapter` is a high-level class responsible for ensuring that
 * the appropriate filter storage is invoked for different types of filters.
 *
 * In the MV3 version, static filters (rulesets) are deployed alongside the extension in JSON format.
 * Our engine operates on binary data (which is part of the preprocessed filters),
 * but these JSON rulesets do not support storing binary data. Additionally,
 * querying data from JSON is not the most efficient operation.
 *
 * To address this, `TSWebExtension` internally manages its own IndexedDB store,
 * where it automatically synchronizes rulesets as preprocessed filter lists.
 * However, this logic applies only to rulesets in MV3. User filters, allowlists, and custom filters
 * are not affected by this mechanism—they are still stored using the classic `FiltersStorage`,
 * which is managed by the browser extension.
 *
 * To simplify the usage of multiple storages, we introduced this adapter,
 * which always calls the appropriate storage for each filter list.
 * This allows the lower-level storage implementations to remain focused on
 * their specific responsibilities while ensuring seamless integration.
 */ class background_FiltersStoragesAdapter {
    /**
     * Sets specified filter list with the specified ID in the storage.
     *
     * @note This method does nothing in MV3 version if the filter ID is a static filter ID,
     * because static filters are managed by TSWebExtension.
     *
     * @param filterId Filter id.
     * @param filter Raw filter list or preprocessed filter list.
     */ static async set(filterId, filter) {
        // Do not allow to modify static filters in MV3.
        if (true) {
            const staticFilterIds = background_FiltersStoragesAdapter.getStaticFilterIds();
            if (staticFilterIds !== null && staticFilterIds.has(filterId)) {
                background_logger_logger.error(`Filter id ${filterId} is a static filter id, modifying it is not allowed from the extension.`);
                return;
            }
        }
        try {
            await background_FiltersStorage.set(filterId, filter);
        } catch (error) {
            background_logger_logger.error(`Failed to set filter list for filter id ${filterId}, got error:`, error);
            throw error;
        }
    }
    /**
     * Checks if the filter list with the specified ID exists in the storage.
     *
     * @param filterId Filter id.
     *
     * @returns `true` if the filter list exists, `false` otherwise.
     */ static async has(filterId) {
        if (true) {
            const staticFilterIds = background_FiltersStoragesAdapter.getStaticFilterIds();
            if (staticFilterIds !== null && staticFilterIds.has(filterId)) {
                return background_filters_storage_FiltersStorage.has(filterId);
            }
        }
        return background_FiltersStorage.has(filterId);
    }
    /**
     * Gets the whole preprocessed filter list for the specified filter ID.
     *
     * @param filterId Filter id.
     *
     * @returns Preprocessed filter list or `undefined` if the filter list does not exist.
     */ static async get(filterId) {
        // eslint-disable-next-line prefer-const
        let [rawFilterList, filterList, conversionMap, sourceMap] = await Promise.all([
            background_FiltersStoragesAdapter.getRawFilterList(filterId),
            background_FiltersStoragesAdapter.getFilterList(filterId),
            background_FiltersStoragesAdapter.getConversionMap(filterId),
            background_FiltersStoragesAdapter.getSourceMap(filterId)
        ]);
        if (rawFilterList === undefined || filterList === undefined || sourceMap === undefined) {
            return undefined;
        }
        if (conversionMap === undefined) {
            conversionMap = {};
        }
        return {
            rawFilterList,
            filterList,
            conversionMap,
            sourceMap
        };
    }
    /**
     * Removes the filter list with the specified ID from the storage.
     *
     * @note This method does nothing in MV3 version if the filter ID is a static filter ID,
     * because static filters are managed by TSWebExtension.
     *
     * @param filterId Filter id.
     */ static async remove(filterId) {
        if (true) {
            const staticFilterIds = background_FiltersStoragesAdapter.getStaticFilterIds();
            if (staticFilterIds !== null && staticFilterIds.has(filterId)) {
                background_logger_logger.error(`Filter id ${filterId} is a static filter id, removing it is not allowed from the extension.`);
                return;
            }
        }
        await background_FiltersStorage.remove(filterId);
    }
    /**
     * Gets the raw filter list for the specified filter ID.
     *
     * @param filterId Filter id.
     *
     * @returns Raw filter list or `undefined` if the filter list does not exist.
     */ static async getRawFilterList(filterId) {
        if (true) {
            const staticFilterIds = background_FiltersStoragesAdapter.getStaticFilterIds();
            if (staticFilterIds !== null && staticFilterIds.has(filterId)) {
                return background_filters_storage_FiltersStorage.getRawFilterList(filterId);
            }
        }
        return background_FiltersStorage.getRawFilterList(filterId);
    }
    /**
     * Gets the byte array of the filter list for the specified filter ID.
     *
     * @param filterId Filter id.
     *
     * @returns Byte array of the filter list or `undefined` if the filter list does not exist.
     */ static async getFilterList(filterId) {
        if (true) {
            const staticFilterIds = background_FiltersStoragesAdapter.getStaticFilterIds();
            if (staticFilterIds !== null && staticFilterIds.has(filterId)) {
                return background_filters_storage_FiltersStorage.getFilterList(filterId);
            }
        }
        return background_FiltersStorage.getFilterList(filterId);
    }
    /**
     * Gets the conversion map for the specified filter ID.
     *
     * @param filterId Filter id.
     *
     * @returns Conversion map or `undefined` if the filter list does not exist.
     */ static async getConversionMap(filterId) {
        if (true) {
            const staticFilterIds = background_FiltersStoragesAdapter.getStaticFilterIds();
            if (staticFilterIds !== null && staticFilterIds.has(filterId)) {
                return background_filters_storage_FiltersStorage.getConversionMap(filterId);
            }
        }
        return background_FiltersStorage.getConversionMap(filterId);
    }
    /**
     * Gets the source map for the specified filter ID.
     *
     * @param filterId Filter id.
     *
     * @returns Source map or `undefined` if the filter list does not exist.
     */ static async getSourceMap(filterId) {
        if (true) {
            const staticFilterIds = background_FiltersStoragesAdapter.getStaticFilterIds();
            if (staticFilterIds !== null && staticFilterIds.has(filterId)) {
                return background_filters_storage_FiltersStorage.getSourceMap(filterId);
            }
        }
        return background_FiltersStorage.getSourceMap(filterId);
    }
    /**
     * Returns original filter list text for the specified filter ID.
     *
     * @param filterId Filter id.
     *
     * @returns Promise, resolved with original user rules strings.
     */ static async getOriginalFilterList(filterId) {
        const [rawFilterList, conversionMap] = await Promise.all([
            background_FiltersStoragesAdapter.getRawFilterList(filterId),
            background_FiltersStoragesAdapter.getConversionMap(filterId)
        ]);
        if (rawFilterList === undefined) {
            return undefined;
        }
        if (conversionMap === undefined) {
            return rawFilterList;
        }
        return background_es/* FilterListPreprocessor */.aQ.getOriginalFilterListText({
            rawFilterList,
            conversionMap
        });
    }
    /**
     * Returns a set of static filter IDs for MV3.
     *
     * @note This method caches the result for subsequent calls.
     *
     * @returns Set of static filter ids or `null` if the extension is not MV3.
     */ static getStaticFilterIds() {
        if (false) {}
        if (background_FiltersStoragesAdapter.staticFilterIds !== null) {
            return background_FiltersStoragesAdapter.staticFilterIds;
        }
        const manifest = background_browser_polyfill_default().runtime.getManifest();
        if (!manifest.declarative_net_request) {
            return null;
        }
        background_FiltersStoragesAdapter.staticFilterIds = new Set(manifest.declarative_net_request.rule_resources.map(({ id })=>background_extractRuleSetId(id))// Metadata ruleset is not a real ruleset, so we should not include it in the list of static rulesets.
        // Also, its ID is conflicting with the ID of User Rules.
        .filter((id)=>id !== null && id !== background_METADATA_RULESET_ID));
        return background_FiltersStoragesAdapter.staticFilterIds;
    }
}
/**
     * Cache for static MV3 filter IDs.
     */ background_filters_adapter_define_property(background_FiltersStoragesAdapter, "staticFilterIds", null);

;// ./Extension/src/background/api/filtering-log.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_filtering_log_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}













/**
 * The filtering log collects all available information about requests
 * and the rules applied to them.
 */ class background_FilteringLogApi {
    /**
     * Purges filters cache.
     *
     * @param filterIds Filter ids to remove from cache. If not provided, the whole cache will be purged.
     */ purgeFiltersCache(filterIds) {
        if (filterIds) {
            filterIds.forEach((filterId)=>this.filtersCache.delete(filterId));
            background_logger_logger.info(`Filtering log filters cache purged for filter ids: ${filterIds.join(', ')}`);
            return;
        }
        this.filtersCache.clear();
        background_logger_logger.info('Filtering log filters cache purged');
    }
    /**
     * Purges filter sync attempts.
     *
     * @param filterIds Filter ids to remove from cache. If not provided, the whole cache will be purged.
     */ purgeFilterSyncAttempts(filterIds) {
        if (filterIds) {
            filterIds.forEach((filterId)=>this.filterSyncAttempts.delete(filterId));
            return;
        }
        this.filterSyncAttempts.clear();
    }
    /**
     * Called when the engine is updated.
     *
     * @param allowlistInverted Whether allowlist mode is inverted.
     */ onEngineUpdated(allowlistInverted) {
        this.allowlistInverted = allowlistInverted;
        if (!this.isOpen()) {
            return;
        }
        // We need to purge the filters cache, because the filters data may be changed after the engine update
        this.purgeFiltersCache();
        this.purgeFilterSyncAttempts();
    }
    /**
     * Helper method to get filter data.
     * It handles a cache internally to speed up requests for the same filter next time.
     *
     * @param filterId Filter id.
     *
     * @returns Filter data or undefined if the filter is not found.
     */ async getFilterData(filterId) {
        if (this.filtersCache.has(filterId)) {
            return this.filtersCache.get(filterId);
        }
        try {
            // eslint-disable-next-line prefer-const
            let [rawFilterList, conversionMap, sourceMap] = await Promise.all([
                background_FiltersStoragesAdapter.getRawFilterList(filterId),
                background_FiltersStoragesAdapter.getConversionMap(filterId),
                background_FiltersStoragesAdapter.getSourceMap(filterId)
            ]);
            // Raw filter list and source map are required to get rule texts
            if (!rawFilterList || !sourceMap) {
                return undefined;
            }
            if (!conversionMap) {
                conversionMap = {};
            }
            const filterData = {
                rawFilterList,
                conversionMap,
                sourceMap
            };
            this.filtersCache.set(filterId, filterData);
            return filterData;
        } catch (e) {
            background_logger_logger.error(`Failed to get filter data for filter id ${filterId}`, e);
        }
        return undefined;
    }
    /**
     * Tries to sync the cached filter data with the storage.
     *
     * @param filterId Filter id.
     *
     * @returns Returns false if the filter was synced within the last
     * {@link FilteringLogApi.SYNC_ATTEMPTS_INTERVAL_MS} milliseconds.
     * Otherwise, returns true.
     */ attemptToSyncFilter(filterId) {
        const lastAttemptTime = this.filterSyncAttempts.get(filterId) || 0;
        if (Date.now() - lastAttemptTime < background_FilteringLogApi.SYNC_ATTEMPTS_INTERVAL_MS) {
            return false;
        }
        // Delete filter from the cache to force a new request next time
        this.purgeFiltersCache([
            filterId
        ]);
        this.filterSyncAttempts.set(filterId, Date.now());
        return true;
    }
    /**
     * Gets rule text for the specified filter id and rule index.
     * If the rule is not found, returns null.
     * It handles a cache internally to speed up requests for the same filter next time.
     *
     * @param filterId Filter id.
     * @param ruleIndex Rule index.
     *
     * @returns Rule text or null if the rule is not found.
     */ async getRuleText(filterId, ruleIndex) {
        // Special case: when inverted allowlist mode is enabled, we generate rules dynamically without rule index,
        // and we don't need to show them, so we return null.
        // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2883
        if (this.allowlistInverted && filterId === background_AntiBannerFiltersId.AllowlistFilterId && ruleIndex === background_es/* RULE_INDEX_NONE */.JX) {
            return null;
        }
        // Note: Stealth and Allowlist are special filters, they're generated dynamically by TSWebExtension internally.
        // We don't store them in the storage, so we need to get rule AST nodes and generate rule text manually.
        if (background_FilteringLogApi.DYNAMIC_FILTER_LISTS.has(filterId)) {
            const ruleNode = background_engine_engine.api.retrieveRuleNode(filterId, ruleIndex);
            // The following error messages should not be displayed during normal operation,
            // but we handle them just in case, and to provide type safety
            if (!ruleNode) {
                background_logger_logger.error(`Failed to get rule node for filter id ${filterId} and rule index ${ruleIndex}`);
                return null;
            }
            const ruleText = background_rule_generator/* RuleGenerator */.u.generate(ruleNode);
            if (!ruleText) {
                background_logger_logger.error(`Failed to get rule text for filter id ${filterId} and rule index ${ruleIndex}`);
                return null;
            }
            return {
                appliedRuleText: ruleText
            };
        }
        const filterData = await this.getFilterData(filterId);
        if (!filterData) {
            background_logger_logger.error(`Failed to get filter data for filter id ${filterId}`);
            return null;
        }
        const { rawFilterList, conversionMap, sourceMap } = filterData;
        // Get line start index in the source file by rule start index in the byte array
        const lineStartIndex = (0,background_es/* getRuleSourceIndex */.gx)(ruleIndex, sourceMap);
        if (lineStartIndex === -1) {
            let baseMessage = `Failed to get line start index for filter id ${filterId} and rule index ${ruleIndex}`;
            const ruleNode = background_engine_engine.api.retrieveRuleNode(filterId, ruleIndex);
            // Note: during normal operation, ruleNode should not be null,
            // but we handle this case just in case, and to provide type safety
            if (ruleNode) {
                const generatedRuleText = background_rule_generator/* RuleGenerator */.u.generate(ruleNode);
                baseMessage += `, generated rule text: ${generatedRuleText}`;
            }
            // If the rule is not found, try to sync the filter and try again
            if (this.attemptToSyncFilter(filterId)) {
                background_logger_logger.warn(`${baseMessage}, trying to sync the filter`);
                return this.getRuleText(filterId, ruleIndex);
            }
            background_logger_logger.error(baseMessage);
            return null;
        }
        const appliedRuleText = (0,background_es/* getRuleSourceText */.Bv)(lineStartIndex, rawFilterList);
        if (!appliedRuleText) {
            let baseMessage = `Failed to get rule text for filter id ${filterId} and rule index ${ruleIndex}`;
            const ruleNode = background_engine_engine.api.retrieveRuleNode(filterId, ruleIndex);
            // Note: during normal operation, ruleNode should not be null,
            // but we handle this case just in case, and to provide type safety
            if (ruleNode) {
                const generatedRuleText = background_rule_generator/* RuleGenerator */.u.generate(ruleNode);
                baseMessage += `, generated rule text: ${generatedRuleText}`;
            }
            // If the rule is not found, try to sync the filter and try again
            if (this.attemptToSyncFilter(filterId)) {
                background_logger_logger.warn(`${baseMessage}, trying to sync the filter`);
                return this.getRuleText(filterId, ruleIndex);
            }
            background_logger_logger.error(baseMessage);
            return null;
        }
        const result = {
            appliedRuleText
        };
        if (conversionMap && conversionMap[lineStartIndex]) {
            result.originalRuleText = conversionMap[lineStartIndex];
        }
        return result;
    }
    /**
     * Checks if filtering log page is opened.
     *
     * @returns True, if filtering log page is opened, else false.
     */ isOpen() {
        return this.openedFilteringLogsPages > 0;
    }
    /**
     * Checks if preserve log is enabled.
     *
     * @returns True, if preserve log is enabled, else false.
     */ isPreserveLogEnabled() {
        return this.preserveLogEnabled;
    }
    /**
     * Sets preserve log state.
     *
     * @param enabled Is preserve log enabled.
     */ setPreserveLogState(enabled) {
        this.preserveLogEnabled = enabled;
    }
    /**
     * We collect filtering events if opened at least one page of log.
     */ onOpenFilteringLogPage() {
        this.openedFilteringLogsPages += 1;
        try {
            background_engine_engine.api.setDebugScriptlets(true);
        } catch (e) {
            background_logger_logger.error('Failed to enable `verbose scriptlets logging` option', e);
        }
        try {
            background_engine_engine.api.setCollectHitStats(true);
        } catch (e) {
            background_logger_logger.error('Failed to enable `collect hit stats` option', e);
        }
    }
    /**
     * Cleanups when last page of log closes.
     */ onCloseFilteringLogPage() {
        this.openedFilteringLogsPages = Math.max(this.openedFilteringLogsPages - 1, 0);
        if (this.openedFilteringLogsPages === 0) {
            // Purge filters cache to free up memory
            this.purgeFiltersCache();
            this.purgeFilterSyncAttempts();
            // Clear events
            this.tabsInfoMap.forEach((tabInfo)=>{
                tabInfo.filteringEvents = [];
            });
            try {
                background_engine_engine.api.setDebugScriptlets(false);
            } catch (e) {
                background_logger_logger.error('Failed to disable `verbose scriptlets logging` option', e);
            }
            if (background_settingsStorage.get(background_SettingOption.DisableCollectHits)) {
                try {
                    background_engine_engine.api.setCollectHitStats(false);
                } catch (e) {
                    background_logger_logger.error('Failed to disable `collect hit stats` option', e);
                }
            }
        }
    }
    /**
     * Creates tab info.
     *
     * @param tab {@link browser.Tabs.Tab} Data.
     * @param isSyntheticTab Is tab is used to send initial requests from new tab in chrome.
     */ createTabInfo(tab, isSyntheticTab = false) {
        const { id, title, url } = tab;
        if (!id || !url || !title) {
            return;
        }
        // Background tab can't be added
        // Synthetic tabs are used to send initial requests from new tab in chrome
        if (id === background_constants_BACKGROUND_TAB_ID || isSyntheticTab) {
            return;
        }
        const tabInfo = {
            tabId: id,
            title,
            isExtensionTab: background_isExtensionUrl(url),
            filteringEvents: [],
            domain: background_getDomain(url)
        };
        this.tabsInfoMap.set(id, tabInfo);
        background_notifier_notifier.notifyListeners(background_constants_NotifierType.TabAdded, tabInfo);
    }
    /**
     * Updates tab title and url.
     *
     * @param tab {@link browser.Tabs.Tab} Data.
     */ updateTabInfo(tab) {
        const { id, title, url } = tab;
        if (!id || !url || !title) {
            return;
        }
        // Background tab can't be updated
        if (id === background_constants_BACKGROUND_TAB_ID) {
            return;
        }
        const tabInfo = this.getFilteringInfoByTabId(id);
        if (!tabInfo) {
            this.createTabInfo(tab);
            return;
        }
        tabInfo.title = title;
        tabInfo.isExtensionTab = background_isExtensionUrl(url);
        background_notifier_notifier.notifyListeners(background_constants_NotifierType.TabUpdate, tabInfo);
    }
    /**
     * Removes tab info.
     *
     * @param id Tab id.
     */ removeTabInfo(id) {
        // Background tab can't be removed
        if (id === background_constants_BACKGROUND_TAB_ID) {
            return;
        }
        const tabInfo = this.tabsInfoMap.get(id);
        if (tabInfo) {
            background_notifier_notifier.notifyListeners(background_constants_NotifierType.TabClose, tabInfo);
        }
        this.tabsInfoMap.delete(id);
    }
    /**
     * Returns filtering info for tab.
     *
     * @param tabId Tab id.
     *
     * @returns Tab data for filtering log window.
     */ getFilteringInfoByTabId(tabId) {
        return this.tabsInfoMap.get(tabId);
    }
    /**
     * Synchronizes currently opened tabs with out state.
     *
     * @returns Array of {@link FilteringLogTabInfo} with data about opened tabs.
     */ async synchronizeOpenTabs() {
        const tabs = await background_TabsApi.getAll();
        // As Object.keys() returns strings we convert them to integers,
        // because tabId is integer in extension API
        const tabIdsToRemove = Object.keys(this.tabsInfoMap).map((id)=>Number(id));
        for(let i = 0; i < tabs.length; i += 1){
            const openTab = tabs[i];
            if (!(openTab === null || openTab === void 0 ? void 0 : openTab.id)) {
                continue;
            }
            const tabInfo = this.tabsInfoMap.get(openTab.id);
            if (!tabInfo) {
                this.createTabInfo(openTab);
            } else {
                // update tab
                this.updateTabInfo(openTab);
            }
            const index = tabIdsToRemove.indexOf(openTab.id);
            if (index >= 0) {
                tabIdsToRemove.splice(index, 1);
            }
        }
        for(let j = 0; j < tabIdsToRemove.length; j += 1){
            const tabIdToRemove = tabIdsToRemove[j];
            if (tabIdToRemove) {
                this.removeTabInfo(tabIdToRemove);
            }
        }
        return Array.from(this.tabsInfoMap.values());
    }
    /**
     * Remove log requests for tab.
     *
     * @param tabId Tab id.
     * @param ignorePreserveLog Is {@link preserveLogEnabled} flag ignored.
     */ clearEventsByTabId(tabId, ignorePreserveLog = false) {
        const tabInfo = this.tabsInfoMap.get(tabId);
        const preserveLog = ignorePreserveLog ? false : this.preserveLogEnabled;
        if (tabInfo && !preserveLog) {
            tabInfo.filteringEvents = [];
            background_notifier_notifier.notifyListeners(background_constants_NotifierType.TabReset, tabInfo);
        }
    }
    /**
     * Adds a filter log event (for example when applying a csp rule, enforcing a script, sending a request)
     * with data related to that event.
     *
     * @param tabId Tab id.
     * @param data {@link FilteringLogEvent} Event data.
     */ async addEventData(tabId, data) {
        const tabInfo = this.getFilteringInfoByTabId(tabId);
        if (!tabInfo || !this.isOpen()) {
            return;
        }
        // Get rule text based on filter id and rule index
        if (data.requestRule) {
            data.requestRule = await this.applyRuleTextToRuleData(data.requestRule);
        }
        tabInfo.filteringEvents.push(data);
        if (tabInfo.filteringEvents.length > background_FilteringLogApi.REQUESTS_SIZE_PER_TAB) {
            // don't remove first item, cause it's request to main frame
            tabInfo.filteringEvents.splice(1, 1);
        }
    }
    /**
     * Updates the event data for an already recorded event.
     *
     * @param tabId Tab id.
     * @param eventId Event id.
     * @param data Event data.
     */ async updateEventData(tabId, eventId, data) {
        var _event_requestRule;
        const tabInfo = this.getFilteringInfoByTabId(tabId);
        if (!tabInfo || !this.isOpen()) {
            return;
        }
        const { filteringEvents } = tabInfo;
        let event = filteringEvents.find((e)=>e.eventId === eventId);
        if (!event) {
            return;
        }
        if (data.requestRule && !((_event_requestRule = event.requestRule) === null || _event_requestRule === void 0 ? void 0 : _event_requestRule.appliedRuleText)) {
            data.requestRule = await this.applyRuleTextToRuleData(data.requestRule);
        }
        if (data.replaceRules) {
            data.replaceRules = await this.applyRuleTextToRuleDataArray(data.replaceRules);
        }
        if (data.stealthAllowlistRules) {
            data.stealthAllowlistRules = await this.applyRuleTextToRuleDataArray(data.stealthAllowlistRules);
        }
        event = Object.assign(event, data);
    }
    /**
     * Retrieves and applies rule text to a single rule data object.
     *
     * @param rule Rule data object containing filterId and ruleIndex.
     *
     * @returns Rule object with rule text applied.
     */ async applyRuleTextToRuleData(rule) {
        const { filterId, ruleIndex } = rule;
        const ruleTextData = await this.getRuleText(filterId, ruleIndex);
        return ruleTextData ? Object.assign(rule, ruleTextData) : rule;
    }
    /**
     * Retrieves and applies rule text to an array of rule data objects.
     *
     * @param rules Array of rule data objects containing filterId and ruleIndex.
     *
     * @returns Array of rule objects with rule text applied.
     */ async applyRuleTextToRuleDataArray(rules) {
        return Promise.all(rules.map(async (rule)=>this.applyRuleTextToRuleData(rule)));
    }
    /**
     * Updates the event data for an already recorded event.
     *
     * @param tabId Tab id.
     * @param eventId Event id.
     * @param declarativeRuleInfo Applied declarative rule in JSON and it`s source rule and filter id.
     */ async attachDeclarativeRuleToEventData(tabId, eventId, declarativeRuleInfo) {
        const tabInfo = this.getFilteringInfoByTabId(tabId);
        if (!tabInfo || !this.isOpen()) {
            return;
        }
        const { filteringEvents } = tabInfo;
        const event = filteringEvents.find((e)=>e.eventId === eventId);
        if (!event) {
            background_logger_logger.debug('Not found event in filtering log to update: ', eventId);
            return;
        }
        /**
         * Search for matching request event inside of filtering events.
         * If found matching event we assign declarative rule to that event,
         * otherwise assign it to original event.
         */ const { sourceRules } = declarativeRuleInfo;
        const matchedFilteringEvent = filteringEvents.find((event)=>{
            if (!event.requestRule) {
                return false;
            }
            const { originalRuleText, appliedRuleText, filterId } = event.requestRule;
            const ruleText = originalRuleText || appliedRuleText;
            return ruleText && sourceRules.some((rule)=>rule.sourceRule === ruleText && rule.filterId === filterId);
        });
        if (matchedFilteringEvent) {
            matchedFilteringEvent.declarativeRuleInfo = declarativeRuleInfo;
        } else {
            event.declarativeRuleInfo = declarativeRuleInfo;
        }
    }
    /**
     * Checks if a cookie event exists or not.
     *
     * @param cookieEvent Cookie event.
     * @param cookieEvent.data Cookie event data.
     *
     * @returns True if a cookie with the same frame domain, name and value
     * has already been written, and false otherwise.
     */ isExistingCookieEvent({ data }) {
        const { tabId, cookieName, cookieValue, frameDomain } = data;
        const tabInfo = this.getFilteringInfoByTabId(tabId);
        const filteringEvents = tabInfo === null || tabInfo === void 0 ? void 0 : tabInfo.filteringEvents;
        if (!filteringEvents) {
            return false;
        }
        return filteringEvents.some((event)=>{
            return event.frameDomain === frameDomain && event.cookieName === cookieName && event.cookieValue === cookieValue;
        });
    }
    constructor(){
        /**
     * Flag to enable/disable preserve log.
     */ background_filtering_log_define_property(this, "preserveLogEnabled", false);
        background_filtering_log_define_property(this, "openedFilteringLogsPages", 0);
        background_filtering_log_define_property(this, "tabsInfoMap", new Map([
            [
                background_constants_BACKGROUND_TAB_ID,
                {
                    tabId: background_constants_BACKGROUND_TAB_ID,
                    title: background_translator.getMessage('background_tab_title'),
                    isExtensionTab: false,
                    filteringEvents: [],
                    domain: null
                }
            ]
        ]));
        /**
     * Cache for filters data.
     *
     * The key is the filter list id and the value is the filter data.
     * This cache is used to avoid unnecessary requests to the storage while filtering log is opened.
     * After closing the filtering log, the cache is purged to free up memory.
     */ background_filtering_log_define_property(this, "filtersCache", new Map());
        /**
     * Map of filter sync attempts. The key is the filter list id and the value is the last attempt time.
     * In some rare edge cases (but maybe never), the filters cache may be become outdated,
     * so we need to sync the filter again.
     * We only try this sync if we encounter an error while getting rule text.
     */ background_filtering_log_define_property(this, "filterSyncAttempts", new Map());
        /**
     * Flag to invert allowlist mode.
     */ background_filtering_log_define_property(this, "allowlistInverted", false);
    }
}
background_filtering_log_define_property(background_FilteringLogApi, "REQUESTS_SIZE_PER_TAB", 1000);
/**
     * Filter lists that are generated dynamically by TSWebExtension.
     * We don't store them in the storage, so we need to get rule AST nodes and generate rule text manually.
     */ background_filtering_log_define_property(background_FilteringLogApi, "DYNAMIC_FILTER_LISTS", new Set([
    background_AntiBannerFiltersId.StealthModeFilterId,
    background_AntiBannerFiltersId.AllowlistFilterId
]));
/**
     * Interval for sync attempts in milliseconds.
     * We should try to sync the filter only once per 10 seconds.
     */ background_filtering_log_define_property(background_FilteringLogApi, "SYNC_ATTEMPTS_INTERVAL_MS", 10000);
const background_filteringLogApi = new background_FilteringLogApi();

;// ./node_modules/.pnpm/@adguard+filters-downloader@2.4.1/node_modules/@adguard/filters-downloader/dist/index.browser.js
var background_commonjsGlobal$1 = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof self !== 'undefined' ? self : {};

function background_getDefaultExportFromCjs$1 (x) {
	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}

var background_commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof background_commonjsGlobal$1 !== 'undefined' ? background_commonjsGlobal$1 : typeof self !== 'undefined' ? self : {};
function background_getDefaultExportFromCjs (x) {
	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
function background_getAugmentedNamespace(n) {
  if (n.__esModule) return n;
  var f = n.default;
	if (typeof f == "function") {
		var a = function a () {
			if (this instanceof a) {
        return Reflect.construct(f, arguments, this.constructor);
			}
			return f.apply(this, arguments);
		};
		a.prototype = f.prototype;
  } else a = {};
  Object.defineProperty(a, '__esModule', {value: true});
	Object.keys(n).forEach(function (k) {
		var d = Object.getOwnPropertyDescriptor(n, k);
		Object.defineProperty(a, k, d.get ? d : {
			enumerable: true,
			get: function () {
				return n[k];
			}
		});
	});
	return a;
}
var background_sha1 = {exports: {}};
function background_commonjsRequire$1(path) {
	throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
}
var background_core$1 = {exports: {}};
var background_nodeResolve_empty = {};
var background_nodeResolve_empty$1 = Object.freeze({
	__proto__: null,
	default: background_nodeResolve_empty
});
var background_require$$0 = background_getAugmentedNamespace(background_nodeResolve_empty$1);
var background_hasRequiredCore$1;
function background_requireCore$1 () {
	if (background_hasRequiredCore$1) return background_core$1.exports;
	background_hasRequiredCore$1 = 1;
	(function (module, exports) {
(function (root, factory) {
			{
				module.exports = factory();
			}
		}(background_commonjsGlobal, function () {
			var CryptoJS = CryptoJS || (function (Math, undefined$1) {
			    var crypto;
			    if (typeof window !== 'undefined' && window.crypto) {
			        crypto = window.crypto;
			    }
			    if (typeof self !== 'undefined' && self.crypto) {
			        crypto = self.crypto;
			    }
			    if (typeof globalThis !== 'undefined' && globalThis.crypto) {
			        crypto = globalThis.crypto;
			    }
			    if (!crypto && typeof window !== 'undefined' && window.msCrypto) {
			        crypto = window.msCrypto;
			    }
			    if (!crypto && typeof background_commonjsGlobal !== 'undefined' && background_commonjsGlobal.crypto) {
			        crypto = background_commonjsGlobal.crypto;
			    }
			    if (!crypto && typeof background_commonjsRequire$1 === 'function') {
			        try {
			            crypto = background_require$$0;
			        } catch (err) {}
			    }
			    var cryptoSecureRandomInt = function () {
			        if (crypto) {
			            if (typeof crypto.getRandomValues === 'function') {
			                try {
			                    return crypto.getRandomValues(new Uint32Array(1))[0];
			                } catch (err) {}
			            }
			            if (typeof crypto.randomBytes === 'function') {
			                try {
			                    return crypto.randomBytes(4).readInt32LE();
			                } catch (err) {}
			            }
			        }
			        throw new Error('Native crypto module could not be used to get secure random number.');
			    };
			    var create = Object.create || (function () {
			        function F() {}
			        return function (obj) {
			            var subtype;
			            F.prototype = obj;
			            subtype = new F();
			            F.prototype = null;
			            return subtype;
			        };
			    }());
			    var C = {};
			    var C_lib = C.lib = {};
			    var Base = C_lib.Base = (function () {
			        return {
			            extend: function (overrides) {
			                var subtype = create(this);
			                if (overrides) {
			                    subtype.mixIn(overrides);
			                }
			                if (!subtype.hasOwnProperty('init') || this.init === subtype.init) {
			                    subtype.init = function () {
			                        subtype.$super.init.apply(this, arguments);
			                    };
			                }
			                subtype.init.prototype = subtype;
			                subtype.$super = this;
			                return subtype;
			            },
			            create: function () {
			                var instance = this.extend();
			                instance.init.apply(instance, arguments);
			                return instance;
			            },
			            init: function () {
			            },
			            mixIn: function (properties) {
			                for (var propertyName in properties) {
			                    if (properties.hasOwnProperty(propertyName)) {
			                        this[propertyName] = properties[propertyName];
			                    }
			                }
			                if (properties.hasOwnProperty('toString')) {
			                    this.toString = properties.toString;
			                }
			            },
			            clone: function () {
			                return this.init.prototype.extend(this);
			            }
			        };
			    }());
			    var WordArray = C_lib.WordArray = Base.extend({
			        init: function (words, sigBytes) {
			            words = this.words = words || [];
			            if (sigBytes != undefined$1) {
			                this.sigBytes = sigBytes;
			            } else {
			                this.sigBytes = words.length * 4;
			            }
			        },
			        toString: function (encoder) {
			            return (encoder || Hex).stringify(this);
			        },
			        concat: function (wordArray) {
			            var thisWords = this.words;
			            var thatWords = wordArray.words;
			            var thisSigBytes = this.sigBytes;
			            var thatSigBytes = wordArray.sigBytes;
			            this.clamp();
			            if (thisSigBytes % 4) {
			                for (var i = 0; i < thatSigBytes; i++) {
			                    var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
			                    thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
			                }
			            } else {
			                for (var j = 0; j < thatSigBytes; j += 4) {
			                    thisWords[(thisSigBytes + j) >>> 2] = thatWords[j >>> 2];
			                }
			            }
			            this.sigBytes += thatSigBytes;
			            return this;
			        },
			        clamp: function () {
			            var words = this.words;
			            var sigBytes = this.sigBytes;
			            words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
			            words.length = Math.ceil(sigBytes / 4);
			        },
			        clone: function () {
			            var clone = Base.clone.call(this);
			            clone.words = this.words.slice(0);
			            return clone;
			        },
			        random: function (nBytes) {
			            var words = [];
			            for (var i = 0; i < nBytes; i += 4) {
			                words.push(cryptoSecureRandomInt());
			            }
			            return new WordArray.init(words, nBytes);
			        }
			    });
			    var C_enc = C.enc = {};
			    var Hex = C_enc.Hex = {
			        stringify: function (wordArray) {
			            var words = wordArray.words;
			            var sigBytes = wordArray.sigBytes;
			            var hexChars = [];
			            for (var i = 0; i < sigBytes; i++) {
			                var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
			                hexChars.push((bite >>> 4).toString(16));
			                hexChars.push((bite & 0x0f).toString(16));
			            }
			            return hexChars.join('');
			        },
			        parse: function (hexStr) {
			            var hexStrLength = hexStr.length;
			            var words = [];
			            for (var i = 0; i < hexStrLength; i += 2) {
			                words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
			            }
			            return new WordArray.init(words, hexStrLength / 2);
			        }
			    };
			    var Latin1 = C_enc.Latin1 = {
			        stringify: function (wordArray) {
			            var words = wordArray.words;
			            var sigBytes = wordArray.sigBytes;
			            var latin1Chars = [];
			            for (var i = 0; i < sigBytes; i++) {
			                var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
			                latin1Chars.push(String.fromCharCode(bite));
			            }
			            return latin1Chars.join('');
			        },
			        parse: function (latin1Str) {
			            var latin1StrLength = latin1Str.length;
			            var words = [];
			            for (var i = 0; i < latin1StrLength; i++) {
			                words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
			            }
			            return new WordArray.init(words, latin1StrLength);
			        }
			    };
			    var Utf8 = C_enc.Utf8 = {
			        stringify: function (wordArray) {
			            try {
			                return decodeURIComponent(escape(Latin1.stringify(wordArray)));
			            } catch (e) {
			                throw new Error('Malformed UTF-8 data');
			            }
			        },
			        parse: function (utf8Str) {
			            return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
			        }
			    };
			    var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
			        reset: function () {
			            this._data = new WordArray.init();
			            this._nDataBytes = 0;
			        },
			        _append: function (data) {
			            if (typeof data == 'string') {
			                data = Utf8.parse(data);
			            }
			            this._data.concat(data);
			            this._nDataBytes += data.sigBytes;
			        },
			        _process: function (doFlush) {
			            var processedWords;
			            var data = this._data;
			            var dataWords = data.words;
			            var dataSigBytes = data.sigBytes;
			            var blockSize = this.blockSize;
			            var blockSizeBytes = blockSize * 4;
			            var nBlocksReady = dataSigBytes / blockSizeBytes;
			            if (doFlush) {
			                nBlocksReady = Math.ceil(nBlocksReady);
			            } else {
			                nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
			            }
			            var nWordsReady = nBlocksReady * blockSize;
			            var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
			            if (nWordsReady) {
			                for (var offset = 0; offset < nWordsReady; offset += blockSize) {
			                    this._doProcessBlock(dataWords, offset);
			                }
			                processedWords = dataWords.splice(0, nWordsReady);
			                data.sigBytes -= nBytesReady;
			            }
			            return new WordArray.init(processedWords, nBytesReady);
			        },
			        clone: function () {
			            var clone = Base.clone.call(this);
			            clone._data = this._data.clone();
			            return clone;
			        },
			        _minBufferSize: 0
			    });
			    C_lib.Hasher = BufferedBlockAlgorithm.extend({
			        cfg: Base.extend(),
			        init: function (cfg) {
			            this.cfg = this.cfg.extend(cfg);
			            this.reset();
			        },
			        reset: function () {
			            BufferedBlockAlgorithm.reset.call(this);
			            this._doReset();
			        },
			        update: function (messageUpdate) {
			            this._append(messageUpdate);
			            this._process();
			            return this;
			        },
			        finalize: function (messageUpdate) {
			            if (messageUpdate) {
			                this._append(messageUpdate);
			            }
			            var hash = this._doFinalize();
			            return hash;
			        },
			        blockSize: 512/32,
			        _createHelper: function (hasher) {
			            return function (message, cfg) {
			                return new hasher.init(cfg).finalize(message);
			            };
			        },
			        _createHmacHelper: function (hasher) {
			            return function (message, key) {
			                return new C_algo.HMAC.init(hasher, key).finalize(message);
			            };
			        }
			    });
			    var C_algo = C.algo = {};
			    return C;
			}(Math));
			return CryptoJS;
		}));
	} (background_core$1));
	return background_core$1.exports;
}
(function (module, exports) {
(function (root, factory) {
		{
			module.exports = factory(background_requireCore$1());
		}
	}(background_commonjsGlobal, function (CryptoJS) {
		(function () {
		    var C = CryptoJS;
		    var C_lib = C.lib;
		    var WordArray = C_lib.WordArray;
		    var Hasher = C_lib.Hasher;
		    var C_algo = C.algo;
		    var W = [];
		    var SHA1 = C_algo.SHA1 = Hasher.extend({
		        _doReset: function () {
		            this._hash = new WordArray.init([
		                0x67452301, 0xefcdab89,
		                0x98badcfe, 0x10325476,
		                0xc3d2e1f0
		            ]);
		        },
		        _doProcessBlock: function (M, offset) {
		            var H = this._hash.words;
		            var a = H[0];
		            var b = H[1];
		            var c = H[2];
		            var d = H[3];
		            var e = H[4];
		            for (var i = 0; i < 80; i++) {
		                if (i < 16) {
		                    W[i] = M[offset + i] | 0;
		                } else {
		                    var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
		                    W[i] = (n << 1) | (n >>> 31);
		                }
		                var t = ((a << 5) | (a >>> 27)) + e + W[i];
		                if (i < 20) {
		                    t += ((b & c) | (~b & d)) + 0x5a827999;
		                } else if (i < 40) {
		                    t += (b ^ c ^ d) + 0x6ed9eba1;
		                } else if (i < 60) {
		                    t += ((b & c) | (b & d) | (c & d)) - 0x70e44324;
		                } else  {
		                    t += (b ^ c ^ d) - 0x359d3e2a;
		                }
		                e = d;
		                d = c;
		                c = (b << 30) | (b >>> 2);
		                b = a;
		                a = t;
		            }
		            H[0] = (H[0] + a) | 0;
		            H[1] = (H[1] + b) | 0;
		            H[2] = (H[2] + c) | 0;
		            H[3] = (H[3] + d) | 0;
		            H[4] = (H[4] + e) | 0;
		        },
		        _doFinalize: function () {
		            var data = this._data;
		            var dataWords = data.words;
		            var nBitsTotal = this._nDataBytes * 8;
		            var nBitsLeft = data.sigBytes * 8;
		            dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
		            dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
		            dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
		            data.sigBytes = dataWords.length * 4;
		            this._process();
		            return this._hash;
		        },
		        clone: function () {
		            var clone = Hasher.clone.call(this);
		            clone._hash = this._hash.clone();
		            return clone;
		        }
		    });
		    C.SHA1 = Hasher._createHelper(SHA1);
		    C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
		}());
		return CryptoJS.SHA1;
	}));
} (background_sha1));
var background_sha1Exports = background_sha1.exports;
var background_SHA1 = background_getDefaultExportFromCjs(background_sha1Exports);
const background_calculateChecksumSHA1 = (content) => {
    const res = background_SHA1(content);
    return res.toString();
};
const background_DIFF_PATH_TAG = 'Diff-Path';
const background_TypesOfChanges = {
    Add: 'a',
    Delete: 'd',
};
const background_DIFF_DIRECTIVE = 'diff';
const background_DIFF_DIRECTIVE_NAME = 'name';
const background_DIFF_DIRECTIVE_CHECKSUM = 'checksum';
const background_DIFF_DIRECTIVE_LINE = 'lines';
const background_parseDiffDirective = (s) => {
    if (!s.startsWith(background_DIFF_DIRECTIVE)) {
        return null;
    }
    const parts = s
        .split(' ')
        .slice(1);
    const nameExists = parts[0].startsWith(background_DIFF_DIRECTIVE_NAME);
    if (nameExists) {
        return {
            name: parts[0].slice(`${background_DIFF_DIRECTIVE_NAME}:`.length),
            checksum: parts[1].slice(`${background_DIFF_DIRECTIVE_CHECKSUM}:`.length),
            lines: Number(parts[2].slice(`${background_DIFF_DIRECTIVE_LINE}:`.length)),
        };
    }
    return {
        checksum: parts[0].slice(`${background_DIFF_DIRECTIVE_CHECKSUM}:`.length),
        lines: Number(parts[1].slice(`${background_DIFF_DIRECTIVE_LINE}:`.length)),
    };
};
const background_FILE_EXTENSION = '.patch';
const background_MS_IN_SECONDS = 1000;
const background_MS_IN_MINUTES = background_MS_IN_SECONDS * 60;
const background_MS_IN_HOURS = background_MS_IN_MINUTES * 60;
const background_Resolution = {
    Hours: 'h',
    Minutes: 'm',
    Seconds: 's',
};
const background_assertNever = (x) => {
    throw new Error(`Unexpected value in resolution: ${x}`);
};
const background_timestampWithResolutionToMs = (timestamp, resolution) => {
    switch (resolution) {
        case background_Resolution.Hours:
            return timestamp * background_MS_IN_HOURS;
        case background_Resolution.Minutes:
            return timestamp * background_MS_IN_MINUTES;
        case background_Resolution.Seconds:
            return timestamp * background_MS_IN_SECONDS;
        default:
            return background_assertNever(resolution);
    }
};
const background_parsePatchName = (patchName) => {
    const parts = patchName
        .slice(0, -background_FILE_EXTENSION.length)
        .split('-');
    if (parts.length === 4) {
        const [name, parsedResolution, parsedEpochTimestamp, parsedTime,] = parts;
        if (!(Object.values(background_Resolution)).includes(parsedResolution)) {
            throw new Error(`Unrecognized resolution in patch name: ${patchName}`);
        }
        return {
            name,
            resolution: parsedResolution,
            epochTimestamp: Number.parseInt(parsedEpochTimestamp, 10),
            time: Number.parseInt(parsedTime, 10),
        };
    }
    if (parts.length === 3) {
        const [name, parsedEpochTimestamp, parsedTime,] = parts;
        const resolution = background_Resolution.Hours;
        return {
            name,
            resolution,
            epochTimestamp: Number.parseInt(parsedEpochTimestamp, 10),
            time: Number.parseInt(parsedTime, 10),
        };
    }
    throw new Error(`Cannot parse the patch name: ${patchName}`);
};
const background_splitByLines = (s) => {
    return s.split(/(?<=\r?\n)/);
};
const background_createLogger = (verbose) => {
    return (message) => {
        if (verbose) {
            console.log(message);
        }
    };
};
function background_index_browser_isErrorWithMessage(error) {
    return (typeof error === 'object'
        && error !== null
        && 'message' in error
        && typeof error.message === 'string');
}
function background_index_browser_toErrorWithMessage(maybeError) {
    if (background_index_browser_isErrorWithMessage(maybeError)) {
        return maybeError;
    }
    try {
        return new Error(JSON.stringify(maybeError));
    }
    catch {
        return new Error(String(maybeError));
    }
}
function background_index_browser_getErrorMessage(error) {
    return background_index_browser_toErrorWithMessage(error).message;
}
const background_AMOUNT_OF_LINES_TO_PARSE = 50;
const background_parseTag = (tagName, rules) => {
    const maxLines = Math.min(background_AMOUNT_OF_LINES_TO_PARSE, rules.length);
    for (let i = 0; i < maxLines; i += 1) {
        const rule = rules[i];
        if (!rule) {
            continue;
        }
        const search = `! ${tagName}: `;
        const indexOfSearch = rule.indexOf(search);
        if (indexOfSearch >= 0) {
            return rule.substring(indexOfSearch + search.length).trim();
        }
    }
    return null;
};
const background_ERROR_NAME = 'UnacceptableResponseError';
class background_UnacceptableResponseError extends Error {
    constructor(message) {
        super(message);
        this.name = background_ERROR_NAME;
        Object.setPrototypeOf(this, background_UnacceptableResponseError.prototype);
    }
}
const background_AcceptableHttpStatusCodes = {
    NotFound: 404,
    NoContent: 204,
    Ok: 200,
};
const background_parseRcsOperation = (rcsOperation) => {
    const [operationInfo, operationCounter] = rcsOperation.split(' ');
    const typeOfOperation = operationInfo[0];
    const startIndex = Number(operationInfo.slice(1)) - 1;
    const numberOfLines = Number(operationCounter);
    if (typeOfOperation !== background_TypesOfChanges.Add && typeOfOperation !== background_TypesOfChanges.Delete) {
        throw new Error(`Operation is not valid: cannot parse type: ${rcsOperation}`);
    }
    if (Number.isNaN(startIndex)) {
        throw new Error(`Operation is not valid: cannot parse index: ${rcsOperation}`);
    }
    if (Number.isNaN(numberOfLines)) {
        throw new Error(`Operation is not valid: cannot parse number of lines: ${rcsOperation}`);
    }
    return {
        typeOfOperation,
        startIndex,
        numberOfLines,
    };
};
const background_applyRcsPatch = (filterContent, patch, checksum) => {
    const lines = filterContent.slice();
    let currentOffset = 0;
    for (let index = 0; index < patch.length; index += 1) {
        const patchLine = patch[index];
        if (patchLine === '') {
            continue;
        }
        const parsedRcsOperation = background_parseRcsOperation(patchLine);
        const { typeOfOperation, startIndex, numberOfLines, } = parsedRcsOperation;
        const startIndexWithOffset = startIndex + currentOffset;
        if (typeOfOperation === background_TypesOfChanges.Delete) {
            lines.splice(startIndexWithOffset, numberOfLines);
            currentOffset -= numberOfLines;
        }
        if (typeOfOperation === background_TypesOfChanges.Add) {
            const stringsToAdd = [];
            let nStringsToAdd = numberOfLines;
            let scanFrom = index + 1;
            while (nStringsToAdd > 0 && scanFrom < patch.length) {
                stringsToAdd.push(patch[scanFrom]);
                scanFrom += 1;
                nStringsToAdd -= 1;
            }
            index += stringsToAdd.length;
            if (startIndexWithOffset < 0) {
                lines.unshift(...stringsToAdd);
            }
            else if (startIndexWithOffset > lines.length) {
                lines.push(...stringsToAdd);
            }
            else {
                lines.splice(startIndexWithOffset + 1, 0, ...stringsToAdd);
            }
            currentOffset += numberOfLines;
        }
    }
    const updatedFilter = lines.join('');
    if (checksum) {
        const c = background_calculateChecksumSHA1(updatedFilter);
        if (c !== checksum) {
            throw new Error('Checksums are not equal.');
        }
    }
    return updatedFilter;
};
const background_checkPatchExpired = (diffPath) => {
    const { resolution, epochTimestamp, time, } = background_parsePatchName(diffPath);
    const createdMs = background_timestampWithResolutionToMs(epochTimestamp, resolution);
    const ttlMs = background_timestampWithResolutionToMs(time, resolution);
    return Date.now() > createdMs + ttlMs;
};
const background_downloadFile = async (baseURL, fileUrl, isFileHostedViaNetworkProtocol, isRecursiveUpdate, log) => {
    try {
        const response = await fetch(new URL(fileUrl, `${baseURL}/`));
        if (!isFileHostedViaNetworkProtocol && !(response.status >= 200 && response.status < 300)) {
            log(`Error during file request: ${response.status} ${response.statusText}`);
            return null;
        }
        if (isFileHostedViaNetworkProtocol) {
            const acceptableHttpStatusCodes = Object.values(background_AcceptableHttpStatusCodes);
            if (!acceptableHttpStatusCodes.includes(response.status)) {
                const err = `Unacceptable response for network request: ${response.status} ${response.statusText}`;
                log(err);
                throw new background_UnacceptableResponseError(err);
            }
        }
        if (response.status === background_AcceptableHttpStatusCodes.NotFound
            || response.status === background_AcceptableHttpStatusCodes.NoContent) {
            if (!isRecursiveUpdate) {
                log('Update is not available.');
            }
            return null;
        }
        const data = await response.text();
        if (response.status === background_AcceptableHttpStatusCodes.Ok && data === '') {
            if (!isRecursiveUpdate) {
                log('Update is not available.');
            }
            return null;
        }
        return background_splitByLines(data);
    }
    catch (e) {
        if (!isFileHostedViaNetworkProtocol) {
            log(`Error during file request to "${baseURL}"/"${fileUrl}": ${background_index_browser_getErrorMessage(e)}`);
            return null;
        }
        if (e instanceof background_UnacceptableResponseError) {
            throw e;
        }
        throw new Error(`Error during network request: ${background_index_browser_getErrorMessage(e)}`, { cause: e });
    }
};
const background_extractBaseUrl = (filterUrl) => {
    let splitDelimeter = '/';
    if (filterUrl.includes('\\')) {
        splitDelimeter = '\\';
    }
    return filterUrl
        .split(splitDelimeter)
        .slice(0, -1)
        .join(splitDelimeter);
};
const background_applyPatch = async (params) => {
    const applyPatchWrapper = async (innerParams) => {
        const { filterUrl, filterContent, verbose = false, isRecursiveUpdate, } = innerParams;
        const filterLines = background_splitByLines(filterContent);
        const diffPath = background_parseTag(background_DIFF_PATH_TAG, filterLines)?.split('#')[0];
        if (!diffPath) {
            return null;
        }
        if (!background_checkPatchExpired(diffPath)) {
            return { filterContent };
        }
        const log = background_createLogger(verbose);
        let patch = [];
        try {
            const baseUrl = background_extractBaseUrl(filterUrl);
            const res = await background_downloadFile(baseUrl, diffPath, baseUrl.startsWith('http://') || baseUrl.startsWith('https://'), isRecursiveUpdate, log);
            if (res === null) {
                return { filterContent };
            }
            patch = res;
        }
        catch (e) {
            if (e instanceof background_UnacceptableResponseError) {
                throw e;
            }
            throw new Error(`Error during downloading patch file from "${diffPath}": ${background_index_browser_getErrorMessage(e)}`, { cause: e });
        }
        let updatedFilter = '';
        try {
            const diffDirective = background_parseDiffDirective(patch[0]);
            updatedFilter = background_applyRcsPatch(filterLines,
            diffDirective ? patch.slice(1) : patch, diffDirective ? diffDirective.checksum : undefined);
        }
        catch (e) {
            throw new Error(`Error during applying the patch from "${diffPath}": ${background_index_browser_getErrorMessage(e)}`, { cause: e });
        }
        try {
            const nextPatchTask = applyPatchWrapper({
                filterUrl,
                filterContent: updatedFilter,
                isRecursiveUpdate: true,
                verbose,
            });
            return { filterContent: updatedFilter, nextPatchTask };
        }
        catch (e) {
            return { filterContent: updatedFilter };
        }
    };
    const paramsWithRecursiveFlag = { ...params, isRecursiveUpdate: false };
    let applyingPatchTask = applyPatchWrapper(paramsWithRecursiveFlag);
    let latestFilter = null;
    while (applyingPatchTask) {
        let freshFilter = null;
        freshFilter = await applyingPatchTask;
        if (!freshFilter) {
            return latestFilter;
        }
        latestFilter = freshFilter.filterContent;
        applyingPatchTask = freshFilter.nextPatchTask || null;
    }
    return latestFilter;
};
const background_DiffUpdater = {
    applyPatch: background_applyPatch,
};
var background_DiffUpdater_1 = background_DiffUpdater;
var background_UnacceptableResponseError_1 = background_UnacceptableResponseError;

var background_md5 = {exports: {}};

function background_commonjsRequire(path) {
	throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
}

var background_core = {exports: {}};

var background_hasRequiredCore;
function background_requireCore () {
	if (background_hasRequiredCore) return background_core.exports;
	background_hasRequiredCore = 1;
	(function (module, exports) {
(function (root, factory) {
			{
				module.exports = factory();
			}
		}(background_commonjsGlobal$1, function () {
			var CryptoJS = CryptoJS || (function (Math, undefined$1) {
			    var crypto;
			    if (typeof window !== 'undefined' && window.crypto) {
			        crypto = window.crypto;
			    }
			    if (typeof self !== 'undefined' && self.crypto) {
			        crypto = self.crypto;
			    }
			    if (typeof globalThis !== 'undefined' && globalThis.crypto) {
			        crypto = globalThis.crypto;
			    }
			    if (!crypto && typeof window !== 'undefined' && window.msCrypto) {
			        crypto = window.msCrypto;
			    }
			    if (!crypto && typeof background_commonjsGlobal$1 !== 'undefined' && background_commonjsGlobal$1.crypto) {
			        crypto = background_commonjsGlobal$1.crypto;
			    }
			    if (!crypto && typeof background_commonjsRequire === 'function') {
			        try {
			            crypto = __webpack_require__(23923);
			        } catch (err) {}
			    }
			    var cryptoSecureRandomInt = function () {
			        if (crypto) {
			            if (typeof crypto.getRandomValues === 'function') {
			                try {
			                    return crypto.getRandomValues(new Uint32Array(1))[0];
			                } catch (err) {}
			            }
			            if (typeof crypto.randomBytes === 'function') {
			                try {
			                    return crypto.randomBytes(4).readInt32LE();
			                } catch (err) {}
			            }
			        }
			        throw new Error('Native crypto module could not be used to get secure random number.');
			    };
			    var create = Object.create || (function () {
			        function F() {}
			        return function (obj) {
			            var subtype;
			            F.prototype = obj;
			            subtype = new F();
			            F.prototype = null;
			            return subtype;
			        };
			    }());
			    var C = {};
			    var C_lib = C.lib = {};
			    var Base = C_lib.Base = (function () {
			        return {
			            extend: function (overrides) {
			                var subtype = create(this);
			                if (overrides) {
			                    subtype.mixIn(overrides);
			                }
			                if (!subtype.hasOwnProperty('init') || this.init === subtype.init) {
			                    subtype.init = function () {
			                        subtype.$super.init.apply(this, arguments);
			                    };
			                }
			                subtype.init.prototype = subtype;
			                subtype.$super = this;
			                return subtype;
			            },
			            create: function () {
			                var instance = this.extend();
			                instance.init.apply(instance, arguments);
			                return instance;
			            },
			            init: function () {
			            },
			            mixIn: function (properties) {
			                for (var propertyName in properties) {
			                    if (properties.hasOwnProperty(propertyName)) {
			                        this[propertyName] = properties[propertyName];
			                    }
			                }
			                if (properties.hasOwnProperty('toString')) {
			                    this.toString = properties.toString;
			                }
			            },
			            clone: function () {
			                return this.init.prototype.extend(this);
			            }
			        };
			    }());
			    var WordArray = C_lib.WordArray = Base.extend({
			        init: function (words, sigBytes) {
			            words = this.words = words || [];
			            if (sigBytes != undefined$1) {
			                this.sigBytes = sigBytes;
			            } else {
			                this.sigBytes = words.length * 4;
			            }
			        },
			        toString: function (encoder) {
			            return (encoder || Hex).stringify(this);
			        },
			        concat: function (wordArray) {
			            var thisWords = this.words;
			            var thatWords = wordArray.words;
			            var thisSigBytes = this.sigBytes;
			            var thatSigBytes = wordArray.sigBytes;
			            this.clamp();
			            if (thisSigBytes % 4) {
			                for (var i = 0; i < thatSigBytes; i++) {
			                    var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
			                    thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
			                }
			            } else {
			                for (var j = 0; j < thatSigBytes; j += 4) {
			                    thisWords[(thisSigBytes + j) >>> 2] = thatWords[j >>> 2];
			                }
			            }
			            this.sigBytes += thatSigBytes;
			            return this;
			        },
			        clamp: function () {
			            var words = this.words;
			            var sigBytes = this.sigBytes;
			            words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
			            words.length = Math.ceil(sigBytes / 4);
			        },
			        clone: function () {
			            var clone = Base.clone.call(this);
			            clone.words = this.words.slice(0);
			            return clone;
			        },
			        random: function (nBytes) {
			            var words = [];
			            for (var i = 0; i < nBytes; i += 4) {
			                words.push(cryptoSecureRandomInt());
			            }
			            return new WordArray.init(words, nBytes);
			        }
			    });
			    var C_enc = C.enc = {};
			    var Hex = C_enc.Hex = {
			        stringify: function (wordArray) {
			            var words = wordArray.words;
			            var sigBytes = wordArray.sigBytes;
			            var hexChars = [];
			            for (var i = 0; i < sigBytes; i++) {
			                var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
			                hexChars.push((bite >>> 4).toString(16));
			                hexChars.push((bite & 0x0f).toString(16));
			            }
			            return hexChars.join('');
			        },
			        parse: function (hexStr) {
			            var hexStrLength = hexStr.length;
			            var words = [];
			            for (var i = 0; i < hexStrLength; i += 2) {
			                words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
			            }
			            return new WordArray.init(words, hexStrLength / 2);
			        }
			    };
			    var Latin1 = C_enc.Latin1 = {
			        stringify: function (wordArray) {
			            var words = wordArray.words;
			            var sigBytes = wordArray.sigBytes;
			            var latin1Chars = [];
			            for (var i = 0; i < sigBytes; i++) {
			                var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
			                latin1Chars.push(String.fromCharCode(bite));
			            }
			            return latin1Chars.join('');
			        },
			        parse: function (latin1Str) {
			            var latin1StrLength = latin1Str.length;
			            var words = [];
			            for (var i = 0; i < latin1StrLength; i++) {
			                words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
			            }
			            return new WordArray.init(words, latin1StrLength);
			        }
			    };
			    var Utf8 = C_enc.Utf8 = {
			        stringify: function (wordArray) {
			            try {
			                return decodeURIComponent(escape(Latin1.stringify(wordArray)));
			            } catch (e) {
			                throw new Error('Malformed UTF-8 data');
			            }
			        },
			        parse: function (utf8Str) {
			            return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
			        }
			    };
			    var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
			        reset: function () {
			            this._data = new WordArray.init();
			            this._nDataBytes = 0;
			        },
			        _append: function (data) {
			            if (typeof data == 'string') {
			                data = Utf8.parse(data);
			            }
			            this._data.concat(data);
			            this._nDataBytes += data.sigBytes;
			        },
			        _process: function (doFlush) {
			            var processedWords;
			            var data = this._data;
			            var dataWords = data.words;
			            var dataSigBytes = data.sigBytes;
			            var blockSize = this.blockSize;
			            var blockSizeBytes = blockSize * 4;
			            var nBlocksReady = dataSigBytes / blockSizeBytes;
			            if (doFlush) {
			                nBlocksReady = Math.ceil(nBlocksReady);
			            } else {
			                nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
			            }
			            var nWordsReady = nBlocksReady * blockSize;
			            var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
			            if (nWordsReady) {
			                for (var offset = 0; offset < nWordsReady; offset += blockSize) {
			                    this._doProcessBlock(dataWords, offset);
			                }
			                processedWords = dataWords.splice(0, nWordsReady);
			                data.sigBytes -= nBytesReady;
			            }
			            return new WordArray.init(processedWords, nBytesReady);
			        },
			        clone: function () {
			            var clone = Base.clone.call(this);
			            clone._data = this._data.clone();
			            return clone;
			        },
			        _minBufferSize: 0
			    });
			    C_lib.Hasher = BufferedBlockAlgorithm.extend({
			        cfg: Base.extend(),
			        init: function (cfg) {
			            this.cfg = this.cfg.extend(cfg);
			            this.reset();
			        },
			        reset: function () {
			            BufferedBlockAlgorithm.reset.call(this);
			            this._doReset();
			        },
			        update: function (messageUpdate) {
			            this._append(messageUpdate);
			            this._process();
			            return this;
			        },
			        finalize: function (messageUpdate) {
			            if (messageUpdate) {
			                this._append(messageUpdate);
			            }
			            var hash = this._doFinalize();
			            return hash;
			        },
			        blockSize: 512/32,
			        _createHelper: function (hasher) {
			            return function (message, cfg) {
			                return new hasher.init(cfg).finalize(message);
			            };
			        },
			        _createHmacHelper: function (hasher) {
			            return function (message, key) {
			                return new C_algo.HMAC.init(hasher, key).finalize(message);
			            };
			        }
			    });
			    var C_algo = C.algo = {};
			    return C;
			}(Math));
			return CryptoJS;
		}));
	} (background_core));
	return background_core.exports;
}

(function (module, exports) {
(function (root, factory) {
		{
			module.exports = factory(background_requireCore());
		}
	}(background_commonjsGlobal$1, function (CryptoJS) {
		(function (Math) {
		    var C = CryptoJS;
		    var C_lib = C.lib;
		    var WordArray = C_lib.WordArray;
		    var Hasher = C_lib.Hasher;
		    var C_algo = C.algo;
		    var T = [];
		    (function () {
		        for (var i = 0; i < 64; i++) {
		            T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
		        }
		    }());
		    var MD5 = C_algo.MD5 = Hasher.extend({
		        _doReset: function () {
		            this._hash = new WordArray.init([
		                0x67452301, 0xefcdab89,
		                0x98badcfe, 0x10325476
		            ]);
		        },
		        _doProcessBlock: function (M, offset) {
		            for (var i = 0; i < 16; i++) {
		                var offset_i = offset + i;
		                var M_offset_i = M[offset_i];
		                M[offset_i] = (
		                    (((M_offset_i << 8)  | (M_offset_i >>> 24)) & 0x00ff00ff) |
		                    (((M_offset_i << 24) | (M_offset_i >>> 8))  & 0xff00ff00)
		                );
		            }
		            var H = this._hash.words;
		            var M_offset_0  = M[offset + 0];
		            var M_offset_1  = M[offset + 1];
		            var M_offset_2  = M[offset + 2];
		            var M_offset_3  = M[offset + 3];
		            var M_offset_4  = M[offset + 4];
		            var M_offset_5  = M[offset + 5];
		            var M_offset_6  = M[offset + 6];
		            var M_offset_7  = M[offset + 7];
		            var M_offset_8  = M[offset + 8];
		            var M_offset_9  = M[offset + 9];
		            var M_offset_10 = M[offset + 10];
		            var M_offset_11 = M[offset + 11];
		            var M_offset_12 = M[offset + 12];
		            var M_offset_13 = M[offset + 13];
		            var M_offset_14 = M[offset + 14];
		            var M_offset_15 = M[offset + 15];
		            var a = H[0];
		            var b = H[1];
		            var c = H[2];
		            var d = H[3];
		            a = FF(a, b, c, d, M_offset_0,  7,  T[0]);
		            d = FF(d, a, b, c, M_offset_1,  12, T[1]);
		            c = FF(c, d, a, b, M_offset_2,  17, T[2]);
		            b = FF(b, c, d, a, M_offset_3,  22, T[3]);
		            a = FF(a, b, c, d, M_offset_4,  7,  T[4]);
		            d = FF(d, a, b, c, M_offset_5,  12, T[5]);
		            c = FF(c, d, a, b, M_offset_6,  17, T[6]);
		            b = FF(b, c, d, a, M_offset_7,  22, T[7]);
		            a = FF(a, b, c, d, M_offset_8,  7,  T[8]);
		            d = FF(d, a, b, c, M_offset_9,  12, T[9]);
		            c = FF(c, d, a, b, M_offset_10, 17, T[10]);
		            b = FF(b, c, d, a, M_offset_11, 22, T[11]);
		            a = FF(a, b, c, d, M_offset_12, 7,  T[12]);
		            d = FF(d, a, b, c, M_offset_13, 12, T[13]);
		            c = FF(c, d, a, b, M_offset_14, 17, T[14]);
		            b = FF(b, c, d, a, M_offset_15, 22, T[15]);
		            a = GG(a, b, c, d, M_offset_1,  5,  T[16]);
		            d = GG(d, a, b, c, M_offset_6,  9,  T[17]);
		            c = GG(c, d, a, b, M_offset_11, 14, T[18]);
		            b = GG(b, c, d, a, M_offset_0,  20, T[19]);
		            a = GG(a, b, c, d, M_offset_5,  5,  T[20]);
		            d = GG(d, a, b, c, M_offset_10, 9,  T[21]);
		            c = GG(c, d, a, b, M_offset_15, 14, T[22]);
		            b = GG(b, c, d, a, M_offset_4,  20, T[23]);
		            a = GG(a, b, c, d, M_offset_9,  5,  T[24]);
		            d = GG(d, a, b, c, M_offset_14, 9,  T[25]);
		            c = GG(c, d, a, b, M_offset_3,  14, T[26]);
		            b = GG(b, c, d, a, M_offset_8,  20, T[27]);
		            a = GG(a, b, c, d, M_offset_13, 5,  T[28]);
		            d = GG(d, a, b, c, M_offset_2,  9,  T[29]);
		            c = GG(c, d, a, b, M_offset_7,  14, T[30]);
		            b = GG(b, c, d, a, M_offset_12, 20, T[31]);
		            a = HH(a, b, c, d, M_offset_5,  4,  T[32]);
		            d = HH(d, a, b, c, M_offset_8,  11, T[33]);
		            c = HH(c, d, a, b, M_offset_11, 16, T[34]);
		            b = HH(b, c, d, a, M_offset_14, 23, T[35]);
		            a = HH(a, b, c, d, M_offset_1,  4,  T[36]);
		            d = HH(d, a, b, c, M_offset_4,  11, T[37]);
		            c = HH(c, d, a, b, M_offset_7,  16, T[38]);
		            b = HH(b, c, d, a, M_offset_10, 23, T[39]);
		            a = HH(a, b, c, d, M_offset_13, 4,  T[40]);
		            d = HH(d, a, b, c, M_offset_0,  11, T[41]);
		            c = HH(c, d, a, b, M_offset_3,  16, T[42]);
		            b = HH(b, c, d, a, M_offset_6,  23, T[43]);
		            a = HH(a, b, c, d, M_offset_9,  4,  T[44]);
		            d = HH(d, a, b, c, M_offset_12, 11, T[45]);
		            c = HH(c, d, a, b, M_offset_15, 16, T[46]);
		            b = HH(b, c, d, a, M_offset_2,  23, T[47]);
		            a = II(a, b, c, d, M_offset_0,  6,  T[48]);
		            d = II(d, a, b, c, M_offset_7,  10, T[49]);
		            c = II(c, d, a, b, M_offset_14, 15, T[50]);
		            b = II(b, c, d, a, M_offset_5,  21, T[51]);
		            a = II(a, b, c, d, M_offset_12, 6,  T[52]);
		            d = II(d, a, b, c, M_offset_3,  10, T[53]);
		            c = II(c, d, a, b, M_offset_10, 15, T[54]);
		            b = II(b, c, d, a, M_offset_1,  21, T[55]);
		            a = II(a, b, c, d, M_offset_8,  6,  T[56]);
		            d = II(d, a, b, c, M_offset_15, 10, T[57]);
		            c = II(c, d, a, b, M_offset_6,  15, T[58]);
		            b = II(b, c, d, a, M_offset_13, 21, T[59]);
		            a = II(a, b, c, d, M_offset_4,  6,  T[60]);
		            d = II(d, a, b, c, M_offset_11, 10, T[61]);
		            c = II(c, d, a, b, M_offset_2,  15, T[62]);
		            b = II(b, c, d, a, M_offset_9,  21, T[63]);
		            H[0] = (H[0] + a) | 0;
		            H[1] = (H[1] + b) | 0;
		            H[2] = (H[2] + c) | 0;
		            H[3] = (H[3] + d) | 0;
		        },
		        _doFinalize: function () {
		            var data = this._data;
		            var dataWords = data.words;
		            var nBitsTotal = this._nDataBytes * 8;
		            var nBitsLeft = data.sigBytes * 8;
		            dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
		            var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
		            var nBitsTotalL = nBitsTotal;
		            dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (
		                (((nBitsTotalH << 8)  | (nBitsTotalH >>> 24)) & 0x00ff00ff) |
		                (((nBitsTotalH << 24) | (nBitsTotalH >>> 8))  & 0xff00ff00)
		            );
		            dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
		                (((nBitsTotalL << 8)  | (nBitsTotalL >>> 24)) & 0x00ff00ff) |
		                (((nBitsTotalL << 24) | (nBitsTotalL >>> 8))  & 0xff00ff00)
		            );
		            data.sigBytes = (dataWords.length + 1) * 4;
		            this._process();
		            var hash = this._hash;
		            var H = hash.words;
		            for (var i = 0; i < 4; i++) {
		                var H_i = H[i];
		                H[i] = (((H_i << 8)  | (H_i >>> 24)) & 0x00ff00ff) |
		                       (((H_i << 24) | (H_i >>> 8))  & 0xff00ff00);
		            }
		            return hash;
		        },
		        clone: function () {
		            var clone = Hasher.clone.call(this);
		            clone._hash = this._hash.clone();
		            return clone;
		        }
		    });
		    function FF(a, b, c, d, x, s, t) {
		        var n = a + ((b & c) | (~b & d)) + x + t;
		        return ((n << s) | (n >>> (32 - s))) + b;
		    }
		    function GG(a, b, c, d, x, s, t) {
		        var n = a + ((b & d) | (c & ~d)) + x + t;
		        return ((n << s) | (n >>> (32 - s))) + b;
		    }
		    function HH(a, b, c, d, x, s, t) {
		        var n = a + (b ^ c ^ d) + x + t;
		        return ((n << s) | (n >>> (32 - s))) + b;
		    }
		    function II(a, b, c, d, x, s, t) {
		        var n = a + (c ^ (b | ~d)) + x + t;
		        return ((n << s) | (n >>> (32 - s))) + b;
		    }
		    C.MD5 = Hasher._createHelper(MD5);
		    C.HmacMD5 = Hasher._createHmacHelper(MD5);
		}(Math));
		return CryptoJS.MD5;
	}));
} (background_md5));
var background_md5Exports = background_md5.exports;
var background_MD5 = background_getDefaultExportFromCjs$1(background_md5Exports);

var background_encBase64 = {exports: {}};

(function (module, exports) {
(function (root, factory) {
		{
			module.exports = factory(background_requireCore());
		}
	}(background_commonjsGlobal$1, function (CryptoJS) {
		(function () {
		    var C = CryptoJS;
		    var C_lib = C.lib;
		    var WordArray = C_lib.WordArray;
		    var C_enc = C.enc;
		    C_enc.Base64 = {
		        stringify: function (wordArray) {
		            var words = wordArray.words;
		            var sigBytes = wordArray.sigBytes;
		            var map = this._map;
		            wordArray.clamp();
		            var base64Chars = [];
		            for (var i = 0; i < sigBytes; i += 3) {
		                var byte1 = (words[i >>> 2]       >>> (24 - (i % 4) * 8))       & 0xff;
		                var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
		                var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
		                var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
		                for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
		                    base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
		                }
		            }
		            var paddingChar = map.charAt(64);
		            if (paddingChar) {
		                while (base64Chars.length % 4) {
		                    base64Chars.push(paddingChar);
		                }
		            }
		            return base64Chars.join('');
		        },
		        parse: function (base64Str) {
		            var base64StrLength = base64Str.length;
		            var map = this._map;
		            var reverseMap = this._reverseMap;
		            if (!reverseMap) {
		                    reverseMap = this._reverseMap = [];
		                    for (var j = 0; j < map.length; j++) {
		                        reverseMap[map.charCodeAt(j)] = j;
		                    }
		            }
		            var paddingChar = map.charAt(64);
		            if (paddingChar) {
		                var paddingIndex = base64Str.indexOf(paddingChar);
		                if (paddingIndex !== -1) {
		                    base64StrLength = paddingIndex;
		                }
		            }
		            return parseLoop(base64Str, base64StrLength, reverseMap);
		        },
		        _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
		    };
		    function parseLoop(base64Str, base64StrLength, reverseMap) {
		      var words = [];
		      var nBytes = 0;
		      for (var i = 0; i < base64StrLength; i++) {
		          if (i % 4) {
		              var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2);
		              var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2);
		              var bitsCombined = bits1 | bits2;
		              words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8);
		              nBytes++;
		          }
		      }
		      return WordArray.create(words, nBytes);
		    }
		}());
		return CryptoJS.enc.Base64;
	}));
} (background_encBase64));
var background_encBase64Exports = background_encBase64.exports;
var background_Base64 = background_getDefaultExportFromCjs$1(background_encBase64Exports);

const background_CHECKSUM_PATTERN = /^\s*!\s*checksum[\s-:]+([\w+/=]+).*[\r\n]+/i;
/**
 * The maximum number of characters to search for the checksum pattern.
 */
const background_CHECKSUM_SEARCH_LIMIT = 200;
/**
 * Removes the checksum line from the given content string.
 * @param content The content to remove the checksum from.
 * @returns The content with the checksum line removed.
 */
const background_removeChecksumLine = (content) => {
    const partOfResponse = content.substring(0, background_CHECKSUM_SEARCH_LIMIT);
    const match = partOfResponse.match(background_CHECKSUM_PATTERN);
    if (match) {
        content = content.replace(match[0], '');
    }
    return content;
};
/**
 * Normalizes a message string by removing carriage return characters ('\r') and
 * replacing multiple newline characters ('\n') with a single newline character.
 * This function standardizes the format of newline characters in the message.
 *
 * @param content The string to normalize.
 *
 * @returns The normalized message with '\r' removed and consecutive '\n'
 * characters replaced with a single '\n'.
 */
const background_normalizeContent = (content) => {
    content = background_removeChecksumLine(content);
    content = content.replace(/\r/g, '');
    content = content.replace(/\n+/g, '\n');
    return content;
};
/**
 * Calculates the checksum of the given content using the MD5 hashing algorithm
 * and encodes it in Base64. It normalizes the content by removing carriage
 * returns and replacing multiple newlines with a single newline.
 * The checksum is then formatted with a trailing special comment identifier.
 * Trailing '=' characters in the Base64 encoded string are removed to match
 * the expected format.
 *
 * @see
 * {@link https://adblockplus.org/en/filters#special-comments Adblock Plus special comments}
 * {@link https://hg.adblockplus.org/adblockplus/file/tip/addChecksum.py Adblock Plus checksum script}
 *
 * @param content The content to hash.
 *
 * @returns The formatted checksum string.
 */
const background_calculateChecksumMD5 = (content) => {
    content = background_normalizeContent(content);
    const checksum = background_Base64.stringify(background_MD5(content));
    return checksum.trim().replace(/=+$/g, '');
};
/**
 * Parses the checksum from the given content string.
 *
 * @param str The content string to parse.
 * @returns The checksum value or null if not found.
 */
const background_parseChecksum = (str) => {
    const partOfResponse = str.substring(0, background_CHECKSUM_SEARCH_LIMIT);
    const checksumMatch = partOfResponse.match(background_CHECKSUM_PATTERN);
    if (!checksumMatch) {
        return null;
    }
    return checksumMatch[1] ?? null;
};
/**
 * Checks if the given filter has a valid checksum. If the filter does not have
 * a checksum, it returns false unless the strict parameter is true.
 *
 * @param filter The filter to check.
 * @param strict If true, the function returns true if the filter does not have a
 * checksum.
 * @returns True if the filter has a valid checksum, false otherwise.
 */
const background_isValidChecksum = (filter, strict = false) => {
    const expectedChecksum = background_parseChecksum(filter);
    if (!expectedChecksum) {
        return !strict;
    }
    const actualChecksum = background_calculateChecksumMD5(filter);
    return actualChecksum === expectedChecksum;
};

/**
 * The number of lines to include before the error line in the error message.
 */
const background_LINES_BEFORE_DIRECTIVE = 3;
/**
 * Merge an error messages by joining the array strings with a newline character.
 *
 * @param {string[]} messages - The array of message strings to format.
 * @returns {string} The formatted error message.
 */
const background_mergeErrorDetails = (messages) => `${messages.join('\n')}\n`;
/**
 * Creates and throws a detailed error message with context information.
 *
 * @param errorDescription The main error message.
 * @param errorRule The rule where the error occurred.
 * @param contextLines The context string (3 lines before) to include in the error message.
 * @param filterUrl The URL of the filter file.
 * @param originalError The original error to include in the error message.
 * @throws {Error} Throws an error with a detailed error message.
 */
const background_throwError = (errorDescription, errorRule, contextLines, filterUrl, originalError) => {
    const errorDetails = [`${errorDescription} '${errorRule}'`];
    if (filterUrl) {
        errorDetails.push(`URL: '${filterUrl}'`);
    }
    if (contextLines) {
        errorDetails.push('Context:');
        errorDetails.push(contextLines);
        errorDetails.push(`\t${errorRule}`);
    }
    if (originalError) {
        const originalErrorMessage = originalError instanceof Error ? originalError.message : String(originalError);
        errorDetails.push(`\t${originalErrorMessage}`);
    }
    const formattedErrorMessage = background_mergeErrorDetails(errorDetails);
    throw new Error(formattedErrorMessage);
};
/**
 * Get (3) lines before the error rule for error messages.
 * @param rulesList List of rules to get context from.
 * @param errorRuleIndex Index of the error line.
 * @returns Lines before the error rule.
 */
const background_getContext = (rulesList, errorRuleIndex) => {
    return rulesList
        .slice(Math.max(0, errorRuleIndex - background_LINES_BEFORE_DIRECTIVE), errorRuleIndex)
        .map((line) => `\t${line}`)
        .join('\n');
};

/**
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with AdGuard Browser Extension.  If not, see <http://www.gnu.org/licenses/>.
 */
const background_FiltersDownloaderCreator = (FileDownloadWrapper) => {
    const CONDITION_IF_DIRECTIVE_START = '!#if';
    const CONDITION_ELSE_DIRECTIVE_START = '!#else';
    const CONDITION_DIRECTIVE_END = '!#endif';
    const CONDITION_OPERATOR_NOT = '!';
    const CONDITION_OPERATOR_AND = '&&';
    const CONDITION_OPERATOR_OR = '||';
    const CONDITION_BRACKET_OPEN_CHAR = '(';
    const CONDITION_BRACKET_CLOSE_CHAR = ')';
    const INCLUDE_DIRECTIVE = '!#include';
    const REGEXP_ABSOLUTE_URL = /^([a-z]+:\/\/|\/\/)/i;
    const REGEXP_EXTERNAL_ABSOLUTE_URL = /^((?!file)[a-z]+:\/\/|\/\/)/i;
    /**
     * Checks if the opening and closing brackets in a string are balanced.
     *
     * @param str The input string to check for bracket balance.
     * @returns Returns `true` if the brackets are balanced, `false` otherwise.
     */
    const checkBracketsBalance = (str) => {
        let depth = 0;
        for (let i = 0; i < str.length; i += 1) {
            if (str[i] === CONDITION_BRACKET_OPEN_CHAR) {
                // if the char is an opening parenthesis, then we increase the depth
                depth += 1;
            }
            else if (str[i] === CONDITION_BRACKET_CLOSE_CHAR) {
                // if the char is a closing parenthesis, then we decrease the depth
                depth -= 1;
            }
            //  if the depth is negative we have a closing parenthesis
            //  before any matching opening parenthesis
            if (depth < 0) {
                return false;
            }
        }
        // If the depth is not null then a closing parenthesis is missing
        if (depth > 0) {
            return false;
        }
        return true;
    };
    /**
     * Parses url and returns its origin.
     *
     * @param url URL to parse.
     *
     * @returns URL origin if url can be parsed.
     * @throws If url cannot be parsed.
     */
    const getUrlOrigin = (url) => {
        try {
            const { origin } = new URL(url);
            return origin;
        }
        catch (e) {
            throw new Error(`Invalid url: '${url}'`);
        }
    };
    /**
     * Get the `filterOrigin` from url for relative path resolve.
     *
     * @param url Filter file URL.
     * @returns Valid origin url.
     */
    const getFilterUrlOrigin = (url) => {
        return url.substring(0, url.lastIndexOf('/'));
    };
    /**
     * Finds end of condition block started with startIndex.
     *
     * @param rules Array of all rules.
     * @param endDirective End directive for the condition block — `!#else` or `!#endif`.
     * @param startIndex Index of the start for presumed condition block.
     * @param endIndex Index of the end for presumed condition block,
     * needed for `!#else` directive if index of `!#endif` was found before to limit the search.
     *
     * @returns Index of the end of the condition block for the `endDirective`.
     */
    const findConditionBlockEnd = (rules, endDirective, startIndex, endIndex) => {
        const stack = [];
        for (let i = startIndex; i < endIndex; i += 1) {
            const rule = rules[i];
            if (rule.startsWith(CONDITION_IF_DIRECTIVE_START)) {
                stack.push(CONDITION_IF_DIRECTIVE_START);
            }
            else if (rule.startsWith(endDirective)) {
                if (stack.length > 0) {
                    stack.pop();
                }
                else {
                    return i;
                }
            }
        }
        return -1;
    };
    /**
     * Resolves a conditional expression to a boolean value based
     * on defined properties.
     *
     * @param expression The conditional expression to resolve.
     * @param definedExpressions An object containing defined properties for evaluation.
     *
     * @throws Throws an error if the expression is empty.
     *
     * @returns Returns `true` if the expression evaluates to `true` or a defined
     * property exists; otherwise, returns `false`.
     */
    const resolveConditionConstant = (expression, definedExpressions) => {
        if (!expression) {
            throw new Error('Invalid directives: Empty condition');
        }
        const trimmedExpression = expression.trim();
        if (trimmedExpression === 'true') {
            return true;
        }
        const expressionAsKey = trimmedExpression;
        if (definedExpressions?.[expressionAsKey] === true) {
            return true;
        }
        return false;
    };
    /**
     * Resolves a conditional expression and returns whether the expression
     * evaluates to `true` or `false` based on defined properties.
     *
     * @param rawExpression The raw conditional expression to resolve.
     * @param definedProperties An object containing defined expressions for
     * condition resolution.
     *
     * @returns Boolean `true` if the expression evaluates to `true`,
     * `false` otherwise.
     *
     * @throws Error If the expression is empty or contains incorrect brackets.
     */
    const resolveExpression = (rawExpression, definedProperties) => {
        if (!rawExpression) {
            throw new Error('Invalid directives: Empty condition');
        }
        const expression = rawExpression.trim();
        if (!checkBracketsBalance(expression)) {
            throw new Error(`Invalid directives: Incorrect brackets: ${expression}`);
        }
        // Replace bracketed expressions
        const openBracketIndex = expression.lastIndexOf(CONDITION_BRACKET_OPEN_CHAR);
        if (openBracketIndex !== -1) {
            const endBracketIndex = expression.indexOf(CONDITION_BRACKET_CLOSE_CHAR, openBracketIndex);
            const innerExpression = expression.substring(openBracketIndex + 1, endBracketIndex);
            const innerResult = resolveExpression(innerExpression, definedProperties);
            const resolvedInner = expression.substring(0, openBracketIndex)
                + innerResult + expression.substring(endBracketIndex + 1);
            return resolveExpression(resolvedInner, definedProperties);
        }
        let result;
        // Resolve logical operators
        const indexOfAndOperator = expression.indexOf(CONDITION_OPERATOR_AND);
        const indexOfOrOperator = expression.indexOf(CONDITION_OPERATOR_OR);
        const indexOfNotOperator = expression.indexOf(CONDITION_OPERATOR_NOT);
        if (indexOfOrOperator !== -1) {
            result = resolveExpression(expression.substring(0, indexOfOrOperator - 1), definedProperties) || resolveExpression(expression.substring(indexOfOrOperator + CONDITION_OPERATOR_OR.length, expression.length), definedProperties);
        }
        else if (indexOfAndOperator !== -1) {
            result = resolveExpression(expression.substring(0, indexOfAndOperator - 1), definedProperties) && resolveExpression(expression.substring(indexOfAndOperator + CONDITION_OPERATOR_AND.length, expression.length), definedProperties);
        }
        else if (indexOfNotOperator === 0) {
            result = !resolveExpression(expression.substring(CONDITION_OPERATOR_NOT.length), definedProperties);
        }
        else {
            result = resolveConditionConstant(expression, definedProperties);
        }
        return result;
    };
    /**
     * Resolves a conditional directive and returns whether the condition is true based on defined properties.
     *
     * @param directive The conditional directive to resolve.
     * @param definedProperties An object containing defined expressions for condition resolution.
     * @returns `true` if the condition is true, `false` otherwise.
     */
    const resolveCondition = (directive, definedProperties) => {
        const expression = directive.substring(CONDITION_IF_DIRECTIVE_START.length).trim();
        return resolveExpression(expression, definedProperties);
    };
    /**
     * Resolves conditional directives in a list of filtering rules based on
     * defined properties.
     *
     * @param rules The list of filtering rules to resolve.
     * @param definedExpressions An object containing defined expressions for
     * condition resolution.
     * @param urlOrigin The origin of the URL from which the filter was downloaded.
     *
     * @returns The resolved filtering rules after processing conditional directives.
     *
     * @throws Throws an error if invalid conditional directives are encountered.
     */
    const resolveConditions = (rules, definedExpressions, urlOrigin) => {
        if (!definedExpressions) {
            return rules;
        }
        let result = [];
        for (let i = 0; i < rules.length; i += 1) {
            const rule = rules[i];
            if (rule.indexOf(CONDITION_IF_DIRECTIVE_START) === 0) {
                const endLineIndex = findConditionBlockEnd(rules, CONDITION_DIRECTIVE_END, i + 1, rules.length);
                if (endLineIndex === -1) {
                    background_throwError('Invalid directives: Condition end not found', rule, background_getContext(rules, i), urlOrigin);
                }
                const elseLineIndex = findConditionBlockEnd(rules, CONDITION_ELSE_DIRECTIVE_START, i + 1, endLineIndex);
                const isConditionMatched = resolveCondition(rule, definedExpressions);
                // if there is no 'else' branch for the condition
                if (elseLineIndex === -1) {
                    if (isConditionMatched) {
                        const rulesUnderCondition = rules.slice(i + 1, endLineIndex);
                        // Resolve inner conditions in recursion
                        result = result
                            .concat(resolveConditions(rulesUnderCondition, definedExpressions, urlOrigin));
                    }
                }
                else {
                    // check if there is something after !#else
                    if (rules[elseLineIndex].trim().length !== CONDITION_ELSE_DIRECTIVE_START.length) {
                        background_throwError('Found invalid directive !#else', rule, background_getContext(rules, i), urlOrigin);
                    }
                    if (isConditionMatched) {
                        const rulesForConditionTrue = rules.slice(i + 1, elseLineIndex);
                        // Resolve inner conditions in recursion
                        result = result
                            .concat(resolveConditions(rulesForConditionTrue, definedExpressions, urlOrigin));
                    }
                    else {
                        const rulesForConditionFalse = rules.slice(elseLineIndex + 1, endLineIndex);
                        // Resolve inner conditions in recursion
                        result = result.concat(resolveConditions(rulesForConditionFalse, definedExpressions, urlOrigin));
                    }
                }
                // Skip to the end of block
                i = endLineIndex;
            }
            else if (rule.indexOf(CONDITION_ELSE_DIRECTIVE_START) === 0) {
                // Found !#else without !#if
                background_throwError('Found unexpected condition else branch:', rule, background_getContext(rules, i), urlOrigin);
            }
            else if (rule.indexOf(CONDITION_DIRECTIVE_END) === 0) {
                // Found !#endif without !#if
                background_throwError('Found unexpected condition end:', rule, background_getContext(rules, i), urlOrigin);
            }
            else {
                result.push(rule);
            }
        }
        return result;
    };
    /**
     * Validates a URL to ensure it matches the expected origin.
     *
     * @param url The URL to validate.
     * @param filterUrlOrigin The expected origin URL. If provided, the function
     * checks if the URL matches this origin.
     * @throws Throws an error if the URL is absolute and its origin doesn't
     * match the expected origin.
     */
    const validateUrl = (url, filterUrlOrigin) => {
        if (filterUrlOrigin) {
            if (REGEXP_ABSOLUTE_URL.test(url)) {
                // Include url is absolute
                const urlOrigin = getUrlOrigin(url);
                const filterOrigin = getUrlOrigin(filterUrlOrigin);
                if (urlOrigin !== filterOrigin) {
                    throw new Error(`Include url is rejected with origin: ${urlOrigin}`);
                }
            }
        }
    };
    /**
     * Validates and resolves include directive.
     *
     * @param line Line with directive.
     * @param filterOrigin Filter file URL origin or undefined.
     * @param definedExpressions An object with the defined properties.
     * @param context Previous lines for better error messages.
     * These properties might be used in pre-processor directives (`#if`, etc.).
     *
     * @returns A promise that returns string with rules if resolved and Error if rejected.
     * @throws Error if failed to resolve the include directive.
     */
    const resolveInclude = async (line, filterOrigin, definedExpressions, context) => {
        if (line.indexOf(INCLUDE_DIRECTIVE) !== 0) {
            return Promise.resolve(line);
        }
        const url = line.substring(INCLUDE_DIRECTIVE.length).trim();
        validateUrl(url, filterOrigin);
        let filter = [];
        try {
            // eslint-disable-next-line @typescript-eslint/no-use-before-define
            const downloadResult = await downloadFilterRules(url, {
                filterOrigin,
                definedExpressions,
                resolveDirectives: true,
            });
            filter = downloadResult.filter;
        }
        catch (error) {
            background_throwError('Failed to resolve the include directive', line, context, filterOrigin, error);
        }
        const MAX_LINES_TO_SCAN = 50;
        // Math.min inside for loop, because filter.length changes
        for (let i = 0; i < Math.min(MAX_LINES_TO_SCAN, filter.length); i += 1) {
            if (filter[i].trim().startsWith('! Diff-Path:')) {
                filter.splice(i, 1);
            }
        }
        return filter;
    };
    /**
     * Resolves include directives.
     *
     * @param rules Array of rules.
     * @param filterOrigin Filter file URL origin or null.
     * @param definedExpressions An object with the defined expressions for conditions resolution.
     * These properties might be used in pre-processor directives (`#if`, etc.).
     * @returns A promise that returns {string} with rules when if resolved and {Error} if rejected.
     */
    const resolveIncludes = async (rules, filterOrigin, definedExpressions) => {
        const promises = rules.map((rule, index) => {
            return resolveInclude(rule, filterOrigin, definedExpressions, background_getContext(rules, index));
        });
        let result = [];
        // We do not use here Promise.all because it freezes the Chromium browsers and electron built on it, if there
        // are more than 1_100_00 promises. Also, we consider that we can afford promises to be resolved sequentially.
        for (let i = 0; i < promises.length; i += 1) {
            // eslint-disable-next-line no-await-in-loop
            const resolved = await promises[i];
            if (Array.isArray(resolved)) {
                result = result.concat(resolved);
            }
            else {
                result.push(resolved);
            }
        }
        return result;
    };
    /**
     * Splits filter by lines.
     * @param filter Filter to split.
     * @returns Array of strings.
     */
    const splitFilter = (filter) => {
        return filter.trim().split(/[\r\n]+/);
    };
    /**
     * Downloads filter rules from an external URL or a local path and resolves
     * pre-processor directives.
     *
     * @param url Filter file absolute URL or relative path.
     * @param downloadOptions Options to be applied while downloading the filter.
     *
     * @returns A promise that returns an array of strings with rules when
     * resolved or an Error if rejected.
     * @throws Error if validateChecksum flag is true and checksum is invalid.
     */
    const externalDownload = async (url, downloadOptions) => {
        const filterUrlOrigin = downloadOptions?.filterOrigin;
        const filterUrl = !REGEXP_ABSOLUTE_URL.test(url) && REGEXP_ABSOLUTE_URL.test(filterUrlOrigin || '')
            // getting absolute url for external file with relative url
            ? `${filterUrlOrigin}/${url}`
            : url;
        const rawFilter = await FileDownloadWrapper.getExternalFile(filterUrl);
        if (downloadOptions && downloadOptions.validateChecksum) {
            if (!background_isValidChecksum(rawFilter, downloadOptions.validateChecksumStrict)) {
                throw new Error('Invalid checksum');
            }
        }
        const filter = splitFilter(rawFilter);
        if (!downloadOptions?.resolveDirectives) {
            return {
                filter,
                rawFilter,
            };
        }
        const urlOrigin = getFilterUrlOrigin(filterUrl);
        const conditionsResult = resolveConditions(filter, downloadOptions.definedExpressions, urlOrigin);
        const includesResult = await resolveIncludes(conditionsResult, urlOrigin, downloadOptions.definedExpressions);
        return {
            filter: includesResult,
            rawFilter,
        };
    };
    /**
     * Compiles filter content.
     *
     * @param rules Array of strings.
     * @param filterOrigin Filter file URL origin or null.
     * @param definedProperties An object with the defined properties.
     * These properties might be used in pre-processor directives (`#if`, etc.).
     * @returns A promise that returns {string} with rules when if resolved and {Error} if rejected.
     */
    const compile = (rules, filterOrigin, definedProperties) => {
        // Resolve 'if' conditions
        const resolvedConditionsResult = resolveConditions(rules, definedProperties, filterOrigin);
        // Resolve 'includes' directives
        return resolveIncludes(resolvedConditionsResult, filterOrigin, definedProperties);
    };
    /**
     * Gets filter rules from a local path and resolves pre-processor directives.
     *
     * @param url Path to the local file.
     * @param downloadOptions Options to be applied while downloading the filter.
     * @returns A promise that returns an array of strings with rules when resolved or an Error if rejected.
     * @throws Error if validateChecksum flag is true and checksum is invalid.
     */
    const getLocalFile = async (url, downloadOptions) => {
        const { filterOrigin } = downloadOptions;
        const urlToLoad = filterOrigin
            ? `${filterOrigin}/${url}`
            : url;
        const rawFilter = await FileDownloadWrapper.getLocalFile(urlToLoad);
        if (downloadOptions && downloadOptions.validateChecksum) {
            if (!background_isValidChecksum(rawFilter, downloadOptions.validateChecksumStrict)) {
                throw new Error('Invalid checksum');
            }
        }
        const filterContent = splitFilter(rawFilter);
        if (!downloadOptions?.resolveDirectives) {
            return {
                filter: filterContent,
                rawFilter,
            };
        }
        const urlOrigin = getFilterUrlOrigin(urlToLoad);
        // Resolve 'if' conditions and 'includes' directives
        const conditionsResult = resolveConditions(filterContent, downloadOptions.definedExpressions, urlOrigin);
        const includesResult = await resolveIncludes(conditionsResult, urlOrigin, downloadOptions.definedExpressions);
        return {
            filter: includesResult,
            rawFilter,
        };
    };
    /**
     * Downloads filter rules from a URL and resolves pre-processor directives.
     *
     * @param url Filter file URL.
     * @param downloadOptions Options to be applied while downloading the filter.
     * These properties might be used in pre-processor directives (`#if`, etc.).
     *
     * @returns A promise that returns an array of strings with rules when
     * resolved or an Error if rejected.
     */
    const downloadFilterRules = (url, downloadOptions) => {
        if (REGEXP_EXTERNAL_ABSOLUTE_URL.test(url)
            || REGEXP_EXTERNAL_ABSOLUTE_URL.test(downloadOptions.filterOrigin || '')) {
            return externalDownload(url, downloadOptions);
        }
        return getLocalFile(url, downloadOptions);
    };
    /**
     * Downloads a specified filter and resolves all the pre-processor directives from there.
     *
     * @param url The URL of the filter to download.
     * @param definedExpressions An object with the defined properties.
     * These properties might be used in pre-processor directives (`#if`, etc.).
     * @param options Options to be applied while downloading the filter.
     *
     * @returns A promise that resolves with a list of rules and rejects with an error if unable to download.
     * @throws Error if validateChecksum flag is true and checksum is invalid.
     */
    const download = async (url, definedExpressions, options) => {
        let filterUrlOrigin;
        if (url && REGEXP_EXTERNAL_ABSOLUTE_URL.test(url)) {
            filterUrlOrigin = getFilterUrlOrigin(url);
        }
        const result = await downloadFilterRules(url, {
            filterOrigin: filterUrlOrigin,
            definedExpressions,
            resolveDirectives: true,
            validateChecksum: options?.validateChecksum,
            validateChecksumStrict: options?.validateChecksumStrict,
        });
        // if 'allowEmptyResponse' option is not set, an empty filter will not be loaded.
        // only included filters can be empty, in this case.
        // if 'allowEmptyResponse' option is set, the empty file will be downloaded.
        if (result.filter
            && result.filter.join().trim() === ''
            && !options?.allowEmptyResponse) {
            throw new Error('Response is empty');
        }
        return result.filter;
    };
    /**
     * Resolves conditions and includes based on the provided raw filter, options, and filter URL origin.
     *
     * @param rawFilter The raw filter to be resolved.
     * @param options The options used in the resolution process.
     * @param filterUrlOrigin The origin of the filter URL.
     *
     * @returns A Promise that resolves to the result of resolving the includes.
     */
    async function resolveConditionsAndIncludes(rawFilter, options, filterUrlOrigin) {
        const filter = splitFilter(rawFilter);
        const resolvedConditionsResult = resolveConditions(filter, options.definedExpressions, filterUrlOrigin);
        return resolveIncludes(resolvedConditionsResult, filterUrlOrigin, options.definedExpressions);
    }
    /**
     * Downloads filter rules from a URL and resolves pre-processor directives.
     *
     * @param url Filter file URL.
     * @param options Options to be applied while downloading the filter.
     *
     * @returns A promise that returns an array of strings with rules.
     */
    async function downloadAndProcess(url, options) {
        let filterUrlOrigin;
        if (url && REGEXP_EXTERNAL_ABSOLUTE_URL.test(url)) {
            filterUrlOrigin = getFilterUrlOrigin(url);
        }
        const result = await downloadFilterRules(url, {
            filterOrigin: filterUrlOrigin,
            definedExpressions: options.definedExpressions,
            // `false` for not resolving directives
            resolveDirectives: false,
            validateChecksum: options.validateChecksum,
            validateChecksumStrict: options.validateChecksumStrict,
        });
        // if 'allowEmptyResponse' option is not set, an empty filter will not be loaded.
        // only included filters can be empty, in this case.
        // if 'allowEmptyResponse' option is set, the empty file will be downloaded.
        if (result.filter
            && result.filter.join().trim() === ''
            && !options?.allowEmptyResponse) {
            throw new Error('Response is empty');
        }
        const includesResult = await resolveConditionsAndIncludes(result.rawFilter, options, filterUrlOrigin);
        return {
            filter: includesResult,
            rawFilter: result.rawFilter,
        };
    }
    /**
     * Downloads filter rules from a URL without resolving pre-processor directives.
     *
     * @param url Filter file URL.
     * @param options Options to be applied while downloading the filter.
     *
     * @returns A promise that returns an array of strings with rules when
     * resolved or an Error if rejected.
     *
     * @throws An error if
     * - validateChecksum flag is true and checksum is invalid;
     * - DiffUpdater.applyPatch() fails and the thrown error is not {@link UnacceptableResponseError}.
     */
    const downloadWithRaw = async (url, options) => {
        options.verbose ??= false;
        options.force ??= false;
        let filterUrlOrigin;
        if (url && REGEXP_EXTERNAL_ABSOLUTE_URL.test(url)) {
            filterUrlOrigin = getFilterUrlOrigin(url);
        }
        // if options.force, then download the whole filter
        // if !options.rawFilter, then return result as is, since it is not possible to apply
        // patches without the raw filter
        if (options.force || !options.rawFilter) {
            return downloadAndProcess(url, options);
        }
        let rawFilter = '';
        try {
            rawFilter = await background_DiffUpdater_1.applyPatch({
                filterUrl: url,
                filterContent: options.rawFilter,
                verbose: options.verbose,
            });
        }
        catch (e) {
            if (e instanceof background_UnacceptableResponseError_1) {
                return {
                    filter: splitFilter(options.rawFilter),
                    rawFilter: options.rawFilter,
                    isPatchUpdateFailed: true,
                };
            }
            // if the error is not UnacceptableResponseError, then rethrow it further
            throw e;
        }
        // applyPatch returns null if there is no Diff-Path in the filter metadata
        if (rawFilter === null) {
            const downloadResult = await downloadAndProcess(url, options);
            return downloadResult;
        }
        // if nothing changed, then return result as is
        if (rawFilter === options.rawFilter) {
            return {
                filter: splitFilter(options.rawFilter),
                rawFilter: options.rawFilter,
            };
        }
        const resolveResult = await resolveConditionsAndIncludes(rawFilter, options, filterUrlOrigin);
        return {
            filter: resolveResult,
            rawFilter,
        };
    };
    return {
        compile,
        download,
        downloadWithRaw,
        resolveConditions,
        resolveIncludes,
        getFilterUrlOrigin,
    };
};

const background_PREFERRED_CONTENT_TYPE = 'text/plain';
/**
 * Supported content types.
 */
const background_SUPPORTED_CONTENT_TYPES = [
    background_PREFERRED_CONTENT_TYPE,
    // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/1723
    'text/html',
    // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2908
    'application/octet-stream',
];
/**
 * Returns content type error.
 *
 * @returns Error with description of supported content types.
 */
const background_getContentTypeError = () => {
    return new Error(`Response content type should be one of: "${background_SUPPORTED_CONTENT_TYPES.join(', ')}"`);
};
/**
 * Checks if the content type is supported.
 *
 * @param contentTypeHeader Content type header.
 *
 * @returns True if supported.
 */
const background_isContentTypeSupported = (contentTypeHeader) => {
    if (!contentTypeHeader) {
        return false;
    }
    return background_SUPPORTED_CONTENT_TYPES.some((ct) => contentTypeHeader.includes(ct));
};

/**
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with AdGuard Browser Extension.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * Set of network protocols. Used to check if url is local.
 */
const background_networkProtocols = new Set(['http:', 'https:']);
/**
 * If url protocol is not http or https return true, else false.
 *
 * @param url URL address to check.
 *
 * @returns Tue if provided address is local.
 */
const background_isLocal = (url) => {
    const parsedUrl = new URL(url);
    return !background_networkProtocols.has(parsedUrl.protocol);
};
/**
 * Executes async request via fetch.
 * Fetch doesn't allow downloading urls with file:// scheme.
 *
 * @param url URL.
 *
 * @returns Promise which will be resolved with string content of request
 * divided by '/r?/n'.
 */
const background_executeRequestAsyncFetch = async (url) => {
    const response = await fetch(url, {
        cache: 'no-cache',
        headers: {
            Pragma: 'no-cache',
            'Content-Type': background_PREFERRED_CONTENT_TYPE,
        },
    });
    if (response.status !== 200 && response.status !== 0) {
        throw new Error(`Response status for url ${url} is invalid: ${response.status}`);
    }
    // Don't check response headers if url is local,
    // because the edge extension doesn't provide headers for such url
    if (!background_isLocal(response.url)) {
        const responseContentType = response.headers.get('Content-Type');
        if (!background_isContentTypeSupported(responseContentType)) {
            throw background_getContentTypeError();
        }
    }
    return response.text();
};
/**
 * Executes an asynchronous XMLHttpRequest to retrieve the content of a file
 * from the given URL.
 *
 * @param url The URL of the file to retrieve.
 * @returns A Promise that resolves to a string representing data from the file.
 * @throws Throws an error if the response status is invalid,
 * the Content-Type is unsupported, or if there's an error during the request.
 */
const background_executeRequestAsyncXhr = (url) => new Promise((resolve, reject) => {
    const onRequestLoad = (response) => {
        if (response.status !== 200 && response.status !== 0) {
            reject(new Error(`Response status for url ${url} is invalid: ${response.status}`));
        }
        const responseText = response.responseText
            ? response.responseText
            // @ts-ignore
            : response.data;
        // Don't check response headers if url is local,
        // because the edge extension doesn't provide headers for such url
        if (!background_isLocal(response.responseURL)) {
            const responseContentType = response.getResponseHeader('Content-Type');
            if (!background_isContentTypeSupported(responseContentType)) {
                reject(background_getContentTypeError());
            }
        }
        resolve(responseText);
    };
    const request = new XMLHttpRequest();
    try {
        request.open('GET', url);
        request.setRequestHeader('Pragma', 'no-cache');
        request.overrideMimeType(background_PREFERRED_CONTENT_TYPE);
        // @ts-ignore
        request.mozBackgroundRequest = true;
        // eslint-disable-next-line func-names
        request.onload = () => {
            onRequestLoad(request);
        };
        request.onerror = () => reject(new Error(`Request error happened: ${request.statusText || 'status text empty'}`));
        request.onabort = () => reject(new Error(`Request was aborted with status text: ${request.statusText}`));
        request.ontimeout = () => reject(new Error(`Request timed out with status text: ${request.statusText}`));
        request.send(null);
    }
    catch (ex) {
        reject(ex);
    }
});
/**
 * Downloads filter rules from external url.
 *
 * @param url Filter file absolute URL or relative path.
 * @returns A promise that returns string of rules when resolved
 * and error if rejected.
 */
const background_getExternalFile = (url) => background_executeRequestAsyncFetch(url);
/**
 * Retrieves a local file content asynchronously using XMLHttpRequest or fetch API.
 *
 * @param url The URL of the local file to retrieve.
 * @returns A Promise that resolves to string representing the content of the file.
 * @throws Throws an error if neither XMLHttpRequest nor fetch is available or
 * if getting local files inside a service worker is not supported.
 */
const background_getLocalFile = (url) => {
    if (typeof XMLHttpRequest !== 'undefined') {
        return background_executeRequestAsyncXhr(url);
    }
    if (typeof fetch !== 'undefined') {
        return background_executeRequestAsyncFetch(url);
    }
    throw new Error('XMLHttpRequest or fetch are undefined, getting local files inside service worker is not working');
};

const background_FiltersDownloader = background_FiltersDownloaderCreator({
    getLocalFile: background_getLocalFile,
    getExternalFile: background_getExternalFile,
});



;// ./Extension/src/background/api/network/settings.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_network_settings_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}




/**
 * NetworkSettings contains a bunch of url's which are using by extension.
 */ class background_NetworkSettings {
    /**
     * Initializes the network settings.
     */ async init() {
        this.filtersRulesBaseUrl = await this.getFilterRulesBaseUrl();
        background_logger_logger.info('Filters rules base url:', this.filtersRulesBaseUrl);
    }
    /**
     * Used to set the base url for filter rules through the local storage for testing purposes.
     *
     * MV3_REMOTE_POLICY.
     * This keyword can be used to grep all code related to MV3 remote
     * hosting policy.
     *
     * In MV3 extension we download a so-called "Quick Fixes filter" which
     * is used for fixing major issues without the need to update the
     * extension or custom filter lists added by the users themselves.
     * Having this logic is particularly important for an ad blocker since
     * websites breakages can occur at any time and we need to be able to
     * fix them ASAP.
     *
     * We make sure that all these rules that come from the filter
     * were in compliance with CWS policies:
     * "Fetching a remote configuration file for A/B testing or determining
     * enabled features, where all logic for the functionality is contained
     * within the extension package".
     *
     * 1. Network rules from the Quick Fixes filter is converted to DNR
     *    rules and applied via dynamic rules.
     * 2. Cosmetic rules are interpreted in the code. For example, hiding
     *    elements OR on the contrary, unhiding them when it is necessary.
     *    At the same time the cosmetic rules logic is contained in the
     *    extension package.
     *
     * Quick Fixes filter contents can be examined here:
     * https://filters.adtidy.org/extension/chromium-mv3/filters/24.txt.
     *
     * To ensure compliance with Chrome Store policies, we have safeguards
     * that restrict execution to rules that are included into the extension
     * package and can be reviewed there. These safeguards can be found by
     * searching for 'JS_RULES_EXECUTION'.
     *
     * @returns The base url for filter rules.
     */ async getFilterRulesBaseUrl() {
        // We don't need to set base url in MV3 because we cannot update filters via patches.
        // TODO: Remove check when filters will support patches in MV3.
        if (false) {}
        return this.DEFAULT_FILTER_RULES_BASE_URL;
    }
    /**
     * Returns the url from which the filters can be loaded.
     *
     * @returns The url from which filters can be downloaded.
     */ // eslint-disable-next-line class-methods-use-this
    get filtersUrl() {
        // first of all check whether it is mv3-build
        // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2985
        if (true) {
            /**
             * MV3_REMOTE_POLICY.
             * This keyword can be used to grep all code related to MV3 remote
             * hosting policy.
             *
             * In MV3 extension we download a so-called "Quick Fixes filter" which
             * is used for fixing major issues without the need to update the
             * extension or custom filter lists added by the users themselves.
             * Having this logic is particularly important for an ad blocker since
             * websites breakages can occur at any time and we need to be able to
             * fix them ASAP.
             *
             * We make sure that all these rules that come from the filter
             * were in compliance with CWS policies:
             * "Fetching a remote configuration file for A/B testing or determining
             * enabled features, where all logic for the functionality is contained
             * within the extension package".
             *
             * 1. Network rules from the Quick Fixes filter is converted to DNR
             *    rules and applied via dynamic rules.
             * 2. Cosmetic rules are interpreted in the code. For example, hiding
             *    elements OR on the contrary, unhiding them when it is necessary.
             *    At the same time the cosmetic rules logic is contained in the
             *    extension package.
             *
             * Quick Fixes filter contents can be examined here:
             * https://filters.adtidy.org/extension/chromium-mv3/filters/24.txt.
             *
             * To ensure compliance with Chrome Store policies, we have safeguards
             * that restrict execution to rules that are included into the extension
             * package and can be reviewed there. These safeguards can be found by
             * searching for 'JS_RULES_EXECUTION'.
             */ return null;
        }
        if (background_UserAgent.isFirefox) {
            return `${this.filtersRulesBaseUrl}/firefox`;
        }
        if (background_UserAgent.isEdge) {
            return `${this.filtersRulesBaseUrl}/edge`;
        }
        if (background_UserAgent.isOpera) {
            return `${this.filtersRulesBaseUrl}/opera`;
        }
        return `${this.filtersRulesBaseUrl}/chromium`;
    }
    /**
     * Returns URL for downloading AG filters or null if downloading
     * is not allowed.
     *
     * @returns URL for downloading AG filters or null if downloading
     * is not allowed.
     */ get filterRulesUrl() {
        return !this.filtersUrl ? null : `${this.filtersUrl}/filters/{filter_id}.txt`;
    }
    /**
     * Returns URL for downloading optimized AG filters or null if downloading
     * is not allowed.
     *
     * @returns URL for downloading optimized AG filters or null if downloading
     * is not allowed.
     */ get optimizedFilterRulesUrl() {
        return !this.filtersUrl ? null : `${this.filtersUrl}/filters/{filter_id}_optimized.txt`;
    }
    /**
     * Returns URL for checking filter updates.
     *
     * @returns URL for checking filter updates.
     */ get filtersMetadataUrl() {
        const params = background_BrowserUtils.getExtensionParams();
        return `${this.filtersUrl}/${background_REMOTE_METADATA_FILE_NAME}?${params.join('&')}`;
    }
    /**
     * Returns URL for downloading i18n localizations.
     *
     * @returns URL for downloading i18n localizations.
     */ get filtersI18nMetadataUrl() {
        const params = background_BrowserUtils.getExtensionParams();
        return `${this.filtersUrl}/${background_REMOTE_I18N_METADATA_FILE_NAME}?${params.join('&')}`;
    }
    /**
     * URL for collecting filter rules statistics.
     * We do not collect it by default, unless user is willing to help.
     * Filter rules stats are covered in our privacy policy and on also here:
     * http://adguard.com/en/filter-rules-statistics.html.
     *
     * @returns Rule stats url.
     */ get ruleStatsUrl() {
        return `${this.backendUrl}/api/1.0/rulestats.html`;
    }
    /**
     * Constructor.
     */ constructor(){
        // Base url of our backend server
        background_network_settings_define_property(this, "backendUrl", 'https://chrome.adtidy.org');
        // Api key
        background_network_settings_define_property(this, "apiKey", '4DDBE80A3DA94D819A00523252FB6380');
        // Browsing Security lookups. In case of Firefox lookups are disabled for HTTPS urls.
        background_network_settings_define_property(this, "safebrowsingLookupUrl", 'https://sb.adtidy.org/safebrowsing-lookup-short-hash.html');
        /**
     * Default base url for downloading filter rules.
     *
     * MV3_REMOTE_POLICY.
     * This keyword can be used to grep all code related to MV3 remote
     * hosting policy.
     *
     * In MV3 extension we download a so-called "Quick Fixes filter" which
     * is used for fixing major issues without the need to update the
     * extension or custom filter lists added by the users themselves.
     * Having this logic is particularly important for an ad blocker since
     * websites breakages can occur at any time and we need to be able to
     * fix them ASAP.
     *
     * We make sure that all these rules that come from the filter
     * were in compliance with CWS policies:
     * "Fetching a remote configuration file for A/B testing or determining
     * enabled features, where all logic for the functionality is contained
     * within the extension package".
     *
     * 1. Network rules from the Quick Fixes filter is converted to DNR
     *    rules and applied via dynamic rules.
     * 2. Cosmetic rules are interpreted in the code. For example, hiding
     *    elements OR on the contrary, unhiding them when it is necessary.
     *    At the same time the cosmetic rules logic is contained in the
     *    extension package.
     *
     * Quick Fixes filter contents can be examined here:
     * https://filters.adtidy.org/extension/chromium-mv3/filters/24.txt.
     *
     * To ensure compliance with Chrome Store policies, we have safeguards
     * that restrict execution to rules that are included into the extension
     * package and can be reviewed there. These safeguards can be found by
     * searching for 'JS_RULES_EXECUTION'.
     *
     * @private
     */ background_network_settings_define_property(this, "DEFAULT_FILTER_RULES_BASE_URL", 'https://filters.adtidy.org/extension');
        /**
     * By this key, qa can set the base url for filter rules through the local storage for testing
     * purposes.
     *
     * @example
     * ```javascript
     *  localStorage.setItem('ag_filters_base_url', 'https://filters.adtidy.org/extension/');
     * ```
     *
     * @private
     */ background_network_settings_define_property(this, "FILTERS_BASE_URL_KEY", 'ag_filters_base_url');
        // Folder that contains filters metadata and files with rules. 'filters' by default
        background_network_settings_define_property(this, "localFiltersFolder", 'filters');
        // TODO: Check, not using.
        // Path to the redirect sources
        background_network_settings_define_property(this, "redirectSourcesFolder", 'assets/libs/scriptlets');
        // Array of filter identifiers, that have local file with rules.
        // We don't use this check for MV3, because all filters in MV3 already
        // packed in the extension.
        background_network_settings_define_property(this, "localFilterIds", background_ADGUARD_FILTERS_IDS);
        /**
     * Base url for downloading filter rules.
     *
     * @private
     */ background_network_settings_define_property(this, "filtersRulesBaseUrl", '');
        /**
     * Promise that resolves when the network settings are initialized.
     * Only needed in MV3 with async initialization.
     */ background_network_settings_define_property(this, "initPromise", null);
        this.initPromise = this.init();
    }
}

;// ./Extension/src/background/api/network/main.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_main_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}















/**
 * Api for working with our backend server.
 * All requests sent by this class are covered in the privacy policy:
 * http://adguard.com/en/privacy.html#browsers.
 */ class background_Network {
    /**
     * Returns promise that resolves when network is initialized.
     * Only needed in MV3 with async initialization.
     *
     * @returns Promise that resolves when network is initialized.
     */ waitForNetworkInit() {
        return this.settings.initPromise;
    }
    /**
     * Checks if filter has local copy in the extension resources or not.
     *
     * @param filterId Filter id.
     *
     * @returns True if filter has local copy, false otherwise.
     */ isFilterHasLocalCopy(filterId) {
        return this.settings.localFilterIds.includes(filterId);
    }
    /**
     * Downloads filter rules by filter ID.
     *
     * @param filterUpdateOptions Filter update detail.
     * @param forceRemote Force download filter rules from remote server.
     * @param useOptimizedFilters Download optimized filters flag.
     * @param rawFilter Raw filter rules.
     *
     * @returns Downloaded filter rules.
     *
     * @throws An error if FiltersDownloader.downloadWithRaw() fails.
     */ async downloadFilterRules(filterUpdateOptions, forceRemote, useOptimizedFilters, rawFilter) {
        let url;
        const { filterId } = filterUpdateOptions;
        if (false) {}
        let isLocalFilter = false;
        if (true) {
            url = background_browser_polyfill_default().runtime.getURL(`${this.settings.localFiltersFolder}/filter_${filterId}.txt`);
            // TODO: Uncomment this block when Quick Fixes filter will return in another way
            // // `forceRemote` flag for MV3 built-in filters can be used only for Quick Fixes filter,
            // // and custom filters
            // const isRemote = forceRemote
            //     && (filterId === AntiBannerFiltersId.QuickFixesFilterId
            //         || CustomFilterApi.isCustomFilter(filterId));
            // if (isRemote) {
            //     if (useOptimizedFilters) {
            //         logger.info('Optimized filters are not supported in MV3, full versions will be downloaded');
            //     }
            //     url = this.getUrlForDownloadFilterRules(filterId, false);
            // }
            isLocalFilter = true;
        } else {}
        // local filters do not support patches, that is why we always download them fully
        if (isLocalFilter || filterUpdateOptions.ignorePatches || !rawFilter) {
            // TODO: Revert when Quick Fixes filter will return in another way
            if (true /* && filterId !== AntiBannerFiltersId.QuickFixesFilterId */ ) {
                // TODO: Check if its needed
                // eslint-disable-next-line max-len
                await background_TsWebExtension.syncRuleSetWithIdb(filterId, 'filters/declarative');
                const rawFilterList = await background_FiltersStoragesAdapter.getRawFilterList(filterId);
                if (!rawFilterList) {
                    throw new Error(`Cannot find filter with id ${filterId}`);
                }
                return {
                    filter: rawFilterList.split(background_NEWLINE_CHAR_REGEX),
                    rawFilter: rawFilterList
                };
            }
            const result = await background_FiltersDownloader.downloadWithRaw(url, {
                force: true,
                definedExpressions: this.filterCompilerConditionsConstants,
                verbose: background_logger_logger.isVerbose(),
                // Disable checksum checking for local filters, because we
                // apply preprocessing for them, during which some rules may
                // be changed, and as a result, the filter checksum will
                // become invalid.
                validateChecksum: !isLocalFilter,
                // use true because we know that our filters have checksums
                validateChecksumStrict: true
            });
            return result;
        }
        return background_FiltersDownloader.downloadWithRaw(url, {
            rawFilter,
            definedExpressions: this.filterCompilerConditionsConstants,
            verbose: background_logger_logger.isVerbose(),
            validateChecksum: true,
            // use true because we know that our filters have checksums
            validateChecksumStrict: true
        });
    }
    /**
     * Downloads filter rules by url. Needed for custom filter lists.
     *
     * @param url Subscription url.
     * @param rawFilter Raw filter rules.
     * @param force Boolean flag to download filter fully or by patches.
     *
     * @returns Downloaded filter rules.
     */ async downloadFilterRulesBySubscriptionUrl(url, rawFilter, force) {
        if (url in this.loadingSubscriptions) {
            return;
        }
        this.loadingSubscriptions[url] = true;
        try {
            var _downloadData_filter_;
            // TODO: runtime validation
            const downloadData = await background_FiltersDownloader.downloadWithRaw(url, {
                definedExpressions: this.filterCompilerConditionsConstants,
                force,
                rawFilter,
                verbose: background_logger_logger.isVerbose(),
                validateChecksum: true,
                // use false because we know that custom filters might not have checksums
                validateChecksumStrict: false
            });
            delete this.loadingSubscriptions[url];
            // Get the first rule to check if it is an adblock agent (like [Adblock Plus 2.0]). If so, ignore it.
            const firstRule = (_downloadData_filter_ = downloadData.filter[0]) === null || _downloadData_filter_ === void 0 ? void 0 : _downloadData_filter_.trim();
            if (firstRule && firstRule.startsWith('[') && firstRule.endsWith(']')) {
                downloadData.filter.shift();
            }
            return downloadData;
        } catch (e) {
            delete this.loadingSubscriptions[url];
            const message = e instanceof Error ? e.message : 'Unknown error while filter downloading by subscription url';
            throw new Error(message, {
                cause: e
            });
        }
    }
    /**
     * Loads filters metadata from local file.
     * For MV3, it loads metadata from the metadata ruleset file.
     *
     * @returns Object of {@link Metadata}.
     *
     * @throws Error if metadata is invalid.
     */ async getLocalFiltersMetadata() {
        let url;
        if (true) {
            // For MV3, the filters metadata is stored in the metadata ruleset.
            // The reason for this is that it allows us to perform extension updates
            // where only the JSON files of the rulesets are changed.
            const metadataRuleSetPath = background_getRuleSetPath(background_METADATA_RULESET_ID, `${this.settings.localFiltersFolder}/declarative`);
            url = background_browser_polyfill_default().runtime.getURL(metadataRuleSetPath);
        } else {}
        let response;
        try {
            response = await background_Network.fetchJson(url);
        } catch (e) {
            const exMessage = e instanceof Error ? e.message : 'could not load local filters metadata';
            throw background_Network.createError(exMessage, url);
        }
        if (!(response === null || response === void 0 ? void 0 : response.responseText)) {
            throw background_Network.createError('empty response', url, response);
        }
        try {
            let metadata;
            if (true) {
                const metadataRuleSet = background_MetadataRuleSet.deserialize(response.responseText);
                // Filters metadata is stored as an additional property in the metadata ruleset.
                metadata = metadataRuleSet.getAdditionalProperty('metadata');
            } else {}
            return background_metadata_metadataValidator.parse(metadata);
        } catch (e) {
            // TODO: Return regular error
            // TODO: Zod error doesn't display
            throw background_Network.createError('invalid response', url, response, e instanceof Error ? e : undefined);
        }
    }
    /**
     * Loads filter groups metadata from local file.
     *
     * @returns Object of {@link I18nMetadata}.
     *
     * @throws Error if metadata is invalid.
     */ async getLocalFiltersI18nMetadata() {
        const url = background_browser_polyfill_default().runtime.getURL(`${this.settings.localFiltersFolder}/${background_LOCAL_I18N_METADATA_FILE_NAME}`);
        let response;
        try {
            response = await background_Network.fetchJson(url);
        } catch (e) {
            const exMessage = e instanceof Error ? e.message : 'could not load local filters i18n metadata';
            throw background_Network.createError(exMessage, url);
        }
        if (!(response === null || response === void 0 ? void 0 : response.responseText)) {
            throw background_Network.createError('empty response', url, response);
        }
        try {
            const metadata = JSON.parse(response.responseText);
            return background_i18nMetadataValidator.parse(metadata);
        } catch (e) {
            // TODO: Return regular error
            // TODO: Zod error doesn't display
            throw background_Network.createError('invalid response', url, response, e instanceof Error ? e : undefined);
        }
    }
    /**
     * Loads script rules from local file.
     * This method should be called only in the Firefox AMO.
     *
     * @returns Array of string script rules.
     *
     * @throws Error if metadata is invalid.
     */ async getLocalScriptRules() {
        const url = background_browser_polyfill_default().runtime.getURL(`${this.settings.localFiltersFolder}/local_script_rules.json`);
        let response;
        try {
            response = await background_Network.fetchJson(url);
        } catch (e) {
            const exMessage = e instanceof Error ? e.message : 'could not load local script rules';
            throw background_Network.createError(exMessage, url);
        }
        if (!(response === null || response === void 0 ? void 0 : response.responseText)) {
            throw background_Network.createError('empty response', url, response);
        }
        try {
            const localScriptRules = JSON.parse(response.responseText);
            return background_localScriptRulesValidator.parse(localScriptRules);
        } catch (e) {
            throw background_Network.createError('invalid response', url, response, e instanceof Error ? e : undefined);
        }
    }
    /**
     * Downloads metadata from backend.
     *
     * @returns Object of {@link Metadata}.
     *
     * @throws Error if metadata is invalid.
     */ async downloadMetadataFromBackend() {
        const url = this.settings.filtersMetadataUrl;
        const response = await background_Network.fetchJson(url);
        if (!(response === null || response === void 0 ? void 0 : response.responseText)) {
            throw new Error(`Empty response: ${response}`);
        }
        try {
            const metadata = JSON.parse(response.responseText);
            return background_metadata_metadataValidator.parse(metadata);
        } catch (e) {
            throw background_Network.createError('invalid response', url, response, e instanceof Error ? e : undefined);
        }
    }
    /**
     * Downloads i18n metadata from backend and returns it.
     *
     * @returns Object of {@link I18nMetadata}.
     *
     * @throws Error if metadata is invalid.
     */ async downloadI18nMetadataFromBackend() {
        const response = await background_Network.fetchJson(this.settings.filtersI18nMetadataUrl);
        if (!(response === null || response === void 0 ? void 0 : response.responseText)) {
            throw new Error(`Empty response: ${response}`);
        }
        try {
            const metadata = JSON.parse(response.responseText);
            return background_i18nMetadataValidator.parse(metadata);
        } catch (e) {
            throw new Error(`Invalid response: ${response}`, {
                cause: e
            });
        }
    }
    /**
     * Checks specified host hashes with our safebrowsing service.
     *
     * @param hashes Host hashes.
     *
     * @returns Response from the safebrowsing service.
     */ async lookupSafebrowsing(hashes) {
        const url = `${this.settings.safebrowsingLookupUrl}?prefixes=${encodeURIComponent(hashes.join('/'))}`;
        const response = await background_Network.fetchJson(url);
        return response;
    }
    /**
     * Sends filter hits stats to backend server.
     * This method is used if user has enabled "Send statistics for ad filters usage".
     * More information about ad filters usage stats:
     * http://adguard.com/en/filter-rules-statistics.html.
     *
     * @param stats Sent stats.
     */ async sendHitStats(stats) {
        const statsString = JSON.stringify(stats);
        await fetch(this.settings.ruleStatsUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: statsString
        });
    }
    /**
     * URL for downloading AG filter.
     *
     * @param filterId Filter identifier.
     * @param useOptimizedFilters If true, download optimized filters.
     *
     * @returns Url for filter downloading.
     *
     * @throws Error if MV3 is used and remote filter downloading is not supported.
     */ getUrlForDownloadFilterRules(filterId, useOptimizedFilters) {
        if (true) {
            throw new Error('MV3 does not support remote filter downloading');
        }
        if (!this.settings.filterRulesUrl || !this.settings.optimizedFilterRulesUrl) {
            throw new Error('Filter rules URL is not defined');
        }
        const url = useOptimizedFilters ? this.settings.optimizedFilterRulesUrl : this.settings.filterRulesUrl;
        return url.replaceAll('{filter_id}', String(filterId));
    }
    /**
     * Appends request key to url.
     *
     * @param url Url string.
     *
     * @returns Url with key query param.
     */ addKeyParameter(url) {
        return `${url}&key=${this.settings.apiKey}`;
    }
    /**
     * Makes a request for json.
     *
     * @param url Url.
     *
     * @returns Response with type {@link ResponseLikeXMLHttpRequest} to be
     * compatible with XMLHttpRequest.
     */ static async fetchJson(url) {
        const response = await fetch(url, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        const responseText = await response.text();
        // TODO: Use fetch response directly.
        return {
            ...response,
            mozBackgroundRequest: true,
            responseText
        };
    }
    /**
     * Creates a custom network error to throw it to a higher level.
     *
     * @param message Error message.
     * @param url Url where the error occurred.
     * @param response Network response information {@link ExtensionXMLHttpRequest}.
     * @param originError Original error.
     *
     * @returns Error "wrapper".
     */ static createError(message, url, response, originError) {
        let errorMessage = `
            error:                    ${message}
            requested url:            ${url}`;
        if (response) {
            errorMessage = `
            error:                    ${message}
            requested url:            ${url}
            request status text:      ${response.statusText}`;
        }
        return new Error(errorMessage, {
            cause: originError
        });
    }
    constructor(){
        background_main_define_property(this, "settings", new background_NetworkSettings());
        /**
     * FiltersDownloader constants.
     */ background_main_define_property(this, "filterCompilerConditionsConstants", {
            adguard: true,
            adguard_ext_chromium: background_UserAgent.isChromium,
            adguard_ext_firefox: background_UserAgent.isFirefox,
            adguard_ext_edge: background_UserAgent.isEdge,
            adguard_ext_safari: false,
            adguard_ext_opera: background_UserAgent.isOpera
        });
        /**
     * Loading subscriptions map.
     */ background_main_define_property(this, "loadingSubscriptions", {});
    }
}
const background_network = new background_Network();

;// ./Extension/src/background/api/network/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 


;// ./Extension/src/background/api/settings/migrations.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_migrations_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}




/**
 * SettingsMigrations stores migrations to apply to an outdated flat settings
 * object when imported settings from JSON.
 */ class background_SettingsMigrations {
    /**
     * Migrates settings from any outdated version and returns settings of the latest version.
     *
     * @param protocolVersion Protocol version of provided JSON settings.
     * @param settings JSON settings with outdated version.
     *
     * @returns JSON settings of the latest version.
     *
     * @throws Error when not found migration for current version or
     * not found action for migrate.
     */ static async migrateSettings(protocolVersion, settings) {
        // Create copy to not modify arg value
        let settingsCopy = JSON.parse(JSON.stringify(settings));
        const migrations = this.settingsMigrationMap;
        let currentMigrationIdx = migrations.findIndex((migration)=>{
            return migration.from === protocolVersion;
        });
        if (currentMigrationIdx === -1) {
            throw new Error(`Not found migration for version: ${protocolVersion}`);
        }
        for(currentMigrationIdx; currentMigrationIdx < migrations.length; currentMigrationIdx += 1){
            var _migrations_currentMigrationIdx;
            const action = (_migrations_currentMigrationIdx = migrations[currentMigrationIdx]) === null || _migrations_currentMigrationIdx === void 0 ? void 0 : _migrations_currentMigrationIdx.action;
            if (!action) {
                throw new Error(`Not found migration action for migration idx: ${currentMigrationIdx}`);
            }
            // eslint-disable-next-line no-await-in-loop
            settingsCopy = await action(settingsCopy);
        }
        return settingsCopy;
    }
    /**
     * Migrates settings from version 1.0 to version 2.0.
     *
     * @param settings JSON settings with version 1.0.
     *
     * @returns JSON settings of version 2.0.
     *
     * @throws Error when not found field 'filters.whitelist' to rename it.
     */ static async migrateFromV1_0toV2_0(settings) {
        if (!settings || !background_Unknown.hasProp(settings, 'filters') || !background_Unknown.hasProp(settings.filters, 'whitelist') || !background_Unknown.hasProp(settings.filters, 'custom-filters') || !background_Unknown.hasProp(settings, 'stealth') || !background_Unknown.hasProp(settings.stealth, 'stealth_disable_stealth_mode') || !background_Unknown.hasProp(settings.stealth, 'stealth-block-first-party-cookies-time') || !background_Unknown.hasProp(settings.stealth, 'stealth-block-third-party-cookies-time') || !background_Unknown.hasProp(settings, 'general-settings')) {
            throw new Error(`Invalid settings provided: ${JSON.stringify(settings)}`);
        }
        const FILTERS = 'filters';
        const ALLOWLIST = 'whitelist';
        const { filters } = settings;
        const allowlist = filters[ALLOWLIST];
        if (!allowlist) {
            throw new Error('Not found field "filters.whitelist" for migrate to ' + `"filters.allowlist" in the settings: ${settings}`);
        }
        Object.assign(filters, {
            allowlist
        });
        Object.assign(settings, {
            'protocol-version': '2.0'
        });
        delete settings[FILTERS][ALLOWLIST];
        // Moves the value to the new field key without an underscore.
        const { stealth } = settings;
        const OLD_STEALTH_KEY = 'stealth_disable_stealth_mode';
        const disableStealthMode = stealth[OLD_STEALTH_KEY];
        Object.assign(stealth, {
            [background_stealth_StealthOption.DisableStealthMode]: disableStealthMode
        });
        delete settings['stealth'][OLD_STEALTH_KEY];
        // Parsing stealth cookie time values from string values (with possible
        // escaped quotes) to numeric values.
        const FIRST_PARTY_COOKIES_TIME = 'stealth-block-first-party-cookies-time';
        if (typeof stealth[FIRST_PARTY_COOKIES_TIME] === 'string') {
            const rawValue = stealth[FIRST_PARTY_COOKIES_TIME];
            const parsedValue = Number(JSON.parse(rawValue));
            stealth[FIRST_PARTY_COOKIES_TIME] = parsedValue;
        }
        const THIRD_PARTY_COOKIES_TIME = 'stealth-block-third-party-cookies-time';
        if (typeof stealth[THIRD_PARTY_COOKIES_TIME] === 'string') {
            const rawValue = stealth[THIRD_PARTY_COOKIES_TIME];
            const parsedValue = Number(JSON.parse(rawValue));
            stealth[THIRD_PARTY_COOKIES_TIME] = parsedValue;
        }
        // Parsing appearance theme with escaped quotes.
        const APPEARANCE_THEME = 'appearance-theme';
        const GENERAL_SETTINGS = 'general-settings';
        // Check optional field.
        if (background_Unknown.hasProp(settings[GENERAL_SETTINGS], APPEARANCE_THEME) && typeof settings[GENERAL_SETTINGS][APPEARANCE_THEME] === 'string' && settings[GENERAL_SETTINGS][APPEARANCE_THEME].includes('\"')) {
            const rawValue = settings[GENERAL_SETTINGS][APPEARANCE_THEME];
            // Removes escaped quotes.
            const parsedValue = JSON.parse(rawValue);
            settings[GENERAL_SETTINGS][APPEARANCE_THEME] = parsedValue;
        }
        // Sets the missing 'enabled' and 'trusted' fields to custom filters.
        const CUSTOM_FILTERS = 'custom-filters';
        const customFilters = filters[CUSTOM_FILTERS];
        if (Array.isArray(customFilters)) {
            for(let i = 0; i < customFilters.length; i += 1){
                const customFilter = customFilters[i];
                if (customFilter.enabled === undefined) {
                    customFilter.enabled = false;
                }
                if (customFilter.trusted === undefined) {
                    customFilter.trusted = false;
                }
                // Remove deprecated field.
                if (customFilter.languages !== undefined) {
                    delete customFilter.languages;
                }
            }
        }
        return settings;
    }
}
/**
     * Stores migrations with according versions.
     */ background_migrations_define_property(background_SettingsMigrations, "settingsMigrationMap", [
    {
        from: '1.0',
        to: '2.0',
        action: background_SettingsMigrations.migrateFromV1_0toV2_0
    }
]);

;// ./Extension/src/background/api/settings/main.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

















/**
 * SettingsApi is a facade class for encapsulating the work with extension
 * settings: getting, installing, gathering tswebextension configuration from
 * current settings, importing and exporting.
 */ class background_SettingsApi {
    /**
     * Initializes settings: checks the settings from the repository and resets
     * them to defaults if the data are not valid.
     */ static async init() {
        try {
            const data = await background_browserStorage.get(background_ADGUARD_SETTINGS_KEY);
            const settings = background_settingsValidator.parse(data);
            background_settingsStorage.setCache(settings);
        } catch (e) {
            background_logger_logger.error('Cannot init settings from storage: ', e);
            background_logger_logger.info('Reverting settings to default values');
            const settings = {
                ...background_defaultSettings
            };
            // Update settings in the cache and in the storage
            background_settingsStorage.setData(settings);
        }
    }
    /**
     * Set setting to storage and publish setting event.
     *
     * @param key Setting option key.
     * @param value Settings option value.
     */ static async setSetting(key, value) {
        background_settingsStorage.set(key, value);
        await background_settingsEvents.publishEvent(key, value);
        // legacy event mediator for frontend
        background_notifier_notifier.notifyListeners(background_constants_NotifierType.SettingUpdated, {
            propertyName: key,
            propertyValue: value
        });
    }
    /**
     * Returns setting from setting storage.
     *
     * @param key Setting option key.
     *
     * @returns Settings option value.
     */ static getSetting(key) {
        return background_settingsStorage.get(key);
    }
    /**
     * Returns settings data.
     *
     * @returns Object of {@link SettingsData}.
     */ static getData() {
        return {
            names: background_SettingOption,
            defaultValues: background_defaultSettings,
            values: background_settingsStorage.getData()
        };
    }
    /**
     * Collects {@link SettingsConfig} for tswebextension from current extension settings.
     *
     * @param isMV3 Is the extension in MV3 mode.
     *
     * @returns Collected {@link SettingsConfig} for tswebextension.
     */ static getTsWebExtConfiguration(isMV3) {
        return {
            assistantUrl: `/${background_ASSISTANT_INJECT_OUTPUT}.js`,
            documentBlockingPageUrl: `${background_Prefs.baseUrl}${background_DOCUMENT_BLOCK_OUTPUT}.html`,
            ...isMV3 && {
                gpcScriptUrl: `/${background_GPC_SCRIPT_OUTPUT}.js`,
                hideDocumentReferrerScriptUrl: `/${background_HIDE_DOCUMENT_REFERRER_OUTPUT}.js`
            },
            collectStats: !background_settingsStorage.get(background_SettingOption.DisableCollectHits) || background_filteringLogApi.isOpen(),
            debugScriptlets: !isMV3 && background_filteringLogApi.isOpen(),
            allowlistInverted: !background_settingsStorage.get(background_SettingOption.DefaultAllowlistMode),
            allowlistEnabled: background_settingsStorage.get(background_SettingOption.AllowlistEnabled),
            stealthModeEnabled: !background_settingsStorage.get(background_SettingOption.DisableStealthMode),
            filteringEnabled: !background_settingsStorage.get(background_SettingOption.DisableFiltering),
            stealth: {
                blockChromeClientData: background_settingsStorage.get(background_SettingOption.RemoveXClientData),
                // TODO: revert when will be found a better way to add exclusions for $stealth=referrer
                // AG-34765
                // Setting to false so that it will remove already added session rules.
                hideReferrer: isMV3 ? false : background_settingsStorage.get(background_SettingOption.HideReferrer),
                // TODO: revert when will be found a better way to add exclusions for $stealth=searchqueries
                hideSearchQueries: isMV3 ? false : background_settingsStorage.get(background_SettingOption.HideSearchQueries),
                sendDoNotTrack: background_settingsStorage.get(background_SettingOption.SendDoNotTrack),
                blockWebRTC: background_settingsStorage.get(background_SettingOption.BlockWebRTC),
                selfDestructThirdPartyCookies: background_settingsStorage.get(background_SettingOption.SelfDestructThirdPartyCookies),
                selfDestructThirdPartyCookiesTime: background_settingsStorage.get(background_SettingOption.SelfDestructThirdPartyCookiesTime),
                selfDestructFirstPartyCookies: background_settingsStorage.get(background_SettingOption.SelfDestructFirstPartyCookies),
                selfDestructFirstPartyCookiesTime: background_settingsStorage.get(background_SettingOption.SelfDestructFirstPartyCookiesTime)
            }
        };
    }
    /**
     * Resets to default settings.
     *
     * @param enableUntouchedGroups - Should enable untouched groups related to
     * the default filters or not.
     */ static async reset(enableUntouchedGroups) {
        await background_UserRulesApi.setUserRules('');
        // Set settings store to defaults
        background_settingsStorage.setData({
            ...background_defaultSettings
        });
        // Re-init filters
        await background_main_FiltersApi.init(false);
        // On import should enable only groups from imported file.
        await background_CommonFilterApi.initDefaultFilters(enableUntouchedGroups);
        // reset list of consented filter ids on reset settings
        await background_annoyancesConsent.reset();
    }
    /**
     * Imports settings from the configuration string.
     *
     * @param configText Configuration in JSON format.
     *
     * @returns True if the import was successful, or false if not.
     */ static async import(configText) {
        try {
            let json = JSON.parse(configText);
            const protocolVersion = background_Unknown.get(json, background_RootOption.ProtocolVersion);
            if (typeof protocolVersion !== 'string') {
                throw new Error(`Not found string protocol version for provided settings: "${configText}"`);
            }
            // Try to migrate `unknown` settings to the latest version of settings
            if (protocolVersion !== background_PROTOCOL_VERSION) {
                json = await background_SettingsMigrations.migrateSettings(protocolVersion, json);
            }
            const validConfig = background_configValidator.parse(json);
            // Should not enable default groups.
            await background_SettingsApi.reset(false);
            background_SettingsApi.importExtensionSpecificSettings(validConfig[background_RootOption.ExtensionSpecificSettings]);
            const stealthOptions = validConfig[background_RootOption.Stealth];
            if (stealthOptions) {
                await background_SettingsApi.importStealth(stealthOptions);
            }
            await background_SettingsApi.importGeneralSettings(validConfig[background_RootOption.GeneralSettings]);
            await background_SettingsApi.importFilters(validConfig[background_RootOption.Filters]);
            return true;
        } catch (e) {
            background_logger_logger.error(e);
            return false;
        }
    }
    /**
     * Exports settings to string with JSON format.
     *
     * @returns Configuration in JSON format.
     */ static async export() {
        const config = {
            [background_RootOption.ProtocolVersion]: background_PROTOCOL_VERSION,
            [background_RootOption.GeneralSettings]: background_SettingsApi.exportGeneralSettings(),
            [background_RootOption.ExtensionSpecificSettings]: background_SettingsApi.exportExtensionSpecificSettings(),
            [background_RootOption.Filters]: await background_SettingsApi.exportFilters(),
            [background_RootOption.Stealth]: background_SettingsApi.exportStealth()
        };
        return JSON.stringify(config);
    }
    /**
     * Imports general settings from object of {@link GeneralSettingsConfig}.
     */ static async importGeneralSettings({ [background_GeneralSettingsOption.AllowAcceptableAds]: allowAcceptableAds, [background_GeneralSettingsOption.ShowBlockedAdsCount]: showBlockedAdsCount, [background_GeneralSettingsOption.AutodetectFilters]: autodetectFilters, [background_GeneralSettingsOption.SafebrowsingEnabled]: safebrowsingEnabled, [background_GeneralSettingsOption.FiltersUpdatePeriod]: filtersUpdatePeriod, [background_GeneralSettingsOption.AppearanceTheme]: appearanceTheme }) {
        // TODO: AllowAcceptableAds
        background_settingsStorage.set(background_SettingOption.DisableShowPageStats, !showBlockedAdsCount);
        background_settingsStorage.set(background_SettingOption.DisableDetectFilters, !autodetectFilters);
        if (false) {}
        if (appearanceTheme) {
            background_settingsStorage.set(background_SettingOption.AppearanceTheme, appearanceTheme);
            // Config is already validated in the upper level.
            await background_messenger.updateFullscreenUserRulesTheme(appearanceTheme);
        }
        if (allowAcceptableAds) {
            await background_CommonFilterApi.loadFilterRulesFromBackend(// Since this is called on settings import we update filters without patches.
            {
                filterId: background_AntiBannerFiltersId.SearchAndSelfPromoFilterId,
                ignorePatches: false
            }, false);
            background_filterStateStorage.enableFilters([
                background_AntiBannerFiltersId.SearchAndSelfPromoFilterId
            ]);
        } else {
            background_filterStateStorage.disableFilters([
                background_AntiBannerFiltersId.SearchAndSelfPromoFilterId
            ]);
        }
    }
    /**
     * Exports general settings to object of {@link GeneralSettingsConfig}.
     *
     * @returns Object of {@link GeneralSettingsConfig}.
     */ static exportGeneralSettings() {
        var _filterStateStorage_get;
        return {
            [background_GeneralSettingsOption.AllowAcceptableAds]: !!((_filterStateStorage_get = background_filterStateStorage.get(background_AntiBannerFiltersId.SearchAndSelfPromoFilterId)) === null || _filterStateStorage_get === void 0 ? void 0 : _filterStateStorage_get.enabled),
            [background_GeneralSettingsOption.ShowBlockedAdsCount]: !background_settingsStorage.get(background_SettingOption.DisableShowPageStats),
            [background_GeneralSettingsOption.AutodetectFilters]: !background_settingsStorage.get(background_SettingOption.DisableDetectFilters),
            [background_GeneralSettingsOption.SafebrowsingEnabled]: !background_settingsStorage.get(background_SettingOption.DisableSafebrowsing),
            [background_GeneralSettingsOption.FiltersUpdatePeriod]: background_settingsStorage.get(background_SettingOption.FiltersUpdatePeriod),
            [background_GeneralSettingsOption.AppearanceTheme]: background_settingsStorage.get(background_SettingOption.AppearanceTheme)
        };
    }
    /**
     * Imports extension specific settings from object of {@link ExtensionSpecificSettingsConfig}.
     */ static importExtensionSpecificSettings({ [background_ExtensionSpecificSettingsOption.UseOptimizedFilters]: useOptimizedFilters, [background_ExtensionSpecificSettingsOption.CollectHitsCount]: collectHitsCount, [background_ExtensionSpecificSettingsOption.ShowContextMenu]: showContextMenu, [background_ExtensionSpecificSettingsOption.ShowInfoAboutAdguard]: showInfoAboutAdguard, [background_ExtensionSpecificSettingsOption.ShowAppUpdatedInfo]: showAppUpdatedInfo, [background_ExtensionSpecificSettingsOption.HideRateAdguard]: hideRateAdguard, [background_ExtensionSpecificSettingsOption.UserRulesEditorWrap]: userRulesEditorWrap }) {
        background_settingsStorage.set(background_SettingOption.UseOptimizedFilters, useOptimizedFilters);
        background_settingsStorage.set(background_SettingOption.DisableCollectHits, !collectHitsCount);
        background_settingsStorage.set(background_SettingOption.DisableShowContextMenu, !showContextMenu);
        background_settingsStorage.set(background_SettingOption.DisableShowAdguardPromoInfo, !showInfoAboutAdguard);
        background_settingsStorage.set(background_SettingOption.DisableShowAppUpdatedNotification, !showAppUpdatedInfo);
        background_settingsStorage.set(background_SettingOption.HideRateBlock, hideRateAdguard);
        background_settingsStorage.set(background_SettingOption.UserRulesEditorWrap, userRulesEditorWrap);
    }
    /**
     * Exports extension specific settings to object of {@link ExtensionSpecificSettingsConfig}.
     *
     * @returns Object of {@link ExtensionSpecificSettingsConfig}.
     */ static exportExtensionSpecificSettings() {
        return {
            [background_ExtensionSpecificSettingsOption.UseOptimizedFilters]: background_settingsStorage.get(background_SettingOption.UseOptimizedFilters),
            [background_ExtensionSpecificSettingsOption.CollectHitsCount]: !background_settingsStorage.get(background_SettingOption.DisableCollectHits),
            [background_ExtensionSpecificSettingsOption.ShowContextMenu]: !background_settingsStorage.get(background_SettingOption.DisableShowContextMenu),
            [background_ExtensionSpecificSettingsOption.ShowInfoAboutAdguard]: !background_settingsStorage.get(background_SettingOption.DisableShowAdguardPromoInfo),
            [background_ExtensionSpecificSettingsOption.ShowAppUpdatedInfo]: !background_settingsStorage.get(background_SettingOption.DisableShowAppUpdatedNotification),
            [background_ExtensionSpecificSettingsOption.HideRateAdguard]: background_settingsStorage.get(background_SettingOption.HideRateBlock),
            [background_ExtensionSpecificSettingsOption.UserRulesEditorWrap]: background_settingsStorage.get(background_SettingOption.UserRulesEditorWrap)
        };
    }
    /**
     * Loads built-in filters and enables them.
     *
     * Firstly, tries to load filters from the backend:
     * - if loaded successfully, enables them;
     * - if loading fails, returns the array of filters that were not loaded
     *   to try to load them from the local storage later.
     *
     * @param filterIds Array of built-in filters ids.
     *
     * @returns Array of filters that were not loaded from the backend.
     *
     * @private
     */ static async loadBuiltInFiltersRemote(filterIds) {
        const failedFilterIds = [];
        const filterIdsToEnable = [];
        const tasks = filterIds.map(async (filterId)=>{
            try {
                // eslint-disable-next-line no-await-in-loop
                await background_CommonFilterApi.loadFilterRulesFromBackend({
                    filterId,
                    ignorePatches: true
                }, true);
                filterIdsToEnable.push(filterId);
            } catch (e) {
                background_logger_logger.debug(`Filter rules were not loaded from backend for filter: ${filterId}, error: ${e}`);
                failedFilterIds.push(filterId);
            }
        });
        const promises = await Promise.allSettled(tasks);
        // Handles errors
        promises.forEach((promise)=>{
            if (promise.status === 'rejected') {
                background_logger_logger.error(promise.reason);
            }
        });
        background_filterStateStorage.enableFilters(filterIdsToEnable);
        return failedFilterIds;
    }
    /**
     * Loads built-in filters from the local storage, and enables them.
     *
     * @param filterIds Ids of filters to load and enable.
     *
     * @private
     */ static async loadBuiltInFiltersLocal(filterIds) {
        const tasks = filterIds.map(async (filterId)=>{
            await background_CommonFilterApi.loadFilterRulesFromBackend({
                filterId,
                ignorePatches: true
            }, false);
        });
        const promises = await Promise.allSettled(tasks);
        background_filterStateStorage.enableFilters(filterIds);
        // Handles errors
        promises.forEach((promise)=>{
            if (promise.status === 'rejected') {
                background_logger_logger.error(promise.reason);
            }
        });
    }
    /**
     * Loads built-in filters and enables them **for MV2**.
     * Firstly, tries to load filters from the backend, if it fails, tries to load them from the embedded.
     *
     * @param builtInFilters Array of built-in filters ids.
     *
     * @private
     */ static async loadBuiltInFiltersMv2(builtInFilters) {
        const remoteFailedFilterIds = await background_SettingsApi.loadBuiltInFiltersRemote(builtInFilters);
        if (remoteFailedFilterIds.length === 0) {
            return;
        }
        const filterIdsToLoadLocal = [];
        const filterIdsWithNoLocalCopy = [];
        remoteFailedFilterIds.forEach((filterId)=>{
            if (background_network.isFilterHasLocalCopy(filterId)) {
                filterIdsToLoadLocal.push(filterId);
            } else {
                filterIdsWithNoLocalCopy.push(filterId);
            }
        });
        if (filterIdsWithNoLocalCopy.length > 0) {
            throw new Error(`There is no local copy of filters with ids: ${filterIdsWithNoLocalCopy.join(', ')}`);
        }
        background_logger_logger.debug(`Trying to load from storage filters with ids: ${filterIdsToLoadLocal.join(', ')}`);
        await background_SettingsApi.loadBuiltInFiltersLocal(filterIdsToLoadLocal);
    }
    /**
     * Loads built-in filters and enables them **for MV3**.
     *
     * Checks whether the filter is supported by MV3.
     * Tries to load them from the storage only.
     *
     * @param builtInFilters Array of built-in filters ids.
     *
     * @private
     */ static async loadBuiltInFiltersMv3(builtInFilters) {
        const filtersToLoad = [];
        builtInFilters.forEach((filterId)=>{
            if (background_CommonFilterApi.isMv3Supported(filterId)) {
                filtersToLoad.push(filterId);
            } else {
                background_logger_logger.debug(`MV3 extension does not support filter with id ${filterId}`);
            }
        });
        await background_SettingsApi.loadBuiltInFiltersLocal(filtersToLoad);
    }
    /**
     * Imports filters settings from object of {@link FiltersConfig}.
     */ static async importFilters({ [background_FiltersOption.EnabledFilters]: enabledFilters, [background_FiltersOption.EnabledGroups]: enabledGroups, [background_FiltersOption.CustomFilters]: customFilters, [background_FiltersOption.UserFilter]: userFilter, [background_FiltersOption.Allowlist]: allowlist }) {
        await background_SettingsApi.importUserFilter(userFilter);
        background_SettingsApi.importAllowlist(allowlist);
        const builtInFilters = enabledFilters.filter((filterId)=>background_CommonFilterApi.isCommonFilter(filterId));
        if (true) {
            await background_SettingsApi.loadBuiltInFiltersMv3(builtInFilters);
        // TODO: Uncomment this block when Quick Fixes filter will be supported for MV3
        // forcibly enable Quick Fixes filter on import for MV3
        // because it is a must-have filter
        // await QuickFixesRulesApi.loadAndEnableQuickFixesRules();
        } else {}
        // TODO: Uncomment this block when custom filters will be supported for MV3.
        // Ignoring custom filters for MV3 since AG-39385.
        if (false) {}
        background_groupStateStorage.enableGroups(enabledGroups);
        background_logger_logger.info(`Import filters: next groups were enabled: ${enabledGroups}`);
        // Disable groups not listed in the imported list.
        const allGroups = background_groupStateStorage.getData();
        const allGroupsIds = Object.keys(allGroups).map((id)=>Number(id));
        const groupIdsToDisable = allGroupsIds.filter((groupId)=>!enabledGroups.includes(groupId));
        // Disable all other groups and mark them as untouched.
        background_groupStateStorage.disableGroups(groupIdsToDisable, false);
    }
    /**
     * Exports filters settings to object of {@link FiltersConfig}.
     *
     * @returns Object of {@link FiltersConfig}.
     */ static async exportFilters() {
        return {
            [background_FiltersOption.EnabledFilters]: background_filterStateStorage.getEnabledFilters(),
            [background_FiltersOption.EnabledGroups]: background_groupStateStorage.getEnabledGroups(),
            [background_FiltersOption.CustomFilters]: background_custom_CustomFilterApi.getFiltersData(),
            [background_FiltersOption.UserFilter]: await background_SettingsApi.exportUserFilter(),
            [background_FiltersOption.Allowlist]: background_SettingsApi.exportAllowlist()
        };
    }
    /**
     * Imports user rules from object of {@link UserFilterConfig}.
     */ static async importUserFilter({ [background_UserFilterOption.Enabled]: enabled, [background_UserFilterOption.Rules]: rulesText }) {
        if (typeof enabled === 'boolean') {
            background_settingsStorage.set(background_SettingOption.UserFilterEnabled, enabled);
        } else {
            background_settingsStorage.set(background_SettingOption.UserFilterEnabled, true);
        }
        await background_UserRulesApi.setUserRules(rulesText);
    }
    /**
     * Exports user rules to object of {@link UserFilterConfig}.
     *
     * @returns Object of {@link UserFilterConfig}.
     */ static async exportUserFilter() {
        return {
            [background_UserFilterOption.Enabled]: background_settingsStorage.get(background_SettingOption.UserFilterEnabled),
            [background_UserFilterOption.Rules]: await background_UserRulesApi.getOriginalUserRules(),
            [background_UserFilterOption.DisabledRules]: ''
        };
    }
    /**
     * Imports extension allowlist from object of {@link AllowlistConfig}.
     */ static importAllowlist({ [background_AllowlistOption.Enabled]: enabled, [background_AllowlistOption.Inverted]: inverted, [background_AllowlistOption.Domains]: domains, [background_AllowlistOption.InvertedDomains]: invertedDomains }) {
        if (typeof enabled === 'boolean') {
            background_settingsStorage.set(background_SettingOption.AllowlistEnabled, enabled);
        } else {
            background_settingsStorage.set(background_SettingOption.AllowlistEnabled, true);
        }
        if (typeof inverted === 'boolean') {
            background_settingsStorage.set(background_SettingOption.DefaultAllowlistMode, !inverted);
        } else {
            background_settingsStorage.set(background_SettingOption.DefaultAllowlistMode, true);
        }
        background_allowlist_AllowlistApi.setAllowlistDomains(domains);
        background_allowlist_AllowlistApi.setInvertedAllowlistDomains(invertedDomains);
    }
    /**
     * Exports extension allowlist to object of {@link AllowlistConfig}.
     *
     * @returns Object of {@link AllowlistConfig}.
     */ static exportAllowlist() {
        return {
            [background_AllowlistOption.Enabled]: background_settingsStorage.get(background_SettingOption.AllowlistEnabled),
            [background_AllowlistOption.Inverted]: !background_settingsStorage.get(background_SettingOption.DefaultAllowlistMode),
            [background_AllowlistOption.Domains]: background_allowlist_AllowlistApi.getAllowlistDomains(),
            [background_AllowlistOption.InvertedDomains]: background_allowlist_AllowlistApi.getInvertedAllowlistDomains()
        };
    }
    /**
     * Imports Tracking protection (formerly Stealth mode) settings from object of {@link StealthConfig}.
     */ static async importStealth({ [background_stealth_StealthOption.DisableStealthMode]: disableStealthMode, [background_stealth_StealthOption.HideReferrer]: hideReferrer, [background_stealth_StealthOption.HideSearchQueries]: hideSearchQueries, [background_stealth_StealthOption.SendDoNotTrack]: sendDoNotTrack, [background_stealth_StealthOption.BlockWebRTC]: blockWebRTC, [background_stealth_StealthOption.RemoveXClientData]: removeXClientData, [background_stealth_StealthOption.SelfDestructThirdPartyCookies]: selfDestructThirdPartyCookies, [background_stealth_StealthOption.SelfDestructThirdPartyCookiesTime]: selfDestructThirdPartyCookiesTime, [background_stealth_StealthOption.SelfDestructFirstPartyCookies]: selfDestructFirstPartyCookies, [background_stealth_StealthOption.SelfDestructFirstPartyCookiesTime]: selfDestructFirstPartyCookiesTime, [background_stealth_StealthOption.BlockKnownTrackers]: blockKnownTrackers, [background_stealth_StealthOption.StripTrackingParams]: stripTrackingParam }) {
        /**
         * Set "block webrtc" setting as soon as possible. AG-9980
         * don't set the actual value to avoid requesting permissions.
         */ if (background_settingsStorage.get(background_SettingOption.BlockWebRTC) !== blockWebRTC) {
            background_settingsStorage.set(background_SettingOption.BlockWebRTC, blockWebRTC);
        }
        background_settingsStorage.set(background_SettingOption.DisableStealthMode, disableStealthMode);
        background_settingsStorage.set(background_SettingOption.HideReferrer, hideReferrer);
        background_settingsStorage.set(background_SettingOption.HideSearchQueries, hideSearchQueries);
        background_settingsStorage.set(background_SettingOption.SendDoNotTrack, sendDoNotTrack);
        background_settingsStorage.set(background_SettingOption.RemoveXClientData, removeXClientData);
        background_settingsStorage.set(background_SettingOption.SelfDestructThirdPartyCookies, selfDestructThirdPartyCookies);
        if (selfDestructThirdPartyCookiesTime) {
            background_settingsStorage.set(background_SettingOption.SelfDestructThirdPartyCookiesTime, selfDestructThirdPartyCookiesTime);
        }
        background_settingsStorage.set(background_SettingOption.SelfDestructFirstPartyCookies, selfDestructFirstPartyCookies);
        if (selfDestructFirstPartyCookiesTime) {
            background_settingsStorage.set(background_SettingOption.SelfDestructFirstPartyCookiesTime, selfDestructFirstPartyCookiesTime);
        }
        if (stripTrackingParam) {
            const remote = !true;
            await background_main_FiltersApi.loadAndEnableFilters([
                background_AntiBannerFiltersId.UrlTrackingFilterId
            ], remote);
        } else {
            background_filterStateStorage.disableFilters([
                background_AntiBannerFiltersId.UrlTrackingFilterId
            ]);
        }
        if (blockKnownTrackers) {
            const remote = !true;
            await background_main_FiltersApi.loadAndEnableFilters([
                background_AntiBannerFiltersId.TrackingFilterId
            ], remote);
        } else {
            background_filterStateStorage.disableFilters([
                background_AntiBannerFiltersId.TrackingFilterId
            ]);
        }
    }
    /**
     * Exports Tracking protection (formerly Stealth mode) settings to object of {@link StealthConfig}.
     *
     * @returns Object of {@link StealthConfig}.
     */ static exportStealth() {
        var _filterStateStorage_get, _filterStateStorage_get1;
        return {
            [background_stealth_StealthOption.DisableStealthMode]: background_settingsStorage.get(background_SettingOption.DisableStealthMode),
            [background_stealth_StealthOption.HideReferrer]: background_settingsStorage.get(background_SettingOption.HideReferrer),
            [background_stealth_StealthOption.HideSearchQueries]: background_settingsStorage.get(background_SettingOption.HideSearchQueries),
            [background_stealth_StealthOption.SendDoNotTrack]: background_settingsStorage.get(background_SettingOption.SendDoNotTrack),
            [background_stealth_StealthOption.BlockWebRTC]: background_settingsStorage.get(background_SettingOption.BlockWebRTC),
            [background_stealth_StealthOption.RemoveXClientData]: background_settingsStorage.get(background_SettingOption.RemoveXClientData),
            [background_stealth_StealthOption.SelfDestructThirdPartyCookies]: background_settingsStorage.get(background_SettingOption.SelfDestructThirdPartyCookies),
            [background_stealth_StealthOption.SelfDestructThirdPartyCookiesTime]: background_settingsStorage.get(background_SettingOption.SelfDestructThirdPartyCookiesTime),
            [background_stealth_StealthOption.SelfDestructFirstPartyCookies]: background_settingsStorage.get(background_SettingOption.SelfDestructFirstPartyCookies),
            [background_stealth_StealthOption.SelfDestructFirstPartyCookiesTime]: background_settingsStorage.get(background_SettingOption.SelfDestructFirstPartyCookiesTime),
            [background_stealth_StealthOption.BlockKnownTrackers]: !!((_filterStateStorage_get = background_filterStateStorage.get(background_AntiBannerFiltersId.TrackingFilterId)) === null || _filterStateStorage_get === void 0 ? void 0 : _filterStateStorage_get.enabled),
            [background_stealth_StealthOption.StripTrackingParams]: !!((_filterStateStorage_get1 = background_filterStateStorage.get(background_AntiBannerFiltersId.UrlTrackingFilterId)) === null || _filterStateStorage_get1 === void 0 ? void 0 : _filterStateStorage_get1.enabled)
        };
    }
}

;// ./Extension/src/background/api/settings/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

;// ./Extension/src/background/api/ui/context-menu.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_ui_context_menu_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}








/**
 * Wrapper around context menus create method.
 * It helps to handle errors thrown by contextMenus.
 *
 * @param props Options for creating menu.
 */ const background_createMenu = (props)=>{
    return new Promise((resolve, reject)=>{
        background_browser_polyfill_default().contextMenus.create(props, ()=>{
            if ((background_browser_polyfill_default()).runtime.lastError) {
                reject((background_browser_polyfill_default()).runtime.lastError);
                return;
            }
            resolve();
        });
    });
};
/**
 * API for creating and updating browser context menus.
 */ class background_ContextMenuApi {
    /**
     * Initializes Context Menu API.
     */ static init() {
        background_settingsEvents.addListener(background_SettingOption.DisableShowContextMenu, background_ContextMenuApi.handleDisableShowContextMenu);
        background_browser_polyfill_default().contextMenus.onClicked.addListener(async (onClickData)=>{
            await background_contextMenuEvents.publishEvent(onClickData.menuItemId);
        });
    }
    /**
     * Updates context menu depends on tab filtering state.
     *
     * @param frameData Frame data from both tswebextension and app state.
     * @param frameData.applicationFilteringDisabled Is app filtering disabled globally.
     * @param frameData.urlFilteringDisabled Is app filtering disabled for current tab.
     * @param frameData.documentAllowlisted Is website allowlisted.
     * @param frameData.userAllowlisted Is current website allowlisted by user rule.
     * @param frameData.canAddRemoveRule Is user rules was applied on current website.
     * @param frameData.url Current tab url.
     */ static async updateMenu({ applicationFilteringDisabled, urlFilteringDisabled, documentAllowlisted, userAllowlisted, canAddRemoveRule, url }) {
        // TODO add better handling for AdGuard for Firefox
        // There is nothing to do if context menu is not supported
        if (!(background_browser_polyfill_default()).contextMenus) {
            return;
        }
        // Clean up context menu just in case.
        await background_ContextMenuApi.removeAll();
        // There is nothing to do if context menu is disabled
        if (background_SettingsApi.getSetting(background_SettingOption.DisableShowContextMenu)) {
            return;
        }
        // Used no to show settings menu item on the options page
        // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2258
        const isOptionsPage = !!(url === null || url === void 0 ? void 0 : url.startsWith(background_browser_polyfill_default().runtime.getURL(background_OPTIONS_PAGE)));
        try {
            if (applicationFilteringDisabled) {
                await background_ContextMenuApi.addFilteringDisabledMenuItems(isOptionsPage);
            } else if (urlFilteringDisabled) {
                await background_ContextMenuApi.addUrlFilteringDisabledContextMenuAction(isOptionsPage);
            } else {
                if (documentAllowlisted && !userAllowlisted) {
                    await background_ContextMenuApi.addMenuItem(background_ContextMenuAction.SiteException);
                } else if (canAddRemoveRule) {
                    if (documentAllowlisted) {
                        await background_ContextMenuApi.addMenuItem(background_ContextMenuAction.SiteFilteringOn);
                    } else {
                        await background_ContextMenuApi.addMenuItem(background_ContextMenuAction.SiteFilteringOff);
                    }
                }
                await background_ContextMenuApi.addSeparator();
                if (!documentAllowlisted) {
                    await background_ContextMenuApi.addMenuItem(background_ContextMenuAction.BlockSiteAds);
                }
                await background_ContextMenuApi.addMenuItem(background_ContextMenuAction.SecurityReport);
                await background_ContextMenuApi.addMenuItem(background_ContextMenuAction.ComplaintWebsite);
                await background_ContextMenuApi.addSeparator();
                if (false) {}
                if (!isOptionsPage) {
                    await background_ContextMenuApi.addMenuItem(background_ContextMenuAction.OpenSettings);
                }
                await background_ContextMenuApi.addMenuItem(background_ContextMenuAction.OpenLog);
                await background_ContextMenuApi.addMenuItem(background_ContextMenuAction.DisableProtection);
            }
        } catch (e) {
        // do nothing
        }
    }
    /**
     * Removes all context menu items.
     *
     * @private
     */ static async removeAll() {
        await background_browser_polyfill_default().contextMenus.removeAll();
    }
    /**
     * Creates menu items for the context menu, displayed, when app filtering disabled globally.
     *
     * @param isOptionsPage Is current page options page.
     */ static async addFilteringDisabledMenuItems(isOptionsPage) {
        await background_ContextMenuApi.addMenuItem(background_ContextMenuAction.SiteProtectionDisabled);
        await background_ContextMenuApi.addSeparator();
        if (false) {}
        if (!isOptionsPage) {
            await background_ContextMenuApi.addMenuItem(background_ContextMenuAction.OpenSettings);
        }
        await background_ContextMenuApi.addMenuItem(background_ContextMenuAction.EnableProtection);
    }
    /**
     * Creates menu items for the context menu, displayed, when app filtering disabled for current tab.
     *
     * @param isOptionsPage Is current page options page.
     */ static async addUrlFilteringDisabledContextMenuAction(isOptionsPage) {
        // Disabled because it's just informational inactive button
        await background_ContextMenuApi.addMenuItem(background_ContextMenuAction.SiteFilteringDisabled, {
            enabled: false
        });
        await background_ContextMenuApi.addSeparator();
        if (false) {}
        if (!isOptionsPage) {
            await background_ContextMenuApi.addMenuItem(background_ContextMenuAction.OpenSettings);
        }
        if (false) {}
    }
    /**
     * Creates menu item for context menu.
     *
     * @param action Context menu action key.
     * @param options {@link browser.contextMenus.create} Options.
     */ static async addMenuItem(action, options = {}) {
        const { messageArgs, ...rest } = options;
        await background_createMenu({
            id: action,
            contexts: [
                'all'
            ],
            title: background_translator.getMessage(action, messageArgs),
            ...rest
        });
    }
    /**
     * Creates menu separator.
     */ static async addSeparator() {
        await background_createMenu({
            id: background_nanoid(),
            type: 'separator',
            contexts: [
                'all'
            ]
        });
    }
    /**
     * Handles changes of disable context menu setting.
     *
     * @param disable Boolean flag where true means context menu is disabled.
     */ static async handleDisableShowContextMenu(disable) {
        // handle only disable menu, anyway user switch tab button, after enabling
        if (disable) {
            await background_ContextMenuApi.removeAll();
        }
    }
}
/**
     * Throttled updateMenu.
     * Used in because updateMenu can be called multiple times from various event listeners, but
     * context menu doesn't require fast update.
     */ background_ui_context_menu_define_property(background_ContextMenuApi, "throttledUpdateMenu", background_lodash_es_throttle(background_ContextMenuApi.updateMenu, 100));

;// ./Extension/src/background/api/page-stats/page-stats.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 






/**
 * Supported popup stats categories.
 */ var background_PopupStatsCategories = /*#__PURE__*/ function(PopupStatsCategories) {
    PopupStatsCategories["Advertising"] = "Advertising";
    PopupStatsCategories["Trackers"] = "Trackers";
    PopupStatsCategories["SocialMedia"] = "SocialMedia";
    PopupStatsCategories["Cdn"] = "Cdn";
    PopupStatsCategories["Other"] = "Other";
    return PopupStatsCategories;
}({});
/**
 * Categories from companiesdb.
 *
 * @see {@link https://github.com/AdguardTeam/companiesdb/blob/a49d8ce239e240bab2dce94c6b9cc2442a61cdfd/source/trackers.json#L3-L21}
 */ var background_CompaniesDbCategories = /*#__PURE__*/ function(CompaniesDbCategories) {
    CompaniesDbCategories["AudioVideoPlayer"] = "audio_video_player";
    CompaniesDbCategories["Comments"] = "comments";
    CompaniesDbCategories["CustomerInteraction"] = "customer_interaction";
    CompaniesDbCategories["Pornvertising"] = "pornvertising";
    CompaniesDbCategories["Advertising"] = "advertising";
    CompaniesDbCategories["Essential"] = "essential";
    CompaniesDbCategories["SiteAnalytics"] = "site_analytics";
    CompaniesDbCategories["SocialMedia"] = "social_media";
    CompaniesDbCategories["Misc"] = "misc";
    CompaniesDbCategories["Cdn"] = "cdn";
    CompaniesDbCategories["Hosting"] = "hosting";
    CompaniesDbCategories["Unknown"] = "unknown";
    CompaniesDbCategories["Extensions"] = "extensions";
    CompaniesDbCategories["Email"] = "email";
    CompaniesDbCategories["Consent"] = "consent";
    CompaniesDbCategories["Telemetry"] = "telemetry";
    CompaniesDbCategories["MobileAnalytics"] = "mobile_analytics";
    return CompaniesDbCategories;
}(background_CompaniesDbCategories || {});
/**
 * Map of corresponding categories between companiesdb categories and popup stats categories.
 *
 * The same categories are used in the DNS (check comments in AG-33728).
 */ const background_CompaniesDbCategoriesMap = {
    ["audio_video_player"]: "Other",
    ["comments"]: "Other",
    ["customer_interaction"]: "Other",
    ["pornvertising"]: "Advertising",
    ["advertising"]: "Advertising",
    ["essential"]: "Other",
    ["site_analytics"]: "Trackers",
    ["social_media"]: "SocialMedia",
    ["misc"]: "Other",
    ["cdn"]: "Cdn",
    ["hosting"]: "Other",
    ["unknown"]: "Other",
    ["extensions"]: "Other",
    ["email"]: "Other",
    ["consent"]: "Other",
    ["telemetry"]: "Other",
    ["mobile_analytics"]: "Trackers"
};
/**
 * Page Stats API is responsible for storing statistics of blocked requests.
 *
 * Based on companiesdb data.
 */ class background_PageStatsApi {
    /**
     * Initializes page stats storage,
     * initializes companiesDbService, and validates the service data.
     */ static async init() {
        try {
            const storageData = await background_pageStatsStorage.read();
            if (typeof storageData === 'string') {
                const data = background_pageStatsValidator.parse(JSON.parse(storageData));
                background_pageStatsStorage.setCache(data);
            } else {
                background_pageStatsStorage.setData({});
            }
        } catch (e) {
            background_logger_logger.warn(`Cannot parse data from "${background_pageStatsStorage.key}" storage, set default states. Origin error: `, e);
            background_pageStatsStorage.setData({});
        }
        background_PageStatsApi.validateCategoriesData();
    }
    /**
     * Returns total count of blocked requests.
     *
     * @returns Total count of blocked requests.
     */ static getTotalBlocked() {
        return background_pageStatsStorage.getTotalBlocked() || 0;
    }
    /**
     * Increment total count of blocked requests.
     *
     * @param value Increment value.
     *
     * @returns Incremented total blocked value.
     */ static incrementTotalBlocked(value) {
        let totalBlocked = background_PageStatsApi.getTotalBlocked();
        totalBlocked += value;
        background_pageStatsStorage.setTotalBlocked(totalBlocked);
        return totalBlocked;
    }
    /**
     * Resets stats.
     */ static async reset() {
        await background_pageStatsStorage.setData({});
    }
    /**
     * Validates categories data from companiesDbService.
     *
     * @throws Error if categories data is invalid.
     */ static validateCategoriesData() {
        let rawCategoriesData = null;
        try {
            rawCategoriesData = background_companiesDbService.getCompaniesDbCategories();
        } catch (e) {
            background_logger_logger.warn('Cannot load categories data from companiesDbService. Origin error: ', e);
        }
        if (!rawCategoriesData) {
            throw new Error('Cannot load categories data from companiesDbService');
        }
        const categoryIds = Object.values(rawCategoriesData);
        if (categoryIds.length === 0) {
            throw new Error('companiesDbService returned empty categories');
        }
        const unknownCompaniesDbCategoryIds = Object.values(background_CompaniesDbCategories).filter((id)=>!categoryIds.includes(id));
        if (unknownCompaniesDbCategoryIds.length > 0) {
            throw new Error(`companiesDbService returned unrecognizable category ids: ${unknownCompaniesDbCategoryIds.join(', ')}`);
        }
    }
    /**
     * Updates stats data.
     *
     * We store last 24 hours, 30 days and all past months stats.
     *
     * @param companyCategoryId Category id.
     * @param blocked Count of blocked requests.
     *
     * @returns Promise which resolves when stats are updated.
     */ static async updateStats(companyCategoryId, blocked) {
        let statsCategoryId = background_CompaniesDbCategoriesMap[companyCategoryId];
        if (typeof statsCategoryId === 'undefined') {
            background_logger_logger.debug(`Not mapped category id: ${companyCategoryId}, set to "Other"`);
            statsCategoryId = "Other";
        }
        const stats = background_pageStatsStorage.getStatisticsData();
        if (stats) {
            const updated = background_PageStatsStorage.updateStatsData(statsCategoryId, blocked, stats);
            return background_pageStatsStorage.setStatisticsData(updated);
        }
        const created = background_PageStatsStorage.createStatsData(statsCategoryId, blocked);
        await background_pageStatsStorage.setStatisticsData(created);
    }
    /**
     * Returns page stats and groups data from storages for popup statistics section.
     *
     * @returns Full statistics data record.
     */ static getStatisticsData() {
        const stats = background_pageStatsStorage.getStatisticsData();
        return {
            today: stats.hours,
            lastWeek: stats.days.slice(-7),
            lastMonth: stats.days.slice(-30),
            lastYear: stats.months.slice(-12),
            overall: stats.months,
            blockedCategories: background_PageStatsApi.getGroups()
        };
    }
    /**
     * Returns categories data
     * with a _total_ category for combined popup statistics.
     *
     * @returns Categories data.
     */ static getGroups() {
        return [
            {
                categoryId: background_PageStatsStorage.TOTAL_GROUP_ID,
                categoryName: background_translator.getMessage('popup_statistics_all_categories')
            },
            {
                categoryId: "Advertising",
                categoryName: background_translator.getMessage('popup_statistics_category_advertising')
            },
            {
                categoryId: "Trackers",
                categoryName: background_translator.getMessage('popup_statistics_category_trackers')
            },
            {
                categoryId: "SocialMedia",
                categoryName: background_translator.getMessage('popup_statistics_category_social_media')
            },
            {
                categoryId: "Cdn",
                categoryName: background_translator.getMessage('popup_statistics_category_cdn')
            },
            {
                categoryId: "Other",
                categoryName: background_translator.getMessage('popup_statistics_category_other')
            }
        ];
    }
}

;// ./Extension/src/background/api/page-stats/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

;// ./Extension/src/background/api/ui/frames.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 





/**
 * Helper class for retrieving main frame data from both tswebextension and app state.
 */ class background_FramesApi {
    /**
     * Tries to find the main frame data for the provided tab context
     * and returns it.
     *
     * @param tabContext Tab context.
     * @param tabContext.info Tab's context information from webextension tabs API.
     * @param tabContext.frames Tab's context frames.
     * @param tabContext.blockedRequestCount Tab's context blocked request count.
     * @param tabContext.mainFrameRule Tab's context document level rule.
     *
     * @returns The {@link FrameData} object can be partially empty if no frames
     * were found for a given tab context.
     */ static getMainFrameData({ info, frames, blockedRequestCount, mainFrameRule }) {
        const mainFrame = frames.get(background_MAIN_FRAME_ID);
        const url = (info === null || info === void 0 ? void 0 : info.url) || (mainFrame === null || mainFrame === void 0 ? void 0 : mainFrame.url) || null;
        const domainName = url ? background_getDomain(url) : null;
        const urlFilteringDisabled = !url || !background_isHttpRequest(url);
        const isFilteringPossible = background_appContext.get(background_AppContextKey.IsInit) && !urlFilteringDisabled;
        let frameRule = null;
        let documentAllowlisted = false;
        let userAllowlisted = false;
        let canAddRemoveRule = false;
        const totalBlocked = background_PageStatsApi.getTotalBlocked();
        const totalBlockedTab = blockedRequestCount;
        const applicationFilteringDisabled = background_SettingsApi.getSetting(background_SettingOption.DisableFiltering);
        if (isFilteringPossible) {
            documentAllowlisted = !!mainFrameRule && mainFrameRule.isFilteringDisabled();
            if (documentAllowlisted && mainFrameRule) {
                const filterId = mainFrameRule.getFilterListId();
                userAllowlisted = filterId === background_AntiBannerFiltersId.UserFilterId || filterId === background_AntiBannerFiltersId.AllowlistFilterId;
                frameRule = {
                    filterId,
                    ruleText: mainFrameRule.getText()
                };
            }
            // It means site in exception
            canAddRemoveRule = !(documentAllowlisted && !userAllowlisted);
        }
        return {
            url,
            isFilteringPossible,
            domainName,
            applicationFilteringDisabled,
            urlFilteringDisabled,
            documentAllowlisted,
            userAllowlisted,
            canAddRemoveRule,
            frameRule,
            totalBlockedTab,
            totalBlocked
        };
    }
}

;// ./Extension/src/background/api/ui/main.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_ui_main_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}








/**
 * The UI API provides a singleton to update the tab icon and the counters of
 * blocked requests on the tab.
 */ class background_UiApi {
    /**
     * Initializes UI service.
     */ static async init() {
        await background_iconsApi.init();
    }
    /**
     * Updates the UI on the provided tab.
     *
     * @param tabContext Updated {@link TabContext}.
     */ static async update(tabContext) {
        const frameData = background_FramesApi.getMainFrameData(tabContext);
        await background_ContextMenuApi.throttledUpdateMenu(frameData);
        const tabId = tabContext.info.id;
        background_UiApi.throttledUpdateAction(tabId, frameData);
    }
    /**
     * Handles promo notification being viewed.
     */ static async dismissPromo() {
        let frameData;
        const tab = await background_TabsApi.getActive();
        const tabId = tab === null || tab === void 0 ? void 0 : tab.id;
        if (tabId) {
            const tabContext = background_tabsApi.getTabContext(tabId);
            if (tabContext) {
                frameData = background_FramesApi.getMainFrameData(tabContext);
            }
        }
        await background_iconsApi.dismissPromoIcon(tabId, frameData);
    }
    /**
     * Sends message with updated counters of blocked requests.
     *
     * @param tabId Tab's id.
     * @param frameData Broadcasted {@link FrameData}.
     * @param frameData.totalBlocked Total count of blocked requests.
     * @param frameData.totalBlockedTab Number of blocked requests.
     */ static async broadcastTotalBlockedMessage(tabId, frameData) {
        const { totalBlocked, totalBlockedTab } = frameData;
        try {
            await background_sendMessage({
                type: background_constants_MessageType.UpdateTotalBlocked,
                data: {
                    tabId,
                    totalBlocked,
                    totalBlockedTab
                }
            });
        } catch (e) {
            background_logger_logger.info('Failed to broadcast total blocked message:', e);
        }
    }
}
/**
     * Throttle to update tab's information.
     */ background_ui_main_define_property(background_UiApi, "THROTTLE_DELAY_MS", 100);
/**
     * Updates the tab action icon and the blocked requests counter
     * on the provided tab with throttle {@link UiApi.THROTTLE_DELAY_MS}.
     *
     * @param tabId Tab's id.
     * @param frameData The {@link FrameData} object.
     */ background_ui_main_define_property(background_UiApi, "throttledUpdateAction", background_lodash_es_throttle((tabId, frameData)=>{
    background_iconsApi.updateTabAction(tabId, frameData);
    background_UiApi.broadcastTotalBlockedMessage(tabId, frameData);
}, background_UiApi.THROTTLE_DELAY_MS));

;// ./Extension/src/background/api/ui/promo-notification.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_promo_notification_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}









/**
 * Promo notification API is needed to work with notifications.
 */ class background_PromoNotificationApi {
    /**
     * Scans notifications list and prepares them to be used (or removes expired).
     */ init() {
        background_notificationStorage.forEach((notification, notificationKey, map)=>{
            notification.text = background_PromoNotificationApi.getNotificationText(notification) || null;
            const to = new Date(notification.to).getTime();
            const expired = new Date().getTime() > to;
            if (!notification.text || expired) {
                // Remove expired and invalid
                map.delete(notificationKey);
            }
        });
        this.isInit = true;
    }
    /**
     * Marks current notification as viewed.
     *
     * @param withDelay If true, do this after a 30 sec delay.
     */ async setNotificationViewed(withDelay) {
        if (!this.currentNotification) {
            return;
        }
        if (withDelay) {
            clearTimeout(this.timeoutId);
            // eslint-disable-next-line no-restricted-globals
            this.timeoutId = self.setTimeout(()=>{
                this.setNotificationViewed(false);
            }, background_PromoNotificationApi.DELAY_MS);
            return;
        }
        const { id } = this.currentNotification;
        const viewedNotifications = await background_browserStorage.get(background_VIEWED_NOTIFICATIONS_KEY) || [];
        if (Array.isArray(viewedNotifications) && !viewedNotifications.includes(id)) {
            viewedNotifications.push(id);
            await background_browserStorage.set(background_VIEWED_NOTIFICATIONS_KEY, viewedNotifications);
            this.currentNotification = null;
            await background_UiApi.dismissPromo();
        }
    }
    /**
     * Finds out notification for current time and checks if notification wasn't shown yet.
     *
     * @returns Promo notification object or null if there is no promo notification to show.
     */ async getCurrentNotification() {
        // Do not display notification on Firefox
        if (background_UserAgent.isFirefox) {
            return null;
        }
        // Do not display notification before initialization
        if (!this.isInit) {
            return null;
        }
        const currentTime = Date.now();
        const timeSinceLastNotification = currentTime - await background_PromoNotificationApi.getLastNotificationTime();
        //  Do not show notification too often
        if (timeSinceLastNotification < background_PromoNotificationApi.MIN_PERIOD_MS) {
            return null;
        }
        // Check no more than every 10 minutes
        const timeSinceLastCheck = currentTime - this.notificationCheckTime;
        if (this.notificationCheckTime > 0 && timeSinceLastCheck <= background_PromoNotificationApi.CHECK_TIMEOUT_MS) {
            return this.currentNotification;
        }
        // Update the last notification check time
        this.notificationCheckTime = currentTime;
        const notificationsValues = Array.from(background_notificationStorage.values());
        const viewedNotifications = await background_browserStorage.get(background_VIEWED_NOTIFICATIONS_KEY) || [];
        for(let i = 0; i < notificationsValues.length; i += 1){
            const notification = notificationsValues[i];
            if (!notification) {
                continue;
            }
            const from = new Date(notification.from).getTime();
            const to = new Date(notification.to).getTime();
            if (from < currentTime && to > currentTime && Array.isArray(viewedNotifications) && !viewedNotifications.includes(notification.id)) {
                this.currentNotification = notification;
                return this.currentNotification;
            }
        }
        this.currentNotification = null;
        return this.currentNotification;
    }
    /**
     * Handles Spanish locale codes:
     * - for non-Spanish locales, returns the same code;
     * - for Latin American Spanish, e.g. 'es_mx', returns 'es_419';
     * - for Spain Spanish, e.g. 'es_es', returns 'es'.
     *
     * @param normalizedLocale Normalized locale code.
     *
     * @returns Normalized locale code.
     */ static handleSpanishLocale(normalizedLocale) {
        const GENERAL_SPANISH_NORMALIZED_CODE = 'es';
        const SPAIN_SPANISH_NORMALIZED_CODE = 'es_es';
        const LATIN_AMERICAN_SPANISH_NORMALIZED_CODE = 'es_419';
        if (!normalizedLocale.startsWith(GENERAL_SPANISH_NORMALIZED_CODE)) {
            return normalizedLocale;
        }
        if (normalizedLocale === GENERAL_SPANISH_NORMALIZED_CODE || normalizedLocale === SPAIN_SPANISH_NORMALIZED_CODE) {
            return GENERAL_SPANISH_NORMALIZED_CODE;
        }
        return LATIN_AMERICAN_SPANISH_NORMALIZED_CODE;
    }
    /**
     * Handles Serbian locale codes:
     * - for non-Serbian locales, returns the same code;
     * - for any Serbian, e.g. 'sr', 'sr_latn', 'sr_cyrl_rs', returns 'sr_latn'.
     *
     * @param normalizedLocale Normalized locale code.
     *
     * @returns Normalized locale code.
     */ static handleSerbianLocale(normalizedLocale) {
        const GENERAL_SERBIAN_LOCALE = 'sr';
        const GENERAL_SERBIAN_LATIN_LOCALE = 'sr_latn';
        if (normalizedLocale.startsWith(GENERAL_SERBIAN_LOCALE)) {
            return GENERAL_SERBIAN_LATIN_LOCALE;
        }
        return normalizedLocale;
    }
    /**
     * Scans notification locales and returns the one matching navigator.language.
     *
     * @param notification Promo notification object.
     *
     * @returns {NotificationTextRecord | undefined} Matching notification text settings or undefined.
     */ static getNotificationText(notification) {
        let language = background_I18n.normalizeLanguageCode(background_browser_polyfill_default().i18n.getUILanguage());
        if (!language) {
            return;
        }
        language = background_PromoNotificationApi.handleSpanishLocale(language);
        language = background_PromoNotificationApi.handleSerbianLocale(language);
        const languageCode = language.split('_')[0];
        if (!languageCode) {
            return;
        }
        return notification.locales[language] || notification.locales[languageCode];
    }
    /**
     * Returns the last time a notification was shown.
     * If it was not shown yet, initialized with the current time.
     *
     * @returns Last notification time.
     */ static async getLastNotificationTime() {
        let lastTime = Number(await background_browserStorage.get(background_LAST_NOTIFICATION_TIME_KEY) || 0);
        if (lastTime === 0) {
            lastTime = Date.now();
            await background_browserStorage.set(background_LAST_NOTIFICATION_TIME_KEY, lastTime);
        }
        return lastTime;
    }
    constructor(){
        background_promo_notification_define_property(this, "currentNotification", null);
        background_promo_notification_define_property(this, "notificationCheckTime", 0);
        background_promo_notification_define_property(this, "timeoutId", undefined);
        background_promo_notification_define_property(this, "isInit", false);
    }
}
background_promo_notification_define_property(background_PromoNotificationApi, "CHECK_TIMEOUT_MS", 10 * 60 * 1000) // 10 minutes
;
background_promo_notification_define_property(background_PromoNotificationApi, "MIN_PERIOD_MS", 30 * 60 * 1000) // 30 minutes
;
background_promo_notification_define_property(background_PromoNotificationApi, "DELAY_MS", 30 * 1000) // clear notification in 30 seconds
;
const background_promoNotificationApi = new background_PromoNotificationApi();

;// ./Extension/src/background/api/ui/browser-action.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
const background_browserAction =  true ? (background_browser_polyfill_default()).action : 0;

;// ./Extension/src/background/api/ui/icons.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_icons_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}








const background_defaultIconVariants = {
    enabled: {
        '19': background_browser_polyfill_default().runtime.getURL('assets/icons/on-19.png'),
        '38': background_browser_polyfill_default().runtime.getURL('assets/icons/on-38.png')
    },
    disabled: {
        '19': background_browser_polyfill_default().runtime.getURL('assets/icons/off-19.png'),
        '38': background_browser_polyfill_default().runtime.getURL('assets/icons/off-38.png')
    },
    warning: {
        '19': background_browser_polyfill_default().runtime.getURL('assets/icons/warning-19.png'),
        '38': background_browser_polyfill_default().runtime.getURL('assets/icons/warning-38.png')
    }
};
/**
 * The Icons API is responsible for managing the extension's action state.
 */ class background_IconsApi {
    /**
     * Initializes Icons API.
     */ async init() {
        var _this_promoIcons;
        await this.setPromoIconIfAny();
        if ((_this_promoIcons = this.promoIcons) === null || _this_promoIcons === void 0 ? void 0 : _this_promoIcons.enabled) {
            // Pre-set promo icon to avoid flicker on tabs change
            await this.update();
        }
    }
    /**
     * Updates the icon state.
     */ async update() {
        const icon = await this.pickIconVariant();
        // Update all tabs icons
        const allTabs = await background_browser_polyfill_default().tabs.query({});
        const results = await Promise.allSettled(allTabs.map(async (tab)=>{
            if (tab.id) {
                await background_IconsApi.setActionIcon(icon, tab.id);
            }
        }));
        // Log any failures for debugging
        results.forEach((result, index)=>{
            if (result.status === 'rejected') {
                var _allTabs_index;
                background_logger_logger.debug(`Failed to update icon for tab ${(_allTabs_index = allTabs[index]) === null || _allTabs_index === void 0 ? void 0 : _allTabs_index.id}:`, result.reason);
            }
        });
    }
    /**
     * Updates current extension icon for specified tab.
     *
     * @param tabId Tab's id.
     * @param frameData The information from {@link FrameData} is needed
     * to estimate the current status of the background extension
     * in the specified tab.
     */ async updateTabAction(tabId, frameData) {
        try {
            await this.resetPromoIconIfAny(tabId, frameData);
        } catch  {}
        const { documentAllowlisted, applicationFilteringDisabled, totalBlockedTab } = frameData;
        const isDisabled = documentAllowlisted || applicationFilteringDisabled;
        // Determine extension's action new state based on the current tab state
        const icon = await this.pickIconVariant(isDisabled);
        const badgeText = background_IconsApi.getBadgeText(totalBlockedTab, isDisabled);
        try {
            await background_IconsApi.setActionIcon(icon, tabId);
            if (badgeText.length !== 0) {
                await background_browserAction.setBadgeBackgroundColor({
                    color: this.BADGE_COLOR
                });
                await background_browserAction.setBadgeText({
                    tabId,
                    text: badgeText
                });
            }
        } catch (e) {
            background_logger_logger.info('Failed to update tab icon:', e);
        }
    }
    /**
     * Cleans up the promo icon variants. If the current tab action data is provided,
     * updates the icon for the current tab.
     *
     * @param tabId Tab's id.
     * @param frameData Tab's {@link FrameData}.
     */ async dismissPromoIcon(tabId, frameData) {
        this.setPromoIcons(null);
        const icon = await this.pickIconVariant();
        // Get rid of promo icon on all tabs, this prevents icon flickering on tab change
        await background_IconsApi.setActionIcon(icon);
        // Update current tab action
        if (tabId && frameData) {
            const isDisabled = frameData.documentAllowlisted || frameData.applicationFilteringDisabled;
            const disabledIcon = await this.pickIconVariant(isDisabled);
            await background_IconsApi.setActionIcon(disabledIcon, tabId);
        }
    }
    /**
     * Sets the icon for the extension action.
     *
     * @param icon Icon to set.
     * @param tabId Tab's id, if not specified, the icon will be set for all tabs.
     */ static async setActionIcon(icon, tabId) {
        await background_browserAction.setIcon({
            imageData: await background_getIconImageData(icon),
            tabId
        });
    }
    /**
     * Picks the icon variant based on the current tab state.
     * Fallbacks to default icon variants if the current icon variants are not provided.
     *
     * @param isDisabled Is website allowlisted or app filtering disabled.
     *
     * @returns Icon variant to display.
     */ async pickIconVariant(isDisabled = false) {
        var _this_promoIcons, _this_promoIcons1;
        const isMv3LimitsExceeded =  true ? await background_RulesLimitsService.areFilterLimitsExceeded() : 0;
        if (isMv3LimitsExceeded) {
            return background_defaultIconVariants.warning;
        }
        return isDisabled ? ((_this_promoIcons = this.promoIcons) === null || _this_promoIcons === void 0 ? void 0 : _this_promoIcons.disabled) || background_defaultIconVariants.disabled : ((_this_promoIcons1 = this.promoIcons) === null || _this_promoIcons1 === void 0 ? void 0 : _this_promoIcons1.enabled) || background_defaultIconVariants.enabled;
    }
    /**
     * Calculates the badge text based on the current tab state.
     *
     * @param totalBlockedTab Number of blocked requests.
     * @param isDisabled Is website allowlisted or app filtering disabled.
     *
     * @returns Badge text to display.
     */ static getBadgeText(totalBlockedTab, isDisabled) {
        let totalBlocked;
        if (!isDisabled && !background_settingsStorage.get(background_SettingOption.DisableShowPageStats)) {
            totalBlocked = totalBlockedTab;
        } else {
            totalBlocked = 0;
        }
        if (totalBlocked === 0) {
            return '';
        }
        if (totalBlocked > 99) {
            return '\u221E'; // infinity symbol
        }
        return String(totalBlocked);
    }
    /**
     * Sets the promo icon variants.
     *
     * @param iconVariants Icon variants to set.
     */ setPromoIcons(iconVariants) {
        this.promoIcons = iconVariants;
    }
    /**
     * If promo icons variants are not set,
     * fetches icon variants from the promo notification api (if any),
     * otherwise does nothing.
     */ async setPromoIconIfAny() {
        if (this.promoIcons) {
            return;
        }
        const notification = await background_promoNotificationApi.getCurrentNotification();
        if (notification && notification.icons) {
            this.setPromoIcons(notification.icons);
        }
    }
    /**
     * Always fetches icon variants from the promo notification api,
     * and sets the promo icons if any,
     * otherwise promo icon is dismissed.
     *
     * @param tabId Tab's id.
     * @param frameData Tab's {@link FrameData}.
     */ async resetPromoIconIfAny(tabId, frameData) {
        const notification = await background_promoNotificationApi.getCurrentNotification();
        if (notification && notification.icons) {
            this.setPromoIcons(notification.icons);
        } else {
            await this.dismissPromoIcon(tabId, frameData);
        }
    }
    constructor(){
        /**
     * Badge background color.
     */ background_icons_define_property(this, "BADGE_COLOR", '#555');
        /**
     * Icon variants for the promo notification, if any is available.
     */ background_icons_define_property(this, "promoIcons", null);
    }
}
const background_iconsApi = new background_IconsApi();

;// ./Extension/src/background/storages/notification.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 


const background_BIRTHDAY_25_ID = 'birthday25';
const background_birthday25Notification = {
    id: background_BIRTHDAY_25_ID,
    locales: {
        en: {
            title: 'Long story short: birthday sale',
            btn: 'Dive in'
        },
        fr: {
            title: "La chose à noter : c'est notre anniversaire !",
            btn: 'Voyons voir'
        },
        it: {
            title: "C'é il nostro anniversario, vieni vedere",
            btn: 'Vedi le cose'
        },
        de: {
            title: 'Eine Geschichte mit Rabatten',
            btn: 'Jetzt entdecken'
        },
        ru: {
            title: 'Есть что рассказать и подарить',
            btn: 'А ну-ка'
        },
        es: {
            title: 'Tenemos algo que decir y algo que regalarte',
            btn: '¿Qué és?'
        },
        es_419: {
            title: 'Tenemos algo que decir y algo que regalarte',
            btn: '¿Qué és?'
        },
        pt_pt: {
            title: 'Temos algo a dizer, e algo a presentear',
            btn: 'O que é?'
        },
        pt_br: {
            title: 'Há algo que precisamos dizer… e uma surpresa',
            btn: 'O que é?'
        },
        zh_cn: {
            title: '周年庆大促',
            btn: '立即参与'
        },
        zh_tw: {
            title: '周年慶大促',
            btn: '立即參與'
        },
        ja: {
            title: 'AdGuard 16周年セール',
            btn: 'セール内容はこちら'
        },
        ko: {
            title: '16주년 기념 세일',
            btn: '자세히 알아보기'
        },
        uk: {
            title: 'Історія зі знижкою',
            btn: 'Дізнатися'
        },
        ar: {
            title: 'قصة تنتهي بخصم',
            btn: 'اكتشف'
        },
        be: {
            title: 'Гісторыя са зніжкай',
            btn: 'Даведайся'
        },
        bg: {
            title: 'История с отстъпка',
            btn: 'Научи се'
        },
        ca: {
            title: 'Història amb descompte',
            btn: 'Descobreix'
        },
        cs: {
            title: 'Příběh se slevou',
            btn: 'Zjistit'
        },
        da: {
            title: 'Historie med rabat',
            btn: 'Find ud af'
        },
        el: {
            title: 'Ιστορία με έκπτωση',
            btn: 'Μάθετε'
        },
        fa: {
            title: 'داستانی با تخفیف',
            btn: 'کشف کن'
        },
        fi: {
            title: 'Tarina alennuksella',
            btn: 'Opi'
        },
        he: {
            title: 'סיפור עם הנחה',
            btn: 'גלה'
        },
        hr: {
            title: 'Priča s popustom',
            btn: 'Saznaj'
        },
        hu: {
            title: 'Történet kedvezménnyel',
            btn: 'Tudj meg'
        },
        hy: {
            title: 'Պատմություն զեղչով',
            btn: 'Բացահայտել'
        },
        id: {
            title: 'Cerita dengan diskon',
            btn: 'Cari tahu'
        },
        lt: {
            title: 'Istorija su nuolaida',
            btn: 'Sužinoti'
        },
        ms: {
            title: 'Kisah dengan diskaun',
            btn: 'Ketahui'
        },
        nb: {
            title: 'Historie med rabatt',
            btn: 'Finn ut'
        },
        nl: {
            title: 'Verhaal met korting',
            btn: 'Ontdek'
        },
        pl: {
            title: 'Historia ze zniżką',
            btn: 'Dowiedz się'
        },
        ro: {
            title: 'Poveste cu reducere',
            btn: 'Află'
        },
        sk: {
            title: 'Príbeh so zľavou',
            btn: 'Zistiť'
        },
        sl: {
            title: 'Zgodba s popustom',
            btn: 'Izvedi'
        },
        sr_latn: {
            title: 'Priča sa popustom',
            btn: 'Saznaj'
        },
        sv: {
            title: 'Berättelse med rabatt',
            btn: 'Ta reda på'
        },
        tr: {
            title: 'İndirimli hikaye',
            btn: 'Keşfet'
        },
        vi: {
            title: 'Câu chuyện giảm giá',
            btn: 'Tìm hiểu'
        },
        mk: {
            title: 'Приказна со попуст',
            btn: 'Дознај'
        },
        hi: {
            title: 'छूट वाली कहानी',
            btn: 'जानें'
        },
        et: {
            title: 'Lugu allahindlusega',
            btn: 'Uuri'
        },
        th: {
            title: 'เรื่องราวพร้อมส่วนลด',
            btn: 'ค้นหา'
        }
    },
    text: '',
    url: background_Forward.get({
        action: background_ForwardAction.Birthday25
    }),
    from: '30 May 2025 12:00:00',
    to: '5 June 2025 23:59:00',
    type: 'animated',
    bgImage: background_browser_polyfill_default().runtime.getURL('assets/images/birthday25.svg'),
    bgImageOnUpdate: background_browser_polyfill_default().runtime.getURL('assets/images/birthday25-update.svg'),
    icons: {
        enabled: {
            '19': background_browser_polyfill_default().runtime.getURL('assets/icons/birthday25-on-19.png'),
            '38': background_browser_polyfill_default().runtime.getURL('assets/icons/birthday25-on-38.png')
        },
        disabled: {
            '19': background_browser_polyfill_default().runtime.getURL('assets/icons/birthday25-off-19.png'),
            '38': background_browser_polyfill_default().runtime.getURL('assets/icons/birthday25-off-38.png')
        },
        warning: background_defaultIconVariants.warning
    }
};
/**
 * In-memory notifications mapping.
 */ const background_notificationStorage = new Map([
    [
        background_BIRTHDAY_25_ID,
        background_birthday25Notification
    ]
]);

;// ./Extension/src/background/storages/trusted-domains.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 


/**
 * Instance of {@link StringStorage}, that stores
 * {@link TrustedDomainData} list in {@link browserStorage} under
 * {@link TRUSTED_DOCUMENTS_CACHE_KEY} key.
 */ const background_trustedDomainsStorage = new background_StringStorage(background_TRUSTED_DOCUMENTS_CACHE_KEY, background_browserStorage);

;// ./Extension/src/background/storages/hit-stats.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 




/**
 * Class for asynchronous control {@link HitStats} storage data,
 * that is persisted as string in another key value storage.
 *
 * @see {@link StringStorage}
 */ class background_HitStatsStorage extends background_StringStorage {
    /**
     * Caches filter version if it is not cached yet.
     *
     * @param filterId Filter id.
     *
     * @throws Error, if storage is not initialized.
     */ cacheFilterVersionIfNeeded(filterId) {
        if (!this.data) {
            throw background_HitStatsStorage.createNotInitializedError();
        }
        if (!this.data.versions) {
            this.data.versions = {};
        }
        const id = String(filterId);
        if (!this.data.versions[id]) {
            const data = background_filterVersionStorage.get(filterId);
            if (data) {
                this.data.versions[id] = data.version;
            }
        }
    }
    /**
     * Add 1 rule hit to stats.
     *
     * @param filterId Filter id.
     * @param ruleIndex Rule index.
     *
     * @throws Error, if storage is not initialized.
     */ addRuleHitToCache(filterId, ruleIndex) {
        if (!this.data) {
            throw background_HitStatsStorage.createNotInitializedError();
        }
        if (!this.data.stats) {
            this.data.stats = {};
        }
        if (!this.data.stats.filters) {
            this.data.stats.filters = {};
        }
        const id = String(filterId);
        this.cacheFilterVersionIfNeeded(filterId);
        let rules = this.data.stats.filters[id];
        if (!rules) {
            rules = {};
        }
        rules[ruleIndex] = (rules[ruleIndex] || 0) + 1;
        this.data.stats.filters[id] = rules;
        this.data.totalHits = (this.data.totalHits || 0) + 1;
    }
    /**
     * Helper function to create a basic {@link Error} with a custom message.
     *
     * @returns A basic {@link Error} with a custom message.
     */ static createNotInitializedError() {
        return new Error('hit stats is not initialized');
    }
}
/**
 * Instance of {@link HitStatsStorage}, that stores
 * stringified {@link HitStats} in {@link browserStorage} under
 * {@link HIT_STATISTIC_KEY} key.
 */ const background_hitStatsStorage = new background_HitStatsStorage(background_HIT_STATISTIC_KEY, background_browserStorage);

;// ./Extension/src/background/storages/annoyances-consent.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 


/**
 * Instance of {@link StringStorage} that stores filter ids for granted consent of
 * annoyances filters in {@link browserStorage} under {@link ANNOYANCES_CONSENT_KEY} key.
 */ const background_annoyancesConsentStorage = new background_StringStorage(background_ANNOYANCES_CONSENT_KEY, background_browserStorage);

;// ./Extension/src/background/storages/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ // entry point of `storages` layer
// `storages` contains app data storage models based on `schema` layer





















;// ./Extension/src/background/api/filters/userrules.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 









/**
 * API for managing user rules list.
 */ class background_UserRulesApi {
    /**
     * Parses data from user rules list.
     * If it's undefined or if it's an initialization after installation - sets
     * empty user rules list.
     *
     * @param isInstall Is this is an installation initialization or not.
     */ static async init(isInstall) {
        try {
            // Check if user filter is present in the storage to avoid errors.
            if (!await background_FiltersStorage.has(background_AntiBannerFiltersId.UserFilterId)) {
                await background_FiltersStorage.set(background_AntiBannerFiltersId.UserFilterId, background_es/* FilterListPreprocessor */.aQ.createEmptyPreprocessedFilterList());
            } else {
                // In this case zod will validate the data.
                await background_FiltersStorage.get(background_AntiBannerFiltersId.UserFilterId);
            }
        } catch (e) {
            if (!isInstall) {
                background_logger_logger.warn('Cannot parse user filter list from persisted storage, reset to default. Origin error: ', e);
            }
            await background_FiltersStorage.set(background_AntiBannerFiltersId.UserFilterId, background_es/* FilterListPreprocessor */.aQ.createEmptyPreprocessedFilterList());
        }
    }
    /**
     * Checks, if user list is enabled.
     *
     * @returns True, if user list is enabled, else returns false.
     */ static isEnabled() {
        return background_settingsStorage.get(background_SettingOption.UserFilterEnabled);
    }
    /**
     * Checks, if user list contains rules for specified url.
     *
     * @param url Page url.
     *
     * @returns True, if user list contains rules for {@link url}, else returns false.
     */ static async hasRulesForUrl(url) {
        if (!url) {
            return false;
        }
        try {
            const chunks = await background_UserRulesApi.getBinaryUserRules();
            const buffer = new background_input_byte_buffer/* InputByteBuffer */.N(chunks);
            let ruleNode;
            // If the next byte is 0, it means that there's nothing to read.
            while(buffer.peekUint8() !== 0){
                background_rule_deserializer/* RuleDeserializer */.Y.deserialize(buffer, ruleNode = {});
                if (background_es/* RuleSyntaxUtils */.Tl.isRuleForUrl(ruleNode, url)) {
                    return true;
                }
            }
        } catch (e) {
            background_logger_logger.error('Cannot check user rules for url', e);
        }
        return false;
    }
    /**
     * Returns rules from user list.
     *
     * @returns User rules list.
     */ static async getUserRules() {
        const data = await background_FiltersStorage.get(background_AntiBannerFiltersId.UserFilterId);
        if (!data) {
            return background_es/* FilterListPreprocessor */.aQ.createEmptyPreprocessedFilterList();
        }
        return data;
    }
    /**
     * Returns binary serialized, preprocessed rules from user list.
     *
     * @note This may include converted rules and does not include syntactically invalid rules.
     *
     * @returns User rules list in binary format.
     */ static async getBinaryUserRules() {
        const data = await background_FiltersStorage.getFilterList(background_AntiBannerFiltersId.UserFilterId);
        if (!data) {
            return background_es/* FilterListPreprocessor */.aQ.createEmptyPreprocessedFilterList().filterList;
        }
        return data;
    }
    /**
     * Returns original rules from user list.
     *
     * When we save user rules, the rules may be modified (e.g converted),
     * but when user opens the editor, we need to show their original rules.
     * User rules is a bit special because for that list we store the whole original filter list.
     * This method return that original list and we use it to load content in the editor.
     *
     * @returns User rules list.
     */ static async getOriginalUserRules() {
        var _ref;
        return (_ref = await background_FiltersStoragesAdapter.getOriginalFilterList(background_AntiBannerFiltersId.UserFilterId)) !== null && _ref !== void 0 ? _ref : '';
    }
    /**
     * Adds rule to user list.
     *
     * @param rule Rule text.
     */ static async addUserRule(rule) {
        let userRulesFilter = await background_UserRulesApi.getOriginalUserRules();
        if (!userRulesFilter.endsWith(background_NEWLINE_CHAR_UNIX)) {
            userRulesFilter += background_NEWLINE_CHAR_UNIX;
        }
        userRulesFilter += rule;
        await background_UserRulesApi.setUserRules(userRulesFilter);
    }
    /**
     * Removes rule from user list.
     *
     * @param rule Rule text.
     */ static async removeUserRule(rule) {
        const userRulesTest = await background_UserRulesApi.getOriginalUserRules();
        const userRulesToSave = userRulesTest.split(background_NEWLINE_CHAR_REGEX).filter((r)=>r !== rule).join(background_NEWLINE_CHAR_UNIX);
        await background_UserRulesApi.setUserRules(userRulesToSave);
    }
    /**
     * Removes rules for specified url from user list.
     *
     * @param url Page url.
     */ static async removeRulesByUrl(url) {
        const userRulesTest = await background_UserRulesApi.getOriginalUserRules();
        await background_UserRulesApi.setUserRules(userRulesTest.split(background_NEWLINE_CHAR_REGEX).filter((rule)=>{
            try {
                return !background_es/* RuleSyntaxUtils */.Tl.isRuleForUrl(background_rule_parser/* RuleParser */.G.parse(rule), url);
            } catch (e) {
                // Possible parsing error here.
                // Keep invalid rules in the list, because we need to keep everything that user added.
                return true;
            }
        }).join(background_NEWLINE_CHAR_UNIX));
    }
    /**
     * Sets user rule list to storage.
     *
     * @param rulesText Rule text.
     */ static async setUserRules(rulesText) {
        await background_FiltersStorage.set(background_AntiBannerFiltersId.UserFilterId, rulesText);
        background_notifier_notifier.notifyListeners(background_constants_NotifierType.UserFilterUpdated);
    }
    /**
     * Returns persisted rules during switches between common and fullscreen modes.
     *
     * @returns User rules editor content.
     */ static getEditorStorageData() {
        return background_editorStorage.get();
    }
    /**
     * Sets persisted rules during switches between common and fullscreen modes.
     *
     * @param data User rules editor content.
     */ static setEditorStorageData(data) {
        background_editorStorage.set(data);
    }
}

;// ./Extension/src/background/api/filters/allowlist.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 











/**
 * API for managing allowlist domain lists.
 *
 * This class provided methods for creating and deleting rules in
 * {@link allowlistDomainsStorage} and {@link invertedAllowlistDomainsStorage}.
 *
 */ class background_allowlist_AllowlistApi {
    /**
     * Reads stringified domains arrays from persisted storages
     * and saves it in cache.
     * If data is not exist, set empty arrays.
     */ static init() {
        background_allowlist_AllowlistApi.initStorage(background_allowlistDomainsStorage);
        background_allowlist_AllowlistApi.initStorage(background_invertedAllowlistDomainsStorage);
    }
    /**
     * Checks if allowlist in inverted.
     *
     * @returns True, if inverted, else returns false.
     */ static isInverted() {
        return !background_settingsStorage.get(background_SettingOption.DefaultAllowlistMode);
    }
    /**
     * Checks if allowlist is enabled.
     *
     * @returns True, if enabled, else returns false.
     */ static isEnabled() {
        return background_settingsStorage.get(background_SettingOption.AllowlistEnabled);
    }
    /**
     * Returns domain list from {@link allowlistDomainsStorage}.
     *
     * @returns List of allowlisted domains in default mode.
     */ static getAllowlistDomains() {
        return background_allowlist_AllowlistApi.getDomains(background_allowlistDomainsStorage);
    }
    /**
     * Returns domain list from {@link invertedAllowlistDomainsStorage}.
     *
     * @returns List of allowlisted domains in inverted mode.
     */ static getInvertedAllowlistDomains() {
        return background_allowlist_AllowlistApi.getDomains(background_invertedAllowlistDomainsStorage);
    }
    /**
     * Sets domain list to {@link allowlistDomainsStorage}.
     *
     * @param domains - Array of domains.
     */ static setAllowlistDomains(domains) {
        background_allowlist_AllowlistApi.setDomains(domains, background_allowlistDomainsStorage);
    }
    /**
     * Sets domain list to {@link invertedAllowlistDomainsStorage}.
     *
     * @param domains - Array of domains.
     */ static setInvertedAllowlistDomains(domains) {
        background_allowlist_AllowlistApi.setDomains(domains, background_invertedAllowlistDomainsStorage);
    }
    /**
     * Add domain to {@link allowlistDomainsStorage}.
     *
     * @param domain - Domain string.
     */ static addAllowlistDomain(domain) {
        background_allowlist_AllowlistApi.addDomain(domain, background_allowlistDomainsStorage);
    }
    /**
     * Add domain to {@link invertedAllowlistDomainsStorage}.
     *
     * @param domain - Domain string.
     */ static addInvertedAllowlistDomain(domain) {
        background_allowlist_AllowlistApi.addDomain(domain, background_invertedAllowlistDomainsStorage);
    }
    /**
     * Remove allowlist records for domain from {@link allowlistDomainsStorage}.
     *
     * @param domain - Domain string.
     */ static removeAllowlistDomain(domain) {
        background_allowlist_AllowlistApi.findAndRemoveMatchedDomainsAndSubdomainMasks(domain, background_allowlistDomainsStorage);
    }
    /**
     * Remove allowlist records for domain from {@link invertedAllowlistDomainsStorage}.
     *
     * @param domain - Domain string.
     */ static removeInvertedAllowlistDomain(domain) {
        background_allowlist_AllowlistApi.findAndRemoveMatchedDomainsAndSubdomainMasks(domain, background_invertedAllowlistDomainsStorage);
    }
    /**
     * Finds and removes any domains which can match provided domain by exactly
     * same domain or by sub-domain mask.
     *
     * @param domain Domain which should be excluded from allowlist.
     * @param storage Storage with allowlist domains.
     */ static findAndRemoveMatchedDomainsAndSubdomainMasks(domain, storage) {
        const domainsToCheck = background_allowlist_AllowlistApi.getDomains(storage);
        // Firstly check for exactly same domains in allowlist.
        const domainsToRemove = domainsToCheck.filter((record)=>record === domain);
        // Make a copy of parameter before editing.
        let domainToCheck = domain.split('').join('');
        // While we have at least one dot, check for possible upper mask domains.
        while(domainToCheck.indexOf('.') > -1){
            // Domain can be match by upper-domain mask.
            domainToCheck = background_UrlUtils.getUpperLevelDomain(domainToCheck);
            // eslint-disable-next-line @typescript-eslint/no-loop-func
            const matchedSubDomainMasks = domainsToCheck.filter((record)=>record === `*.${domainToCheck}`);
            domainsToRemove.push(...matchedSubDomainMasks);
        }
        domainsToRemove.forEach((d)=>{
            background_allowlist_AllowlistApi.removeDomain(d, storage);
        });
    }
    /**
     * Enable filtering for specified tab by changing the allowlist or deleting allowlist rule from user list.
     *
     * @param tabId Tab id.
     * @param tabRefresh Tab refresh flag.
     */ static async enableTabFiltering(tabId, tabRefresh = false) {
        const tabContext = background_tabsApi.getTabContext(tabId);
        if (!tabContext) {
            return;
        }
        const { mainFrameRule } = tabContext;
        if (!mainFrameRule) {
            return;
        }
        const filterId = mainFrameRule.getFilterListId();
        if (filterId === background_AntiBannerFiltersId.UserFilterId) {
            const ruleText = mainFrameRule.getText();
            await background_allowlist_AllowlistApi.removeAllowlistRuleFromUserList(ruleText, tabId, tabRefresh);
            return;
        }
        const { info: { url } } = tabContext;
        if (url && filterId === background_AntiBannerFiltersId.AllowlistFilterId) {
            await background_allowlist_AllowlistApi.enableTabUrlFiltering(url, tabId, tabRefresh);
        }
    }
    /**
     * Disable filtering for specified tab by adding url to the allowlist.
     *
     * @param tabId Tab id.
     */ static async disableTabFiltering(tabId) {
        const tabContext = background_tabsApi.getTabContext(tabId);
        if (!tabContext) {
            return;
        }
        const { info: { url } } = tabContext;
        if (url) {
            await background_allowlist_AllowlistApi.disableTabUrlFiltering(url, tabId);
        }
    }
    /**
     * Enable filtering for specified tab by changing the allowlist.
     *
     * If default allowlist mode, removes domain from {@link allowlistDomainsStorage}.
     * If inverted allowlist mode, adds domain to {@link invertedAllowlistDomainsStorage}.
     * Updates {@link Engine} and reloads the tab if {@link tabRefresh} is true.
     *
     * @param url Tab document url.
     * @param tabId Tab id.
     * @param tabRefresh Is tab refresh needed after removing tab url from the allowlist.
     * We do not refresh the tab after changing the allowlist via the filtering log.
     */ static async enableTabUrlFiltering(url, tabId, tabRefresh = false) {
        const domain = background_getDomain(url);
        if (!domain) {
            return;
        }
        if (background_allowlist_AllowlistApi.isInverted()) {
            background_allowlist_AllowlistApi.addInvertedAllowlistDomain(domain);
        } else {
            background_allowlist_AllowlistApi.removeAllowlistDomain(domain);
        }
        await background_engine_engine.update();
        if (tabRefresh) {
            await background_TabsApi.reload(tabId);
        }
    }
    /**
     * Disable filtering for specified tab by changing the allowlist.
     *
     * If default allowlist mode, adds domain to {@link allowlistDomainsStorage}.
     * If inverted allowlist mode, removes domain from {@link invertedAllowlistDomainsStorage}.
     * Updates tswebextension configuration and reload tab after changes apply.
     *
     * @param url Tab document url.
     * @param tabId Tab id.
     */ static async disableTabUrlFiltering(url, tabId) {
        const domain = background_getDomain(url);
        if (!domain) {
            return;
        }
        if (background_allowlist_AllowlistApi.isInverted()) {
            background_allowlist_AllowlistApi.removeInvertedAllowlistDomain(domain);
        } else {
            background_allowlist_AllowlistApi.addAllowlistDomain(domain);
        }
        await background_engine_engine.update();
        await background_TabsApi.reload(tabId);
    }
    /**
     * Enable filtering for specified tab by deleting allowlist rule from user list.
     *
     * Updates {@link Engine} and reloads the tab if {@link tabRefresh} is true.
     *
     * @param ruleText Tab document rule text.
     * @param tabId Tab id.
     * @param tabRefresh Is tab refresh needed after removing rule from the user list.
     * We do not refresh the tab after rule deletion via the filtering log.
     */ static async removeAllowlistRuleFromUserList(ruleText, tabId, tabRefresh = false) {
        await background_UserRulesApi.removeUserRule(ruleText);
        await background_engine_engine.update();
        if (tabRefresh) {
            await background_TabsApi.reload(tabId);
        }
    }
    /**
     * Add domain to specified {@link DomainsStorage}.
     *
     * @param domain - Domain string.
     * @param storage - Specified {@link DomainsStorage}.
     */ static addDomain(domain, storage) {
        const domains = storage.getData();
        domains.push(domain);
        background_allowlist_AllowlistApi.setDomains(domains, storage);
    }
    /**
     * Remove domain to specified storage.
     *
     * @param domain - Domain string.
     * @param storage - Specified {@link DomainsStorage}.
     */ static removeDomain(domain, storage) {
        const domains = storage.getData();
        background_allowlist_AllowlistApi.setDomains(domains.filter((d)=>d !== domain), storage);
    }
    /**
     * Returns domains from specified storage.
     *
     * @param storage - Specified {@link DomainsStorage}.
     *
     * @returns List of domains.
     */ static getDomains(storage) {
        return storage.getData();
    }
    /**
     * Set domains list to specified storage.
     *
     * @param domains - List of domains.
     * @param storage - Specified {@link DomainsStorage}.
     */ static setDomains(domains, storage) {
        // remove empty strings
        domains = domains.filter((domain)=>!!domain);
        // remove duplicates
        domains = Array.from(new Set(domains));
        storage.setData(domains);
        background_notifier_notifier.notifyListeners(background_constants_NotifierType.UpdateAllowlistFilterRules);
    }
    /**
     * Read stringified domains array from specified allowlist storage,
     * parse it and set memory cache.
     *
     * If data is not exist, set default data.
     *
     * @param storage - Default allowlist or inverted domains storage.
     * @param defaultData - Default storage data.
     */ static initStorage(storage, defaultData = []) {
        try {
            const storageData = storage.read();
            if (typeof storageData === 'string') {
                const data = background_lib/* default.string */.Ay.string().array().parse(JSON.parse(storageData));
                storage.setCache(data);
            } else {
                storage.setData(defaultData);
            }
        } catch (e) {
            // eslint-disable-next-line max-len
            background_logger_logger.warn(`Cannot parse ${storage.key} storage data from persisted storage, reset to default. Origin error: `, e);
            storage.setData(defaultData);
        }
    }
}

// EXTERNAL MODULE: ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/md5.js
var background_crypto_js_md5 = __webpack_require__(55625);
var background_md5_default = /*#__PURE__*/__webpack_require__.n(background_crypto_js_md5);
;// ./Extension/src/common/custom-filter-helper.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
/**
 * Extracted to common helper class because it is used in background and options pages
 */ class background_CustomFilterHelper {
    /**
     * Check if filter is custom.
     *
     * @param filterId Filter id.
     *
     * @returns True, if filter is custom, else returns false.
     */ static isCustomFilter(filterId) {
        return filterId >= background_CUSTOM_FILTERS_START_ID;
    }
}

;// ./Extension/src/background/utils/timeouts.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ /**
 * Creates a promise with a timeout.
 *
 * @param promise Promise to execute.
 * @param timeoutMs Promise execution limit in milliseconds. Reject promise after it.
 * @param errorMessage Message of error, thrown after timeout.
 *
 * @returns Resolved promise.
 *
 * @throws Error, if promise is not resolved after limit.
 */ 

async function background_createPromiseWithTimeout(promise, timeoutMs = 5000, errorMessage = 'Promise execution timeout') {
    return Promise.race([
        promise,
        background_rejectAfterTimeout(timeoutMs, errorMessage)
    ]);
}
/**
 * Rejects promise after timeout.
 *
 * @param timeoutMs Timeout in milliseconds.
 * @param message Message of error, thrown after timeout.
 *
 * @throws Error after timeout.
 */ async function background_rejectAfterTimeout(timeoutMs, message) {
    return new Promise((resolve, reject)=>{
        // eslint-disable-next-line no-restricted-globals
        self.setTimeout(()=>{
            reject(new Error(message));
        }, timeoutMs);
    });
}

;// ./Extension/src/background/api/filters/parser.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_parser_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
/**
 * Helper class for parsing custom filter metadata, loaded from a remote source.
 */ class background_FilterParser {
    /**
     * Parses filter metadata from rules' header.
     *
     * @param rules Lines of raw filter data text.
     *
     * @returns Parsed filter data.
     */ static parseFilterDataFromHeader(rules) {
        return {
            name: background_FilterParser.parseTag('Title', rules),
            description: background_FilterParser.parseTag('Description', rules),
            homepage: background_FilterParser.parseTag('Homepage', rules),
            version: background_FilterParser.parseTag('Version', rules),
            expires: Number(background_FilterParser.parseTag('Expires', rules)),
            timeUpdated: background_FilterParser.parseTag('TimeUpdated', rules),
            // Specs - https://github.com/ameshkov/diffupdates/tree/b81243c50d23e0a8be0fe95a80d55abd00b08981?tab=readme-ov-file#-diff-path
            diffPath: background_FilterParser.parseTag('Diff-Path', rules)
        };
    }
    /**
     * Finds value of specified header tag in filter rules text.
     *
     * @param tagName Filter header tag name.
     * @param rules Lines of filter rules text.
     *
     * @returns Value of specified header tag.
     */ static parseTag(tagName, rules) {
        let result = '';
        // Look up no more than 50 first lines
        const maxLines = Math.min(background_FilterParser.AMOUNT_OF_LINES_TO_PARSE, rules.length);
        for(let i = 0; i < maxLines; i += 1){
            const rule = rules[i];
            if (!rule) {
                continue;
            }
            const search = `! ${tagName}: `;
            const indexOfSearch = rule.indexOf(search);
            if (indexOfSearch >= 0) {
                result = rule.substring(indexOfSearch + search.length);
                // WARNING!
                // Potential memory leak mitigation for substring operation due to V8 optimizations:
                // When extracting a substring with rule.substring(), there's a concern in some JS environments
                // that the resulting substring might retain a hidden reference to the entire original 'rule' string.
                // This could prevent the garbage collector (GC) from freeing the memory allocated for filter rules.
                // This hidden reference occurs because the substring might not create a new string but rather
                // a view into the original, keeping it in memory longer than necessary.
                // And we receive a memory leak here because we store parsed tags from first N lines of the filter rules
                // which have references to the original large string with filter rules.
                // To ensure that the original large string can be garbage collected, and only the necessary
                // substring is retained, we explicitly force a copy of the substring via split and join,
                // thereby breaking the direct reference to the original string and allowing the GC to free the memory
                // for filter rules when they are no longer in use.
                result = result.split('').join('');
                break;
            }
        }
        if (tagName === 'Expires') {
            result = String(background_FilterParser.parseExpiresStr(result));
        }
        if (tagName === 'TimeUpdated') {
            result = result || new Date().toISOString();
        }
        return result;
    }
    /**
     * Parses string value of 'Expires' header tag.
     *
     * @param str Line of the rule text with 'Expires' tag.
     *
     * @returns Parsed value of 'Expires' header tag.
     */ static parseExpiresStr(str) {
        const regexp = /(\d+)\s+(day|hour)/;
        const parseRes = str.match(regexp);
        if (!parseRes) {
            const parsed = Number.parseInt(str, 10);
            return Number.isNaN(parsed) ? 0 : parsed;
        }
        const [, num, period] = parseRes;
        let multiplier = 1;
        switch(period){
            case 'day':
                {
                    multiplier = 24 * 60 * 60;
                    break;
                }
            case 'hour':
                {
                    multiplier = 60 * 60;
                    break;
                }
            default:
                {
                    break;
                }
        }
        return Number(num) * multiplier;
    }
}
/**
     * Number of lines to parse metadata from filter's header.
     */ background_parser_define_property(background_FilterParser, "AMOUNT_OF_LINES_TO_PARSE", 50);

;// ./Extension/src/background/api/filters/custom/loader.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_loader_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}


const background_emptyDownloadResult = {
    filter: [],
    rawFilter: ''
};
/**
 * Helper class for custom filters downloading with specified request time limitation.
 */ class background_CustomFilterLoader {
    /**
     * Limits custom filter rules downloading with timeout.
     *
     * @param url Custom filter download url.
     * @param rawFilter Optional raw filter rules.
     * @param force Optional flag to choose download filter in whole or by patches.
     *
     * @returns Downloaded custom filter rules.
     *
     * @throws Error if filter was not downloaded in {@link DOWNLOAD_LIMIT_MS}.
     */ static async downloadRulesWithTimeout(url, rawFilter, force) {
        return background_createPromiseWithTimeout(background_network.downloadFilterRulesBySubscriptionUrl(url, rawFilter, force).then((val)=>val || background_emptyDownloadResult), background_CustomFilterLoader.DOWNLOAD_LIMIT_MS, 'Fetch timeout is over');
    }
}
/**
     * Custom filter rules downloading limit in ms.
     */ background_loader_define_property(background_CustomFilterLoader, "DOWNLOAD_LIMIT_MS", 3 * 1000);

;// ./Extension/src/background/api/filters/custom.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_custom_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}















const background_custom_emptyDownloadResult = {
    filter: [],
    rawFilter: ''
};
/**
 * API for managing custom filters data.
 *
 * Custom filter subscription is divided into several stages:
 * - User requests custom filter data by subscription url;
 * - App downloads filter data and check, if filter was loaded before;
 * - App shows 'Add custom filter' modal window with parsed data;
 * - If user confirms subscription, filter data will be saved in app storages.
 *
 * This class also provided methods for updating and removing custom filters.
 *
 * Custom metadata is stored in {@link customFilterMetadataStorage}.
 * Filters states is stored in {@link filterStateStorage}.
 * Filters versions is stored in {@link filterVersionStorage}.
 * Filters rules is stored in {@link FiltersStorage}.
 * Raw filter rules (before applying directives) is saved in {@link FiltersStorage}.
 */ class background_custom_CustomFilterApi {
    /**
     * Reads stringified {@link CustomFilterMetadata} array from persisted storage
     * and saves it in cache.
     * If data is not exist, set empty array.
     *
     * @param network Network instance, needed for correct DI and exclude
     * circular dependencies.
     */ static init(network) {
        background_custom_CustomFilterApi.network = network;
        try {
            const storageData = background_customFilterMetadataStorage.read();
            if (typeof storageData === 'string') {
                const data = background_customFilterMetadataStorageDataValidator.parse(JSON.parse(storageData));
                background_customFilterMetadataStorage.setCache(data);
            } else {
                background_customFilterMetadataStorage.setData([]);
            }
        } catch (e) {
            background_logger_logger.warn('Cannot parse custom filter metadata from persisted storage, reset to default. Origin error: ', e);
            background_customFilterMetadataStorage.setData([]);
        }
    }
    /**
     * Returns Custom filter info for modal window.
     * Checks if custom filter with passed url is exist.
     * If url is new, downloads filter data from remote source, parse it and create new {@link CustomFilterInfo}.
     *
     * @param url Filter subscription url.
     * @param title User-defined filter title.
     *
     * @returns
     * One of three options:
     * - {@link CreateCustomFilterResponse} on new filter subscription,
     * - {@link CustomFilterAlreadyExistResponse} if custom filter was added before
     * - null, if filter rules are not downloaded.
     */ static async getFilterInfo(url, title) {
        // Check if filter from this url was added before
        if (background_customFilterMetadataStorage.getByUrl(url)) {
            return {
                errorAlreadyExists: true
            };
        }
        const rules = await background_custom_CustomFilterApi.network.downloadFilterRulesBySubscriptionUrl(url);
        if (!rules) {
            return null;
        }
        const parsedData = background_FilterParser.parseFilterDataFromHeader(rules.filter);
        const filter = {
            ...parsedData,
            name: parsedData.name ? parsedData.name : title,
            timeUpdated: parsedData.timeUpdated ? parsedData.timeUpdated : new Date().toISOString(),
            customUrl: url,
            rulesCount: rules.filter.filter((rule)=>rule.trim().indexOf('!') !== 0).length
        };
        return {
            filter
        };
    }
    /**
     * Creates and save new custom filter data in linked storages from passed {@link CustomFilterDTO}.
     *
     * Downloads filter data by {@link CustomFilterDTO.customUrl} and parse it.
     * Create new {@link CustomFilterMetadata} record and save it in {@link customFilterMetadataStorage},
     * Based on parsed data.
     * Creates new {@link FilterStateData} and save it in {@link filterStateStorage}.
     * Creates new {@link FilterVersionData} and save it in {@link filterVersionStorage}.
     * Filters rules are saved in {@link FiltersStorage}.
     * Raw filter rules (before applying directives) are saved in {@link RawFiltersStorage}.
     *
     * If the custom filter group has never been enabled, turn it on.
     *
     * @param filterData Custom filter data transfer object, received from modal window.
     *
     * @returns Created filter metadata.
     */ static async createFilter(filterData) {
        const { customUrl, trusted, enabled } = filterData;
        // download and parse custom filter data
        const { rawRules, rules, parsed, checksum } = await background_custom_CustomFilterApi.getRemoteFilterData(customUrl);
        // create new filter id
        const filterId = background_custom_CustomFilterApi.genFilterId();
        background_logger_logger.info(`Create new custom filter with id ${filterId}`);
        const name = filterData.title ? filterData.title : parsed.name;
        const { description, homepage, expires, timeUpdated, version, diffPath } = parsed;
        const filterMetadata = {
            filterId,
            displayNumber: 0,
            groupId: background_AntibannerGroupsId.CustomFiltersGroupId,
            name,
            description,
            homepage,
            version,
            checksum,
            tags: [
                0
            ],
            customUrl,
            trusted,
            expires: Number(expires),
            timeUpdated: new Date(timeUpdated).getTime()
        };
        background_customFilterMetadataStorage.set(filterMetadata);
        background_filterVersionStorage.set(filterId, {
            version,
            diffPath,
            expires: filterMetadata.expires,
            lastUpdateTime: filterMetadata.timeUpdated,
            lastCheckTime: Date.now(),
            lastScheduledCheckTime: Date.now()
        });
        background_filterStateStorage.set(filterId, {
            loaded: true,
            installed: true,
            enabled
        });
        // Note: we should join array of rules here, because they contain
        // preprocessed directives, e.g. including another filter via `!#include`
        // directive.
        await background_FiltersStorage.set(filterId, rules.join('\n'));
        await background_RawFiltersStorage.set(filterId, rawRules);
        const group = background_groupStateStorage.get(filterMetadata.groupId);
        // If group has never been enabled - enables it.
        if (group && !group.touched) {
            background_groupStateStorage.enableGroups([
                filterMetadata.groupId
            ]);
        }
        return filterMetadata;
    }
    /**
     * Creates new custom filters from the passed DTO array.
     *
     * @param filtersData Array of {@link CustomFilterDTO}.
     */ static async createFilters(filtersData) {
        const tasks = filtersData.map((filterData)=>background_custom_CustomFilterApi.createFilter(filterData));
        const promises = await Promise.allSettled(tasks);
        // Handles errors
        promises.forEach((promise)=>{
            if (promise.status === 'rejected') {
                background_logger_logger.error('Cannot create filter due to: ', promise.reason);
            }
        });
    }
    /**
     * Updates custom filter data by id.
     *
     * Returns subscription url from {@link customFilterMetadataStorage}.
     * Downloads data from remote source.
     * Checks, if new filter version available.
     * If filter need for update, save new filter data in storages.
     *
     * @param filterUpdateOptions Filter update detail.
     *
     * @returns Updated filter metadata or null, if filter is not existed
     * or new version is not available.
     */ static async updateFilter(filterUpdateOptions) {
        background_logger_logger.info(`Update Custom filter ${filterUpdateOptions.filterId} ...`);
        const filterMetadata = background_customFilterMetadataStorage.getById(filterUpdateOptions.filterId);
        if (!filterMetadata) {
            background_logger_logger.error(`Cannot find custom filter ${filterUpdateOptions.filterId} metadata`);
            return null;
        }
        const { customUrl } = filterMetadata;
        const rawFilter = await background_RawFiltersStorage.get(filterUpdateOptions.filterId);
        const filterRemoteData = await background_custom_CustomFilterApi.getRemoteFilterData(customUrl, rawFilter, filterUpdateOptions.ignorePatches);
        if (!background_custom_CustomFilterApi.isFilterNeedUpdate(filterMetadata, filterRemoteData)) {
            background_logger_logger.info(`Custom filter ${filterUpdateOptions.filterId} is already updated`);
            return null;
        }
        background_logger_logger.info(`Successfully update custom filter ${filterUpdateOptions.filterId}`);
        return background_custom_CustomFilterApi.updateFilterData(filterMetadata, filterRemoteData);
    }
    /**
     * Removes custom filter data from storages,
     * and returns boolean value whether the filter was enabled.
     *
     * Note: this method **does not update the engine**.
     *
     * @param filterId Custom filter id.
     *
     * @returns True if removed filter was enabled, otherwise false.
     */ static async removeFilter(filterId) {
        background_logger_logger.info(`Removing a custom filter ${filterId}...`);
        background_customFilterMetadataStorage.remove(filterId);
        background_filterVersionStorage.delete(filterId);
        const filterState = background_filterStateStorage.get(filterId);
        background_filterStateStorage.delete(filterId);
        await background_FiltersStorage.remove(filterId);
        await background_RawFiltersStorage.remove(filterId);
        background_logger_logger.info('Custom filter removed');
        var _filterState_enabled;
        return (_filterState_enabled = filterState === null || filterState === void 0 ? void 0 : filterState.enabled) !== null && _filterState_enabled !== void 0 ? _filterState_enabled : false;
    }
    /**
     * Check if filter is custom.
     *
     * @param filterId Filter id.
     *
     * @returns True, if filter is custom, else returns false.
     */ static isCustomFilter(filterId) {
        return background_CustomFilterHelper.isCustomFilter(filterId);
    }
    /**
     * Check if filter is custom.
     *
     * @param filter Filter metadata.
     *
     * @returns True, if filter is custom, else returns false.
     */ static isCustomFilterMetadata(filter) {
        return background_CustomFilterHelper.isCustomFilter(filter.filterId);
    }
    /**
     * Returns custom filter metadata for {@link customFilterMetadataStorage}.
     *
     * @param filterId Custom filter id.
     *
     * @returns Custom filter metadata or undefined, if custom filter doesn't exist.
     */ static getFilterMetadata(filterId) {
        return background_customFilterMetadataStorage.getById(filterId);
    }
    /**
     * Returns metadata for all custom filters.
     *
     * @returns Array of metadata records for all custom filters.
     */ static getFiltersMetadata() {
        return background_customFilterMetadataStorage.getData();
    }
    /**
     * Returns saved custom filters data transfer objects.
     *
     * @returns Array of existed custom filters DTO's.
     */ static getFiltersData() {
        const filtersMetadata = background_custom_CustomFilterApi.getFiltersMetadata();
        return filtersMetadata.map(({ filterId, customUrl, name, trusted })=>{
            var _filterStateStorage_get;
            return {
                customUrl,
                title: name,
                trusted,
                enabled: !!((_filterStateStorage_get = background_filterStateStorage.get(filterId)) === null || _filterStateStorage_get === void 0 ? void 0 : _filterStateStorage_get.enabled)
            };
        });
    }
    /**
     * Save new custom version, state and stored rules on update.
     *
     * @param filterMetadata Current custom filter metadata.
     * @param downloadedData Downloaded filter data.
     * @param downloadedData.rules New rules.
     * @param downloadedData.checksum New checksum.
     * @param downloadedData.parsed New parsed data.
     * @param downloadedData.rawRules New raw rules.
     *
     * @returns Updated custom filter metadata.
     */ static async updateFilterData(filterMetadata, { rules, rawRules, checksum, parsed }) {
        const { filterId } = filterMetadata;
        const { version, expires, timeUpdated, diffPath } = parsed;
        background_filterVersionStorage.set(filterId, {
            version,
            diffPath,
            expires: Number(expires),
            lastUpdateTime: new Date(timeUpdated).getTime(),
            lastCheckTime: Date.now(),
            lastScheduledCheckTime: Date.now()
        });
        const newFilterMetadata = {
            ...filterMetadata,
            version,
            checksum
        };
        background_customFilterMetadataStorage.set(newFilterMetadata);
        // Note: we should join array of rules here, because they contain
        // preprocessed directives, e.g. including another filter via `!#include`
        // directive.
        await background_FiltersStorage.set(filterId, rules.join('\n'));
        await background_RawFiltersStorage.set(filterId, rawRules);
        return newFilterMetadata;
    }
    /**
     * Generates new filter id for new custom filter.
     *
     * Custom filters ids starts from {@link CUSTOM_FILTERS_START_ID}.
     * Every new custom filter id is incremented on 1 from last one.
     *
     * @returns Generated filter id.
     */ static genFilterId() {
        let max = 0;
        background_customFilterMetadataStorage.getData().forEach((f)=>{
            if (f.filterId > max) {
                max = f.filterId;
            }
        });
        return max >= background_CUSTOM_FILTERS_START_ID ? max + 1 : background_CUSTOM_FILTERS_START_ID;
    }
    /**
     * Counts MD5 checksum for the filter rules content.
     *
     * @param rules Array of filter rules lines.
     *
     * @returns MD5 checksum of filter rules text.
     */ static getChecksum(rules) {
        const rulesText = rules.join('\n');
        return background_md5_default()(rulesText).toString();
    }
    /**
     * Checks if custom filter data need to update.
     *
     * @param filter Current custom filter metadata.
     * @param downloadedData Downloaded filter data.
     * @param downloadedData.checksum Checksum of downloaded filter text.
     * @param downloadedData.parsed New parsed data.
     *
     * @returns True, if filter data need to update, else returns false.
     */ static isFilterNeedUpdate(filter, { checksum, parsed }) {
        background_logger_logger.info(`Check if custom filter ${filter.filterId} need to update`);
        // If filter has version, we simply compare it with the new one.
        // Sometimes version field is not available (e.g. for some custom filters),
        // in this case, we should check only checksum.
        // If checksum is also not available, we should update filter anyway.
        if (// If version is not available or empty, we don't need to check it deeply
        typeof filter.version === 'string' && filter.version.length > 0 && background_BrowserUtils.isSemver(filter.version) && background_BrowserUtils.isSemver(parsed.version)) {
            return !background_BrowserUtils.isGreaterOrEqualsVersion(filter.version, parsed.version);
        }
        if (!filter.checksum) {
            return true;
        }
        return checksum !== filter.checksum;
    }
    /**
     * Loads filter data from specified url and parse it.
     *
     * @param url Custom filter subscription url.
     * @param rawFilter Optional raw filter rules.
     * @param force If true filter data will be downloaded directly, not through patches.
     *
     * @returns Downloaded and parsed filter data.
     */ static async getRemoteFilterData(url, rawFilter, force) {
        background_logger_logger.info(`Get custom filter data from ${url}`);
        const downloadResult = await background_CustomFilterLoader.downloadRulesWithTimeout(url, rawFilter, force);
        const parsed = background_FilterParser.parseFilterDataFromHeader(downloadResult.filter);
        const { version } = parsed;
        const checksum = !version || !background_BrowserUtils.isSemver(version) ? background_custom_CustomFilterApi.getChecksum(downloadResult.filter) : null;
        return {
            rawRules: downloadResult.rawFilter,
            rules: downloadResult.filter,
            parsed,
            checksum
        };
    }
    /**
     * Limits custom filter rules downloading with timeout.
     *
     * @param url Custom filter download url.
     * @param rawFilter Optional raw filter rules.
     * @param force Optional flag to choose download filter in whole or by patches.
     *
     * @returns Downloaded custom filter rules.
     *
     * @throws Error if filter was not downloaded in {@link DOWNLOAD_LIMIT_MS}.
     */ static async downloadRulesWithTimeout(url, rawFilter, force) {
        return background_createPromiseWithTimeout(background_custom_CustomFilterApi.network.downloadFilterRulesBySubscriptionUrl(url, rawFilter, force).then((val)=>val || background_custom_emptyDownloadResult), background_custom_CustomFilterApi.DOWNLOAD_LIMIT_MS, 'Fetch timeout is over');
    }
}
background_custom_define_property(background_custom_CustomFilterApi, "network", void 0);
/**
     * Custom filter rules downloading limit in ms.
     */ background_custom_define_property(background_custom_CustomFilterApi, "DOWNLOAD_LIMIT_MS", 10 * 1000);

;// ./Extension/src/background/api/filters/common.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 













/**
 * API for managing AdGuard's filters data.
 *
 * This class provides methods for reading common filter metadata from {@link metadataStorage.data.filters},
 * installation and updating common filters data, stored in next storages:
 * - {@link filterStateStorage} filters states;
 * - {@link filterVersionStorage} filters versions;
 * - {@link FiltersStorage} filter rules.
 * - {@link RawFiltersStorage} raw filter rules, before applying directives.
 */ class background_CommonFilterApi {
    /**
     * Returns common filter metadata.
     *
     * @param filterId Filter id.
     *
     * @returns Common filter metadata.
     */ static getFilterMetadata(filterId) {
        return background_metadataStorage.getFilter(filterId);
    }
    /**
     * Returns common filters metadata.
     *
     * @returns Common filters metadata array.
     */ static getFiltersMetadata() {
        return background_metadataStorage.getFilters();
    }
    /**
     * Checks if filter is built-in: not custom, not user-rules, not allowlist
     * and not quick fixes filter (used only for MV3 version).
     *
     * @param filterId Filter id.
     *
     * @returns True, if filter is common, else returns false.
     */ static isCommonFilter(filterId) {
        return !background_custom_CustomFilterApi.isCustomFilter(filterId) && filterId !== background_AntiBannerFiltersId.UserFilterId && filterId !== background_AntiBannerFiltersId.AllowlistFilterId;
    // TODO: Uncomment this line when Quick Fixes filter will be supported for MV3
    // && filterId !== AntiBannerFiltersId.QuickFixesFilterId;
    }
    /**
     * Update common filter.
     *
     * @param filterUpdateOptions Filter update detail.
     *
     * @returns Updated filter metadata or null, if update is not required.
     */ static async updateFilter(filterUpdateOptions) {
        background_logger_logger.info(`Update filter ${filterUpdateOptions.filterId}`);
        // We do not have to check metadata for the filters which do not update with force, because
        // they even do not trigger metadata update.
        if (filterUpdateOptions.ignorePatches) {
            const filterMetadata = background_CommonFilterApi.getFilterMetadata(filterUpdateOptions.filterId);
            if (!filterMetadata) {
                background_logger_logger.error(`Cannot find filter ${filterUpdateOptions.filterId} metadata`);
                return null;
            }
            if (!background_CommonFilterApi.isFilterNeedUpdate(filterMetadata)) {
                background_logger_logger.info(`Filter ${filterUpdateOptions.filterId} is already updated`);
                return null;
            }
        }
        background_logger_logger.info(`Filter ${filterUpdateOptions.filterId} needs to be updated`);
        try {
            const filterMetadata = await background_CommonFilterApi.loadFilterRulesFromBackend(filterUpdateOptions, true);
            background_logger_logger.info(`Filter ${filterUpdateOptions.filterId} updated successfully`);
            return filterMetadata;
        } catch (e) {
            background_logger_logger.error(e);
            return null;
        }
    }
    /**
     * Download filter rules from backend and update filter state and metadata.
     *
     * @param filterUpdateOptions Filter update detail.
     * @param forceRemote Whether to download filter rules from remote resources or
     * from local resources.
     *
     * **IMPORTANT: `forceRemote` can't be used for MV3** except Quick Fixes
     * filter, because we update filters, their metadata, and rulesets with
     * whole extension update, because static ruleset cannot be updated
     * dynamically.
     * To prevent mismatch filters and rulesets version - we do not support load
     * them from remote, except Quick Fixes Filter, because it will applied
     * dynamically.
     *
     * @returns Filter metadata — {@link RegularFilterMetadata}.
     */ static async loadFilterRulesFromBackend(filterUpdateOptions, forceRemote) {
        const isOptimized = background_settingsStorage.get(background_SettingOption.UseOptimizedFilters);
        const oldRawFilter = await background_RawFiltersStorage.get(filterUpdateOptions.filterId);
        // TODO: Uncomment this block when Quick Fixes filter will be supported for MV3
        // if (__IS_MV3__ && forceRemote && filterUpdateOptions.filterId !== AntiBannerFiltersId.QuickFixesFilterId) {
        //     forceRemote = false;
        // }
        // TODO: remove this block when we revert support for custom and quick fixes filters
        if (true) {
            forceRemote = false;
        }
        const { filter, rawFilter, isPatchUpdateFailed } = await background_network.downloadFilterRules(filterUpdateOptions, forceRemote, isOptimized, oldRawFilter);
        const currentFilterState = background_filterStateStorage.get(filterUpdateOptions.filterId);
        background_filterStateStorage.set(filterUpdateOptions.filterId, {
            installed: true,
            loaded: true,
            enabled: !!(currentFilterState === null || currentFilterState === void 0 ? void 0 : currentFilterState.enabled)
        });
        const parsedMetadata = background_FilterParser.parseFilterDataFromHeader(filter);
        let filterMetadata = background_CommonFilterApi.getFilterMetadata(filterUpdateOptions.filterId);
        if (!(parsedMetadata && filterMetadata)) {
            throw new Error(`Not found metadata for filter id ${filterUpdateOptions.filterId}`);
        }
        // update filter metadata with new values
        filterMetadata = {
            ...filterMetadata,
            ...parsedMetadata
        };
        const { version, expires, timeUpdated, diffPath } = filterMetadata;
        const filterVersion = background_filterVersionStorage.get(filterUpdateOptions.filterId);
        // We only update the expiration date if it is a forced update to
        // avoid updating the expiration date during patch updates.
        const nextExpires = (filterVersion === null || filterVersion === void 0 ? void 0 : filterVersion.expires) && !filterUpdateOptions.ignorePatches ? filterVersion.expires : Number(expires);
        // We only update the last check time if it is a forced update to
        // avoid updating the last check time during patch updates.
        const nextLastCheckTime = (filterVersion === null || filterVersion === void 0 ? void 0 : filterVersion.lastCheckTime) && !filterUpdateOptions.ignorePatches ? filterVersion.lastCheckTime : Date.now();
        background_filterVersionStorage.set(filterUpdateOptions.filterId, {
            version,
            diffPath,
            expires: nextExpires,
            lastUpdateTime: new Date(timeUpdated).getTime(),
            lastCheckTime: nextLastCheckTime,
            lastScheduledCheckTime: (filterVersion === null || filterVersion === void 0 ? void 0 : filterVersion.lastScheduledCheckTime) || Date.now(),
            // Unaccessible status may be returned during patch update
            // which is considered as a fatal error https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2717.
            // And if it happens, isPatchUpdateFailed is returned as true,
            // and we should set shouldWaitFullUpdate flag to true for the filter so it will be checked later
            shouldWaitFullUpdate: isPatchUpdateFailed
        });
        // Note: we should join array of rules here, because they contain
        // preprocessed directives, e.g. including another filter via `!#include`
        // directive.
        await background_FiltersStorage.set(filterUpdateOptions.filterId, filter.join('\n'));
        await background_RawFiltersStorage.set(filterUpdateOptions.filterId, rawFilter);
        return filterMetadata;
    }
    /**
     * Updates metadata for filters and after that loads and enables default
     * common filters.
     *
     * Called on extension installation and reset settings.
     *
     * @param enableUntouchedGroups - Should enable untouched groups related to
     * the default filters or not.
     */ static async initDefaultFilters(enableUntouchedGroups) {
        const filterIds = [
            background_AntiBannerFiltersId.EnglishFilterId,
            background_AntiBannerFiltersId.SearchAndSelfPromoFilterId
        ];
        if (background_UserAgent.isAndroid) {
            filterIds.push(background_AntiBannerFiltersId.MobileAdsFilterId);
        }
        filterIds.push(...background_CommonFilterApi.getLangSuitableFilters());
        // TODO: Move the use of FiltersApi.loadAndEnableFilters into a separate
        // module to reduce the risk of cyclic dependency, since FiltersApi
        // depends on CommonFilterApi and CustomFilterApi.
        // On the first run, we update the common filters from the backend.
        const remote = !true;
        await background_main_FiltersApi.loadAndEnableFilters(filterIds, remote, enableUntouchedGroups);
    // TODO: Uncomment this block when Quick Fixes filter will be supported for MV3
    // // For MV3 version we have QuickFixes filter which does not have local
    // // version and always should be updated from the server.
    // if (__IS_MV3__) {
    //     await FiltersApi.loadAndEnableFilters(
    //         [AntiBannerFiltersId.QuickFixesFilterId],
    //         true, // Install from remote.
    //         enableUntouchedGroups,
    //     );
    // }
    }
    /**
     * Returns language-specific filters by user locale.
     *
     * @returns List of language-specific filters ids.
     */ static getLangSuitableFilters() {
        let filterIds = [];
        let localeFilterIds = background_metadataStorage.getFilterIdsForLanguage(background_browser_polyfill_default().i18n.getUILanguage());
        filterIds = filterIds.concat(localeFilterIds);
        // Get language-specific filters by navigator languages
        // Get all used languages
        const languages = background_BrowserUtils.getNavigatorLanguages();
        languages.forEach((language)=>{
            localeFilterIds = background_metadataStorage.getFilterIdsForLanguage(language);
            filterIds = filterIds.concat(localeFilterIds);
        });
        return Array.from(new Set(filterIds));
    }
    /**
     * Checks if common filter needs update.
     * Matches the version from updated metadata with data in filter version storage.
     *
     * @param filterMetadata Updated filter metadata.
     *
     * @returns True, if filter update is required, else returns false.
     */ static isFilterNeedUpdate(filterMetadata) {
        background_logger_logger.info(`Check if filter ${filterMetadata.filterId} need to update`);
        const filterVersion = background_filterVersionStorage.get(filterMetadata.filterId);
        if (!filterVersion) {
            return true;
        }
        return !background_BrowserUtils.isGreaterOrEqualsVersion(filterVersion.version, filterMetadata.version);
    }
    /**
     * Checks whether the filter is supported for MV3.
     *
     * @param filterId Filter id.
     *
     * @returns True if filter is supported for MV3, false otherwise.
     */ static isMv3Supported(filterId) {
        const supportedFilterIds = background_CommonFilterApi.getFiltersMetadata().map((filter)=>filter.filterId);
        return supportedFilterIds.includes(filterId);
    }
}

;// ./Extension/src/background/api/filters/update.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_update_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}












/**
 * API for manual and automatic (by period) filter rules updates.
 */ class background_FilterUpdateApi {
    /**
     * Filters the provided filter list with {@link FilterUpdateApi.selectFiltersIdsToUpdate},
     * then gets fresh metadata from the remote server for all filters (it
     * cannot be updated selectively), and, after updating, refreshes
     * lastCheckTime for each of those selected for checking filters.
     *
     * Called:
     * - by the user's action to enable a filter or a filter group (even when
     * a filter is enabled from the Stealth menu);
     * - when the language filter is automatically turned on.
     *
     * @param filterIds List of filter ids to check.
     *
     * @returns List of metadata for updated filters.
     */ static async checkForFiltersUpdates(filterIds) {
        // TODO: We can add update filters in MV3 via patches via using
        // dynamic conversion of these patches, but it can be done later.
        if (true) {
            return [];
        }
        const filtersToCheck = background_FilterUpdateApi.selectFiltersIdsToUpdate(filterIds);
        // We update filters without patches when we enable groups.
        const filterDetails = filtersToCheck.map((id)=>({
                filterId: id,
                ignorePatches: true
            }));
        const updatedFilters = await background_FilterUpdateApi.updateFilters(filterDetails);
        background_filterVersionStorage.refreshLastCheckTime(filterDetails);
        return updatedFilters;
    }
    /**
     * If filtering is disabled or there is no selected filter update period in
     * the settings and if it is not a forced update, it returns an empty array.
     * Otherwise it checks all installed and enabled filters and only those that
     * have their group enabled for available updates: if it is a forced
     * update - it checks for updates for those (described above) filters,
     * otherwise it additional checks those filters for possible expose by
     * comparing 'lastTimeCheck' of each filter with updatePeriod from settings
     * or by checking 'expires' field.
     *
     * After that gets fresh metadata from the remote server for all filters (it
     * cannot be updated selectively).
     *
     * 'Installed filters' are filters whose rules are loaded in
     * browser.storage.local.
     *
     * Called when user manually run update:
     * - on request from context menu;
     * - on request from popup menu;
     *
     * Or from the update scheduler @see FilterUpdateService.
     *
     * @param forceUpdate Is it a force manual check by user action or first run
     * or not.
     *
     * @returns List of metadata for updated filters.
     */ static async autoUpdateFilters(forceUpdate = false) {
        const startUpdateLogMessage = forceUpdate ? 'Update filters forced by user.' : 'Update filters by scheduler.';
        background_logger_logger.info(startUpdateLogMessage);
        // If filtering is disabled, and it is not a forced update, it does nothing.
        const filteringDisabled = background_settingsStorage.get(background_SettingOption.DisableFiltering);
        if (filteringDisabled && !forceUpdate) {
            return [];
        }
        const updatePeriod = background_settingsStorage.get(background_SettingOption.FiltersUpdatePeriod);
        // Auto update disabled.
        if (updatePeriod === background_FiltersUpdateTime.Disabled && !forceUpdate) {
            return [];
        }
        // Selects to check only installed and enabled filters and only those
        // that have their group enabled.
        const installedAndEnabledFilters = background_main_FiltersApi.getInstalledAndEnabledFiltersIds();
        // If it is a force check - updates all installed and enabled filters.
        let filterUpdateDetailsToUpdate = installedAndEnabledFilters.map((id)=>({
                filterId: id,
                ignorePatches: forceUpdate
            }));
        // If not a force check - updates only outdated filters.
        if (!forceUpdate) {
            // Select filters with diff paths and mark them for no force update
            const filtersToPatchUpdate = background_FilterUpdateApi.selectFiltersToPatchUpdate(filterUpdateDetailsToUpdate).map((filterData)=>({
                    ...filterData,
                    ignorePatches: false
                }));
            /**
             * Select filters for a forced update and mark them accordingly.
             *
             * Filters with diff path must be also full updated from time to time.
             * Full update period for such full (forced) update is determined by FiltersUpdateTime,
             * which is set in extension settings.
             */ const filtersToFullUpdate = background_FilterUpdateApi.selectFiltersToFullUpdate(filterUpdateDetailsToUpdate, updatePeriod).map((filter)=>({
                    ...filter,
                    ignorePatches: true
                }));
            // Combine both arrays
            const combinedFilters = [
                ...filtersToPatchUpdate,
                ...filtersToFullUpdate
            ];
            const uniqueFiltersMap = new Map();
            combinedFilters.forEach((filter)=>{
                if (!uniqueFiltersMap.has(filter.filterId) || filter.ignorePatches) {
                    uniqueFiltersMap.set(filter.filterId, filter);
                }
            });
            filterUpdateDetailsToUpdate = Array.from(uniqueFiltersMap.values());
        }
        const updatedFilters = await background_FilterUpdateApi.updateFilters(filterUpdateDetailsToUpdate);
        // Updates last check time of all installed and enabled filters,
        // which where updated with force
        background_filterVersionStorage.refreshLastCheckTime(filterUpdateDetailsToUpdate);
        // If some filters were updated, then it is time to update the engine.
        if (updatedFilters.length > 0) {
            background_engine_engine.debounceUpdate();
        }
        return updatedFilters;
    }
    /**
     * Updates the metadata of all filters and updates the filter contents from
     * the provided list of identifiers.
     *
     * @param filterUpdateOptionsList List of filters ids to update.
     *
     * @returns Promise with a list of updated {@link FilterMetadata filters' metadata}.
     */ static async updateFilters(filterUpdateOptionsList) {
        /**
         * Reload common filters metadata from backend for correct
         * version matching on update check.
         * We do not update metadata on each check if there are no filters or only custom filters.
         */ const shouldLoadMetadata = filterUpdateOptionsList.some((filterUpdateOptions)=>{
            return filterUpdateOptions.ignorePatches && background_CommonFilterApi.isCommonFilter(filterUpdateOptions.filterId);
        });
        if (shouldLoadMetadata) {
            try {
                await background_main_FiltersApi.updateMetadata();
            } catch (e) {
                // No need to throw an error here, because we still can load
                // filters using the old metadata: checking metadata needed to
                // check for updates - without fresh metadata we still can load
                // newest filter, checking it's version will be against the old,
                // local metadata, which is possible outdated.
                background_logger_logger.error('Failed to update metadata due to an error:', background_error_getErrorMessage(e));
            }
        }
        const updatedFiltersMetadata = [];
        const updateTasks = filterUpdateOptionsList.map(async (filterData)=>{
            // TODO: Remove this block when custom filters will be supported for MV3
            if (true) {
                return;
            }
            let filterMetadata = null;
            if (background_custom_CustomFilterApi.isCustomFilter(filterData.filterId)) {
                filterMetadata = await background_custom_CustomFilterApi.updateFilter(filterData);
            } else {
                filterMetadata = await background_CommonFilterApi.updateFilter(filterData);
            }
            if (filterMetadata) {
                updatedFiltersMetadata.push(filterMetadata);
            }
        });
        const promises = await Promise.allSettled(updateTasks);
        // Handles errors
        promises.forEach((promise)=>{
            if (promise.status === 'rejected') {
                background_logger_logger.error('Cannot update filter due to: ', promise.reason);
            }
        });
        return updatedFiltersMetadata;
    }
    /**
     * Selects from the provided list of filters only those that have not been
     * {@link RECENTLY_CHECKED_FILTER_TIMEOUT_MS recently} updated (added,
     * enabled or updated by the scheduler) and those that are custom filters.
     *
     * @param filterIds List of filter ids.
     *
     * @returns List of filter ids to update.
     */ static selectFiltersIdsToUpdate(filterIds) {
        const filterVersions = background_filterVersionStorage.getData();
        return filterIds.filter((id)=>{
            // Always check for updates for custom filters
            const isCustom = background_custom_CustomFilterApi.isCustomFilter(Number(id));
            // Select only not recently checked filters
            const filterVersion = filterVersions[Number(id)];
            const outdated = filterVersion !== undefined ? Date.now() - filterVersion.lastCheckTime > background_FilterUpdateApi.RECENTLY_CHECKED_FILTER_TIMEOUT_MS : true;
            return isCustom || outdated;
        });
    }
    /**
     * Selects filters to update with patches. Such filters should
     * 1. Have `diffPath`
     * 2. Not have `shouldWaitFullUpdate` flag which means that patch update failed previously.
     *
     * @param filterUpdateOptionsList Filter update details.
     *
     * @returns List with filter update details, which have diff path.
     */ static selectFiltersToPatchUpdate(filterUpdateOptionsList) {
        const filterVersions = background_filterVersionStorage.getData();
        return filterUpdateOptionsList.filter((filterData)=>{
            const filterVersion = filterVersions[filterData.filterId];
            // we do not check here expires, since @adguard/filters-downloader does it.
            return (filterVersion === null || filterVersion === void 0 ? void 0 : filterVersion.diffPath) && !(filterVersion === null || filterVersion === void 0 ? void 0 : filterVersion.shouldWaitFullUpdate);
        });
    }
    /**
     * Selects outdated filters from the provided filter list for a full update.
     * The selecting is based on the provided filter update period from the settings.
     *
     * @param filterUpdateOptionsList List of filter update details.
     * @param updatePeriod Period of checking updates in ms.
     *
     * @returns List of outdated filter ids.
     */ static selectFiltersToFullUpdate(filterUpdateOptionsList, updatePeriod) {
        const filterVersions = background_filterVersionStorage.getData();
        return filterUpdateOptionsList.filter((data)=>{
            const filterVersion = filterVersions[data.filterId];
            if (!filterVersion) {
                return true;
            }
            const { lastCheckTime, expires } = filterVersion;
            // By default, checks the "expires" field for each filter.
            if (updatePeriod === background_DEFAULT_FILTERS_UPDATE_PERIOD) {
                // If it is time to check the update, adds it to the array.
                // IMPORTANT: "expires" in filter is specified in SECONDS.
                return lastCheckTime + expires * 1000 <= Date.now();
            }
            // Check, if the renewal period of each filter has passed.
            // If it is time to check the renewal, add to the array.
            return lastCheckTime + updatePeriod <= Date.now();
        });
    }
}
/**
     * Timeout for recently checked (added, enabled or updated by the scheduler)
     * filters - 5 minutes.
     */ background_update_define_property(background_FilterUpdateApi, "RECENTLY_CHECKED_FILTER_TIMEOUT_MS", 1000 * 60 * 5);
// TODO: remove later
// This method is exposed for the testing purposes.
// eslint-disable-next-line no-restricted-globals
Object.assign(self, {
    adguard: {
        // eslint-disable-next-line no-restricted-globals
        ...self.adguard,
        autoUpdate: background_FilterUpdateApi.autoUpdateFilters
    }
});

;// ./Extension/src/background/api/filters/categories.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_categories_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}










/**
 * Class for filter groups management.
 */ class background_Categories {
    /**
     * Returns aggregated filters category data for option page.
     *
     * @returns Categories aggregated data.
     */ static getCategories() {
        const groups = background_Categories.getGroups();
        let filters = background_Categories.getFilters();
        // Exclude Quick Fixes filter and custom filters from filters list
        // TODO: remove this check when Quick Fixes Filter and custom filters will be supported for MV3 again
        if (true) {
            filters = filters.filter((f)=>{
                return f.filterId !== background_AntiBannerFiltersId.QuickFixesFilterId && !background_CustomFilterHelper.isCustomFilter(f.filterId);
            });
        }
        const categories = groups.map((group)=>({
                ...group,
                filters: background_Categories.selectFiltersByGroupId(group.groupId, filters)
            }));
        return {
            filters,
            categories
        };
    }
    /**
     * Gets group state data from storage.
     *
     * @param groupId Id of group of filters.
     *
     * @returns Group state data if group is found, else returns undefined.
     */ static getGroupState(groupId) {
        return background_groupStateStorage.get(groupId);
    }
    /**
     * Enables specified group of filters and check updates for enabled filters.
     *
     * On first group activation we provide recommended filters,
     * that will be loaded end enabled before update checking.
     *
     * @param groupId Id of group of filters.
     * @param update Whether to download metadata and filter rules from remote
     * resources or from local resources and should it to check for updates.
     * @param recommendedFiltersIds Array of filters ids to enable on first time
     * the group has been activated after enabling.
     */ static async enableGroup(groupId, update, recommendedFiltersIds = []) {
        if (recommendedFiltersIds.length > 0) {
            await background_main_FiltersApi.loadAndEnableFilters(recommendedFiltersIds, update);
        }
        if (update) {
            // Always checks updates for enabled filters of the group.
            const enabledFiltersIds = background_Categories.getEnabledFiltersIdsByGroupId(groupId);
            await background_FilterUpdateApi.checkForFiltersUpdates(enabledFiltersIds);
        }
        background_groupStateStorage.enableGroups([
            groupId
        ]);
    }
    /**
     * Disable group.
     *
     * @param groupId Group id.
     */ static disableGroup(groupId) {
        background_groupStateStorage.disableGroups([
            groupId
        ]);
    }
    /**
     * Returns specified group metadata by filter id.
     *
     * @param filterId Filter id.
     *
     * @returns Specified {@link GroupMetadata | group metadata }
     * or undefined.
     */ static getGroupByFilterId(filterId) {
        const filter = background_metadataStorage.getFilter(filterId) || background_customFilterMetadataStorage.getById(filterId);
        if (!filter) {
            return;
        }
        return background_metadataStorage.getGroup(filter.groupId);
    }
    /**
     * Checks if filter has recommended tag.
     *
     * @param filter Filter metadata.
     *
     * @returns True, if filter has recommended tag, else returns false.
     */ static isRecommendedFilter(filter) {
        return filter.tags.includes(background_RECOMMENDED_TAG_ID);
    }
    /**
     * Checks if filter has mobile tag.
     *
     * @param filter Filter metadata.
     *
     * @returns True, if filter has mobile tag, else returns false.
     */ static isMobileFilter(filter) {
        return filter.tags.includes(background_Categories.PURPOSE_MOBILE_TAG_ID);
    }
    /**
     * If filter has mobile tag we check if platform is mobile, in other cases we do not check.
     *
     * @param filter Filter metadata.
     *
     * @returns True, if filter match platform, else returns false.
     */ static isFilterMatchPlatform(filter) {
        if (background_Categories.isMobileFilter(filter)) {
            return !!background_UserAgent.isAndroid;
        }
        return true;
    }
    /**
     * Returns recommended filters, which meet next requirements:
     * 1. Filter has recommended tag;
     * 2. If filter has language tag, tag should match with user locale;
     * 3. Filter should correspond to platform mobile or desktop.
     *
     * @param groupId Group id.
     *
     * @returns Recommended filters by groupId.
     */ static getRecommendedFilterIdsByGroupId(groupId) {
        const { categories } = background_Categories.getCategories();
        const langSuitableFilters = background_CommonFilterApi.getLangSuitableFilters();
        const group = categories.find((category)=>category.groupId === groupId);
        if (!(group === null || group === void 0 ? void 0 : group.filters)) {
            return [];
        }
        const { filters } = group;
        const result = [];
        filters.forEach((filter)=>{
            if (background_Categories.isRecommendedFilter(filter) && background_Categories.isFilterMatchPlatform(filter)) {
                // get ids intersection to enable recommended filters matching the lang tag
                // only if filter has language
                if (filter.languages && filter.languages.length > 0) {
                    if (langSuitableFilters.includes(filter.filterId)) {
                        result.push(filter.filterId);
                    }
                } else {
                    result.push(filter.filterId);
                }
            }
        });
        return result;
    }
    /**
     * Returns tags metadata from {@link metadataStorage}.
     *
     * @param tagsIds Tags ids.
     *
     * @returns Aggregated groups data.
     */ static getTagsDetails(tagsIds) {
        const tagsMetadata = background_metadataStorage.getTags();
        const tagsDetails = [];
        for(let i = 0; i < tagsIds.length; i += 1){
            const tagId = tagsIds[i];
            const tagDetails = tagsMetadata.find((tag)=>tag.tagId === tagId);
            if (tagDetails) {
                if (tagDetails.keyword.startsWith('reference:')) {
                    continue;
                }
                if (!tagDetails.keyword.startsWith('lang:')) {
                    // Hide prefixes except of 'lang:'
                    tagDetails.keyword = tagDetails.keyword.substring(tagDetails.keyword.indexOf(':') + 1);
                }
                tagsDetails.push(tagDetails);
            }
        }
        return tagsDetails;
    }
    /**
     * Returns filters merged data from {@link metadataStorage},
     * {@link customFilterMetadataStorage}, {@link filterStateStorage} and
     * {@link filterVersionStorage}.
     *
     * @returns Aggregated filters data.
     */ static getFilters() {
        const filtersMetadata = background_main_FiltersApi.getFiltersMetadata();
        const result = [];
        filtersMetadata.forEach((filterMetadata)=>{
            const { filterId, tags, version, expires, timeUpdated, diffPath } = filterMetadata;
            const tagsDetails = background_Categories.getTagsDetails(tags);
            const filterState = background_filterStateStorage.get(filterId);
            if (!filterState) {
                background_logger_logger.error(`Cannot find filter ${filterId} state data`);
                return;
            }
            let filterVersion = background_filterVersionStorage.get(filterId);
            if (!filterVersion) {
                // TODO: remove this hack after we find how to reproduce this issue
                // Sometimes filter version data might be missing https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2693,
                // so we set it to values from metadata
                background_logger_logger.info(`Cannot find filter ${filterId} version data, restoring it from metadata`);
                const dayAgoMs = Date.now() - 1000 * 60 * 60 * 24; // 24 hours
                filterVersion = {
                    version,
                    expires,
                    lastUpdateTime: new Date(timeUpdated).getTime(),
                    // this is set in the past to force update check
                    lastCheckTime: dayAgoMs,
                    lastScheduledCheckTime: dayAgoMs,
                    diffPath
                };
                background_filterVersionStorage.set(filterId, filterVersion);
            }
            result.push({
                ...filterMetadata,
                ...filterState,
                ...filterVersion,
                tagsDetails
            });
        });
        return result;
    }
    /**
     * Returns groups data from {@link metadataStorage} and {@link groupStateStorage}.
     *
     * @returns Aggregated groups data.
     */ static getGroups() {
        const groupsMetadata = background_metadataStorage.getGroups();
        const result = [];
        groupsMetadata.forEach((groupMetadata)=>{
            const groupState = background_groupStateStorage.get(groupMetadata.groupId);
            if (!groupState) {
                background_logger_logger.error(`Cannot find group ${groupMetadata.groupId} state data`);
                return;
            }
            result.push({
                ...groupMetadata,
                ...groupState
            });
        });
        return result;
    }
    /**
     * Returns filters data for specified group.
     *
     * @param groupId Group id.
     * @param filters Aggregated filters data.
     *
     * @returns Aggregated filters data for specified group.
     */ static selectFiltersByGroupId(groupId, filters) {
        return filters.filter((filter)=>filter.groupId === groupId);
    }
    /**
     * Returns ids of enabled filters for specified group id.
     *
     * @param groupId Group id.
     *
     * @returns List of filters ids.
     */ static getEnabledFiltersIdsByGroupId(groupId) {
        const filtersMetadata = background_main_FiltersApi.getFiltersMetadata();
        return filtersMetadata.filter((filter)=>filter.groupId === groupId).filter(({ filterId })=>{
            const filterState = background_filterStateStorage.get(filterId);
            return filterState === null || filterState === void 0 ? void 0 : filterState.enabled;
        }).map(({ filterId })=>filterId);
    }
}
background_categories_define_property(background_Categories, "PURPOSE_MOBILE_TAG_ID", 19);

;// ./Extension/src/background/api/filters/main.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 















/**
 * API for managing filters data. This class is a facade for working with
 * filters, for example, its methods are called by the handlers of user actions:
 * enabling or disabling a filter or filter group, updating, etc. It depends on
 * CommonFilterApi and CustomFilterApi.
 */ class background_main_FiltersApi {
    /**
     * Initialize filters storages.
     * Called while filters service initialization and app resetting.
     *
     * @param isInstall Is this is an installation initialization or not.
     */ static async init(isInstall) {
        await background_main_FiltersApi.initI18nMetadata();
        await background_main_FiltersApi.initMetadata();
        background_custom_CustomFilterApi.init(background_network);
        background_allowlist_AllowlistApi.init();
        await background_UserRulesApi.init(isInstall);
        background_main_FiltersApi.loadFilteringStates();
        await background_main_FiltersApi.removeObsoleteFilters();
    }
    /**
     * Tries to load metadata from remote source and reloads linked storages.
     * Called before filters rules are updated or loaded from backend.
     *
     * The metadata cannot be loaded individually because the all metadata needs
     * to be updated in order to, for example, update translations or track
     * the removal/addition of filters.
     *
     * If remote loading fails (due to server issues or network problems, etc.),
     * and if `shouldUseLocalAssets` is true, the method loads metadata from local assets.
     *
     * @param shouldUseLocalAssets Whether to load metadata from local assets
     * if remote loading fails. Default is false.
     */ static async updateMetadata(shouldUseLocalAssets = false) {
        try {
            await background_main_FiltersApi.loadI18nMetadataFromBackend(true);
            await background_main_FiltersApi.loadMetadataFromFromBackend(true);
        } catch (e) {
            background_logger_logger.debug('Cannot load remote metadata due to: ', background_error_getErrorMessage(e));
            // loading metadata from local assets is needed to avoid the extension init stopping after the install
            // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2761
            if (shouldUseLocalAssets) {
                background_logger_logger.debug('Trying to load metadata from local assets...');
                await background_main_FiltersApi.loadI18nMetadataFromBackend(false);
                await background_main_FiltersApi.loadMetadataFromFromBackend(false);
            }
        }
        background_main_FiltersApi.loadFilteringStates();
        await background_main_FiltersApi.removeObsoleteFilters();
    }
    /**
     * Checks if filter rules exist in browser storage.
     * Called while filters loading.
     *
     * @param filterId Filter id.
     *
     * @returns True, if filter is loaded, else returns false.
     */ static isFilterLoaded(filterId) {
        const filterState = background_filterStateStorage.get(filterId);
        return !!(filterState === null || filterState === void 0 ? void 0 : filterState.loaded);
    }
    /**
     * Checks if filter is enabled.
     *
     * @param filterId Filter id.
     *
     * @returns True, if filter is enabled, else returns false.
     */ static isFilterEnabled(filterId) {
        const filterState = background_filterStateStorage.get(filterId);
        return !!(filterState === null || filterState === void 0 ? void 0 : filterState.enabled);
    }
    /**
     * Checks if filter is trusted.
     *
     * @param filterId Filter id.
     *
     * @returns True, if filter is trusted, else returns false.
     */ static isFilterTrusted(filterId) {
        if (!background_custom_CustomFilterApi.isCustomFilter(filterId)) {
            return true;
        }
        const metadata = background_custom_CustomFilterApi.getFilterMetadata(filterId);
        return !!(metadata === null || metadata === void 0 ? void 0 : metadata.trusted);
    }
    /**
     * Checks if group is enabled.
     *
     * @param groupId Group id.
     *
     * @returns True, if group is enabled, else returns false.
     */ static isGroupEnabled(groupId) {
        const groupState = background_groupStateStorage.get(groupId);
        return !!(groupState === null || groupState === void 0 ? void 0 : groupState.enabled);
    }
    /**
     * Update metadata from local or remote source and download rules for filters.
     *
     * If loading filters from remote failed, try to load from local resources,
     * but only those filters, for which extension has local copies in resources.
     *
     * @param filterIds Filter ids to load.
     * @param remote Whether to download metadata and filter rules from remote
     * resources or from local resources.
     *
     * @returns List of loaded filters ids.
     */ static async loadFilters(filterIds, remote) {
        if (filterIds.length === 0) {
            return [];
        }
        if (remote) {
            try {
                // the arg is 'true' for loading locally stored metadata if remote loading failed.
                // needed not to stop the initialization process after the extension install
                // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2761
                await background_main_FiltersApi.updateMetadata(true);
            } catch (e) {
                // No need to throw an error here, because we still can load
                // filters using the old metadata: checking metadata needed to
                // check for updates - without fresh metadata we still can load
                // newest filter, checking it's version will be against the old,
                // local metadata, which is possible outdated.
                background_logger_logger.error('Failed to update metadata due to an error:', background_error_getErrorMessage(e));
            }
        }
        const tasks = filterIds.map(async (filterId)=>{
            if (filterId === background_AntiBannerFiltersId.QuickFixesFilterId) {
                // Quick fixes filter was disabled in MV3 to comply with CWR policies.
                // TODO: remove code totally later.
                return null;
            }
            try {
                // 'ignorePatches: true' here for loading filters without patches
                const f = await background_CommonFilterApi.loadFilterRulesFromBackend({
                    filterId,
                    ignorePatches: true
                }, remote);
                return f.filterId;
            } catch (e) {
                background_logger_logger.debug(`Filter rules were not loaded from backend for filter: ${filterId}, error: ${e}`);
                if (!background_network.isFilterHasLocalCopy(filterId)) {
                    background_logger_logger.debug(`Filter rules cannot be loaded because there is no local assets for filter ${filterId}.`);
                    return null;
                }
                background_logger_logger.debug(`Trying to load locally stored filter rules for filter: ${filterId}...`);
                // second arg is 'false' to load locally stored filter rules if remote loading failed
                // e.g. server is not available
                // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2761
                // 'ignorePatches: true' here for loading filters without patches
                const f = await background_CommonFilterApi.loadFilterRulesFromBackend({
                    filterId,
                    ignorePatches: true
                }, false);
                return f.filterId;
            }
        });
        const promises = await Promise.allSettled(tasks);
        // Handles errors
        promises.forEach((promise)=>{
            if (promise.status === 'rejected') {
                background_logger_logger.error('Cannot load filter rules due to: ', promise.reason);
            }
        });
        return promises.map((p)=>p.status === 'fulfilled' ? p.value : null).filter((p)=>background_guards_isNumber(p));
    }
    /**
     * Loads and enables specified filters. Once the filters are enabled,
     * the untouched groups belonging to those filters will be enabled too.
     *
     * If the method is called in offline mode, some filters may not be loaded
     * because we have local copies only for our built-in filters.
     *
     * @param filterIds Array of filter ids to load and enable.
     * @param remote Whether to download metadata and filter rules from remote
     * resources or from local resources.
     * **IMPORTANT NOTE:** We don't want to update the filters in MV3 version,
     * because it will lead to situation, where extension will use old rulesets
     * from local resources, but newest filter with text rules from remote resources
     * (which will be loaded to tsurlfilter for cosmetic rules).
     * @param enableGroups Should enable groups that were not touched by users
     * or by code.
     */ static async loadAndEnableFilters(filterIds, remote = false, enableGroups = false) {
        // Ignore already loaded filters
        // Custom filters always have a loaded state, so we don't need additional checks
        const unloadedFiltersIds = filterIds.filter((id)=>!background_main_FiltersApi.isFilterLoaded(id));
        const alreadyLoadedFilterIds = filterIds.filter((id)=>background_main_FiltersApi.isFilterLoaded(id));
        const loadedFilters = await background_main_FiltersApi.loadFilters(unloadedFiltersIds, remote);
        // Concatenate filters loaded just now with already loaded filters
        loadedFilters.push(...alreadyLoadedFilterIds);
        background_filterStateStorage.enableFilters(loadedFilters);
        if (!remote) {
            // Update the enabled filters only if loading happens from local resources
            // When loading from remote resources, the filters are already up-to-date,
            // except for the previously loaded filters, which we update below
            await background_FilterUpdateApi.checkForFiltersUpdates(loadedFilters);
        } else if (alreadyLoadedFilterIds.length > 0) {
            // Update previously loaded filters because they won't be loaded,
            // but still need to be updated to the latest versions
            await background_FilterUpdateApi.checkForFiltersUpdates(alreadyLoadedFilterIds);
        }
        if (enableGroups) {
            // Enable filter groups if they were never enabled or disabled earlier
            background_main_FiltersApi.enableGroupsWereNotTouched(loadedFilters);
        }
    }
    /**
     * Disables specified filters.
     * Called on filter option switch.
     *
     * Note: this method **does not update the engine**.
     *
     * @param filtersIds Filters ids.
     */ static disableFilters(filtersIds) {
        background_filterStateStorage.disableFilters(filtersIds);
    }
    /**
     * Reload filters and their metadata from local storage.
     * Needed only in MV3 version because we don't update filters from remote,
     * we use bundled filters from local resources and their converted rulesets.
     *
     * @returns List of loaded filter IDs.
     */ static async reloadFiltersFromLocal() {
        try {
            await background_main_FiltersApi.loadI18nMetadataFromBackend(false);
            await background_main_FiltersApi.loadMetadataFromFromBackend(false);
        } catch (e) {
            background_logger_logger.error('Cannot load local metadata due to: ', background_error_getErrorMessage(e));
        }
        background_main_FiltersApi.loadFilteringStates();
        await background_main_FiltersApi.removeObsoleteFilters();
        const filterIds = background_filterStateStorage.getLoadFilters();
        // Ignore custom filters, user-rules, allowlist
        // and quick fixes filter (used only in MV3).
        const commonFiltersIds = filterIds.filter((id)=>background_CommonFilterApi.isCommonFilter(id));
        try {
            // Only re-load filters without changed their states: enabled or disabled.
            const loadedFiltersIds = await background_main_FiltersApi.loadFilters(commonFiltersIds, false);
            return loadedFiltersIds;
        } catch (e) {
            background_logger_logger.error('Cannot load local filters due to: ', background_error_getErrorMessage(e));
            return [];
        }
    }
    /**
     * Force reload enabled common filters metadata and rules from backend.
     * Called on "use optimized filters" setting switch.
     *
     * If method called in offline mode, some filters may not be loaded,
     * because we have local copies only for our built-in filters.
     */ static async reloadEnabledFilters() {
        const filterIds = background_main_FiltersApi.getEnabledFilters();
        // Ignore custom filters
        const commonFiltersIds = filterIds.filter((id)=>background_CommonFilterApi.isCommonFilter(id));
        const loadedFiltersIds = await background_main_FiltersApi.loadFilters(commonFiltersIds, true);
        // Enable only loaded filters, because click on "use optimized filters"
        // can happen in offline mode and not every filter can be loaded, only
        // built-in filters from local extension's resources.
        background_filterStateStorage.enableFilters(loadedFiltersIds);
    }
    /**
     * Returns filter metadata from correct storage.
     *
     * Common filters metadata is stored in {@link metadataStorage.data.filters}.
     * Custom filters metadata is stored in {@link customFilterMetadataStorage}.
     *
     * @param filterId Filter id.
     *
     * @returns Filter metadata.
     */ static getFilterMetadata(filterId) {
        if (background_custom_CustomFilterApi.isCustomFilter(filterId)) {
            return background_custom_CustomFilterApi.getFilterMetadata(filterId);
        }
        return background_CommonFilterApi.getFilterMetadata(filterId);
    }
    /**
     * Returns filters metadata from both {@link metadataStorage.data.filters} and {@link customFilterMetadataStorage}.
     *
     * @returns Filters metadata array.
     */ static getFiltersMetadata() {
        return [
            ...background_CommonFilterApi.getFiltersMetadata(),
            ...background_custom_CustomFilterApi.getFiltersMetadata()
        ];
    }
    /**
     * Returns enabled filters given the state of the group.
     *
     * @returns Filters ids array.
     */ static getEnabledFilters() {
        const enabledFilters = background_filterStateStorage.getEnabledFilters();
        const enabledGroups = background_groupStateStorage.getEnabledGroups();
        return enabledFilters.filter((id)=>{
            const filterMetadata = background_main_FiltersApi.getFilterMetadata(id);
            return enabledGroups.some((groupId)=>groupId === (filterMetadata === null || filterMetadata === void 0 ? void 0 : filterMetadata.groupId));
        });
    }
    /**
     * Returns enabled filters with metadata.
     *
     * @returns Enabled filters metadata array.
     */ static getEnabledFiltersWithMetadata() {
        return background_main_FiltersApi.getEnabledFilters().map((f)=>background_main_FiltersApi.getFilterMetadata(f)).filter((f)=>f !== undefined);
    }
    /**
     * Enable filters groups that were not touched by users or by code.
     *
     * Called on filter enabling.
     *
     * @param filtersIds Filters ids.
     */ static enableGroupsWereNotTouched(filtersIds) {
        const groupIds = [];
        filtersIds.forEach((filterId)=>{
            const filterMetadata = background_main_FiltersApi.getFilterMetadata(filterId);
            if (!filterMetadata) {
                return;
            }
            const { groupId } = filterMetadata;
            const group = background_groupStateStorage.get(groupId);
            if (!(group === null || group === void 0 ? void 0 : group.touched)) {
                groupIds.push(filterMetadata.groupId);
            }
        });
        if (groupIds.length > 0) {
            background_groupStateStorage.enableGroups(groupIds);
        }
    }
    /**
     * Updates `metadata` with `i18nMetadata`, handles custom group name as well,
     * and saves it.
     *
     * @param metadata Filters, groups and tags metadata.
     * @param i18nMetadata Filters, groups and tags i18n metadata.
     */ static updateMetadataWithI18nMetadata(metadata, i18nMetadata) {
        const localizedMetadata = background_MetadataStorage.applyI18nMetadata(metadata, i18nMetadata);
        const customFiltersGroup = localizedMetadata.groups.find((group)=>{
            return group.groupId === background_AntibannerGroupsId.CustomFiltersGroupId;
        });
        if (!customFiltersGroup) {
            localizedMetadata.groups.push({
                groupId: background_AntibannerGroupsId.CustomFiltersGroupId,
                displayNumber: background_CUSTOM_FILTERS_GROUP_DISPLAY_NUMBER,
                groupName: background_translator.getMessage('options_antibanner_custom_group')
            });
        }
        background_metadataStorage.setData(localizedMetadata);
    }
    /**
     * Loads i18n metadata from remote source and save it.
     *
     * @param remote If true, download data from backend, else load it from local files.
     */ static async loadI18nMetadataFromBackend(remote) {
        const i18nMetadata = remote ? await background_network.downloadI18nMetadataFromBackend() : await background_network.getLocalFiltersI18nMetadata();
        background_i18nMetadataStorage.setData(i18nMetadata);
    }
    /**
     * Loads metadata from remote source, applies i18n metadata, adds custom group
     * and saves it.
     *
     * @param remote If true, download data from backend, else load it from local files.
     */ static async loadMetadataFromFromBackend(remote) {
        const rawMetadata = remote ? await background_network.downloadMetadataFromBackend() : await background_network.getLocalFiltersMetadata();
        const metadata = {
            ...rawMetadata,
            filters: rawMetadata.filters.filter((f)=>{
                // Quick fixes filter was disabled in MV3 to comply with CWR policies.
                // TODO: remove code totally later.
                return f.filterId !== background_AntiBannerFiltersId.QuickFixesFilterId;
            })
        };
        const i18nMetadata = background_i18nMetadataStorage.getData();
        background_main_FiltersApi.updateMetadataWithI18nMetadata(metadata, i18nMetadata);
    }
    /**
     * Read stringified i18n metadata from settings storage.
     * If data is not exist, load it from local assets.
     * If data is exist, update cache version to faster read.
     */ static async initI18nMetadata() {
        const storageData = background_i18nMetadataStorage.read();
        if (typeof storageData !== 'string') {
            await background_main_FiltersApi.loadI18nMetadataFromBackend(false);
            return;
        }
        try {
            const i18nMetadata = background_i18nMetadataValidator.parse(JSON.parse(storageData));
            background_i18nMetadataStorage.setCache(i18nMetadata);
        } catch (e) {
            // eslint-disable-next-line max-len
            background_logger_logger.warn(`Cannot parse data from "${background_i18nMetadataStorage.key}" storage, load from local assets. Origin error: `, e);
            await background_main_FiltersApi.loadI18nMetadataFromBackend(false);
        }
    }
    /**
     * Read stringified metadata from settings storage.
     * If data is not exist, load it from local assets.
     * If data is exist, update cache version to faster read.
     */ static async initMetadata() {
        const storageData = background_metadataStorage.read();
        if (typeof storageData !== 'string') {
            await background_main_FiltersApi.loadMetadataFromFromBackend(false);
            return;
        }
        try {
            const metadata = background_metadata_metadataValidator.parse(JSON.parse(storageData));
            background_metadataStorage.setCache(metadata);
        } catch (e) {
            // eslint-disable-next-line max-len
            background_logger_logger.warn(`Cannot parse data from "${background_metadataStorage.key}" storage, load from local assets. Origin error: `, e);
            await background_main_FiltersApi.loadMetadataFromFromBackend(false);
        }
    }
    /**
     * Set filtering states storages based on app metadata.
     */ static loadFilteringStates() {
        const metadata = background_metadataStorage.getData();
        background_main_FiltersApi.initFilterStateStorage(metadata);
        background_main_FiltersApi.initGroupStateStorage(metadata);
        background_main_FiltersApi.initFilterVersionStorage(metadata);
    }
    /**
     * Read stringified filter states data from settings storage.
     * If data is not exist or partial, update filter states storage based on current metadata.
     *
     * @param metadata App metadata.
     */ static initFilterStateStorage(metadata) {
        const storageData = background_filterStateStorage.read();
        if (typeof storageData !== 'string') {
            background_filterStateStorage.setData(background_FilterStateStorage.applyMetadata({}, metadata));
            return;
        }
        try {
            let data = background_filterStateStorageDataValidator.parse(JSON.parse(storageData));
            data = background_FilterStateStorage.applyMetadata(data, metadata);
            background_filterStateStorage.setData(data);
        } catch (e) {
            // eslint-disable-next-line max-len
            background_logger_logger.warn(`Cannot parse data from "${background_filterStateStorage.key}" storage, load default states. Origin error: `, e);
            background_filterStateStorage.setData(background_FilterStateStorage.applyMetadata({}, metadata));
        }
    }
    /**
     * Read stringified group states data from settings storage.
     * If data is not exist or partial, update group states storage based on current group metadata.
     *
     * @param metadata App metadata.
     */ static initGroupStateStorage(metadata) {
        const storageData = background_groupStateStorage.read();
        if (typeof storageData !== 'string') {
            background_groupStateStorage.setData(background_GroupStateStorage.applyMetadata({}, metadata));
            return;
        }
        try {
            let data = background_groupStateStorageDataValidator.parse(JSON.parse(storageData));
            data = background_GroupStateStorage.applyMetadata(data, metadata);
            background_groupStateStorage.setData(data);
        } catch (e) {
            // eslint-disable-next-line max-len
            background_logger_logger.warn(`Cannot parse data from "${background_groupStateStorage.key}" storage, set default states. Origin error: `, e);
            background_groupStateStorage.setData(background_GroupStateStorage.applyMetadata({}, metadata));
        }
    }
    /**
     * Read stringified filter version data from settings storage.
     * If data is not exist or partial, update filter version storage based on current filter metadata.
     *
     * @param metadata App metadata.
     */ static initFilterVersionStorage(metadata) {
        const storageData = background_filterVersionStorage.read();
        if (typeof storageData !== 'string') {
            background_filterVersionStorage.setData(background_FilterVersionStorage.applyMetadata({}, metadata));
            return;
        }
        try {
            let data = background_filterVersionStorageDataValidator.parse(JSON.parse(storageData));
            data = background_FilterVersionStorage.applyMetadata(data, metadata);
            background_filterVersionStorage.setData(data);
        } catch (e) {
            // eslint-disable-next-line max-len
            background_logger_logger.warn(`Cannot parse data from "${background_filterVersionStorage.key}" storage, set default states. Origin error: `, e);
            background_filterVersionStorage.setData(background_FilterVersionStorage.applyMetadata({}, metadata));
        }
    }
    /**
     * Remove if necessary obsolete filters.
     */ static async removeObsoleteFilters() {
        const installedFiltersIds = background_filterStateStorage.getInstalledFilters();
        const metadataFiltersIds = background_main_FiltersApi.getFiltersMetadata().map(({ filterId })=>filterId);
        const tasks = installedFiltersIds.filter((id)=>!metadataFiltersIds.includes(id)).map(async (id)=>{
            background_filterVersionStorage.delete(id);
            background_filterStateStorage.delete(id);
            await background_FiltersStorage.remove(id);
            await background_RawFiltersStorage.remove(id);
            background_logger_logger.info(`Filter with id: ${id} removed from the storage`);
        });
        const promises = await Promise.allSettled(tasks);
        // Handles errors
        promises.forEach((promise)=>{
            if (promise.status === 'rejected') {
                background_logger_logger.error('Cannot remove obsoleted filter from storage due to: ', promise.reason);
            }
        });
    }
    /**
     * Partially updates metadata for one specified not custom filter without
     * changing metadata with translations for the filter.
     *
     * @param filterMetadata Filter metadata.
     */ static partialUpdateMetadataForFilter(filterMetadata) {
        // i18n metadata not changed, but it is needed for updating metadata
        // via one method (without creating new methods) with translations.
        const oldMetadata = background_metadataStorage.getData();
        const { filterId } = filterMetadata;
        const oldMetadataFilterIdx = oldMetadata.filters.findIndex((f)=>f.filterId === filterId);
        if (oldMetadataFilterIdx !== -1) {
            oldMetadata.filters[oldMetadataFilterIdx] = filterMetadata;
        } else {
            oldMetadata.filters.push(filterMetadata);
        }
        background_main_FiltersApi.updateMetadataWithI18nMetadata(oldMetadata, // i18n metadata not changed.
        background_i18nMetadataStorage.getData());
    }
    /**
     * Selects filters ids where filters are installed and enabled and only those
     * that have their group enabled.
     *
     * @returns List of installed and enabled filters and only those
     * that have their group enabled.
     */ static getInstalledAndEnabledFiltersIds() {
        // Collects filters ids and their states and filters groups ids.
        const filtersStates = background_filterStateStorage.getData();
        const enabledGroupsIds = background_groupStateStorage.getEnabledGroups();
        const allFiltersIds = Object.keys(filtersStates).map((id)=>Number(id));
        // Selects to check only installed and enabled filters and only those
        // that have their group enabled.
        return allFiltersIds.filter((id)=>{
            const filterState = filtersStates[id];
            if (!filterState) {
                return false;
            }
            const { installed, enabled } = filterState;
            if (!installed || !enabled) {
                return false;
            }
            const groupMetadata = background_Categories.getGroupByFilterId(id);
            if (!groupMetadata) {
                return false;
            }
            const groupEnabled = enabledGroupsIds.includes(groupMetadata.groupId);
            return groupEnabled;
        });
    }
}

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isEmpty.js









/** `Object#toString` result references. */
var background_isEmpty_mapTag = '[object Map]',
    background_isEmpty_setTag = '[object Set]';

/** Used for built-in method references. */
var background_isEmpty_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var background_isEmpty_hasOwnProperty = background_isEmpty_objectProto.hasOwnProperty;

/**
 * Checks if `value` is an empty object, collection, map, or set.
 *
 * Objects are considered empty if they have no own enumerable string keyed
 * properties.
 *
 * Array-like values such as `arguments` objects, arrays, buffers, strings, or
 * jQuery-like collections are considered empty if they have a `length` of `0`.
 * Similarly, maps and sets are considered empty if they have a `size` of `0`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is empty, else `false`.
 * @example
 *
 * _.isEmpty(null);
 * // => true
 *
 * _.isEmpty(true);
 * // => true
 *
 * _.isEmpty(1);
 * // => true
 *
 * _.isEmpty([1, 2, 3]);
 * // => false
 *
 * _.isEmpty({ 'a': 1 });
 * // => false
 */
function background_isEmpty(value) {
  if (value == null) {
    return true;
  }
  if (background_lodash_es_isArrayLike(value) &&
      (background_lodash_es_isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
        background_lodash_es_isBuffer(value) || background_lodash_es_isTypedArray(value) || background_lodash_es_isArguments(value))) {
    return !value.length;
  }
  var tag = pages_background_getTag(value);
  if (tag == background_isEmpty_mapTag || tag == background_isEmpty_setTag) {
    return !value.size;
  }
  if (pages_background_isPrototype(value)) {
    return !pages_background_baseKeys(value).length;
  }
  for (var key in value) {
    if (background_isEmpty_hasOwnProperty.call(value, key)) {
      return false;
    }
  }
  return true;
}

/* harmony default export */ const background_lodash_es_isEmpty = (background_isEmpty);

;// ./Extension/src/background/api/filters/hit-stats.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_hit_stats_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}











/**
 * This API is used to store and track ad filters usage stats.
 * It is used if user has enabled "Send statistics for ad filters usage" option.
 * More info about ad filters stats: http://adguard.com/en/filter-rules-statistics.html.
 */ class background_HitStatsApi {
    /**
     * Init hit stats storage.
     */ static async init() {
        try {
            const storageData = await background_hitStatsStorage.read();
            if (typeof storageData === 'string') {
                const data = background_hitStatsStorageDataValidator.parse(JSON.parse(storageData));
                background_hitStatsStorage.setCache(data);
            } else {
                background_hitStatsStorage.setData({});
            }
        } catch (e) {
            // eslint-disable-next-line max-len
            background_logger_logger.error(`Cannot parse data from "${background_hitStatsStorage.key}" storage, set default states. Origin error: `, e);
            background_hitStatsStorage.setData({});
        }
    }
    /**
     * Add 1 rule hit to stats.
     *
     * @param filterId Filter id.
     * @param ruleIndex Rule index.
     */ static addRuleHit(filterId, ruleIndex) {
        // We collect hit stats only for own predefined filter lists
        if (!background_HitStatsApi.shouldCollectHitStats(filterId)) {
            return;
        }
        background_hitStatsStorage.addRuleHitToCache(filterId, ruleIndex);
        background_HitStatsApi.debounceSaveAndSendHitStats();
    }
    /**
     * Cleanup stats.
     *
     * @returns Promise, resolved when storage is cleaned.
     */ static cleanup() {
        return background_hitStatsStorage.setData({});
    }
    /**
     * Sends hit stats to backend server.
     */ static async sendStats() {
        var _hitStats_stats;
        const hitStats = background_hitStatsStorage.getData();
        const overallViews = hitStats.totalHits || 0;
        if (overallViews < background_HitStatsApi.maxTotalHits) {
            return;
        }
        var _hitStats_stats_filters;
        // In the hit stats API, we only have rule indexes, so we need to get original rule texts before sending them
        // So we transform `{ [filterId]: { [ruleIndex]: hits } `} to `{ [filterId]: { [originalRuleText]: hits } }`
        const affectedFilterIds = Object.keys((_hitStats_stats_filters = (_hitStats_stats = hitStats.stats) === null || _hitStats_stats === void 0 ? void 0 : _hitStats_stats.filters) !== null && _hitStats_stats_filters !== void 0 ? _hitStats_stats_filters : {});
        /**
         * Helper function to transform one filter list data from the hit stats to the format that we need.
         *
         * @param filterId Filter list id.
         * @param stats Filter list stats.
         *
         * @returns Transformed filter list data.
         */ const transformFilterHits = async (filterId, stats)=>{
            var _hitStats_versions, _filterVersionStorage_get;
            // If the filter version is not cached or it is outdated, we do not send the stats for this filter
            // (we store the version of the filter on the first hit).
            // When saving hits, we do not analyze the source map, as that would be too heavy,
            // but at this point we need to ensure consistency between the saved hits and the source map in storage
            const cachedFilterVersion = (_hitStats_versions = hitStats.versions) === null || _hitStats_versions === void 0 ? void 0 : _hitStats_versions[filterId];
            const filterIdNumber = Number(filterId);
            if (!cachedFilterVersion || cachedFilterVersion !== ((_filterVersionStorage_get = background_filterVersionStorage.get(filterIdNumber)) === null || _filterVersionStorage_get === void 0 ? void 0 : _filterVersionStorage_get.version)) {
                return [
                    filterId,
                    {}
                ];
            }
            const filterData = await background_FiltersStoragesAdapter.get(filterIdNumber);
            if (!filterData) {
                return [
                    filterId,
                    {}
                ];
            }
            const { rawFilterList, conversionMap, sourceMap } = filterData;
            // It is impossible to get rule text if there is no source map
            if (!sourceMap) {
                return [
                    filterId,
                    {}
                ];
            }
            const ruleTexts = Object.entries(stats).map(([ruleIndex, hits])=>{
                // Get line start index in the source file by rule start index in the byte array
                const lineStartIndex = (0,background_es/* getRuleSourceIndex */.gx)(Number(ruleIndex), sourceMap);
                // During normal operation, this should not happen
                if (lineStartIndex === -1) {
                    let baseMessage = `[HitStatsApi] Cannot find rule source index for rule index ${ruleIndex}`;
                    const ruleNode = background_engine_engine.api.retrieveRuleNode(Number(filterId), Number(ruleIndex));
                    // Note: during normal operation, ruleNode should not be null,
                    // but we handle this case just in case, and to provide type safety
                    if (ruleNode) {
                        const generatedRuleText = background_rule_generator/* RuleGenerator */.u.generate(ruleNode);
                        baseMessage += `, generated rule text: ${generatedRuleText}`;
                    }
                    background_logger_logger.error(baseMessage);
                    return null;
                }
                const appliedRuleText = (0,background_es/* getRuleSourceText */.Bv)(lineStartIndex, rawFilterList);
                // During normal operation, this should not happen
                if (!appliedRuleText) {
                    let baseMessage = `[HitStatsApi] Cannot find rule text for rule index ${ruleIndex}`;
                    const ruleNode = background_engine_engine.api.retrieveRuleNode(Number(filterId), Number(ruleIndex));
                    // Note: during normal operation, ruleNode should not be null,
                    // but we handle this case just in case, and to provide type safety
                    if (ruleNode) {
                        const generatedRuleText = background_rule_generator/* RuleGenerator */.u.generate(ruleNode);
                        baseMessage += `, generated rule text: ${generatedRuleText}`;
                    }
                    background_logger_logger.error(baseMessage);
                    return null;
                }
                // In statistics, we need the original rule text which can be found in the filter list
                if (conversionMap) {
                    const originalRuleText = conversionMap[lineStartIndex];
                    if (originalRuleText) {
                        return [
                            originalRuleText,
                            hits
                        ];
                    }
                }
                return [
                    appliedRuleText,
                    hits
                ];
            }).filter((entry)=>entry !== null);
            return [
                filterId,
                Object.fromEntries(ruleTexts)
            ];
        };
        const hitStatsData = Object.fromEntries((await Promise.all(affectedFilterIds.map(async (filterId)=>{
            var _hitStats_stats_filters, _hitStats_stats;
            const stats = ((_hitStats_stats = hitStats.stats) === null || _hitStats_stats === void 0 ? void 0 : (_hitStats_stats_filters = _hitStats_stats.filters) === null || _hitStats_stats_filters === void 0 ? void 0 : _hitStats_stats_filters[filterId]) || {};
            return transformFilterHits(filterId, stats);
        }))).filter(([_, stats])=>!background_lodash_es_isEmpty(stats)));
        try {
            await background_network.sendHitStats({
                filters: hitStatsData
            });
        } catch (e) {
            background_logger_logger.error(background_error_getErrorMessage(e));
        }
        await background_HitStatsApi.cleanup();
    }
    /**
     * Saves and sends hit stats.
     */ static async saveAndSendHitStats() {
        await background_hitStatsStorage.save();
        await background_HitStatsApi.sendStats();
    }
    /**
     * Checks if hit stats should be collected.
     *
     * We collect statistics only for own predefined filter lists.
     *
     * @param filterId Filter list id.
     *
     * @returns True, if hit stats should be collected.
     */ static shouldCollectHitStats(filterId) {
        return filterId < background_CUSTOM_FILTERS_START_ID && filterId !== background_AntiBannerFiltersId.UserFilterId && filterId !== background_AntiBannerFiltersId.AllowlistFilterId && filterId !== background_AntiBannerFiltersId.StealthModeFilterId;
    }
}
/**
     * Maximum total hits to send stats. We send stats only after reaching this limit.
     */ background_hit_stats_define_property(background_HitStatsApi, "maxTotalHits", 1000);
/**
     * Timeout for saving hit stats.
     */ background_hit_stats_define_property(background_HitStatsApi, "saveTimeoutMs", 2000) // 2 sec
;
/**
     * Saves and sends hit stats with {@link saveTimeoutMs} debounce.
     */ background_hit_stats_define_property(background_HitStatsApi, "debounceSaveAndSendHitStats", background_lodash_es_debounce(()=>{
    background_HitStatsApi.saveAndSendHitStats();
}, background_HitStatsApi.saveTimeoutMs));

;// ./Extension/src/background/api/filters/annoyances-consent.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_annoyances_consent_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}



/**
 * Class for managing annoyances filters consent.
 */ class background_AnnoyancesConsentApi {
    /**
     * Returns an array of consented annoyances filter ids from storage.
     *
     * @returns An array of consented annoyances filter ids.
     */ static async getFromStorage() {
        let data = [];
        try {
            const storageData = await background_annoyancesConsentStorage.read();
            if (typeof storageData === 'string') {
                data = background_annoyancesConsentStorageDataValidator.parse(JSON.parse(storageData));
                background_annoyancesConsentStorage.setCache(data);
            } else {
                data = [];
                await background_annoyancesConsentStorage.setData(data);
            }
        } catch (e) {
            // eslint-disable-next-line max-len
            background_logger_logger.warn(`Cannot parse data from "${background_annoyancesConsentStorage.key}" storage, set default states. Origin error: `, e);
            data = [];
            await background_annoyancesConsentStorage.setData(data);
        }
        return data;
    }
    /**
     * Restores consented annoyances filter ids from storage.
     *
     * @returns Set of consented annoyances filter ids.
     */ static async getConsentFromStorage() {
        const storedConsentedFilterIds = await background_AnnoyancesConsentApi.getFromStorage();
        return new Set(storedConsentedFilterIds);
    }
    /**
     * Resets consented annoyances filter ids to empty array.
     */ async reset() {
        this.consentedFilterIds = null;
        await background_annoyancesConsentStorage.setData([]);
    }
    /**
     * Adds filter ids to the list of consented annoyances filter ids.
     *
     * @param filterIds Filter ids.
     */ async addFilterIds(filterIds) {
        if (this.consentedFilterIds === null) {
            this.consentedFilterIds = await background_AnnoyancesConsentApi.getConsentFromStorage();
        }
        filterIds.forEach((id)=>{
            var _this_consentedFilterIds;
            return (_this_consentedFilterIds = this.consentedFilterIds) === null || _this_consentedFilterIds === void 0 ? void 0 : _this_consentedFilterIds.add(id);
        });
        await background_annoyancesConsentStorage.setData(Array.from(this.consentedFilterIds));
    }
    /**
     * Checks whether the filter is consented.
     *
     * @param id Filter id.
     *
     * @returns True if consent is granted for filter, otherwise false.
     */ async isConsentedFilter(id) {
        if (this.consentedFilterIds === null) {
            this.consentedFilterIds = await background_AnnoyancesConsentApi.getConsentFromStorage();
        }
        return this.consentedFilterIds.has(id);
    }
    /**
     * Creates an instance of {@link AnnoyancesConsentApi}.
     */ constructor(){
        background_annoyances_consent_define_property(this, "consentedFilterIds", void 0);
        // init value
        this.consentedFilterIds = null;
    }
}
const background_annoyancesConsent = new background_AnnoyancesConsentApi();

;// ./Extension/src/background/api/filters/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 







 // TODO: support for quick fixes filter was disabled in MV3 to comply with CWR policies,
 // so we need to revert this block when quick fixes filter will be back
 // export * from './quick-fixes';

;// ./Extension/src/common/nav.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ var background_OptionsPageSections = /*#__PURE__*/ function(OptionsPageSections) {
    OptionsPageSections["general"] = "";
    OptionsPageSections["filters"] = "filters";
    OptionsPageSections["stealth"] = "stealth";
    OptionsPageSections["allowlist"] = "allowlist";
    OptionsPageSections["userFilter"] = "user-filter";
    OptionsPageSections["miscellaneous"] = "miscellaneous";
    OptionsPageSections["ruleLimits"] = "rule-limits";
    OptionsPageSections["about"] = "about";
    return OptionsPageSections;
}({});

;// ./Extension/src/background/api/ui/pages.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_pages_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
















// TODO: We can manipulates tabs directly from content-script and other extension pages context.
// So this API can be shared and used for data flow simplifying (direct calls instead of message passing)
/**
 * Pages API provides methods for managing browser pages.
 */ class background_PagesApi {
    /**
     * Opens the settings tab and focuses on it if there is no open setting tab.
     * Otherwise only focuses on the open setting tab.
     */ static async openSettingsPage() {
        let tab = await background_TabsApi.findOne({
            url: `${background_PagesApi.settingsUrl}*`
        });
        if (!tab) {
            tab = await background_browser_polyfill_default().tabs.create({
                url: background_PagesApi.settingsUrl
            });
        }
        await background_TabsApi.focus(tab);
    }
    /**
     * Opens fullscreen user rules page window.
     * If the page has been already opened, focus on window instead creating new one.
     */ static async openFullscreenUserRulesPage() {
        const tab = await background_TabsApi.findOne({
            url: `${background_PagesApi.fullscreenUserRulesPageUrl}*`
        });
        if (tab) {
            await background_TabsApi.focus(tab);
            return;
        }
        const theme = background_settingsStorage.get(background_SettingOption.AppearanceTheme);
        const url = `${background_PagesApi.fullscreenUserRulesPageUrl}?theme=${theme}`;
        // Open a new tab without type to get it as a new tab in a new window
        // with the ability to move and attach it to the current browser window.
        await background_WindowsApi.create({
            url,
            focused: true,
            ...background_PagesApi.defaultPopupWindowState
        });
    }
    /**
     * Updated the theme for the fullscreen user rules page
     * by updating the query parameter with the new theme value.
     *
     * @param message Message of type {@link UpdateFullscreenUserRulesThemeMessage}.
     * @param message.data Contains new theme value.
     */ static async updateFullscreenUserRulesPageTheme({ data }) {
        const tab = await background_TabsApi.findOne({
            url: `${background_PagesApi.fullscreenUserRulesPageUrl}*`
        });
        if (!tab) {
            return;
        }
        const { theme } = data;
        const url = `${background_PagesApi.fullscreenUserRulesPageUrl}?theme=${theme}`;
        await background_browser_polyfill_default().tabs.update(tab.id, {
            url
        });
    }
    /**
     * Opens filtering log page window.
     * If the page has been already opened, focus on window instead creating new one.
     */ static async openFilteringLogPage() {
        const activeTab = await background_TabsApi.getActive();
        if (!activeTab) {
            return;
        }
        const url = background_PagesApi.filteringLogUrl + (activeTab.id ? `#${activeTab.id}` : '');
        const tab = await background_TabsApi.findOne({
            url: `${background_PagesApi.filteringLogUrl}*`
        });
        if (tab) {
            await background_browser_polyfill_default().tabs.update(tab.id, {
                url
            });
            await background_TabsApi.focus(tab);
            return;
        }
        const windowStateString = await background_browserStorage.get(background_FILTERING_LOG_WINDOW_STATE);
        try {
            const options = typeof windowStateString === 'string' ? JSON.parse(windowStateString) : background_PagesApi.defaultPopupWindowState;
            await background_WindowsApi.create({
                url,
                type: 'popup',
                ...options
            });
        } catch (e) {
            const message = background_error_getErrorMessage(e);
            if (message.includes('Invalid value for bounds.')) {
                // Reopen tab with default pos if it was closed too far beyond the screen
                // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2100
                await background_WindowsApi.create({
                    url,
                    type: 'popup',
                    ...background_PagesApi.defaultPopupWindowState
                });
            }
        }
    }
    /**
     * Creates an url with settings in query parameters needed for issue reporting.
     * Query parameters are described here: https://github.com/AdguardTeam/ReportsWebApp.
     *
     * @param siteUrl Target site url.
     * @param from UI which user is forwarded from.
     *
     * @returns Issue report url.
     */ static async getIssueReportUrl(siteUrl, from) {
        var _groupStateStorage_get;
        let browserName = background_UserAgent.browserName;
        let browserDetails;
        if (!background_UserAgent.isSupportedBrowser) {
            browserDetails = browserName;
            browserName = 'Other';
        }
        const commonFilterIds = background_main_FiltersApi.getEnabledFilters().filter((filterId)=>!background_custom_CustomFilterApi.isCustomFilter(filterId));
        const manifestDetails = background_browser_polyfill_default().runtime.getManifest();
        const params = {
            action: background_ForwardAction.IssueReport,
            from,
            product_type: background_PagesApi.PRODUCT_TYPE,
            manifest_version: encodeURIComponent(manifestDetails.manifest_version),
            product_version: encodeURIComponent(manifestDetails.version),
            url: encodeURIComponent(siteUrl)
        };
        const systemInfo = await background_UserAgent.getSystemInfo();
        if (systemInfo) {
            params.system_version = encodeURIComponent(systemInfo);
        }
        if (browserName) {
            params.browser = encodeURIComponent(browserName);
        }
        if (browserDetails) {
            params.browser_detail = encodeURIComponent(browserDetails);
        }
        if (commonFilterIds.length > 0) {
            params.filters = encodeURIComponent(commonFilterIds.join('.'));
        }
        const isCustomFiltersEnabled = (_groupStateStorage_get = background_groupStateStorage.get(background_AntibannerGroupsId.CustomFiltersGroupId)) === null || _groupStateStorage_get === void 0 ? void 0 : _groupStateStorage_get.enabled;
        // Ignoring custom filters in MV3 since AG-39385.
        // TODO: fix the condition when custom filters will be supported for MV3
        if (isCustomFiltersEnabled && !true) {}
        Object.assign(params, background_PagesApi.getStealthParams(commonFilterIds), background_PagesApi.getBrowserSecurityParams());
        const reportUrl = background_Forward.get(params);
        return reportUrl;
    }
    /**
     * Opens abuse page tab.
     *
     * @param siteUrl Target site url.
     * @param from UI which user is forwarded from.
     */ static async openAbusePage(siteUrl, from) {
        const reportUrl = await background_PagesApi.getIssueReportUrl(siteUrl, from);
        await background_browser_polyfill_default().tabs.create({
            url: reportUrl
        });
    }
    /**
     * Opens site report page.
     *
     * @param siteUrl Target site url.
     * @param from UI which user is forwarded from.
     */ static async openSiteReportPage(siteUrl, from) {
        const domain = background_UrlUtils.getDomainName(siteUrl);
        if (!domain) {
            return;
        }
        const punycodeDomain = background_UrlUtils.toPunyCode(domain);
        await background_browser_polyfill_default().tabs.create({
            url: background_Forward.get({
                from,
                action: background_ForwardAction.SiteReport,
                domain: encodeURIComponent(punycodeDomain)
            })
        });
    }
    /**
     * Create full extension page url, based on precomputed values from webextension API.
     *
     * @param filename Page html filename.
     * @param urlQuery Url query string or/and hash.
     *
     * @returns Full extension page url.
     */ static getExtensionPageUrl(filename, urlQuery) {
        let url = `${background_Prefs.baseUrl}${filename}.html`;
        if (typeof urlQuery === 'string') {
            url += urlQuery;
        }
        return url;
    }
    /**
     * Opens filters download page.
     */ static async openPostInstallPage() {
        await background_browser_polyfill_default().tabs.create({
            url: background_PagesApi.postInstallPageUrl
        });
    }
    /**
     * Opens compare page.
     */ static async openComparePage() {
        await background_browser_polyfill_default().tabs.create({
            url: background_PagesApi.comparePageUrl
        });
    }
    /**
     * Opens thank you page.
     */ static async openThankYouPage() {
        const params = background_BrowserUtils.getExtensionParams();
        params.push(`_locale=${encodeURIComponent(background_browser_polyfill_default().i18n.getUILanguage())}`);
        const pageUrl =  true ? background_PagesApi.thankYouPageUrlMv3 : 0;
        const thankYouUrl = `${pageUrl}?${params.join('&')}`;
        const postInstallPage = await background_TabsApi.findOne({
            url: background_PagesApi.postInstallPageUrl
        });
        if (postInstallPage) {
            await background_browser_polyfill_default().tabs.update(postInstallPage.id, {
                url: thankYouUrl
            });
        } else {
            await background_browser_polyfill_default().tabs.create({
                url: thankYouUrl
            });
        }
    }
    /**
     * Opens extension store page.
     */ static async openExtensionStorePage() {
        await background_browser_polyfill_default().tabs.create({
            url: background_PagesApi.extensionStoreUrl
        });
    }
    /**
     * Opens specified path on settings page.
     *
     * @param url URL path to open on settings page.
     *
     * @returns Opened or updated Tab object.
     */ static async openTabOnSettingsPage(url) {
        const tab = await background_TabsApi.findOne({
            url: `${background_PagesApi.settingsUrl}*`
        });
        if (!tab) {
            const newTab = await background_browser_polyfill_default().tabs.create({
                url
            });
            return newTab;
        }
        const updatedTab = await background_browser_polyfill_default().tabs.update(tab.id, {
            url
        });
        return updatedTab;
    }
    /**
     * Opens 'Add custom filter' modal window into settings page.
     * If the page has been already opened, reload it with new custom filter query params, passed from content script.
     *
     * @param message - Content script message with custom filter data.
     */ static async openSettingsPageWithCustomFilterModal(message) {
        const { url, title } = message.data;
        let optionalPart = '#filters?group=0';
        if (title) {
            optionalPart += `&title=${title}`;
        }
        optionalPart += `&subscribe=${encodeURIComponent(url)}`;
        const path = background_PagesApi.getExtensionPageUrl(background_OPTIONS_OUTPUT, optionalPart);
        const tab = await background_PagesApi.openTabOnSettingsPage(path);
        await background_TabsApi.focus(tab);
        // Reload option page for force modal window rerender
        // TODO: track url update in frontend and remove force reloading via webextension API
        await background_TabsApi.reload(tab.id);
    }
    /**
     * Opens rules limits section on settings page.
     * If the page has been already opened, focus on it.
     */ static async openRulesLimitsPage() {
        const queryPart = `#${background_OptionsPageSections.ruleLimits}`;
        const path = background_PagesApi.getExtensionPageUrl(background_OPTIONS_OUTPUT, queryPart);
        const tab = await background_PagesApi.openTabOnSettingsPage(path);
        await background_TabsApi.focus(tab);
    }
    /**
     * Closes page with {@link Runtime.MessageSender} tab id.
     *
     * @param message - Content script message with custom filter data.
     * @param sender - Sender with type {@link Runtime.MessageSender}.
     */ static async closePage(message, sender) {
        var _sender_tab;
        const tabId = (_sender_tab = sender.tab) === null || _sender_tab === void 0 ? void 0 : _sender_tab.id;
        if (tabId) {
            await background_browser_polyfill_default().tabs.remove(tabId);
        }
    }
    /**
     * Returns extension store url based on UA data.
     *
     * @returns Extension store url.
     */ static getExtensionStoreUrl() {
        let action = background_ForwardAction.ChromeStore;
        if (background_UserAgent.isOpera) {
            action = background_ForwardAction.OperaStore;
        } else if (background_UserAgent.isFirefox) {
            action = background_ForwardAction.FirefoxStore;
        } else if (background_UserAgent.isEdge) {
            action = background_ForwardAction.EdgeStore;
        } else if (false) {}
        return background_Forward.get({
            action,
            from: background_ForwardFrom.Options
        });
    }
    /**
     * Returns browser security url params.
     *
     * @returns Browser security url params record.
     */ static getBrowserSecurityParams() {
        if (true) {
            return {};
        }
        const isEnabled = !background_settingsStorage.get(background_SettingOption.DisableSafebrowsing);
        return {
            'browsing_security.enabled': String(isEnabled)
        };
    }
    /**
     * Returns stealth url params.
     *
     * @param filterIds List of filter id.
     *
     * @returns Stealth url params record.
     */ static getStealthParams(filterIds) {
        const stealthEnabled = !background_settingsStorage.get(background_SettingOption.DisableStealthMode);
        if (!stealthEnabled) {
            return {
                'stealth.enabled': 'false'
            };
        }
        // TODO: Check values of queryKey and maybe move them to some ENUM?
        const stealthOptions = [
            {
                queryKey: 'stealth.ext_hide_referrer',
                settingKey: background_SettingOption.HideReferrer
            },
            {
                queryKey: 'stealth.hide_search_queries',
                settingKey: background_SettingOption.HideSearchQueries
            },
            {
                queryKey: 'stealth.DNT',
                settingKey: background_SettingOption.SendDoNotTrack
            },
            {
                queryKey: 'stealth.x_client',
                settingKey: background_SettingOption.RemoveXClientData
            },
            {
                queryKey: 'stealth.webrtc',
                settingKey: background_SettingOption.BlockWebRTC
            },
            {
                queryKey: 'stealth.third_party_cookies',
                settingKey: background_SettingOption.SelfDestructThirdPartyCookies,
                settingValueKey: background_SettingOption.SelfDestructThirdPartyCookiesTime
            },
            {
                queryKey: 'stealth.first_party_cookies',
                settingKey: background_SettingOption.SelfDestructFirstPartyCookies,
                settingValueKey: background_SettingOption.SelfDestructFirstPartyCookiesTime
            }
        ];
        const stealthOptionsEntries = [
            [
                'stealth.enabled',
                'true'
            ]
        ];
        stealthOptions.forEach((stealthOption)=>{
            const { queryKey, settingKey, settingValueKey } = stealthOption;
            const setting = background_settingsStorage.get(settingKey);
            if (!setting) {
                return;
            }
            let option;
            if (!settingValueKey) {
                option = String(setting);
            } else {
                option = String(background_settingsStorage.get(settingValueKey));
            }
            stealthOptionsEntries.push([
                queryKey,
                option
            ]);
        });
        // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2721
        const isBlockTrackersEnabled = filterIds.includes(background_AntiBannerFiltersId.TrackingFilterId);
        if (isBlockTrackersEnabled) {
            stealthOptionsEntries.push([
                'stealth.block_trackers',
                'true'
            ]);
        }
        const isRemoveUrlParamsEnabled = filterIds.includes(background_AntiBannerFiltersId.UrlTrackingFilterId);
        if (isRemoveUrlParamsEnabled) {
            stealthOptionsEntries.push([
                'stealth.strip_url',
                'true'
            ]);
        }
        return Object.fromEntries(stealthOptionsEntries);
    }
}
/**
     * Product type.
     *
     * It has to be an exact string due to the reports docs.
     *
     * @see {@link https://github.com/AdguardTeam/ReportsWebApp#pre-filling-the-app-with-query-parameters}
     */ background_pages_define_property(background_PagesApi, "PRODUCT_TYPE", 'Ext');
/**
     * Settings page url.
     */ background_pages_define_property(background_PagesApi, "settingsUrl", background_PagesApi.getExtensionPageUrl(background_OPTIONS_OUTPUT));
/**
     * Filtering log page url.
     */ background_pages_define_property(background_PagesApi, "filteringLogUrl", background_PagesApi.getExtensionPageUrl(background_FILTERING_LOG_OUTPUT));
/**
     * Fullscreen user rule editor page url.
     */ background_pages_define_property(background_PagesApi, "fullscreenUserRulesPageUrl", background_PagesApi.getExtensionPageUrl(background_FULLSCREEN_USER_RULES_OUTPUT));
/**
     * Default state of popup window.
     */ background_pages_define_property(background_PagesApi, "defaultPopupWindowState", {
    width: 1280,
    height: 720,
    top: 0,
    left: 0
});
/**
     * Filters download page url.
     */ background_pages_define_property(background_PagesApi, "postInstallPageUrl", background_PagesApi.getExtensionPageUrl(background_POST_INSTALL_OUTPUT));
/**
     * Thank you page url.
     */ background_pages_define_property(background_PagesApi, "thankYouPageUrl", background_Forward.get({
    action: background_ForwardAction.ThankYou,
    from: background_ForwardFrom.Background
}));
/**
     * Thank you page url for mv3.
     */ background_pages_define_property(background_PagesApi, "thankYouPageUrlMv3", background_Forward.get({
    action: background_ForwardAction.ThankYouMv3,
    from: background_ForwardFrom.Background
}));
/**
     * Compare page url.
     */ background_pages_define_property(background_PagesApi, "comparePageUrl", background_Forward.get({
    action: background_ForwardAction.Compare,
    from: background_ForwardFrom.Options
}));
/**
     *  Extension browser store url.
     */ background_pages_define_property(background_PagesApi, "extensionStoreUrl", background_PagesApi.getExtensionStoreUrl());

;// ./Extension/src/background/api/ui/toasts.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_toasts_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}











var background_StylesAssetsPath = /*#__PURE__*/ function(StylesAssetsPath) {
    StylesAssetsPath["AlertPopup"] = "/assets/css/alert-popup.css";
    StylesAssetsPath["AlertContainer"] = "/assets/css/alert-container.css";
    StylesAssetsPath["UpdateContainer"] = "/assets/css/update-container.css";
    StylesAssetsPath["RulesLimitsPopup"] = "/assets/css/rules-limits-popup.css";
    StylesAssetsPath["RulesLimitsContainer"] = "/assets/css/rules-limits-container.css";
    return StylesAssetsPath;
}(background_StylesAssetsPath || {});
/**
 * Toasts class handles work with different popups and alert messages.
 */ class background_Toasts {
    /**
     * Downloads styles assets from {@link StylesAssetsPath}.
     */ async init() {
        const tasks = Object.values(background_StylesAssetsPath).map(async (path)=>{
            const url = background_browser_polyfill_default().runtime.getURL(path);
            const response = await fetch(url);
            const styles = await response.text();
            this.styles.set(path, styles);
        });
        await Promise.all(tasks);
    }
    /**
     * Shows alert message about rule limits exceeded.
     *
     * @param triesCount Number of tries to show. If this value exceeds {@link Toasts#maxTries}
     * then the window will not be displayed.
     */ async showRuleLimitsAlert(triesCount = 1) {
        try {
            if (triesCount > background_Toasts.MAX_TRIES) {
                // Give up
                background_logger_logger.warn('Reached max tries on attempts to show rule limits alert popup');
                return;
            }
            const alertStyles = this.styles.get("/assets/css/rules-limits-popup.css");
            const alertContainerStyles = this.styles.get("/assets/css/rules-limits-container.css");
            if (!alertStyles || !alertContainerStyles) {
                background_logger_logger.error('Alert assets is not loaded!');
                return;
            }
            const tab = await background_TabsApi.getActive();
            if (tab === null || tab === void 0 ? void 0 : tab.id) {
                const mainText = background_translator.getMessage('snack_on_websites_limits_exceeded_warning');
                const linkText = background_translator.getMessage('options_rule_limits');
                await background_sendTabMessage(tab.id, {
                    type: background_constants_MessageType.ShowRuleLimitsAlert,
                    data: {
                        // TODO: Remove isAdguardTab because we don't inject content-script
                        // in our settings page and so that we don't have listener
                        // for these messages.
                        isAdguardTab: background_TabsApi.isAdguardExtensionTab(tab),
                        mainText,
                        linkText,
                        alertStyles,
                        alertContainerStyles
                    }
                });
            }
        } catch (e) {
            // eslint-disable-next-line no-restricted-globals
            self.setTimeout(()=>{
                this.showRuleLimitsAlert(triesCount + 1);
            }, background_Toasts.TRIES_TIMEOUT_MS);
        }
    }
    /**
     * TODO: Continue to use only one method for showing alerts (with new design).
     * Shows alert message.
     *
     * @param title Title.
     * @param text Text.
     * @param triesCount Number of tries to show. If this value exceeds {@link Toasts#maxTries}
     * then the window will not be displayed.
     */ async showAlertMessage(title, text, triesCount = 1) {
        try {
            if (triesCount > background_Toasts.MAX_TRIES) {
                // Give up
                background_logger_logger.warn('Reached max tries on attempts to show alert popup');
                return;
            }
            const tab = await background_TabsApi.getActive();
            const alertStyles = this.styles.get("/assets/css/alert-popup.css");
            const alertContainerStyles = this.styles.get("/assets/css/alert-container.css");
            if (!alertStyles || !alertContainerStyles) {
                background_logger_logger.error('Alert assets is not loaded!');
                return;
            }
            if (tab === null || tab === void 0 ? void 0 : tab.id) {
                await background_sendTabMessage(tab.id, {
                    type: background_constants_MessageType.ShowAlertPopup,
                    data: {
                        // TODO: Remove isAdguardTab because we don't inject content-script
                        // in our settings page and so that we don't have listener
                        // for these messages.
                        isAdguardTab: background_TabsApi.isAdguardExtensionTab(tab),
                        title,
                        text,
                        alertStyles,
                        alertContainerStyles
                    }
                });
            }
        } catch (e) {
            // eslint-disable-next-line no-restricted-globals
            self.setTimeout(()=>{
                this.showAlertMessage(title, text, triesCount + 1);
            }, background_Toasts.TRIES_TIMEOUT_MS);
        }
    }
    /**
     * Show message about enabled filters.
     *
     * @param filters Enabled filters.
     */ showFiltersEnabledAlertMessage(filters) {
        const { title, text } = background_Toasts.getFiltersEnabledResultMessage(filters);
        this.showAlertMessage(title, text);
    }
    /**
     * Show message about result of updating filters.
     *
     * @param success Whether the update was successful or not.
     * @param filters List of filters to update.
     */ showFiltersUpdatedAlertMessage(success, filters) {
        const { title, text } = background_Toasts.getFiltersUpdateResultMessage(success, filters);
        this.showAlertMessage(title, text);
    }
    /**
     * Shows application updated popup.
     *
     * @param currentVersion App current semver string.
     * @param previousVersion App previous semver string.
     * @param triesCount Count of show popup tries.
     */ async showApplicationUpdatedPopup(currentVersion, previousVersion, triesCount = 1) {
        const { getMajorVersionNumber, getMinorVersionNumber } = background_BrowserUtils;
        const promoNotification = await background_promoNotificationApi.getCurrentNotification();
        const majorVersionNotChanged = getMajorVersionNumber(currentVersion) === getMajorVersionNumber(previousVersion);
        const minorVersionNotChanged = getMinorVersionNumber(currentVersion) === getMinorVersionNumber(previousVersion);
        if (!promoNotification && majorVersionNotChanged && minorVersionNotChanged) {
            // In case of no promo available or versions equivalence (major and minor).
            return;
        }
        let offer = background_translator.getMessage('options_popup_version_update_offer');
        let offerDesc = '';
        let offerButtonHref = background_Forward.get({
            action: background_ForwardAction.LearnAboutAdGuard,
            from: background_ForwardFrom.VersionPopup
        });
        let offerButtonText = background_translator.getMessage('options_popup_version_update_offer_button_text');
        let offerBgImage = '';
        if (promoNotification) {
            // check if promo notification is NotificationTextRecord
            const res = background_notificationTextRecordValidator.safeParse(promoNotification.text);
            if (res.success) {
                const text = res.data;
                offer = text.title;
                offerButtonText = text.btn;
                offerButtonHref = `${promoNotification.url}&from=version_popup`;
                if (text.desc) {
                    offerDesc = text.desc;
                }
            }
            const bgImageOnUpdate = promoNotification.bgImageOnUpdate || promoNotification.bgImage;
            if (bgImageOnUpdate) {
                try {
                    // dynamically load svg image if offer should look different for different locales; AG-31141
                    const response = await fetch(bgImageOnUpdate);
                    const svgStr = await response.text();
                    offerBgImage = `data:image/svg+xml;base64,${btoa(svgStr)}`;
                } catch (e) {
                    background_logger_logger.warn('Failed to load promo notification background image', e);
                }
            }
        }
        try {
            if (triesCount > background_Toasts.MAX_TRIES) {
                // Give up
                background_logger_logger.warn('Reached max tries on attempts to show application update popup');
                return;
            }
            const tab = await background_TabsApi.getActive();
            const alertStyles = this.styles.get("/assets/css/alert-popup.css");
            const iframeStyles = this.styles.get("/assets/css/update-container.css");
            if (!alertStyles || !iframeStyles) {
                background_logger_logger.error('Update popup assets is not loaded!');
                return;
            }
            if (tab === null || tab === void 0 ? void 0 : tab.id) {
                await background_sendTabMessage(tab.id, {
                    type: background_constants_MessageType.ShowVersionUpdatedPopup,
                    data: {
                        // TODO: Remove isAdguardTab because we don't inject content-script
                        // in our settings page and so that we don't have listener
                        // for these messages.
                        isAdguardTab: background_TabsApi.isAdguardExtensionTab(tab),
                        title: background_translator.getMessage('options_popup_version_update_title_text', {
                            current_version: currentVersion
                        }),
                        description: background_Toasts.getUpdateDescriptionMessage(currentVersion, previousVersion),
                        changelogHref: background_Forward.get({
                            action:  true ? background_ForwardAction.GithubVersion : 0,
                            from: background_ForwardFrom.VersionPopup
                        }),
                        changelogText: background_translator.getMessage('options_popup_version_update_changelog_text'),
                        showPromoNotification: !!promoNotification,
                        offer,
                        offerDesc,
                        offerButtonText,
                        offerButtonHref,
                        offerBgImage,
                        disableNotificationText: background_translator.getMessage('options_popup_version_update_disable_notification'),
                        alertStyles,
                        iframeStyles
                    }
                });
            }
        } catch (e) {
            // eslint-disable-next-line no-restricted-globals
            self.setTimeout(()=>{
                this.showApplicationUpdatedPopup(currentVersion, previousVersion, triesCount + 1);
            }, background_Toasts.TRIES_TIMEOUT_MS);
        }
    }
    /**
     * Returns message with enabled filters.
     *
     * @param enabledFilters List of enabled filters.
     *
     * @returns Title and text lines for message.
     */ static getFiltersEnabledResultMessage(enabledFilters) {
        const title = background_translator.getMessage('alert_popup_filter_enabled_title');
        const text = enabledFilters.sort((a, b)=>a.displayNumber - b.displayNumber).map((filter)=>background_translator.getMessage('alert_popup_filter_enabled_desc', {
                filter_name: filter.name
            }));
        return {
            title,
            text
        };
    }
    /**
     * Returns message with result of updating filters.
     *
     * @param success Whether the update was successful or not.
     * @param updatedFilters List of filters to update.
     *
     * @returns Title and text lines for message.
     */ static getFiltersUpdateResultMessage(success, updatedFilters) {
        if (!success || !updatedFilters) {
            return {
                title: background_translator.getMessage('options_popup_update_title_error'),
                text: background_translator.getMessage('options_popup_update_error')
            };
        }
        const title = '';
        if (updatedFilters.length === 0) {
            return {
                title,
                text: background_translator.getMessage('options_popup_update_not_found')
            };
        }
        let text = updatedFilters.sort((a, b)=>{
            if (a.groupId === b.groupId) {
                return a.displayNumber - b.displayNumber;
            }
            return Number(a.groupId === b.groupId);
        }).map((filter)=>`${filter.name}`).join(', ');
        if (updatedFilters.length > 1) {
            text += ` ${background_translator.getMessage('options_popup_update_filters')}`;
        } else {
            text += ` ${background_translator.getMessage('options_popup_update_filter')}`;
        }
        return {
            title,
            text
        };
    }
    /**
     * Depending on version numbers select proper message for description.
     *
     * @param currentVersion Current semver of app.
     * @param previousVersion Previous semver of app.
     *
     * @returns Message text.
     */ static getUpdateDescriptionMessage(currentVersion, previousVersion) {
        if (background_BrowserUtils.getMajorVersionNumber(currentVersion) > background_BrowserUtils.getMajorVersionNumber(previousVersion) || background_BrowserUtils.getMinorVersionNumber(currentVersion) > background_BrowserUtils.getMinorVersionNumber(previousVersion)) {
            return background_translator.getMessage('options_popup_version_update_description_major');
        }
        return background_translator.getMessage('options_popup_version_update_description_minor');
    }
    constructor(){
        background_toasts_define_property(this, "styles", new Map());
    }
}
background_toasts_define_property(background_Toasts, "MAX_TRIES", 500);
background_toasts_define_property(background_Toasts, "TRIES_TIMEOUT_MS", 5000) // 5 sec
;
const background_toasts = new background_Toasts();

;// ./Extension/src/background/api/ui/assistant.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 


/**
 * Extension assistant API.
 */ class background_AssistantApi {
    /**
     * Opens assistant window in active tab.
     */ static async openAssistant() {
        const activeTab = await background_TabsApi.getActive();
        if (!(activeTab === null || activeTab === void 0 ? void 0 : activeTab.id)) {
            background_logger_logger.warn('Cannot open assistant in active tab');
            return;
        }
        try {
            await background_engine_engine.api.openAssistant(activeTab.id);
        } catch (e) {
            background_logger_logger.warn('Cannot open assistant in active tab due to: ', e);
        }
    }
}

;// ./Extension/src/background/api/ui/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 








;// ./Extension/src/background/api/install/main.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 



/**
 * The Install API should set the base version of the schema and application,
 * generate a client ID and set default values if the extension has been installed.
 */ class background_InstallApi {
    /**
     * Generate client id.
     *
     * @returns Client id string.
     */ static genClientId() {
        const suffix = Date.now() % 1e8;
        return background_nanoid(8) + suffix;
    }
    /**
     * Initializes app install.
     *
     * @param runInfo Info about extension start up.
     * @param runInfo.currentSchemaVersion Current data schema version.
     */ static async install({ currentSchemaVersion }) {
        const clientId = background_InstallApi.genClientId();
        await background_browserStorage.set(background_CLIENT_ID_KEY, clientId);
        await background_browserStorage.set(background_SCHEMA_VERSION_KEY, currentSchemaVersion);
        await background_browserStorage.set(background_ADGUARD_SETTINGS_KEY, background_defaultSettings);
    }
    /**
     * This method is called after a successful update of the extension.
     * If the extension installation is interrupted for some reason,
     * for example, if the user runs the extension in private mode and the initiation stops,
     * this method is not called. This ensures that actions needed upon
     * initialization will be called again since the version did not change.
     * Issue: https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2713.
     *
     * @param currentAppVersion Current extension version.
     */ static async postSuccessInstall(currentAppVersion) {
        await background_browserStorage.set(background_APP_VERSION_KEY, currentAppVersion);
    }
}

;// ./Extension/src/background/api/install/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

// EXTERNAL MODULE: ./node_modules/.pnpm/core-js@3.40.0/node_modules/core-js/modules/es.typed-array.at.js
var background_es_typed_array_at = __webpack_require__(47348);
// EXTERNAL MODULE: ./node_modules/.pnpm/core-js@3.40.0/node_modules/core-js/modules/es.typed-array.find-last.js
var background_es_typed_array_find_last = __webpack_require__(68551);
// EXTERNAL MODULE: ./node_modules/.pnpm/core-js@3.40.0/node_modules/core-js/modules/es.typed-array.find-last-index.js
var background_es_typed_array_find_last_index = __webpack_require__(16022);
// EXTERNAL MODULE: ./node_modules/.pnpm/core-js@3.40.0/node_modules/core-js/modules/es.typed-array.set.js
var background_es_typed_array_set = __webpack_require__(56965);
// EXTERNAL MODULE: ./node_modules/.pnpm/core-js@3.40.0/node_modules/core-js/modules/es.typed-array.to-reversed.js
var background_es_typed_array_to_reversed = __webpack_require__(93491);
// EXTERNAL MODULE: ./node_modules/.pnpm/core-js@3.40.0/node_modules/core-js/modules/es.typed-array.to-sorted.js
var background_es_typed_array_to_sorted = __webpack_require__(90948);
// EXTERNAL MODULE: ./node_modules/.pnpm/core-js@3.40.0/node_modules/core-js/modules/es.typed-array.with.js
var background_es_typed_array_with = __webpack_require__(31873);
;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isString.js




/** `Object#toString` result references. */
var background_isString_stringTag = '[object String]';

/**
 * Checks if `value` is classified as a `String` primitive or object.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a string, else `false`.
 * @example
 *
 * _.isString('abc');
 * // => true
 *
 * _.isString(1);
 * // => false
 */
function background_isString_isString(value) {
  return typeof value == 'string' ||
    (!background_lodash_es_isArray(value) && background_lodash_es_isObjectLike(value) && pages_background_baseGetTag(value) == background_isString_stringTag);
}

/* harmony default export */ const background_lodash_es_isString = (background_isString_isString);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isUndefined.js
/**
 * Checks if `value` is `undefined`.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
 * @example
 *
 * _.isUndefined(void 0);
 * // => true
 *
 * _.isUndefined(null);
 * // => false
 */
function background_isUndefined_isUndefined(value) {
  return value === undefined;
}

/* harmony default export */ const background_lodash_es_isUndefined = (background_isUndefined_isUndefined);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseSlice.js
/**
 * The base implementation of `_.slice` without an iteratee call guard.
 *
 * @private
 * @param {Array} array The array to slice.
 * @param {number} [start=0] The start position.
 * @param {number} [end=array.length] The end position.
 * @returns {Array} Returns the slice of `array`.
 */
function background_baseSlice(array, start, end) {
  var index = -1,
      length = array.length;

  if (start < 0) {
    start = -start > length ? 0 : (length + start);
  }
  end = end > length ? length : end;
  if (end < 0) {
    end += length;
  }
  length = start > end ? 0 : ((end - start) >>> 0);
  start >>>= 0;

  var result = Array(length);
  while (++index < length) {
    result[index] = array[index + start];
  }
  return result;
}

/* harmony default export */ const pages_background_baseSlice = (background_baseSlice);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_castSlice.js


/**
 * Casts `array` to a slice if it's needed.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {number} start The start position.
 * @param {number} [end=array.length] The end position.
 * @returns {Array} Returns the cast slice.
 */
function background_castSlice(array, start, end) {
  var length = array.length;
  end = end === undefined ? length : end;
  return (!start && end >= length) ? array : pages_background_baseSlice(array, start, end);
}

/* harmony default export */ const pages_background_castSlice = (background_castSlice);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseFindIndex.js
/**
 * The base implementation of `_.findIndex` and `_.findLastIndex` without
 * support for iteratee shorthands.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {Function} predicate The function invoked per iteration.
 * @param {number} fromIndex The index to search from.
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function background_baseFindIndex(array, predicate, fromIndex, fromRight) {
  var length = array.length,
      index = fromIndex + (fromRight ? 1 : -1);

  while ((fromRight ? index-- : ++index < length)) {
    if (predicate(array[index], index, array)) {
      return index;
    }
  }
  return -1;
}

/* harmony default export */ const pages_background_baseFindIndex = (background_baseFindIndex);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsNaN.js
/**
 * The base implementation of `_.isNaN` without support for number objects.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
 */
function background_baseIsNaN(value) {
  return value !== value;
}

/* harmony default export */ const pages_background_baseIsNaN = (background_baseIsNaN);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_strictIndexOf.js
/**
 * A specialized version of `_.indexOf` which performs strict equality
 * comparisons of values, i.e. `===`.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} fromIndex The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function background_strictIndexOf(array, value, fromIndex) {
  var index = fromIndex - 1,
      length = array.length;

  while (++index < length) {
    if (array[index] === value) {
      return index;
    }
  }
  return -1;
}

/* harmony default export */ const pages_background_strictIndexOf = (background_strictIndexOf);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIndexOf.js




/**
 * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} fromIndex The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function background_baseIndexOf(array, value, fromIndex) {
  return value === value
    ? pages_background_strictIndexOf(array, value, fromIndex)
    : pages_background_baseFindIndex(array, pages_background_baseIsNaN, fromIndex);
}

/* harmony default export */ const pages_background_baseIndexOf = (background_baseIndexOf);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_charsEndIndex.js


/**
 * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
 * that is not found in the character symbols.
 *
 * @private
 * @param {Array} strSymbols The string symbols to inspect.
 * @param {Array} chrSymbols The character symbols to find.
 * @returns {number} Returns the index of the last unmatched string symbol.
 */
function background_charsEndIndex(strSymbols, chrSymbols) {
  var index = strSymbols.length;

  while (index-- && pages_background_baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
  return index;
}

/* harmony default export */ const pages_background_charsEndIndex = (background_charsEndIndex);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_asciiToArray.js
/**
 * Converts an ASCII `string` to an array.
 *
 * @private
 * @param {string} string The string to convert.
 * @returns {Array} Returns the converted array.
 */
function background_asciiToArray(string) {
  return string.split('');
}

/* harmony default export */ const pages_background_asciiToArray = (background_asciiToArray);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hasUnicode.js
/** Used to compose unicode character classes. */
var background_rsAstralRange = '\\ud800-\\udfff',
    background_rsComboMarksRange = '\\u0300-\\u036f',
    background_reComboHalfMarksRange = '\\ufe20-\\ufe2f',
    background_rsComboSymbolsRange = '\\u20d0-\\u20ff',
    background_rsComboRange = background_rsComboMarksRange + background_reComboHalfMarksRange + background_rsComboSymbolsRange,
    background_rsVarRange = '\\ufe0e\\ufe0f';

/** Used to compose unicode capture groups. */
var background_rsZWJ = '\\u200d';

/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
var background_reHasUnicode = RegExp('[' + background_rsZWJ + background_rsAstralRange  + background_rsComboRange + background_rsVarRange + ']');

/**
 * Checks if `string` contains Unicode symbols.
 *
 * @private
 * @param {string} string The string to inspect.
 * @returns {boolean} Returns `true` if a symbol is found, else `false`.
 */
function background_hasUnicode(string) {
  return background_reHasUnicode.test(string);
}

/* harmony default export */ const pages_background_hasUnicode = (background_hasUnicode);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_unicodeToArray.js
/** Used to compose unicode character classes. */
var background_unicodeToArray_rsAstralRange = '\\ud800-\\udfff',
    background_unicodeToArray_rsComboMarksRange = '\\u0300-\\u036f',
    background_unicodeToArray_reComboHalfMarksRange = '\\ufe20-\\ufe2f',
    background_unicodeToArray_rsComboSymbolsRange = '\\u20d0-\\u20ff',
    background_unicodeToArray_rsComboRange = background_unicodeToArray_rsComboMarksRange + background_unicodeToArray_reComboHalfMarksRange + background_unicodeToArray_rsComboSymbolsRange,
    background_unicodeToArray_rsVarRange = '\\ufe0e\\ufe0f';

/** Used to compose unicode capture groups. */
var background_rsAstral = '[' + background_unicodeToArray_rsAstralRange + ']',
    background_rsCombo = '[' + background_unicodeToArray_rsComboRange + ']',
    background_rsFitz = '\\ud83c[\\udffb-\\udfff]',
    background_rsModifier = '(?:' + background_rsCombo + '|' + background_rsFitz + ')',
    background_rsNonAstral = '[^' + background_unicodeToArray_rsAstralRange + ']',
    background_rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
    background_rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
    background_unicodeToArray_rsZWJ = '\\u200d';

/** Used to compose unicode regexes. */
var background_reOptMod = background_rsModifier + '?',
    background_rsOptVar = '[' + background_unicodeToArray_rsVarRange + ']?',
    background_rsOptJoin = '(?:' + background_unicodeToArray_rsZWJ + '(?:' + [background_rsNonAstral, background_rsRegional, background_rsSurrPair].join('|') + ')' + background_rsOptVar + background_reOptMod + ')*',
    background_rsSeq = background_rsOptVar + background_reOptMod + background_rsOptJoin,
    background_rsSymbol = '(?:' + [background_rsNonAstral + background_rsCombo + '?', background_rsCombo, background_rsRegional, background_rsSurrPair, background_rsAstral].join('|') + ')';

/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
var background_reUnicode = RegExp(background_rsFitz + '(?=' + background_rsFitz + ')|' + background_rsSymbol + background_rsSeq, 'g');

/**
 * Converts a Unicode `string` to an array.
 *
 * @private
 * @param {string} string The string to convert.
 * @returns {Array} Returns the converted array.
 */
function background_unicodeToArray(string) {
  return string.match(background_reUnicode) || [];
}

/* harmony default export */ const pages_background_unicodeToArray = (background_unicodeToArray);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stringToArray.js




/**
 * Converts `string` to an array.
 *
 * @private
 * @param {string} string The string to convert.
 * @returns {Array} Returns the converted array.
 */
function background_stringToArray(string) {
  return pages_background_hasUnicode(string)
    ? pages_background_unicodeToArray(string)
    : pages_background_asciiToArray(string);
}

/* harmony default export */ const pages_background_stringToArray = (background_stringToArray);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/trimEnd.js







/**
 * Removes trailing whitespace or specified characters from `string`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category String
 * @param {string} [string=''] The string to trim.
 * @param {string} [chars=whitespace] The characters to trim.
 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
 * @returns {string} Returns the trimmed string.
 * @example
 *
 * _.trimEnd('  abc  ');
 * // => '  abc'
 *
 * _.trimEnd('-_-abc-_-', '_-');
 * // => '-_-abc'
 */
function background_trimEnd(string, chars, guard) {
  string = background_lodash_es_toString(string);
  if (string && (guard || chars === undefined)) {
    return string.slice(0, pages_background_trimmedEndIndex(string) + 1);
  }
  if (!string || !(chars = pages_background_baseToString(chars))) {
    return string;
  }
  var strSymbols = pages_background_stringToArray(string),
      end = pages_background_charsEndIndex(strSymbols, pages_background_stringToArray(chars)) + 1;

  return pages_background_castSlice(strSymbols, 0, end).join('');
}

/* harmony default export */ const background_lodash_es_trimEnd = (background_trimEnd);

;// ./Extension/src/background/utils/indexed-db.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

/**
 * Helper class for working with IndexedDB.
 */ class background_IDBUtils {
    /**
     * Connects to IndexedDB database.
     *
     * @param name Name of the database to connect to.
     *
     * @returns Promise, resolved with IndexedDB API interface provides a connection to a database.
     *
     * @throws Error, if database is not opened after limit.
     */ static async connect(name) {
        return background_createPromiseWithTimeout(new Promise((resolve, reject)=>{
            const request = indexedDB.open(name);
            request.onerror = (event)=>{
                reject(new Error(`Error opening database: ${event.target.error}`));
            };
            request.onsuccess = (event)=>{
                resolve(event.target.result);
            };
        }));
    }
    /**
     * Gets data from IndexedDB object store.
     *
     * @param db IndexedDB API.
     * @param storeName IndexedDB Object store name.
     *
     * @returns Promise, resolved with data from object store.
     *
     * @throws Error, if request is not resolved after limit.
     */ static async getAll(db, storeName) {
        return background_createPromiseWithTimeout(new Promise((resolve, reject)=>{
            const transaction = db.transaction(storeName, 'readonly');
            const store = transaction.objectStore(storeName);
            const request = store.getAll();
            request.onerror = (event)=>{
                const error = new Error(`Error getting data from object store: ${event.target.error}`);
                reject(error);
            };
            request.onsuccess = (event)=>{
                resolve(event.target.result);
            };
        }));
    }
}

;// ./Extension/src/background/api/update/assets/old-filters-storage-v1.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 












/**
 * Storage prefix for raw preprocessed filter lists.
 */ const background_FILTER_KEY_PREFIX = 'filterrules_';
/**
 * Storage prefix for binary serialized preprocessed filter lists.
 */ const background_BINARY_FILTER_KEY_PREFIX = 'binaryfilterrules_';
/**
 * Storage prefix for conversion map.
 * Conversion map is used to get original user rules from the preprocessed filter list.
 */ const background_CONVERSION_MAP_PREFIX = 'conversionmap_';
/**
 * Storage prefix for source map.
 * Source map is used to map binary serialized rules to the raw preprocessed filter list.
 */ const background_SOURCE_MAP_PREFIX = 'sourcemap_';
/**
 * Schema for the conversion map.
 */ const background_CONVERSION_MAP_SCHEMA = background_lib/* default.record */.Ay.record(background_lib/* default.string */.Ay.string(), background_lib/* default.string */.Ay.string()).default({});
/**
 * Schema for the source map.
 */ const background_SOURCE_MAP_SCHEMA = background_lib/* default.record */.Ay.record(background_lib/* default.string */.Ay.string(), background_lib/* default.number */.Ay.number()).default({});
/**
 * Regular expression that helps to extract filter id from the key.
 */ const background_old_filters_storage_v1_RE_FILTER_KEY = new RegExp(`^(${background_FILTER_KEY_PREFIX})(?<filterId>\\d+)${background_FILTER_LIST_EXTENSION}$`);
const background_extractIdFromKey = (key)=>{
    var _key_split_pop;
    return (_key_split_pop = key.split('_').pop()) !== null && _key_split_pop !== void 0 ? _key_split_pop : null;
};
/**
 * Encapsulates interaction with stored filter rules.
 */ class background_old_filters_storage_v1_FiltersStorage {
    /**
     * Sets specified filter list to {@link storage}.
     *
     * @param filterId Filter id.
     * @param filter Filter rules strings.
     */ static async set(filterId, filter) {
        try {
            const data = background_old_filters_storage_v1_FiltersStorage.prepareFilterForStorage(filterId, filter);
            const succeeded = await background_hybridStorage.setMultiple(data);
            if (!succeeded) {
                throw new Error('Transaction failed');
            }
        } catch (e) {
            background_logger_logger.error(`Failed to set filter list for filter id ${filterId}, got error:`, e);
            throw e;
        }
    }
    /**
     * Helper method to get data to set to the storage for the specified filter list.
     *
     * @param filterId Filter id.
     * @param filter Filter rules strings.
     *
     * @returns Record with data to set to the storage.
     */ static prepareFilterForStorage(filterId, filter) {
        const { rawFilterList, filterList, conversionMap, sourceMap } = background_es/* FilterListPreprocessor */.aQ.preprocess(filter.join('\n'));
        const result = {
            [background_old_filters_storage_v1_FiltersStorage.getFilterKey(filterId)]: rawFilterList,
            [background_old_filters_storage_v1_FiltersStorage.getBinaryFilterKey(filterId)]: filterList,
            [background_old_filters_storage_v1_FiltersStorage.getConversionMapKey(filterId)]: conversionMap,
            [background_old_filters_storage_v1_FiltersStorage.getSourceMapKey(filterId)]: sourceMap
        };
        return result;
    }
    /**
     * Checks if specified filter list is in {@link hybridStorage}.
     *
     * @param filterId Filter id.
     *
     * @returns Promise, resolved with `true` if filter list is in storage, `false` otherwise.
     */ static async has(filterId) {
        const key = background_old_filters_storage_v1_FiltersStorage.getFilterKey(filterId);
        return background_hybridStorage.has(key);
    }
    /**
     * Returns specified filter list from {@link hybridStorage}.
     *
     * @param filterId Filter id.
     * @param logError If `true`, logs error if it occurs.
     *
     * @returns Promise, resolved with filter rules strings.
     *
     * @throws Error, if filter list data is not valid.
     */ static async get(filterId, logError = true) {
        try {
            const binaryFilterKey = background_old_filters_storage_v1_FiltersStorage.getBinaryFilterKey(filterId);
            const data = await background_hybridStorage.get(binaryFilterKey);
            return background_lib/* default.array */.Ay.array(background_lib/* default.instanceof */.Ay["instanceof"](Uint8Array)).parse(data);
        } catch (e) {
            if (logError) {
                background_logger_logger.error(`Failed to get binary filter data for filter id ${filterId}, got error:`, e);
            }
            throw e;
        }
    }
    /**
     * Returns raw preprocessed filter list for the specified filter id.
     *
     * @param filterId Filter id.
     *
     * @returns Promise, resolved with preprocessed filter list.
     *
     * @throws Error, if filter list data is not valid.
     */ static async getPreprocessedFilterList(filterId) {
        try {
            const filterKey = background_old_filters_storage_v1_FiltersStorage.getFilterKey(filterId);
            const data = await background_hybridStorage.get(filterKey);
            return background_lib/* default.string */.Ay.string().parse(data);
        } catch (e) {
            background_logger_logger.error(`Failed to get preprocessed raw filter list for filter id ${filterId}, got error:`, e);
            throw e;
        }
    }
    /**
     * Returns source map for the specified filter list.
     *
     * @param filterId Filter id.
     *
     * @returns Promise, resolved with source map.
     *
     * @throws Error, if source map data is not valid.
     */ static async getSourceMap(filterId) {
        try {
            const sourceMapKey = background_old_filters_storage_v1_FiltersStorage.getSourceMapKey(filterId);
            const data = await background_hybridStorage.get(sourceMapKey);
            return background_SOURCE_MAP_SCHEMA.parse(data);
        } catch (e) {
            background_logger_logger.error(`Failed to get source map for filter id '${filterId}', ${filterId}, got error:`, e);
            throw e;
        }
    }
    /**
     * Returns conversion map for the specified filter list.
     *
     * @param filterId Filter id.
     *
     * @returns Promise, resolved with conversion map.
     *
     * @throws Error, if conversion map data is not valid.
     */ static async getConversionMap(filterId) {
        try {
            const conversionMapKey = background_old_filters_storage_v1_FiltersStorage.getConversionMapKey(filterId);
            const data = await background_hybridStorage.get(conversionMapKey);
            return background_CONVERSION_MAP_SCHEMA.parse(data);
        } catch (e) {
            background_logger_logger.error(`Failed to get conversion map for filter id ${filterId}, got error:`, e);
            throw e;
        }
    }
    /**
     * Returns original user rules from {@link hybridStorage}.
     *
     * @param filterId Filter id.
     *
     * @returns Promise, resolved with original user rules strings.
     *
     * @throws Error, if filter list data is not valid.
     */ static async getOriginalRules(filterId) {
        const [rawFilterList, conversionMap] = await Promise.all([
            background_old_filters_storage_v1_FiltersStorage.getPreprocessedFilterList(filterId),
            background_old_filters_storage_v1_FiltersStorage.getConversionMap(filterId)
        ]);
        return background_es/* FilterListPreprocessor */.aQ.getOriginalRules({
            rawFilterList,
            conversionMap
        });
    }
    /**
     * Returns original filter list text for the specified filter id.
     *
     * @param filterId Filter id.
     *
     * @returns Promise, resolved with original filter list text.
     *
     * @throws Error, if filter list data is not valid.
     */ static async getOriginalFilterListText(filterId) {
        const [rawFilterList, conversionMap] = await Promise.all([
            background_old_filters_storage_v1_FiltersStorage.getPreprocessedFilterList(filterId),
            background_old_filters_storage_v1_FiltersStorage.getConversionMap(filterId)
        ]);
        return background_es/* FilterListPreprocessor */.aQ.getOriginalFilterListText({
            rawFilterList,
            conversionMap
        });
    }
    /**
     * Get all filter data, including conversion map and source map.
     *
     * @param filterId Filter id.
     *
     * @returns Promise, resolved with filter data or `null` if filter is not
     * found or some part of the data is missing.
     */ static async getAllFilterData(filterId) {
        try {
            const [filterList, rawFilterList, conversionMap, sourceMap] = await Promise.all([
                background_old_filters_storage_v1_FiltersStorage.get(filterId),
                background_old_filters_storage_v1_FiltersStorage.getPreprocessedFilterList(filterId),
                background_old_filters_storage_v1_FiltersStorage.getConversionMap(filterId),
                background_old_filters_storage_v1_FiltersStorage.getSourceMap(filterId)
            ]);
            return {
                filterList,
                rawFilterList,
                conversionMap,
                sourceMap
            };
        } catch (e) {
            background_logger_logger.error('Failed to get all filter data', e);
            return null;
        }
    }
    /**
     * Removes specified filter list from {@link hybridStorage}.
     *
     * @param filterId Filter id.
     */ static async remove(filterId) {
        await background_hybridStorage.removeMultiple([
            background_old_filters_storage_v1_FiltersStorage.getBinaryFilterKey(filterId),
            background_old_filters_storage_v1_FiltersStorage.getFilterKey(filterId),
            background_old_filters_storage_v1_FiltersStorage.getConversionMapKey(filterId),
            background_old_filters_storage_v1_FiltersStorage.getSourceMapKey(filterId)
        ]);
    }
    /**
     * Returns {@link hybridStorage} key from specified filter list.
     *
     * @param filterId Filter id.
     *
     * @returns Storage key from specified filter list.
     */ static getFilterKey(filterId) {
        return `${background_FILTER_KEY_PREFIX}${filterId}${background_FILTER_LIST_EXTENSION}`;
    }
    /**
     * Helper method to extract filter id from the key.
     *
     * @param key Storage key.
     *
     * @returns Filter id or `null` if the key is invalid.
     */ static extractFilterIdFromFilterKey(key) {
        var _match_groups;
        const match = key.match(background_old_filters_storage_v1_RE_FILTER_KEY);
        var _match_groups_filterId;
        return match ? parseInt((_match_groups_filterId = (_match_groups = match.groups) === null || _match_groups === void 0 ? void 0 : _match_groups.filterId) !== null && _match_groups_filterId !== void 0 ? _match_groups_filterId : '', 10) : null;
    }
    /**
     * Returns {@link hybridStorage} key to conversion map from specified filter list.
     *
     * @param filterId Filter id.
     *
     * @returns Storage key to conversion map from specified filter list.
     */ static getConversionMapKey(filterId) {
        return `${background_CONVERSION_MAP_PREFIX}${filterId}${background_FILTER_LIST_EXTENSION}`;
    }
    /**
     * Returns {@link hybridStorage} key to source map from specified filter list.
     *
     * @param filterId Filter id.
     *
     * @returns Storage key to source map from specified filter list.
     */ static getSourceMapKey(filterId) {
        return `${background_SOURCE_MAP_PREFIX}${filterId}${background_FILTER_LIST_EXTENSION}`;
    }
    /**
     * Returns {@link hybridStorage} key to binary filter list from specified filter list.
     *
     * @param filterId Filter id.
     *
     * @returns Storage key to binary filter list from specified filter list.
     */ static getBinaryFilterKey(filterId) {
        return `${background_BINARY_FILTER_KEY_PREFIX}${filterId}${background_FILTER_LIST_EXTENSION}`;
    }
}

;// ./Extension/src/background/api/update/assets/old-browser-storage-v1.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_old_browser_storage_v1_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}

/**
 * Wrapper for browser.storage.local with dev-friendly interface.
 */ class background_old_browser_storage_v1_BrowserStorage {
    /**
     * Sets data to storage.
     *
     * @param key Storage key.
     * @param value Storage value.
     */ async set(key, value) {
        await this.storage.set({
            [key]: value
        });
    }
    /**
     * Returns data from storage.
     *
     * @param key Storage key.
     *
     * @returns Storage value.
     */ async get(key) {
        var _this;
        return (_this = await this.storage.get(key)) === null || _this === void 0 ? void 0 : _this[key];
    }
    /**
     * Removes data from storage.
     *
     * @param key Storage key.
     */ async remove(key) {
        await this.storage.remove(key);
    }
    /**
     * Sets multiple key-value pairs in the storage.
     *
     * @param data The key-value pairs to set.
     *
     * @returns True if all operations were successful, false otherwise.
     *
     * @example
     * ```ts
     * const storage = new Storage();
     * await storage.setMultiple({
     *    key1: 'value1',
     *    key2: 'value2',
     * });
     * ```
     */ // TODO: Implement some kind of transaction to ensure atomicity, if possible
    // Note: We only use this method for Firefox if "Never Remember History" is enabled
    async setMultiple(data) {
        try {
            await this.storage.set(data);
            return true;
        } catch (e) {
            return false;
        }
    }
    /**
     * Removes multiple key-value pairs from the storage.
     *
     * @param keys The keys to remove.
     *
     * @returns True if all operations were successful, false otherwise.
     */ async removeMultiple(keys) {
        await this.storage.remove(keys);
        return true;
    }
    /**
     * Get the entire contents of the storage.
     *
     * @returns Promise that resolves with the entire contents of the storage.
     */ async entries() {
        return this.storage.get(null);
    }
    /**
     * Get all keys from the storage.
     *
     * @returns Promise that resolves with all keys from the storage.
     */ async keys() {
        return Object.keys(await this.entries());
    }
    /**
     * Checks if the storage has a key.
     *
     * @param key The key to check.
     *
     * @returns True if the key exists, false otherwise.
     */ async has(key) {
        return this.storage.get(key).then((data)=>key in data);
    }
    constructor(){
        // extension storage API
        background_old_browser_storage_v1_define_property(this, "storage", (background_browser_polyfill_default()).storage.local);
    }
}

;// ./Extension/src/background/api/update/assets/old-idb-storage-v1.ts
/**
 * @file IndexedDB storage implementation.
 */ function background_old_idb_storage_v1_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}



const background_DEFAULT_STORE_NAME = 'defaultStore';
const background_DEFAULT_IDB_NAME = 'adguardIDB';
/**
 * Provides a storage mechanism using IndexedDB. This class implements the
 * StorageInterface with asynchronous methods to interact with the database.
 */ class background_old_idb_storage_v1_IDBStorage {
    /**
     * Ensures the database is opened before any operations. If the database
     * is not already opened, it opens the database.
     *
     * @returns The opened database instance.
     */ async getOpenedDb() {
        if (!this.db) {
            this.db = await background_openDB(this.name, this.version, {
                upgrade: (db)=>{
                    // make sure the store exists
                    if (!db.objectStoreNames.contains(this.store)) {
                        db.createObjectStore(this.store);
                    }
                }
            });
        }
        return this.db;
    }
    /**
     * Retrieves a value by key from the store.
     *
     * @param key The key of the value to retrieve.
     *
     * @returns The value associated with the key.
     */ async get(key) {
        const db = await this.getOpenedDb();
        return db.get(this.store, key);
    }
    /**
     * Sets a value in the store with the specified key.
     *
     * @param key The key under which to store the value.
     * @param value The value to store.
     */ async set(key, value) {
        const db = await this.getOpenedDb();
        await db.put(this.store, value, key);
    }
    /**
     * Removes a value from the store by key.
     *
     * @param key The key of the value to remove.
     */ async remove(key) {
        const db = await this.getOpenedDb();
        await db.delete(this.store, key);
    }
    /**
     * Atomic set operation for multiple key-value pairs.
     * This method is using transaction to ensure atomicity, if any of the operations fail,
     * the entire operation is rolled back. This helps to prevent data corruption / inconsistency.
     *
     * @param data The key-value pairs to set.
     *
     * @returns True if all operations were successful, false otherwise.
     *
     * @example
     * ```ts
     * const storage = new IDBStorage();
     * await storage.setMultiple({
     *    key1: 'value1',
     *    key2: 'value2',
     * });
     * ```
     */ async setMultiple(data) {
        const db = await this.getOpenedDb();
        const tx = db.transaction(this.store, 'readwrite');
        try {
            await Promise.all(Object.entries(data).map(([key, value])=>tx.store.put(value, key)));
            await tx.done;
        } catch (e) {
            background_logger_logger.error('Error while setting multiple keys in the storage:', background_error_getErrorMessage(e));
            tx.abort();
            return false;
        }
        return true;
    }
    /**
     * Removes multiple key-value pairs from the storage.
     *
     * @param keys The keys to remove.
     *
     * @returns True if all operations were successful, false otherwise.
     */ async removeMultiple(keys) {
        const db = await this.getOpenedDb();
        const tx = db.transaction(this.store, 'readwrite');
        try {
            await Promise.all(keys.map((key)=>tx.store.delete(key)));
            await tx.done;
        } catch (e) {
            background_logger_logger.error('Error while removing multiple keys from the storage:', background_error_getErrorMessage(e));
            tx.abort();
            return false;
        }
        return true;
    }
    /**
     * Get the entire contents of the storage.
     *
     * @returns Promise that resolves with the entire contents of the storage.
     */ async entries() {
        const db = await this.getOpenedDb();
        const entries = {};
        const tx = db.transaction(this.store, 'readonly');
        // eslint-disable-next-line no-restricted-syntax
        for await (const cursor of tx.store){
            const key = String(cursor.key);
            entries[key] = cursor.value;
        }
        return entries;
    }
    /**
     * Get all keys in the storage.
     *
     * @returns Promise that resolves with all keys in the storage.
     */ async keys() {
        const db = await this.getOpenedDb();
        const idbKeys = await db.getAllKeys(this.store);
        return idbKeys.map((key)=>key.toString());
    }
    /**
     * Check if a key exists in the storage.
     *
     * @param key The key to check.
     *
     * @returns True if the key exists, false otherwise.
     */ async has(key) {
        const db = await this.getOpenedDb();
        return db.getKey(this.store, key).then((result)=>result !== undefined);
    }
    /**
     * Constructs an instance of the IDBStorage class.
     *
     * @param name The name of the database.
     * @param [version=1] The version of the database.
     * @param [store=DEFAULT_STORE_NAME] The name of the store.
     */ constructor(name = background_DEFAULT_IDB_NAME, version = 1, store = background_DEFAULT_STORE_NAME){
        /**
     * Holds the instance of the IndexedDB database.
     */ background_old_idb_storage_v1_define_property(this, "db", null);
        /**
     * The name of the database.
     */ background_old_idb_storage_v1_define_property(this, "name", void 0);
        /**
     * The version of the database. Used for upgrades.
     */ background_old_idb_storage_v1_define_property(this, "version", void 0);
        /**
     * The name of the store within the database.
     */ background_old_idb_storage_v1_define_property(this, "store", void 0);
        this.name = name;
        this.version = version;
        this.store = store;
    }
}

;// ./Extension/src/background/api/update/assets/old-hybrid-storage-v1.ts
/* eslint-disable @typescript-eslint/no-explicit-any */ /**
 * @file This file implements a hybrid storage solution that abstracts over different storage mechanisms,
 * providing a unified API for storage operations. It automatically chooses between IndexedDB storage and
 * a fallback storage mechanism based on the environment's capabilities.
 */ function background_old_hybrid_storage_v1_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}












/**
 * Prefix for the test IndexedDB database name.
 * This test database is used to check if IndexedDB is supported in the current environment.
 */ const background_TEST_IDB_NAME_PREFIX = 'test_';
/**
 * Implements a hybrid storage mechanism that can switch between IndexedDB and a fallback storage
 * based on browser capabilities and environment constraints. This class adheres to the StorageInterface,
 * allowing for asynchronous get and set operations.
 */ class background_old_hybrid_storage_v1_HybridStorage {
    /**
     * Returns true if the selected storage mechanism is IndexedDB.
     *
     * @returns True if the selected storage mechanism is IndexedDB, false otherwise.
     */ isIdb() {
        return this.storage instanceof background_old_idb_storage_v1_IDBStorage;
    }
    /**
     * Determines the appropriate storage mechanism to use. If IndexedDB is supported, it uses IDBStorage;
     * otherwise, it falls back to a generic Storage mechanism. This selection is made once and cached
     * for subsequent operations.
     *
     * @returns The storage instance to be used for data operations.
     */ async getStorage() {
        if (this.storage) {
            return this.storage;
        }
        if (await background_old_hybrid_storage_v1_HybridStorage.isIDBSupported()) {
            this.storage = new background_old_idb_storage_v1_IDBStorage();
        } else {
            this.storage = new background_old_browser_storage_v1_BrowserStorage();
        }
        return this.storage;
    }
    /**
     * Checks if IndexedDB is supported in the current environment. This is determined by trying to open
     * a test database; if successful, IndexedDB is supported.
     *
     * @returns True if IndexedDB is supported, false otherwise.
     */ static async isIDBSupported() {
        try {
            const testDbName = `${background_TEST_IDB_NAME_PREFIX}${background_nanoid()}`;
            const testDb = await background_openDB(testDbName, 1);
            testDb.close();
            await background_deleteDB(testDbName);
            return true;
        } catch (e) {
            return false;
        }
    }
    /**
     * Asynchronously sets a value for a given key in the selected storage mechanism.
     *
     * @param key The key under which the value is stored.
     * @param value The value to be stored.
     *
     * @returns A promise that resolves when the operation is complete.
     */ async set(key, value) {
        const storage = await this.getStorage();
        if (this.isIdb()) {
            return storage.set(key, value);
        }
        const rawValue = this.serialize(value);
        return storage.set(key, rawValue);
    }
    /**
     * Asynchronously retrieves the value for a given key from the selected storage mechanism.
     *
     * @param key The key whose value is to be retrieved.
     *
     * @returns A promise that resolves with the retrieved value, or undefined if the key does not exist.
     */ async get(key) {
        const storage = await this.getStorage();
        const value = await storage.get(key);
        if (this.isIdb()) {
            return value;
        }
        return this.deserialize(value);
    }
    /**
     * Asynchronously removes the value for a given key from the selected storage mechanism.
     *
     * @param key The key whose value is to be removed.
     *
     * @returns A promise that resolves when the operation is complete.
     */ async remove(key) {
        const storage = await this.getStorage();
        return storage.remove(key);
    }
    /**
     * Atomic set operation for multiple key-value pairs.
     * This method are using transaction to ensure atomicity, if any of the operations fail,
     * the entire operation is rolled back. This helps to prevent data corruption / inconsistency.
     *
     * @param data The key-value pairs to set.
     *
     * @returns True if all operations were successful, false otherwise.
     *
     * @example
     * ```ts
     * const storage = new HybridStorage();
     * await storage.setMultiple({
     *    key1: 'value1',
     *    key2: 'value2',
     * });
     * ```
     */ async setMultiple(data) {
        const storage = await this.getStorage();
        if (this.isIdb()) {
            var _ref;
            return (_ref = await storage.setMultiple(data)) !== null && _ref !== void 0 ? _ref : false;
        }
        const cloneData = {
            ...data
        };
        Object.entries(cloneData).forEach(([key, value])=>{
            cloneData[key] = this.serialize(value);
        });
        var _ref1;
        return (_ref1 = await storage.setMultiple(cloneData)) !== null && _ref1 !== void 0 ? _ref1 : false;
    }
    /**
     * Removes multiple key-value pairs from the storage.
     *
     * @param keys The keys to remove.
     *
     * @returns True if all operations were successful, false otherwise.
     */ async removeMultiple(keys) {
        const storage = await this.getStorage();
        var _ref;
        return (_ref = await storage.removeMultiple(keys)) !== null && _ref !== void 0 ? _ref : false;
    }
    /**
     * Get the entire contents of the storage.
     *
     * @returns Promise that resolves with the entire contents of the storage.
     */ async entries() {
        const storage = await this.getStorage();
        return storage.entries();
    }
    /**
     * Get all keys from the storage.
     *
     * @returns Promise that resolves with all keys from the storage.
     */ async keys() {
        const storage = await this.getStorage();
        return storage.keys();
    }
    /**
     * Check if a key exists in the storage.
     *
     * @param key The key to check.
     *
     * @returns True if the key exists, false otherwise.
     */ async has(key) {
        const storage = await this.getStorage();
        return storage.has(key);
    }
    constructor(){
        /**
     * Holds the instance of the selected storage mechanism.
     */ background_old_hybrid_storage_v1_define_property(this, "storage", null);
        /**
     * Helper function to serialize Uint8Array members of an object.
     * This workaround is needed because by default chrome.storage API doesn't support Uint8Array,
     * and we use it to store serialized filter lists.
     *
     * @param value Object to serialize.
     *
     * @returns Serialized object.
     */ background_old_hybrid_storage_v1_define_property(this, "serialize", (value)=>{
            if (value instanceof Uint8Array) {
                return {
                    __type: 'Uint8Array',
                    data: Array.from(value)
                };
            }
            if (Array.isArray(value)) {
                return value.map(this.serialize);
            }
            if (background_lodash_es_isObject(value)) {
                const serializedObject = {};
                // eslint-disable-next-line no-restricted-syntax
                for (const [key, val] of Object.entries(value)){
                    serializedObject[key] = this.serialize(val);
                }
                return serializedObject;
            }
            return value;
        });
        /**
     * Helper function to deserialize Uint8Array members of an object.
     * This workaround is needed because by default chrome.storage API doesn't support Uint8Array,
     * and we use it to store serialized filter lists.
     *
     * @param value Object to deserialize.
     *
     * @returns Deserialized object.
     */ background_old_hybrid_storage_v1_define_property(this, "deserialize", (value)=>{
            const isObj = background_lodash_es_isObject(value);
            if (isObj && value.__type === 'Uint8Array') {
                return new Uint8Array(value.data);
            }
            if (Array.isArray(value)) {
                return value.map(this.deserialize);
            }
            if (isObj) {
                const deserializedObject = {};
                // eslint-disable-next-line no-restricted-syntax
                for (const [key, val] of Object.entries(value)){
                    deserializedObject[key] = this.deserialize(val);
                }
                return deserializedObject;
            }
            return value;
        });
    }
}

;// ./Extension/src/background/api/update/main.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_update_main_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}



























/**
 * Update API is a facade for handling migrations for the settings object from
 * browser.storage, to make sure that the application runs on the latest schema.
 */ class background_UpdateApi {
    /**
     * Runs app updates depends on previous and current data schema.
     *
     * @param runInfo Info about extension start up.
     * @param runInfo.clientId Client id.
     * @param runInfo.currentAppVersion Current extension version.
     * @param runInfo.currentSchemaVersion Current data schema version.
     * @param runInfo.previousSchemaVersion Previous data schema version.
     */ static async update({ clientId, currentAppVersion, currentSchemaVersion, previousSchemaVersion }) {
        // check clientId existence
        if (clientId) {
            await background_browserStorage.set(background_CLIENT_ID_KEY, clientId);
        } else {
            await background_browserStorage.set(background_CLIENT_ID_KEY, background_InstallApi.genClientId());
        }
        // set actual schema and app version
        await background_browserStorage.set(background_SCHEMA_VERSION_KEY, currentSchemaVersion);
        await background_browserStorage.set(background_APP_VERSION_KEY, currentAppVersion);
        // run migrations, if they needed.
        await background_UpdateApi.runMigrations(currentSchemaVersion, previousSchemaVersion);
    }
    /**
     * Checks previousSchemaVersion and if it is outdated - runs migrations.
     *
     * @param currentSchemaVersion Current data schema version.
     * @param previousSchemaVersion Previous data schema version.
     */ static async runMigrations(currentSchemaVersion, previousSchemaVersion) {
        try {
            // if schema version changes, process migration
            for(let schema = previousSchemaVersion; schema < currentSchemaVersion; schema += 1){
                const schemaMigrationAction = background_UpdateApi.schemaMigrationMap[schema];
                if (!schemaMigrationAction) {
                    // eslint-disable-next-line max-len
                    throw new Error(`Cannot find schema migration action from ${previousSchemaVersion} to ${currentSchemaVersion}.`);
                }
                // eslint-disable-next-line no-await-in-loop
                await background_UpdateApi.runSchemaMigration(schemaMigrationAction, schema, schema + 1);
            }
        } catch (e) {
            background_logger_logger.error('Error while migrate: ', e);
            background_logger_logger.info('Reset settings...');
            await background_browserStorage.set(background_ADGUARD_SETTINGS_KEY, background_defaultSettings);
        }
    }
    /**
     * Runs schema migration.
     *
     * @param schemaMigrationAction Schema migration action.
     * @param previousSchemaVersion Previous data schema version.
     * @param currentSchemaVersion Current data schema version.
     */ static async runSchemaMigration(schemaMigrationAction, previousSchemaVersion, currentSchemaVersion) {
        try {
            await schemaMigrationAction();
        } catch (e) {
            // eslint-disable-next-line max-len
            const errMessage = `Error while schema migrating from ${previousSchemaVersion} to ${currentSchemaVersion}: ${background_error_getErrorMessage(e)}`;
            background_logger_logger.error(errMessage);
            throw new Error(errMessage, {
                cause: e
            });
        }
    }
    /**
     * Run data migration from schema v10 to schema v11.
     */ static async migrateFromV10toV11() {
        let entries = {};
        // Part 1. Migrate serialized data.
        // Some date, like typed arrays, are not JSON serializable. In IDB, we can store such data without any problems.
        // But if IDB is not supported, hybrid storage falls back to browser.storage.local,
        // where we only can store JSON-serializable data.
        // To be able to store such data in browser.storage.local, we serialize such data when using hybrid storage.
        // However, in the latest version, we introduced a more robust way to serialize data:
        // instead of the legacy custom implementation, we use SuperJSON.
        // We migrate old serialized data to the new format in this migration, but only if IDB is not supported.
        if (!await background_HybridStorage.isIDBSupported()) {
            entries = await background_browserStorage.entries();
            // Get relevant keys.
            const keys = Object.keys(entries).filter((key)=>[
                    background_RAW_FILTER_KEY_PREFIX,
                    background_BINARY_FILTER_KEY_PREFIX,
                    background_FILTER_KEY_PREFIX,
                    background_CONVERSION_MAP_PREFIX,
                    background_SOURCE_MAP_PREFIX
                ].some((prefix)=>key.startsWith(prefix)));
            if (keys.length > 0) {
                const migrationData = {};
                keys.forEach((key)=>{
                    const val = entries[key];
                    // Deserialize data using the legacy deserialization function.
                    const deserializeResult = background_UpdateApi.deserialize(val);
                    migrationData[key] = deserializeResult;
                });
                // This will automatically serialize data using SuperJSON.
                const transactionResult = await background_hybridStorage.setMultiple(migrationData);
                if (!transactionResult) {
                    background_logger_logger.error('Failed to save migrated data');
                }
            } else {
                background_logger_logger.debug('No serialized data to migrate');
            }
        } else {
            background_logger_logger.debug('IDB is supported, no need to migrate serialized data');
        }
        // Part 2. Migrate filters keys.
        // To provide better integration with preprocessed filters, we changed keys for filters data:
        // filterrules_<id>.txt -> rawFilterList_<id>
        // binaryfilterrules_<id>.txt -> filterList_<id>
        // conversionmap_<id>.txt -> conversionMap_<id>
        // sourcemap_<id>.txt -> sourceMap_<id>
        entries = await background_hybridStorage.entries();
        /**
         * Mapping of old key prefixes to new key prefixes.
         */ const filtersKeyPrefixesMap = new Map([
            [
                background_FILTER_KEY_PREFIX,
                background_FiltersStorage.KEY_RAW_FILTER_LIST
            ],
            [
                background_BINARY_FILTER_KEY_PREFIX,
                background_FiltersStorage.KEY_FILTER_LIST
            ],
            [
                background_CONVERSION_MAP_PREFIX,
                background_FiltersStorage.KEY_CONVERSION_MAP
            ],
            [
                background_SOURCE_MAP_PREFIX,
                background_FiltersStorage.KEY_SOURCE_MAP
            ]
        ]);
        const filtersKeyPrefixesEntries = Array.from(filtersKeyPrefixesMap.entries());
        const migrationData = {};
        const keysToRemove = [];
        const keys = Object.keys(entries);
        keys.forEach((key)=>{
            filtersKeyPrefixesEntries.forEach(([oldPrefix, newPrefix])=>{
                if (key.startsWith(oldPrefix)) {
                    const newKey = background_lodash_es_trimEnd(key.replace(oldPrefix, `${newPrefix}${background_FiltersStorage.KEY_COMBINER}`), background_FILTER_LIST_EXTENSION);
                    migrationData[newKey] = entries[key];
                    keysToRemove.push(key);
                }
            });
        });
        await background_hybridStorage.setMultiple(migrationData);
        if (keysToRemove.length > 0) {
            await background_hybridStorage.removeMultiple(keysToRemove);
        }
    }
    /**
     * Run data migration from schema v9 to schema v10.
     *
     * For the extension update to v5.0.187.
     *
     * For MV2 version we will run empty migration since we don't need
     * to do anything, just increase the schema version.
     *
     * For MV3 version we need to again remove Quick Fixes filter state.
     */ static async migrateFromV9toV10() {
        // This migration should be done only for MV3 version.
        if (false) {}
        await background_UpdateApi.removeQuickFixesFilter();
    }
    /**
     * Run data migration from schema v8 to schema v9.
     *
     * For the extension update to v5.0.185.
     *
     * For MV2 version we will run empty migration since we don't need
     * to do anything, just increase the schema version.
     *
     * In this update we re-added AdGuard Quick Fixes filter
     * and want to enable it by default for all users.
     */ static async migrateFromV8toV9() {
        // This migration should be done only for MV3 version.
        if (false) {}
        // We cannot load and enable filter here, because filter's API is not
        // initialized yet. So we just set the filter state to enabled
        // and loaded.
        // After that it will be renew from the local copy of filters
        // - which will create all needed filter's objects in memory to correct
        // work.
        const settings = await background_browserStorage.get(background_ADGUARD_SETTINGS_KEY);
        if (!background_UpdateApi.isObject(settings)) {
            throw new Error('Settings is not an object');
        }
        const filtersStateData = settings['filters-state'];
        if (typeof filtersStateData !== 'string') {
            throw new Error('Cannot read filters state data');
        }
        const filtersState = background_lib/* default.record */.Ay.record(background_lib/* default.string */.Ay.string(), background_lib/* default.object */.Ay.object({
            enabled: background_lib/* default.boolean */.Ay.boolean(),
            installed: background_lib/* default.boolean */.Ay.boolean(),
            loaded: background_lib/* default.boolean */.Ay.boolean()
        })).parse(JSON.parse(filtersStateData));
        // Little hack to mark filter as enabled before it is actually loaded.
        Object.assign(filtersState, {
            [background_AntiBannerFiltersId.QuickFixesFilterId]: {
                // Enabled by default.
                enabled: true,
                // Installed is false, because otherwise this filter state
                // will be marked as "obsoleted" (because this filter not
                // exists in metadata yet) and will be removed from the memory.
                installed: false,
                // Mark as loaded to update filter from local resources and
                // create filter object in memory.
                loaded: true
            }
        });
        settings['filters-state'] = JSON.stringify(filtersState);
        // Set empty filter to create it in the memory.
        // Right after launch it will be updated to the newest version from remote.
        await background_old_filters_storage_v1_FiltersStorage.set(background_AntiBannerFiltersId.QuickFixesFilterId, []);
        await background_RawFiltersStorage.set(background_AntiBannerFiltersId.QuickFixesFilterId, '');
        await background_browserStorage.set(background_ADGUARD_SETTINGS_KEY, settings);
    }
    /**
     * Run data migration from schema v7 to schema v8.
     *
     * For the extension update to v5.0.183.
     *
     * For MV2 version we will run empty migration since we don't need to do anything,
     * just increase the schema version.
     *
     * For MV3 version we need to remove deprecated Quick Fixes filter state.
     */ static async migrateFromV7toV8() {
        // This migration should be done only for MV3 version.
        if (false) {}
        await background_UpdateApi.removeQuickFixesFilter();
    }
    /**
     * Run data migration from schema v6 to schema v7.
     *
     * For the extension update to
     * - v5.0.78-beta;
     * - v5.0.91.
     *
     * IMPORTANT: should not be combined with {@link migrateFromV5toV6} just because it is
     * for the same *release* version — the related changes became available
     * in *different beta* versions, so they should be run separately.
     *
     * For MV2 version we will run empty migration since we don't need
     * to do anything, just increase the schema version.
     *
     * In this update we added new filter - AdGuard Quick Fixes and want
     * to enable it by default for all users.
     */ static async migrateFromV6toV7() {
        // This migration should be done only for MV3 version.
        if (false) {}
        // We cannot load and enable filter here, because filter's API is not
        // initialized yet. So we just set the filter state to enabled
        // and loaded.
        // After that it will be renew from the local copy of filters
        // - which will create all needed filter's objects in memory to correct
        // work.
        const settings = await background_browserStorage.get(background_ADGUARD_SETTINGS_KEY);
        if (!background_UpdateApi.isObject(settings)) {
            throw new Error('Settings is not an object');
        }
        const filtersStateData = settings['filters-state'];
        if (typeof filtersStateData !== 'string') {
            throw new Error('Cannot read filters state data');
        }
        const filtersState = background_lib/* default.record */.Ay.record(background_lib/* default.string */.Ay.string(), background_lib/* default.object */.Ay.object({
            enabled: background_lib/* default.boolean */.Ay.boolean(),
            installed: background_lib/* default.boolean */.Ay.boolean(),
            loaded: background_lib/* default.boolean */.Ay.boolean()
        })).parse(JSON.parse(filtersStateData));
        // Little hack to mark filter as enabled before it is actually loaded.
        Object.assign(filtersState, {
            [background_AntiBannerFiltersId.QuickFixesFilterId]: {
                // Enabled by default.
                enabled: true,
                // Installed is false, because otherwise this filter state
                // will be marked as "obsoleted" (because this filter not
                // exists in metadata yet) and will be removed from the memory.
                installed: false,
                // Mark as loaded to update filter from local resources and
                // create filter object in memory.
                loaded: true
            }
        });
        settings['filters-state'] = JSON.stringify(filtersState);
        // Set empty filter to create it in the memory.
        // Right after launch it will be updated to the newest version from remote.
        await background_old_filters_storage_v1_FiltersStorage.set(background_AntiBannerFiltersId.QuickFixesFilterId, []);
        await background_RawFiltersStorage.set(background_AntiBannerFiltersId.QuickFixesFilterId, '');
        await background_browserStorage.set(background_ADGUARD_SETTINGS_KEY, settings);
    }
    /**
     * Run data migration from schema v5 to schema v6.
     *
     * For the extension update to
     * - v5.0.49-beta;
     * - v5.0.91.
     */ static async migrateFromV5toV6() {
        const rawOldPageStatistics = await background_browserStorage.get(background_PAGE_STATISTIC_KEY);
        if (typeof rawOldPageStatistics !== 'string') {
            background_logger_logger.debug('Missing page statistics, nothing to migrate');
            return;
        }
        let oldPageStatisticsStr = rawOldPageStatistics;
        if (oldPageStatisticsStr.startsWith('"') && oldPageStatisticsStr.endsWith('"') || oldPageStatisticsStr.startsWith("'") && oldPageStatisticsStr.endsWith("'")) {
            // beautify the string before parsing
            oldPageStatisticsStr = oldPageStatisticsStr.slice(1, -1);
        }
        let oldPageStatistics;
        try {
            const oldPageStatisticsObj = JSON.parse(oldPageStatisticsStr);
            oldPageStatistics = background_pageStatsValidator.parse(oldPageStatisticsObj);
        } catch (e) {
            background_logger_logger.debug('Nothing to migrate, since page statistics cannot be parsed:', background_error_getErrorMessage(e));
            return;
        }
        if (!oldPageStatistics.data) {
            background_logger_logger.debug('No page statistics data to migrate');
            return;
        }
        /**
         * Mapping of old group ids to new categories: where
         * - key — filters group id (old stats format),
         * - value — category name (new stats format).
         */ const STATS_CATEGORIES_MIGRATION_MAP = {
            '0': background_PopupStatsCategories.Advertising,
            '1': background_PopupStatsCategories.Advertising,
            '2': background_PopupStatsCategories.Trackers,
            '3': background_PopupStatsCategories.SocialMedia,
            '4': background_PopupStatsCategories.Advertising,
            '5': background_PopupStatsCategories.Advertising,
            '6': background_PopupStatsCategories.Advertising,
            '7': background_PopupStatsCategories.Advertising
        };
        /**
         * Migrate old stats data item (where filters group ids were used)
         * to the new format (where stats categories are used based on companiesdb).
         *
         * @param oldDataItem Old stats data item for `hours`, `days`, and `months`.
         *
         * @returns Migrated stats data item.
         *
         * @example
         * `{"0":10,"1":10,"2":10,"3":10,"4":10,"5":10,"6":10,"7":10,"total":80}`
         * ↓↓↓
         * `{"Advertising":60,"Trackers":10,"SocialMedia":10,"total":80}`
         */ const migrateStatsDataItem = (oldDataItem)=>{
            let total = 0;
            const newDataItem = {};
            const oldKeys = Object.keys(oldDataItem);
            oldKeys.forEach((key)=>{
                if (key !== 'total') {
                    const statsCount = oldDataItem[key];
                    if (typeof statsCount === 'undefined') {
                        return;
                    }
                    const category = STATS_CATEGORIES_MIGRATION_MAP[key];
                    if (category) {
                        newDataItem[category] = (newDataItem[category] || 0) + statsCount;
                    } else {
                        background_logger_logger.debug(`Unknown category for old group id: ${key}, migrated into "Other"`);
                        // eslint-disable-next-line max-len
                        newDataItem[background_PopupStatsCategories.Other] = (newDataItem[background_PopupStatsCategories.Other] || 0) + statsCount;
                    }
                    total += statsCount;
                }
            });
            newDataItem.total = total;
            return newDataItem;
        };
        const newPageStatisticsData = {
            hours: oldPageStatistics.data.hours.map(migrateStatsDataItem),
            days: oldPageStatistics.data.days.map(migrateStatsDataItem),
            months: oldPageStatistics.data.months.map(migrateStatsDataItem),
            updated: oldPageStatistics.data.updated
        };
        const newPageStatistics = {
            totalBlocked: oldPageStatistics.totalBlocked,
            data: newPageStatisticsData
        };
        await background_browserStorage.set(background_PAGE_STATISTIC_KEY, JSON.stringify(newPageStatistics));
    }
    /**
     * Run data migration from schema v4 to schema v5.
     *
     * For the extension update to:
     * - v5.0.43-beta;
     * - v5.0.91.
     */ static async migrateFromV4toV5() {
        const settings = await background_browserStorage.get(background_ADGUARD_SETTINGS_KEY);
        if (!background_UpdateApi.isObject(settings)) {
            throw new Error('Settings is not an object');
        }
        const filtersStateData = settings['filters-state'];
        if (typeof filtersStateData !== 'string') {
            throw new Error('Cannot read filters state data');
        }
        const filtersState = background_lib/* default.record */.Ay.record(background_lib/* default.string */.Ay.string(), background_lib/* default.object */.Ay.object({
            enabled: background_lib/* default.boolean */.Ay.boolean(),
            installed: background_lib/* default.boolean */.Ay.boolean(),
            loaded: background_lib/* default.boolean */.Ay.boolean()
        })).parse(JSON.parse(filtersStateData));
        const groupsStateData = settings['groups-state'];
        if (typeof groupsStateData !== 'string') {
            throw new Error('Cannot read groups state data');
        }
        const groupsState = background_lib/* default.record */.Ay.record(background_lib/* default.string */.Ay.string(), background_lib/* default.object */.Ay.object({
            enabled: background_lib/* default.boolean */.Ay.boolean(),
            touched: background_lib/* default.boolean */.Ay.boolean()
        })).parse(JSON.parse(groupsStateData));
        // AdGuard Annoyances filters group id.
        const annoyancesGroupId = '4';
        /**
         * AdGuard Annoyances filter has been splitted into 5 other filters:
         * Cookie Notices, Popups, Mobile App Banners, Other Annoyances
         * and Widgets - which we should enable if the Annoyances filter is enabled.
         */ const deprecatedAnnoyancesFilterId = '14';
        /**
         * AdGuard Annoyances filter has been splitted into 5 other filters:
         * Cookie Notices, Popups, Mobile App Banners, Other Annoyances
         * and Widgets - which we should enable if the Annoyances filter is enabled.
         */ const annoyancesFiltersIds = [
            '18',
            '19',
            '20',
            '21',
            '22'
        ];
        var _groupsState_annoyancesGroupId;
        // AdGuard Annoyances filters group state.
        const annoyancesGroup = (_groupsState_annoyancesGroupId = groupsState[annoyancesGroupId]) !== null && _groupsState_annoyancesGroupId !== void 0 ? _groupsState_annoyancesGroupId : {
            enabled: false,
            touched: false
        };
        // AdGuard Annoyances filters states.
        const annoyancesFiltersState = Object.fromEntries(annoyancesFiltersIds.map((filterId)=>{
            var _filtersState_filterId;
            const state = (_filtersState_filterId = filtersState[filterId]) !== null && _filtersState_filterId !== void 0 ? _filtersState_filterId : {
                loaded: false,
                enabled: false,
                touched: false
            };
            return [
                filterId,
                state
            ];
        }));
        const deprecatedAnnoyancesFilter = filtersState[deprecatedAnnoyancesFilterId];
        if (background_UpdateApi.isObject(deprecatedAnnoyancesFilter)) {
            // If the deprecated Annoyances filter is enabled, we should enable new groups and filters.
            if (deprecatedAnnoyancesFilter.enabled) {
                annoyancesGroup.enabled = true;
                annoyancesFiltersIds.forEach((id)=>{
                    annoyancesFiltersState[id].enabled = true;
                });
            }
            // delete deprecated filter state;
            delete filtersState[deprecatedAnnoyancesFilterId];
        }
        // Set updated states and new metadata to the settings.
        groupsState[annoyancesGroupId] = annoyancesGroup;
        Object.assign(filtersState, annoyancesFiltersState);
        settings['groups-state'] = JSON.stringify(groupsState);
        settings['filters-state'] = JSON.stringify(filtersState);
        await background_browserStorage.set(background_ADGUARD_SETTINGS_KEY, settings);
        // Sets default rules limits.
        await background_browserStorage.set(background_RULES_LIMITS_KEY, JSON.stringify([]));
    }
    /**
     * Run data migration from schema v3 to schema v4.
     *
     * @throws If previous data schema is invalid or saving data to the hybrid storage fails.
     */ static async migrateFromV3toV4() {
        // Get all entries from the `browser.browserStorage.local`.
        const entries = await background_browserStorage.entries();
        // Find all keys that are related to filters.
        const keys = Object.keys(entries);
        const rawFilterKeys = keys.filter((key)=>key.startsWith(background_RAW_FILTER_KEY_PREFIX));
        const filterKeys = keys.filter((key)=>key.startsWith(background_FILTER_KEY_PREFIX));
        // Check if there are no filters to migrate.
        if (rawFilterKeys.length === 0 && filterKeys.length === 0) {
            background_logger_logger.debug('No filters to migrate from storage to hybrid storage');
            return;
        }
        // Prepare data to migrate.
        const migrationData = {};
        const filterSchema = background_lib/* default.union */.Ay.union([
            background_lib/* default.string */.Ay.string(),
            background_lib/* default.array */.Ay.array(background_lib/* default.string */.Ay.string())
        ]);
        // Migrate filters.
        filterKeys.forEach((key)=>{
            const filterId = background_old_filters_storage_v1_FiltersStorage.extractFilterIdFromFilterKey(key);
            if (filterId === null) {
                background_logger_logger.debug(`Failed to extract filter ID from the key: ${key}, skipping`);
                return;
            }
            const filterParsingResult = filterSchema.safeParse(entries[key]);
            if (!filterParsingResult.success) {
                background_logger_logger.debug(// eslint-disable-next-line max-len
                `Failed to parse data from filter ID ${filterId} from the old storage: ${background_error_getErrorMessage(filterParsingResult.error)}`);
                return;
            }
            const lines = Array.isArray(filterParsingResult.data) ? filterParsingResult.data : filterParsingResult.data.split(background_NEWLINE_CHAR_REGEX);
            Object.assign(migrationData, background_old_filters_storage_v1_FiltersStorage.prepareFilterForStorage(filterId, lines));
        });
        // Migrate raw filters.
        rawFilterKeys.forEach((key)=>{
            const filterId = background_RawFiltersStorage.extractFilterIdFromFilterKey(key);
            if (filterId === null) {
                background_logger_logger.debug(`Failed to extract raw filter ID from the key: ${key}, skipping`);
                return;
            }
            const filterParsingResult = background_lib/* default.string */.Ay.string().safeParse(entries[key]);
            if (!filterParsingResult.success) {
                background_logger_logger.debug(// eslint-disable-next-line max-len
                `Failed to parse data from raw filter ID ${filterId} from the old storage: ${background_error_getErrorMessage(filterParsingResult.error)}`);
                return;
            }
            migrationData[key] = filterParsingResult.data;
        });
        // Delete filters from the `browser.browserStorage.local` after successful migration.
        await background_browserStorage.removeMultiple([
            ...rawFilterKeys,
            ...filterKeys
        ]);
        const hybridStorageV1 = new background_old_hybrid_storage_v1_HybridStorage();
        // Save migrated data to the hybrid storage with a single transaction.
        const transactionResult = await hybridStorageV1.setMultiple(migrationData);
        if (!transactionResult) {
            throw new Error('Failed to migrate filters from storage to hybrid storage, transaction failed');
        }
        background_logger_logger.debug('Filters successfully migrated from storage to hybrid storage');
        // We use passthrough to keep all other data as is, in this case we only need to update check times.
        const filterVersionDataValidatorV3 = background_lib/* default.object */.Ay.object({
            lastCheckTime: background_lib/* default.number */.Ay.number(),
            lastScheduledCheckTime: background_lib/* default.number */.Ay.number().optional()
        }).passthrough();
        const filtersVersionDataValidatorV3 = background_lib/* default.record */.Ay.record(background_SchemaPreprocessor.numberValidator, filterVersionDataValidatorV3);
        const storageData = await background_browserStorage.get(background_ADGUARD_SETTINGS_KEY);
        const settings = background_lib/* default.record */.Ay.record(background_lib/* default.unknown */.Ay.unknown()).parse(storageData);
        const rawFiltersVersion = settings[background_SettingOption.FiltersVersion];
        if (background_lodash_es_isString(rawFiltersVersion)) {
            const filtersVersionParsed = filtersVersionDataValidatorV3.safeParse(JSON.parse(rawFiltersVersion));
            if (filtersVersionParsed.success) {
                const filtersVersion = filtersVersionParsed.data;
                Object.values(filtersVersion).forEach((filterData)=>{
                    if (background_lodash_es_isUndefined(filterData.lastScheduledCheckTime)) {
                        filterData.lastScheduledCheckTime = filterData.lastCheckTime;
                    }
                });
                settings[background_SettingOption.FiltersVersion] = JSON.stringify(filtersVersion);
                await background_browserStorage.set(background_ADGUARD_SETTINGS_KEY, settings);
                background_logger_logger.debug('Filters version data successfully migrated from the old storage');
            } else {
                background_logger_logger.debug(// eslint-disable-next-line max-len
                `Failed to parse filters version data from the old storage: ${background_error_getErrorMessage(filtersVersionParsed.error)}`);
            }
        } else {
            background_logger_logger.debug('Filters version data is not a string, skipping migration');
        }
    }
    /**
     * Run data migration from schema v2 to schema v3.
     */ static async migrateFromV2toV3() {
        /**
         * From v4.2.144 we don't store filter rules in indexed DB, die to bug
         * https://bugzilla.mozilla.org/show_bug.cgi?id=1841806.
         */ let db = null;
        try {
            db = await background_IDBUtils.connect('AdguardRulesStorage');
            const data = await background_IDBUtils.getAll(db, 'AdguardRulesStorage');
            const lists = background_lib/* default.object */.Ay.object({
                key: background_lib/* default.string */.Ay.string(),
                value: background_lib/* default.string */.Ay.string()
            }).array().parse(data);
            const results = await Promise.allSettled(lists.map(async ({ key, value })=>background_browserStorage.set(key, value.split(/\r?\n/))));
            results.forEach((result)=>{
                if (result.status === 'rejected') {
                    background_logger_logger.info(background_error_getErrorMessage(result.reason));
                }
            });
        } catch (e) {
            background_logger_logger.info('Error while migrate user rules', background_error_getErrorMessage(e));
        } finally{
            if (db) {
                db.close();
            }
        }
        /**
         * Add missed trusted flags for custom filters.
         */ const storageData = await background_browserStorage.get('adguard-settings');
        const settings = background_lib/* default.record */.Ay.record(background_lib/* default.unknown */.Ay.unknown()).parse(storageData);
        const customFilters = settings['custom-filters'];
        if (typeof customFilters === 'string') {
            const customFiltersDataTransformer = background_lib/* default.object */.Ay.object({
                trusted: background_lib/* default.boolean */.Ay.boolean().optional()
            }).passthrough().transform(({ trusted, ...rest })=>({
                    ...rest,
                    trusted: Boolean(trusted)
                })).array();
            const customFiltersData = JSON.parse(customFilters);
            settings['custom-filters'] = JSON.stringify(customFiltersDataTransformer.parse(customFiltersData));
            await background_browserStorage.set('adguard-settings', settings);
        }
    }
    /**
     * Run data migration from schema v1 to schema v2.
     */ static async migrateFromV1toV2() {
        // From v4.2.135 we store timestamp of expiration time for safebrowsing cache records.
        const storageData = await background_browserStorage.get('sb-lru-cache');
        if (typeof storageData !== 'string') {
            return;
        }
        // parse v1 safebrowsing cache data
        const sbStorageDataV1 = background_lib/* default.object */.Ay.object({
            key: background_lib/* default.string */.Ay.string(),
            value: background_lib/* default.string */.Ay.string()
        }).strict().array().parse(JSON.parse(storageData));
        const now = Date.now();
        // transform v1 safebrowsing storage data to v2
        const sbStorageDataV2 = sbStorageDataV1.map(({ key, value })=>{
            const safebrowsingCacheRecord = {
                list: value
            };
            if (safebrowsingCacheRecord.list !== 'allowlist') {
                safebrowsingCacheRecord.expires = now + background_SbCache.CACHE_TTL_MS;
            }
            return {
                key,
                value: safebrowsingCacheRecord
            };
        });
        await background_browserStorage.set('sb-lru-cache', JSON.stringify(sbStorageDataV2));
    }
    /**
     * Run data migration from schema v0 to schema v1.
     */ static async migrateFromV0toV1() {
        // In the v4.0.171 we have littered window.localStorage with proms used in the promo notifications module,
        // now we are clearing them
        if (typeof window !== 'undefined') {
            // there is no window in the mv3 extension service worker
            window.localStorage.removeItem('viewed-notifications');
            window.localStorage.removeItem('viewed-notification-time');
        }
        // In the v4.2.0 we are refactoring storage data structure
        // get current settings
        const storageData = await background_browserStorage.get('adguard-settings');
        // check if current settings is record
        const currentSettings = background_lib/* default.record */.Ay.record(background_lib/* default.unknown */.Ay.unknown()).parse(storageData);
        // delete app version from settings
        if (currentSettings['app-version']) {
            delete currentSettings['app-version'];
        }
        // delete metadata from settings (new one will be loaded while filter initialization)
        if (currentSettings['filters-i18n-metadata']) {
            delete currentSettings['filters-i18n-metadata'];
        }
        if (currentSettings['filters-metadata']) {
            delete currentSettings['filters-metadata'];
        }
        // TODO: use zod preprocessors instead direct remapping and data transformation
        // rename fields
        let keyToCheck = 'default-whitelist-mode';
        if (currentSettings[keyToCheck] !== undefined) {
            currentSettings['default-allowlist-mode'] = currentSettings[keyToCheck];
            delete currentSettings[keyToCheck];
        }
        keyToCheck = 'white-list-domains';
        if (currentSettings[keyToCheck] !== undefined) {
            currentSettings['allowlist-domains'] = currentSettings[keyToCheck];
            delete currentSettings[keyToCheck];
        }
        keyToCheck = 'stealth_disable_stealth_mode';
        if (currentSettings[keyToCheck] !== undefined) {
            currentSettings['stealth-disable-stealth-mode'] = currentSettings[keyToCheck];
            delete currentSettings[keyToCheck];
        }
        keyToCheck = 'custom_filters';
        if (currentSettings[keyToCheck] !== undefined) {
            currentSettings['custom-filters'] = currentSettings[keyToCheck];
            delete currentSettings[keyToCheck];
        }
        // New group state 'touched' field added in 4.2
        // zod 'parse then transform' approach is used to transform data to actual schema
        if (typeof currentSettings['groups-state'] === 'string') {
            // create data transformer
            const groupsStateTransformer = background_lib/* default.record */.Ay.record(background_lib/* default.object */.Ay.object({
                enabled: background_lib/* default.boolean */.Ay.boolean().optional()
            }).passthrough().transform((data)=>{
                const enabled = Boolean(data.enabled);
                return {
                    ...data,
                    enabled,
                    touched: enabled
                };
            }));
            const currentGroupsStateData = JSON.parse(currentSettings['groups-state']);
            currentSettings['groups-state'] = JSON.stringify(groupsStateTransformer.parse(currentGroupsStateData));
        }
        // Check non exists fields in filters-state
        if (typeof currentSettings['filters-state'] === 'string') {
            const filtersStateTransformer = background_lib/* default.record */.Ay.record(background_lib/* default.object */.Ay.object({
                enabled: background_lib/* default.boolean */.Ay.boolean().optional(),
                installed: background_lib/* default.boolean */.Ay.boolean().optional()
            }).passthrough().transform(({ installed, enabled, ...rest })=>({
                    ...rest,
                    enabled: Boolean(enabled),
                    installed: Boolean(installed)
                })));
            const filtersState = JSON.parse(currentSettings['filters-state']);
            currentSettings['filters-state'] = JSON.stringify(filtersStateTransformer.parse(filtersState));
        }
        // Check not exists fields in custom filters
        if (typeof currentSettings['custom-filters'] === 'string') {
            const customFiltersDataTransformer = background_lib/* default.object */.Ay.object({
                trusted: background_lib/* default.boolean */.Ay.boolean().optional(),
                timeUpdated: background_lib/* default.number */.Ay.number().or(background_lib/* default.string */.Ay.string()).optional()
            }).passthrough().transform((data)=>{
                const trusted = Boolean(data.trusted);
                const timeUpdated = typeof data.timeUpdated === 'undefined' ? 0 : Number(data.timeUpdated);
                // Remove deprecated field.
                if (data.languages !== undefined) {
                    delete data.languages;
                }
                return {
                    ...data,
                    trusted,
                    timeUpdated
                };
            }).array();
            const customFilters = JSON.parse(currentSettings['custom-filters']);
            currentSettings['custom-filters'] = JSON.stringify(customFiltersDataTransformer.parse(customFilters));
        }
        // Check not exists fields in filters version for custom filters
        if (typeof currentSettings['filters-version'] === 'string') {
            const filtersVersionsTransformer = background_lib/* default.record */.Ay.record(background_lib/* default.object */.Ay.object({
                lastUpdateTime: background_lib/* default.number */.Ay.number().optional()
            }).passthrough().transform(({ lastUpdateTime, ...rest })=>({
                    ...rest,
                    lastUpdateTime: lastUpdateTime !== null && lastUpdateTime !== void 0 ? lastUpdateTime : 0
                })));
            const filtersVersion = JSON.parse(currentSettings['filters-version']);
            currentSettings['filters-version'] = JSON.stringify(filtersVersionsTransformer.parse(filtersVersion));
        }
        // mode notification data from settings to root storage
        await background_UpdateApi.moveStorageData('viewed-notifications', currentSettings);
        await background_UpdateApi.moveStorageData('viewed-notification-time', currentSettings);
        // move client id from settings to root storage
        await background_UpdateApi.moveStorageData('client-id', currentSettings);
        // move page stats to root storage
        await background_UpdateApi.moveStorageData('page-statistic', currentSettings);
        // move safebrowsing from settings data to root storage
        await background_UpdateApi.moveStorageData('safebrowsing-suspended-from', currentSettings);
        await background_UpdateApi.moveStorageData('sb-lru-cache', currentSettings);
        const settingsValidator = background_lib/* default.object */.Ay.object({
            'appearance-theme': background_lib/* default.preprocess */.Ay.preprocess((value)=>{
                if (typeof value === 'string' && value.includes('\"')) {
                    return JSON.parse(value);
                }
                return value;
            }, background_appearanceValidator),
            'disable-show-page-statistic': background_SchemaPreprocessor.booleanValidator,
            'detect-filters-disabled': background_SchemaPreprocessor.booleanValidator,
            'safebrowsing-disabled': background_SchemaPreprocessor.booleanValidator,
            'filters-update-period': background_SchemaPreprocessor.numberValidator,
            'use-optimized-filters': background_SchemaPreprocessor.booleanValidator,
            'hits-count-disabled': background_SchemaPreprocessor.booleanValidator,
            'context-menu-disabled': background_SchemaPreprocessor.booleanValidator,
            'show-info-about-adguard-disabled': background_SchemaPreprocessor.booleanValidator,
            'show-app-updated-disabled': background_SchemaPreprocessor.booleanValidator,
            'hide-rate-block': background_SchemaPreprocessor.booleanValidator,
            'user-rules-editor-wrap': background_SchemaPreprocessor.booleanValidator,
            'allowlist-domains': background_lib/* default.string */.Ay.string(),
            'block-list-domains': background_lib/* default.string */.Ay.string(),
            'allowlist-enabled': background_SchemaPreprocessor.booleanValidator,
            'default-allowlist-mode': background_SchemaPreprocessor.booleanValidator,
            'stealth-disable-stealth-mode': background_SchemaPreprocessor.booleanValidator,
            'stealth-hide-referrer': background_SchemaPreprocessor.booleanValidator,
            'stealth-hide-search-queries': background_SchemaPreprocessor.booleanValidator,
            'stealth-send-do-not-track': background_SchemaPreprocessor.booleanValidator,
            'stealth-block-webrtc': background_SchemaPreprocessor.booleanValidator,
            'stealth-remove-x-client': background_SchemaPreprocessor.booleanValidator,
            'stealth-block-third-party-cookies': background_SchemaPreprocessor.booleanValidator,
            'stealth-block-third-party-cookies-time': background_SchemaPreprocessor.numberValidator,
            'stealth-block-first-party-cookies': background_SchemaPreprocessor.booleanValidator,
            'stealth-block-first-party-cookies-time': background_SchemaPreprocessor.numberValidator,
            'user-filter-enabled': background_SchemaPreprocessor.booleanValidator,
            'filters-state': background_lib/* default.string */.Ay.string().optional(),
            'filters-version': background_lib/* default.string */.Ay.string().optional(),
            'groups-state': background_lib/* default.string */.Ay.string().optional(),
            'custom-filters': background_lib/* default.string */.Ay.string().optional(),
            'adguard-disabled': background_SchemaPreprocessor.booleanValidator
        });
        // merge current with default settings and validate
        const settings = settingsValidator.parse({
            ...background_defaultSettings,
            ...currentSettings
        });
        // set new settings to storage
        await background_browserStorage.set('adguard-settings', settings);
    }
    /**
     * Removes the deprecated Quick Fixes filter from settings and storages.
     *
     * @returns A promise that resolves when complete.
     *
     * @throws Error if settings are invalid or data cannot be read.
     */ static async removeQuickFixesFilter() {
        const settings = await background_browserStorage.get(background_ADGUARD_SETTINGS_KEY);
        if (!background_UpdateApi.isObject(settings)) {
            throw new Error('Settings is not an object');
        }
        const filtersStateData = settings['filters-state'];
        if (typeof filtersStateData !== 'string') {
            throw new Error('Cannot read filters state data');
        }
        const filtersState = background_lib/* default.record */.Ay.record(background_lib/* default.string */.Ay.string(), background_lib/* default.object */.Ay.object({
            enabled: background_lib/* default.boolean */.Ay.boolean(),
            installed: background_lib/* default.boolean */.Ay.boolean(),
            loaded: background_lib/* default.boolean */.Ay.boolean()
        })).parse(JSON.parse(filtersStateData));
        const groupsStateData = settings['groups-state'];
        if (typeof groupsStateData !== 'string') {
            throw new Error('Cannot read groups state data');
        }
        const deprecatedQuickFixesFilter = filtersState[background_AntiBannerFiltersId.QuickFixesFilterId];
        if (background_UpdateApi.isObject(deprecatedQuickFixesFilter)) {
            // delete the deprecated filter state
            delete filtersState[background_AntiBannerFiltersId.QuickFixesFilterId];
        }
        settings['filters-state'] = JSON.stringify(filtersState);
        // Remove deprecated Quick Fixes filter from the storages.
        await background_old_filters_storage_v1_FiltersStorage.remove(background_AntiBannerFiltersId.QuickFixesFilterId);
        await background_RawFiltersStorage.remove(background_AntiBannerFiltersId.QuickFixesFilterId);
        await background_browserStorage.set(background_ADGUARD_SETTINGS_KEY, settings);
    }
    /**
     * Moves data from settings to root browserStorage.
     *
     * @param key Settings key.
     * @param currentSettings Current settings object.
     */ static async moveStorageData(key, currentSettings) {
        const data = currentSettings === null || currentSettings === void 0 ? void 0 : currentSettings[key];
        if (data) {
            delete currentSettings[key];
            await background_browserStorage.set(key, data);
        }
    }
    /**
     * Checks if value is an object.
     *
     * @param value Unknown value to check.
     *
     * @returns True if value is an object, false otherwise.
     */ static isObject(value) {
        return value != null && value.constructor.name === 'Object';
    }
}
background_update_main_define_property(background_UpdateApi, "schemaMigrationMap", {
    '0': background_UpdateApi.migrateFromV0toV1,
    '1': background_UpdateApi.migrateFromV1toV2,
    '2': background_UpdateApi.migrateFromV2toV3,
    '3': background_UpdateApi.migrateFromV3toV4,
    '4': background_UpdateApi.migrateFromV4toV5,
    '5': background_UpdateApi.migrateFromV5toV6,
    '6': background_UpdateApi.migrateFromV6toV7,
    '7': background_UpdateApi.migrateFromV7toV8,
    '8': background_UpdateApi.migrateFromV8toV9,
    '9': background_UpdateApi.migrateFromV9toV10,
    '10': background_UpdateApi.migrateFromV10toV11
});
/**
     * Legacy deserialization function for Uint8Array.
     *
     * Helper function to deserialize Uint8Array members of an object.
     * This workaround is needed because by default chrome.storage API doesn't support Uint8Array,
     * and we use it to store serialized filter lists.
     *
     * @param value Object to deserialize.
     *
     * @returns Deserialized object.
     */ background_update_main_define_property(background_UpdateApi, "deserialize", (value)=>{
    const isObj = background_lodash_es_isObject(value);
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    if (isObj && value.__type === 'Uint8Array') {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        return new Uint8Array(value.data);
    }
    if (Array.isArray(value)) {
        return value.map(background_UpdateApi.deserialize);
    }
    if (isObj) {
        const deserializedObject = {};
        // eslint-disable-next-line no-restricted-syntax
        for (const [key, val] of Object.entries(value)){
            deserializedObject[key] = background_UpdateApi.deserialize(val);
        }
        return deserializedObject;
    }
    return value;
});

;// ./Extension/src/background/api/update/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

// EXTERNAL MODULE: ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/sha256.js
var background_sha256 = __webpack_require__(67050);
var background_sha256_default = /*#__PURE__*/__webpack_require__.n(background_sha256);
;// ./Extension/src/background/api/safebrowsing.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_api_safebrowsing_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}











/**
 * The Safe Browsing API checks whether a site is in a database of potentially
 * dangerous sites or not by creating a hash of the requested URL to eliminate
 * the possibility of identifying visited sites.
 */ class background_SafebrowsingApi {
    /**
     * Initialize new safebrowsing cache from {@link Storage}.
     *
     * @see {@link SbCache#init}
     */ static async initCache() {
        await background_sbCache.init();
    }
    /**
     * Clears safebrowsing cache.
     */ static async clearCache() {
        await background_sbCache.clear();
    }
    /**
     * Temporarily allowlist URL.
     * Adds URL to trusted sites (this URL will be ignored by safebrowsing filter).
     *
     * @param url URL.
     */ static async addToSafebrowsingTrusted(url) {
        const host = background_UrlUtils.getHost(url);
        if (!host) {
            return;
        }
        await background_sbCache.set(background_SafebrowsingApi.createHash(host), background_SbCache.SB_ALLOW_LIST);
    }
    /**
     * Checks URL with safebrowsing filter.
     *
     * @see {@link http://adguard.com/en/how-malware-blocked.html#extension}
     *
     * @param requestUrl Request URL.
     * @param referrerUrl Referrer URL.
     *
     * @returns Safebrowsing list we've detected or null.
     */ static async checkSafebrowsingFilter(requestUrl, referrerUrl) {
        background_logger_logger.debug('Checking safebrowsing filter for', requestUrl);
        const sbList = await background_SafebrowsingApi.lookupUrl(requestUrl);
        if (!sbList) {
            background_logger_logger.debug('No safebrowsing rule found');
            return;
        }
        background_logger_logger.debug('Following safebrowsing filter has been fired:', sbList);
        return background_SafebrowsingApi.getErrorPageURL(requestUrl, referrerUrl, sbList);
    }
    /**
     * Performs lookup to safebrowsing service.
     *
     * @param requestUrl Request url.
     *
     * @returns Safebrowsing list we've detected or null.
     */ static async lookupUrl(requestUrl) {
        const host = background_UrlUtils.getHost(requestUrl);
        if (!host) {
            return null;
        }
        const hosts = background_SafebrowsingApi.extractHosts(host);
        if (!hosts || hosts.length === 0) {
            return null;
        }
        // try find request url in cache
        let sbList = background_SafebrowsingApi.checkHostsInSbCache(hosts);
        if (sbList) {
            return background_SafebrowsingApi.createResponse(sbList);
        }
        // check safebrowsing is active
        const now = Date.now();
        const suspendedFrom = Number(await background_browserStorage.get(background_SB_SUSPENDED_CACHE_KEY));
        if (suspendedFrom && now - suspendedFrom < background_SafebrowsingApi.SUSPEND_TTL_MS) {
            return null;
        }
        const hashesMap = background_SafebrowsingApi.createHashesMap(hosts);
        const hashes = Object.keys(hashesMap);
        const shortHashes = hashes.map((hash)=>hash.substring(0, background_SafebrowsingApi.DOMAIN_HASH_LENGTH))// Filter already checked hashes
        .filter((x)=>!background_sbRequestCache.get(x));
        if (shortHashes.length === 0) {
            // In case we have not found anything in safebrowsingCache and all short hashes have been checked in
            // safebrowsingRequestsCache - means that there is no need to request backend again
            await background_sbCache.set(background_SafebrowsingApi.createHash(host), background_SbCache.SB_ALLOW_LIST);
            return background_SafebrowsingApi.createResponse(background_SbCache.SB_ALLOW_LIST);
        }
        let response;
        try {
            response = await background_network.lookupSafebrowsing(shortHashes);
        } catch (e) {
            background_logger_logger.error('Error response from safebrowsing lookup server for', host);
            await background_SafebrowsingApi.suspendSafebrowsing();
            return null;
        }
        if (response && response.status >= 500) {
            // Error on server side, suspend request
            background_logger_logger.error(`Error response status ${response.status} received from safebrowsing lookup server.`);
            await background_SafebrowsingApi.suspendSafebrowsing();
            return null;
        }
        if (!response) {
            background_logger_logger.error('Cannot read response from the server');
            return null;
        }
        await background_SafebrowsingApi.resumeSafebrowsing();
        shortHashes.forEach((x)=>{
            background_sbRequestCache.set(x, true);
        });
        sbList = background_SbCache.SB_ALLOW_LIST;
        if (response.status !== 204) {
            sbList = await background_SafebrowsingApi.processSbResponse(response.responseText, hashesMap) || background_SbCache.SB_ALLOW_LIST;
        }
        await background_sbCache.set(background_SafebrowsingApi.createHash(host), sbList);
        return background_SafebrowsingApi.createResponse(sbList);
    }
    /**
     * Calculates hash for host string.
     *
     * Public for test purposes.
     *
     * @param host Host string.
     *
     * @returns Host SHA256 hash.
     */ static createHash(host) {
        return background_sha256_default()(`${host}/`).toString().toUpperCase();
    }
    /**
     * Access denied page URL.
     *
     * @param requestUrl    Request URL.
     * @param referrerUrl   Referrer URL.
     * @param sbList        Safebrowsing list.
     *
     * @returns Page URL.
     */ static getErrorPageURL(requestUrl, referrerUrl, sbList) {
        const listName = sbList || 'malware';
        const isMalware = listName.includes('malware');
        let url = `${background_SAFEBROWSING_OUTPUT}.html`;
        url += `?malware=${isMalware}`;
        const host = background_UrlUtils.getHost(requestUrl);
        if (host) {
            url += `&host=${encodeURIComponent(host)}`;
        }
        url += `&url=${encodeURIComponent(requestUrl)}`;
        url += `&ref=${encodeURIComponent(referrerUrl)}`;
        return background_browser_polyfill_default().runtime.getURL(url);
    }
    /**
     * Parses safebrowsing service response.
     *
     * @param responseText Response text.
     * @param hashesMap Hashes hosts map.
     *
     * @returns Safebrowsing list or null.
     */ static async processSbResponse(responseText, hashesMap) {
        if (!responseText || responseText.length > 10 * 1024) {
            return null;
        }
        try {
            const data = [];
            responseText.split('\n')// filter empty lines
            .filter((line)=>!!line).forEach((line)=>{
                const row = line.split(':');
                const hash = row[2];
                const list = row[0];
                if (hash && list) {
                    data.push({
                        hash,
                        list
                    });
                }
            });
            const saveTasks = data.map(({ hash, list })=>background_sbCache.set(hash, list));
            await Promise.all(saveTasks);
            const matched = data.find(({ hash })=>hashesMap[hash]);
            if (matched) {
                return matched.list;
            }
            return null;
        } catch (ex) {
            background_logger_logger.error('Error parse safebrowsing response, cause', ex);
        }
        return null;
    }
    /**
     * Creates lookup callback parameter.
     *
     * @param sbList Safebrowsing list we've detected or null.
     *
     * @returns Safebrowsing list or null if this list is SB_ALLOW_LIST (means that site was allowlisted).
     */ static createResponse(sbList) {
        return sbList === background_SbCache.SB_ALLOW_LIST ? null : sbList;
    }
    /**
     * Resumes previously suspended work of SafebrowsingFilter.
     */ static async resumeSafebrowsing() {
        await background_browserStorage.remove(background_SB_SUSPENDED_CACHE_KEY);
    }
    /**
     * Suspend work of SafebrowsingFilter (in case of backend error).
     */ static async suspendSafebrowsing() {
        await background_browserStorage.set(background_SB_SUSPENDED_CACHE_KEY, Date.now());
    }
    /**
     * Calculates SHA256 hashes for strings in hosts and then
     * Returns prefixes for calculated hashes.
     *
     * @param hosts List of hosts.
     *
     * @returns Key value record, where key is calculated hash and value is host.
     */ static createHashesMap(hosts) {
        const result = Object.create(null);
        for(let i = 0; i < hosts.length; i += 1){
            const host = hosts[i];
            if (!host) {
                continue;
            }
            const hash = background_SafebrowsingApi.createHash(host);
            result[hash] = host;
        }
        return result;
    }
    /**
     * Checks safebrowsing cache.
     *
     * @param hosts List of hosts.
     *
     * @returns Matched safebrowsing list name or null.
     */ static checkHostsInSbCache(hosts) {
        for(let i = 0; i < hosts.length; i += 1){
            const host = hosts[i];
            if (!host) {
                continue;
            }
            const sbList = background_sbCache.get(background_SafebrowsingApi.createHash(host));
            if (sbList) {
                return sbList;
            }
        }
        return null;
    }
    /**
     * Extracts hosts from one host.
     * This method returns all sub-domains and IP address of the specified host.
     *
     * @param host Host string.
     *
     * @returns List of sub-domains and ip addresses strings.
     */ static extractHosts(host) {
        const hosts = [];
        if (background_UrlUtils.isIpv4(host) || background_UrlUtils.isIpv6(host)) {
            hosts.push(host);
            return hosts;
        }
        const parts = host.split('.');
        if (parts.length <= 2) {
            hosts.push(host);
        } else {
            for(let i = 0; i <= parts.length - 2; i += 1){
                hosts.push(parts.slice(i).join('.'));
            }
        }
        return hosts;
    }
}
/**
     * If we've got an error response from the backend, suspend requests for
     * this time: 40 minutes.
     */ background_api_safebrowsing_define_property(background_SafebrowsingApi, "SUSPEND_TTL_MS", 40 * 60 * 1000);
/**
     * Domain hash length.
     */ background_api_safebrowsing_define_property(background_SafebrowsingApi, "DOMAIN_HASH_LENGTH", 4);

;// ./Extension/src/background/api/document-block.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_document_block_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}





/**
 * Provides an API for working with trusted domains (domains that have been
 * excluded from blocking by $document rules for
 * {@link DocumentBlockApi.TRUSTED_TTL_MS} time).
 */ class background_DocumentBlockApi {
    /**
     * Initializes the storage for the API.
     */ static async init() {
        try {
            const storageData = await background_trustedDomainsStorage.read();
            if (typeof storageData === 'string') {
                background_trustedDomainsStorage.setCache(JSON.parse(storageData));
            } else {
                await background_trustedDomainsStorage.setData([]);
            }
        } catch (e) {
            await background_trustedDomainsStorage.setData([]);
        }
    }
    /**
     * Returns an array of trusted domains.
     *
     * @returns An array of trusted domains.
     */ static async getTrustedDomains() {
        const now = Date.now();
        // remove expired
        const data = background_trustedDomainsStorage.getData().filter(({ expires })=>now < expires);
        await background_trustedDomainsStorage.setData(data);
        return data.map(({ domain })=>domain);
    }
    /**
     * Adds the domain to the list of trusted domains with DocumentBlockApi#TRUSTED_TTL_MS timeout.
     *
     * @param url A trusted domain to add.
     */ static async setTrustedDomain(url) {
        const { hostname } = new URL(url);
        const now = Date.now();
        // remove expired and duplicates
        const data = background_trustedDomainsStorage.getData().filter(({ expires, domain })=>now < expires && domain !== hostname);
        data.push({
            domain: hostname,
            expires: background_DocumentBlockApi.TRUSTED_TTL_MS + now
        });
        await background_trustedDomainsStorage.setData(data);
    }
}
/**
     * For how long will the application exclude the provided domain
     * from blocking by the $document rule.
     */ background_document_block_define_property(background_DocumentBlockApi, "TRUSTED_TTL_MS", 40 * 60 * 1000) // 40 min
;

;// ./Extension/src/background/api/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 











;// ./Extension/src/background/storages/rules-limits.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 


/**
 * Instance of {@link StringStorage} that stores filter enabled before chrome decided to disable them
 * in {@link storage} under {@link RULES_LIMITS_KEY} key.
 */ const background_rulesLimitsStorage = new background_StringStorage(background_RULES_LIMITS_KEY, background_browserStorage);

;// ./Extension/src/background/schema/rules-limits/rules-limits.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
const background_rulesLimitsStorageDataValidator = background_lib/* default.array */.Ay.array(background_lib/* default.number */.Ay.number());

;// ./Extension/src/background/schema/rules-limits/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ // Rules limits schema entry point
// Rules limits validators and types


;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setCacheAdd.js
/** Used to stand-in for `undefined` hash values. */
var background_setCacheAdd_HASH_UNDEFINED = '__lodash_hash_undefined__';

/**
 * Adds `value` to the array cache.
 *
 * @private
 * @name add
 * @memberOf SetCache
 * @alias push
 * @param {*} value The value to cache.
 * @returns {Object} Returns the cache instance.
 */
function background_setCacheAdd(value) {
  this.__data__.set(value, background_setCacheAdd_HASH_UNDEFINED);
  return this;
}

/* harmony default export */ const pages_background_setCacheAdd = (background_setCacheAdd);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setCacheHas.js
/**
 * Checks if `value` is in the array cache.
 *
 * @private
 * @name has
 * @memberOf SetCache
 * @param {*} value The value to search for.
 * @returns {number} Returns `true` if `value` is found, else `false`.
 */
function background_setCacheHas(value) {
  return this.__data__.has(value);
}

/* harmony default export */ const pages_background_setCacheHas = (background_setCacheHas);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_SetCache.js




/**
 *
 * Creates an array cache object to store unique values.
 *
 * @private
 * @constructor
 * @param {Array} [values] The values to cache.
 */
function background_SetCache(values) {
  var index = -1,
      length = values == null ? 0 : values.length;

  this.__data__ = new pages_background_MapCache;
  while (++index < length) {
    this.add(values[index]);
  }
}

// Add methods to `SetCache`.
background_SetCache.prototype.add = background_SetCache.prototype.push = pages_background_setCacheAdd;
background_SetCache.prototype.has = pages_background_setCacheHas;

/* harmony default export */ const pages_background_SetCache = (background_SetCache);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arraySome.js
/**
 * A specialized version of `_.some` for arrays without support for iteratee
 * shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {boolean} Returns `true` if any element passes the predicate check,
 *  else `false`.
 */
function background_arraySome(array, predicate) {
  var index = -1,
      length = array == null ? 0 : array.length;

  while (++index < length) {
    if (predicate(array[index], index, array)) {
      return true;
    }
  }
  return false;
}

/* harmony default export */ const pages_background_arraySome = (background_arraySome);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_cacheHas.js
/**
 * Checks if a `cache` value for `key` exists.
 *
 * @private
 * @param {Object} cache The cache to query.
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function background_cacheHas(cache, key) {
  return cache.has(key);
}

/* harmony default export */ const pages_background_cacheHas = (background_cacheHas);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalArrays.js




/** Used to compose bitmasks for value comparisons. */
var background_COMPARE_PARTIAL_FLAG = 1,
    background_COMPARE_UNORDERED_FLAG = 2;

/**
 * A specialized version of `baseIsEqualDeep` for arrays with support for
 * partial deep comparisons.
 *
 * @private
 * @param {Array} array The array to compare.
 * @param {Array} other The other array to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `array` and `other` objects.
 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
 */
function background_equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  var isPartial = bitmask & background_COMPARE_PARTIAL_FLAG,
      arrLength = array.length,
      othLength = other.length;

  if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
    return false;
  }
  // Check that cyclic values are equal.
  var arrStacked = stack.get(array);
  var othStacked = stack.get(other);
  if (arrStacked && othStacked) {
    return arrStacked == other && othStacked == array;
  }
  var index = -1,
      result = true,
      seen = (bitmask & background_COMPARE_UNORDERED_FLAG) ? new pages_background_SetCache : undefined;

  stack.set(array, other);
  stack.set(other, array);

  // Ignore non-index properties.
  while (++index < arrLength) {
    var arrValue = array[index],
        othValue = other[index];

    if (customizer) {
      var compared = isPartial
        ? customizer(othValue, arrValue, index, other, array, stack)
        : customizer(arrValue, othValue, index, array, other, stack);
    }
    if (compared !== undefined) {
      if (compared) {
        continue;
      }
      result = false;
      break;
    }
    // Recursively compare arrays (susceptible to call stack limits).
    if (seen) {
      if (!pages_background_arraySome(other, function(othValue, othIndex) {
            if (!pages_background_cacheHas(seen, othIndex) &&
                (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
              return seen.push(othIndex);
            }
          })) {
        result = false;
        break;
      }
    } else if (!(
          arrValue === othValue ||
            equalFunc(arrValue, othValue, bitmask, customizer, stack)
        )) {
      result = false;
      break;
    }
  }
  stack['delete'](array);
  stack['delete'](other);
  return result;
}

/* harmony default export */ const pages_background_equalArrays = (background_equalArrays);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapToArray.js
/**
 * Converts `map` to its key-value pairs.
 *
 * @private
 * @param {Object} map The map to convert.
 * @returns {Array} Returns the key-value pairs.
 */
function background_mapToArray(map) {
  var index = -1,
      result = Array(map.size);

  map.forEach(function(value, key) {
    result[++index] = [key, value];
  });
  return result;
}

/* harmony default export */ const pages_background_mapToArray = (background_mapToArray);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setToArray.js
/**
 * Converts `set` to an array of its values.
 *
 * @private
 * @param {Object} set The set to convert.
 * @returns {Array} Returns the values.
 */
function background_setToArray(set) {
  var index = -1,
      result = Array(set.size);

  set.forEach(function(value) {
    result[++index] = value;
  });
  return result;
}

/* harmony default export */ const pages_background_setToArray = (background_setToArray);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalByTag.js







/** Used to compose bitmasks for value comparisons. */
var background_equalByTag_COMPARE_PARTIAL_FLAG = 1,
    background_equalByTag_COMPARE_UNORDERED_FLAG = 2;

/** `Object#toString` result references. */
var background_equalByTag_boolTag = '[object Boolean]',
    background_equalByTag_dateTag = '[object Date]',
    background_equalByTag_errorTag = '[object Error]',
    background_equalByTag_mapTag = '[object Map]',
    background_equalByTag_numberTag = '[object Number]',
    background_equalByTag_regexpTag = '[object RegExp]',
    background_equalByTag_setTag = '[object Set]',
    background_equalByTag_stringTag = '[object String]',
    background_equalByTag_symbolTag = '[object Symbol]';

var background_equalByTag_arrayBufferTag = '[object ArrayBuffer]',
    background_equalByTag_dataViewTag = '[object DataView]';

/** Used to convert symbols to primitives and strings. */
var background_equalByTag_symbolProto = background_Symbol ? background_Symbol.prototype : undefined,
    background_equalByTag_symbolValueOf = background_equalByTag_symbolProto ? background_equalByTag_symbolProto.valueOf : undefined;

/**
 * A specialized version of `baseIsEqualDeep` for comparing objects of
 * the same `toStringTag`.
 *
 * **Note:** This function only supports comparing values with tags of
 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {string} tag The `toStringTag` of the objects to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function background_equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
  switch (tag) {
    case background_equalByTag_dataViewTag:
      if ((object.byteLength != other.byteLength) ||
          (object.byteOffset != other.byteOffset)) {
        return false;
      }
      object = object.buffer;
      other = other.buffer;

    case background_equalByTag_arrayBufferTag:
      if ((object.byteLength != other.byteLength) ||
          !equalFunc(new background_Uint8Array(object), new background_Uint8Array(other))) {
        return false;
      }
      return true;

    case background_equalByTag_boolTag:
    case background_equalByTag_dateTag:
    case background_equalByTag_numberTag:
      // Coerce booleans to `1` or `0` and dates to milliseconds.
      // Invalid dates are coerced to `NaN`.
      return background_lodash_es_eq(+object, +other);

    case background_equalByTag_errorTag:
      return object.name == other.name && object.message == other.message;

    case background_equalByTag_regexpTag:
    case background_equalByTag_stringTag:
      // Coerce regexes to strings and treat strings, primitives and objects,
      // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
      // for more details.
      return object == (other + '');

    case background_equalByTag_mapTag:
      var convert = pages_background_mapToArray;

    case background_equalByTag_setTag:
      var isPartial = bitmask & background_equalByTag_COMPARE_PARTIAL_FLAG;
      convert || (convert = pages_background_setToArray);

      if (object.size != other.size && !isPartial) {
        return false;
      }
      // Assume cyclic values are equal.
      var stacked = stack.get(object);
      if (stacked) {
        return stacked == other;
      }
      bitmask |= background_equalByTag_COMPARE_UNORDERED_FLAG;

      // Recursively compare objects (susceptible to call stack limits).
      stack.set(object, other);
      var result = pages_background_equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
      stack['delete'](object);
      return result;

    case background_equalByTag_symbolTag:
      if (background_equalByTag_symbolValueOf) {
        return background_equalByTag_symbolValueOf.call(object) == background_equalByTag_symbolValueOf.call(other);
      }
  }
  return false;
}

/* harmony default export */ const pages_background_equalByTag = (background_equalByTag);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalObjects.js


/** Used to compose bitmasks for value comparisons. */
var background_equalObjects_COMPARE_PARTIAL_FLAG = 1;

/** Used for built-in method references. */
var background_equalObjects_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var background_equalObjects_hasOwnProperty = background_equalObjects_objectProto.hasOwnProperty;

/**
 * A specialized version of `baseIsEqualDeep` for objects with support for
 * partial deep comparisons.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function background_equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
  var isPartial = bitmask & background_equalObjects_COMPARE_PARTIAL_FLAG,
      objProps = pages_background_getAllKeys(object),
      objLength = objProps.length,
      othProps = pages_background_getAllKeys(other),
      othLength = othProps.length;

  if (objLength != othLength && !isPartial) {
    return false;
  }
  var index = objLength;
  while (index--) {
    var key = objProps[index];
    if (!(isPartial ? key in other : background_equalObjects_hasOwnProperty.call(other, key))) {
      return false;
    }
  }
  // Check that cyclic values are equal.
  var objStacked = stack.get(object);
  var othStacked = stack.get(other);
  if (objStacked && othStacked) {
    return objStacked == other && othStacked == object;
  }
  var result = true;
  stack.set(object, other);
  stack.set(other, object);

  var skipCtor = isPartial;
  while (++index < objLength) {
    key = objProps[index];
    var objValue = object[key],
        othValue = other[key];

    if (customizer) {
      var compared = isPartial
        ? customizer(othValue, objValue, key, other, object, stack)
        : customizer(objValue, othValue, key, object, other, stack);
    }
    // Recursively compare objects (susceptible to call stack limits).
    if (!(compared === undefined
          ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
          : compared
        )) {
      result = false;
      break;
    }
    skipCtor || (skipCtor = key == 'constructor');
  }
  if (result && !skipCtor) {
    var objCtor = object.constructor,
        othCtor = other.constructor;

    // Non `Object` object instances with different constructors are not equal.
    if (objCtor != othCtor &&
        ('constructor' in object && 'constructor' in other) &&
        !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
          typeof othCtor == 'function' && othCtor instanceof othCtor)) {
      result = false;
    }
  }
  stack['delete'](object);
  stack['delete'](other);
  return result;
}

/* harmony default export */ const pages_background_equalObjects = (background_equalObjects);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsEqualDeep.js









/** Used to compose bitmasks for value comparisons. */
var background_baseIsEqualDeep_COMPARE_PARTIAL_FLAG = 1;

/** `Object#toString` result references. */
var background_baseIsEqualDeep_argsTag = '[object Arguments]',
    background_baseIsEqualDeep_arrayTag = '[object Array]',
    background_baseIsEqualDeep_objectTag = '[object Object]';

/** Used for built-in method references. */
var background_baseIsEqualDeep_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var background_baseIsEqualDeep_hasOwnProperty = background_baseIsEqualDeep_objectProto.hasOwnProperty;

/**
 * A specialized version of `baseIsEqual` for arrays and objects which performs
 * deep comparisons and tracks traversed objects enabling objects with circular
 * references to be compared.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function background_baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
  var objIsArr = background_lodash_es_isArray(object),
      othIsArr = background_lodash_es_isArray(other),
      objTag = objIsArr ? background_baseIsEqualDeep_arrayTag : pages_background_getTag(object),
      othTag = othIsArr ? background_baseIsEqualDeep_arrayTag : pages_background_getTag(other);

  objTag = objTag == background_baseIsEqualDeep_argsTag ? background_baseIsEqualDeep_objectTag : objTag;
  othTag = othTag == background_baseIsEqualDeep_argsTag ? background_baseIsEqualDeep_objectTag : othTag;

  var objIsObj = objTag == background_baseIsEqualDeep_objectTag,
      othIsObj = othTag == background_baseIsEqualDeep_objectTag,
      isSameTag = objTag == othTag;

  if (isSameTag && background_lodash_es_isBuffer(object)) {
    if (!background_lodash_es_isBuffer(other)) {
      return false;
    }
    objIsArr = true;
    objIsObj = false;
  }
  if (isSameTag && !objIsObj) {
    stack || (stack = new pages_background_Stack);
    return (objIsArr || background_lodash_es_isTypedArray(object))
      ? pages_background_equalArrays(object, other, bitmask, customizer, equalFunc, stack)
      : pages_background_equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
  }
  if (!(bitmask & background_baseIsEqualDeep_COMPARE_PARTIAL_FLAG)) {
    var objIsWrapped = objIsObj && background_baseIsEqualDeep_hasOwnProperty.call(object, '__wrapped__'),
        othIsWrapped = othIsObj && background_baseIsEqualDeep_hasOwnProperty.call(other, '__wrapped__');

    if (objIsWrapped || othIsWrapped) {
      var objUnwrapped = objIsWrapped ? object.value() : object,
          othUnwrapped = othIsWrapped ? other.value() : other;

      stack || (stack = new pages_background_Stack);
      return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
    }
  }
  if (!isSameTag) {
    return false;
  }
  stack || (stack = new pages_background_Stack);
  return pages_background_equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}

/* harmony default export */ const pages_background_baseIsEqualDeep = (background_baseIsEqualDeep);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsEqual.js



/**
 * The base implementation of `_.isEqual` which supports partial comparisons
 * and tracks traversed objects.
 *
 * @private
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @param {boolean} bitmask The bitmask flags.
 *  1 - Unordered comparison
 *  2 - Partial comparison
 * @param {Function} [customizer] The function to customize comparisons.
 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 */
function background_baseIsEqual(value, other, bitmask, customizer, stack) {
  if (value === other) {
    return true;
  }
  if (value == null || other == null || (!background_lodash_es_isObjectLike(value) && !background_lodash_es_isObjectLike(other))) {
    return value !== value && other !== other;
  }
  return pages_background_baseIsEqualDeep(value, other, bitmask, customizer, background_baseIsEqual, stack);
}

/* harmony default export */ const pages_background_baseIsEqual = (background_baseIsEqual);

;// ./node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isEqual.js


/**
 * Performs a deep comparison between two values to determine if they are
 * equivalent.
 *
 * **Note:** This method supports comparing arrays, array buffers, booleans,
 * date objects, error objects, maps, numbers, `Object` objects, regexes,
 * sets, strings, symbols, and typed arrays. `Object` objects are compared
 * by their own, not inherited, enumerable properties. Functions and DOM
 * nodes are compared by strict equality, i.e. `===`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * var object = { 'a': 1 };
 * var other = { 'a': 1 };
 *
 * _.isEqual(object, other);
 * // => true
 *
 * object === other;
 * // => false
 */
function background_isEqual(value, other) {
  return pages_background_baseIsEqual(value, other);
}

/* harmony default export */ const background_lodash_es_isEqual = (background_isEqual);

;// ./Extension/src/background/utils/arrays-are-equal.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
/**
 * Compare two arrays and return true if they are equal.
 *
 * @param arrA Array A.
 * @param arrB Array B.
 *
 * @returns True if arrays are equal.
 */ const background_arraysAreEqual = (arrA, arrB)=>{
    return background_lodash_es_isEqual(arrA.sort((a, b)=>a - b), arrB.sort((a, b)=>a - b));
};

;// ./Extension/src/background/services/rules-limits/rules-limits-service-mv3.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_rules_limits_service_mv3_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}











// Note: due to circular dependencies, import message-handler.ts after all
// other imports.



const { MAX_NUMBER_OF_DYNAMIC_RULES: background_MAX_NUMBER_OF_DYNAMIC_RULES, MAX_NUMBER_OF_REGEX_RULES: background_MAX_NUMBER_OF_REGEX_RULES, MAX_NUMBER_OF_ENABLED_STATIC_RULESETS: background_MAX_NUMBER_OF_ENABLED_STATIC_RULESETS, /**
     * @see {@link https://developer.chrome.com/docs/extensions/reference/api/declarativeNetRequest#property-MAX_NUMBER_OF_UNSAFE_DYNAMIC_RULES}
     */ // TODO: remove default value and following ts-ignore
// when the value is available in webextension-polyfill
// @ts-ignore
MAX_NUMBER_OF_UNSAFE_DYNAMIC_RULES: background_MAX_NUMBER_OF_UNSAFE_DYNAMIC_RULES = 5000 } = (background_browser_polyfill_default()).declarativeNetRequest;
/**
 * Service to work with configuration result.
 */ class background_RulesLimitsService {
    /**
     * Subscribes to messages from the options' page.
     */ async init() {
        // Rules limits page overall status with all counters.
        background_message_handler_messageHandler.addListener(background_constants_MessageType.GetRulesLimitsCountersMv3, this.onGetRulesLimitsCounters.bind(this));
        // Static filters checks before enable them.
        background_message_handler_messageHandler.addListener(background_constants_MessageType.CanEnableStaticFilterMv3, this.canEnableStaticFilter.bind(this));
        background_message_handler_messageHandler.addListener(background_constants_MessageType.CanEnableStaticGroupMv3, this.canEnableStaticGroup.bind(this));
        // Checks for possible limits exceeding based on the current configuration result.
        background_message_handler_messageHandler.addListener(background_constants_MessageType.CurrentLimitsMv3, this.getRulesLimits.bind(this));
        // Drop warning.
        background_message_handler_messageHandler.addListener(background_constants_MessageType.ClearRulesLimitsWarningMv3, background_RulesLimitsService.clearRulesLimitsWarning);
        // First read from storage and set data to cache.
        await background_RulesLimitsService.initStorage();
    }
    /**
     * Get the number of enabled static filters.
     *
     * @returns The number of enabled static filters.
     */ static getStaticEnabledFiltersCount() {
        return background_main_FiltersApi.getEnabledFiltersWithMetadata().filter((f)=>!background_custom_CustomFilterApi.isCustomFilter(f.filterId)).length;
    }
    /**
     * Clears the rules limits warning by resetting the expected enabled filters.
     * This function is intended to be used when the user acknowledges the warning
     * and wants to reset the state to avoid further notifications.
     */ static async clearRulesLimitsWarning() {
        // Reset the warning state by clearing the list of expected enabled filters.
        await background_RulesLimitsService.cleanExpectedEnabledFilters();
        // Force update the icon state immediately
        // to ensure it reflects the current status without waiting for user actions.
        await background_iconsApi.update();
    }
    /**
     * Returns an array of ruleset counters.
     *
     * @param filters List of filters with metadata.
     * @param ruleSetsCounters A map of ruleset counters.
     *
     * @returns An array of ruleset counters by filters ids.
     */ static getRuleSetCounters(filters, ruleSetsCounters) {
        return filters.filter((f)=>!background_custom_CustomFilterApi.isCustomFilter(f.filterId)).map((filter)=>ruleSetsCounters[filter.filterId]).filter((ruleSet)=>ruleSet !== undefined);
    }
    /**
     * Gets the static ruleset counter by filter id.
     *
     * @param result Configuration result.
     * @param filterId Filter id.
     *
     * @returns The static ruleset counter.
     *
     * @throws Error if the ruleset counter is not found.
     */ static getStaticRuleSetCounter(result, filterId) {
        const ruleSetsCounters = background_RulesLimitsService.getRuleSetsCountersMap(result);
        const ruleSetsCounter = ruleSetsCounters[filterId];
        if (!ruleSetsCounter) {
            throw new Error(`RuleSetCounter for filterId ${filterId} not found`);
        }
        return ruleSetsCounter;
    }
    /**
     * Get the number of static rules enabled.
     *
     * @param result Configuration result.
     * @param filters Filters with metadata.
     *
     * @returns The number of static rules enabled.
     */ static getStaticRulesEnabledCount(result, filters) {
        const ruleSetsCounters = background_RulesLimitsService.getRuleSetsCountersMap(result);
        const ruleSets = background_RulesLimitsService.getRuleSetCounters(filters, ruleSetsCounters);
        return ruleSets.reduce((sum, ruleSet)=>{
            return sum + ruleSet.rulesCount;
        }, 0);
    }
    /**
     * Calculates how many regexp rules are in the rulesets.
     *
     * @param result Configuration result.
     * @param filters Filters with metadata.
     *
     * @returns Count of the regexp rules.
     */ static getStaticRulesRegexpsCount(result, filters) {
        const ruleSetsCounters = background_RulesLimitsService.getRuleSetsCountersMap(result);
        const ruleSets = background_RulesLimitsService.getRuleSetCounters(filters, ruleSetsCounters);
        return ruleSets.reduce((sum, ruleSet)=>{
            return sum + ruleSet.regexpRulesCount;
        }, 0);
    }
    /**
     * How many dynamic rules are enabled.
     *
     * @param result Configuration result.
     *
     * @returns Count of enabled dynamic rules.
     */ static getDynamicRulesEnabledCount(result) {
        var _result_dynamicRules;
        const rulesLimitExceedErr = background_RulesLimitsService.getRulesLimitExceedErr(result);
        const declarativeRulesCount = ((_result_dynamicRules = result.dynamicRules) === null || _result_dynamicRules === void 0 ? void 0 : _result_dynamicRules.ruleSet.getRulesCount()) || 0;
        return (rulesLimitExceedErr === null || rulesLimitExceedErr === void 0 ? void 0 : rulesLimitExceedErr.numberOfMaximumRules) || declarativeRulesCount;
    }
    /**
     * How many dynamic rules are excluded and cannot be enabled.
     *
     * @param result Configuration result.
     *
     * @returns Count of excluded rules.
     */ static getDynamicRulesExcludedCount(result) {
        const rulesLimitExceedErr = background_RulesLimitsService.getRulesLimitExceedErr(result);
        return (rulesLimitExceedErr === null || rulesLimitExceedErr === void 0 ? void 0 : rulesLimitExceedErr.numberOfExcludedDeclarativeRules) || 0;
    }
    /**
     * Returns number of maximum possible dynamic rules.
     *
     * @param result Configuration result.
     *
     * @returns Count of rules.
     */ static getDynamicRulesMaximumCount(result) {
        const rulesLimitExceedErr = background_RulesLimitsService.getRulesLimitExceedErr(result);
        return (rulesLimitExceedErr === null || rulesLimitExceedErr === void 0 ? void 0 : rulesLimitExceedErr.numberOfMaximumRules) || background_MAX_NUMBER_OF_DYNAMIC_RULES;
    }
    /**
     * Returns how much dynamic regex rules are enabled.
     *
     * @param result Configuration result.
     *
     * @returns Number rules.
     */ static getDynamicRegexpRulesEnabledCount(result) {
        var _result_dynamicRules;
        const regexpsCount = ((_result_dynamicRules = result.dynamicRules) === null || _result_dynamicRules === void 0 ? void 0 : _result_dynamicRules.ruleSet.getRegexpRulesCount()) || 0;
        const regexpRulesLimitExceedErr = background_RulesLimitsService.getRegexpRulesLimitExceedErr(result);
        const excludedRulesCount = (regexpRulesLimitExceedErr === null || regexpRulesLimitExceedErr === void 0 ? void 0 : regexpRulesLimitExceedErr.excludedRulesIds.length) || 0;
        return regexpsCount + excludedRulesCount;
    }
    /**
     * Returns maximum count of the dynamic regexp rules.
     *
     * @param result Configuration result.
     *
     * @returns Rules count.
     */ static getDynamicRegexpRulesMaximumCount(result) {
        const regexpRulesLimitExceedErr = background_RulesLimitsService.getRegexpRulesLimitExceedErr(result);
        return (regexpRulesLimitExceedErr === null || regexpRulesLimitExceedErr === void 0 ? void 0 : regexpRulesLimitExceedErr.numberOfMaximumRules) || background_MAX_NUMBER_OF_REGEX_RULES;
    }
    /**
     * How many dynamic **unsafe** rules are enabled.
     *
     * @param result Configuration result.
     *
     * @returns Count of enabled dynamic unsafe rules.
     */ static getDynamicUnsafeRulesEnabledCount(result) {
        var _result_dynamicRules;
        const unsafeRulesCount = ((_result_dynamicRules = result.dynamicRules) === null || _result_dynamicRules === void 0 ? void 0 : _result_dynamicRules.ruleSet.getUnsafeRulesCount()) || 0;
        const unsafeRulesLimitExceedErr = background_RulesLimitsService.getUnsafeRulesLimitExceedErr(result);
        const excludedRulesCount = (unsafeRulesLimitExceedErr === null || unsafeRulesLimitExceedErr === void 0 ? void 0 : unsafeRulesLimitExceedErr.excludedRulesIds.length) || 0;
        return unsafeRulesCount + excludedRulesCount;
    }
    /**
     * Returns number of maximum possible dynamic **unsafe** rules.
     *
     * @param result Configuration result.
     *
     * @returns Count of rules.
     */ static getDynamicUnsafeRulesMaximumCount(result) {
        const rulesLimitExceedErr = background_RulesLimitsService.getUnsafeRulesLimitExceedErr(result);
        return (rulesLimitExceedErr === null || rulesLimitExceedErr === void 0 ? void 0 : rulesLimitExceedErr.numberOfMaximumRules) || background_MAX_NUMBER_OF_UNSAFE_DYNAMIC_RULES;
    }
    /**
     * Returns filters which where enabled in the last configuration
     * before exceeding limits.
     *
     * @returns Filters which where enabled in the last configuration
     * before exceeding limits.
     */ static getExpectedEnabledFilters() {
        return background_rulesLimitsStorage.getData();
    }
    /**
     * Returns filters which marked as enabled in the last configuration
     * (current settings in the storage).
     *
     * @returns Filters which marked as enabled in the last configuration
     * (current settings in the storage).
     */ static getCurrentConfigurationEnabledFilters() {
        const ids = background_main_FiltersApi.getEnabledFiltersWithMetadata()// Ignore custom filters, user rules, allowlist and quick fixes lists
        // because they are user-defined (except quick fixes - it loaded
        // dynamically from the remote) and do not use quota of the static
        // rules.
        // of them is going via dynamic part of DNR rules.
        .filter((f)=>background_CommonFilterApi.isCommonFilter(f.filterId)).map((filter)=>filter.filterId);
        return ids;
    }
    /**
     * Returns filters which rulesets (we have 1 to 1 relation) actually enabled.
     *
     * @returns Filters which rulesets (we have 1 to 1 relation) actually enabled.
     */ static async getActuallyEnabledFilters() {
        const enabledRuleSetsIds = await chrome.declarativeNetRequest.getEnabledRulesets();
        return enabledRuleSetsIds.map((id)=>Number.parseInt(id.slice(background_RULESET_NAME_PREFIX.length), 10));
    }
    /**
     * Determines and returns rules limits.
     *
     * @returns Rules limits or undefined if the configuration result is not ready yet.
     */ async onGetRulesLimitsCounters() {
        const result = this.configurationResult;
        if (!result) {
            return undefined;
        }
        const filters = background_main_FiltersApi.getEnabledFiltersWithMetadata();
        const staticRulesEnabledCount = background_RulesLimitsService.getStaticRulesEnabledCount(result, filters);
        const availableStaticRulesCount = await background_browser_polyfill_default().declarativeNetRequest.getAvailableStaticRuleCount();
        const staticRulesMaximumCount = staticRulesEnabledCount + availableStaticRulesCount;
        return {
            dynamicRulesEnabledCount: background_RulesLimitsService.getDynamicRulesEnabledCount(result),
            dynamicRulesMaximumCount: background_RulesLimitsService.getDynamicRulesMaximumCount(result),
            dynamicRulesUnsafeEnabledCount: background_RulesLimitsService.getDynamicUnsafeRulesEnabledCount(result),
            dynamicRulesUnsafeMaximumCount: background_RulesLimitsService.getDynamicUnsafeRulesMaximumCount(result),
            dynamicRulesRegexpsEnabledCount: background_RulesLimitsService.getDynamicRegexpRulesEnabledCount(result),
            dynamicRulesRegexpsMaximumCount: background_RulesLimitsService.getDynamicRegexpRulesMaximumCount(result),
            staticFiltersEnabledCount: background_RulesLimitsService.getStaticEnabledFiltersCount(),
            staticFiltersMaximumCount: background_MAX_NUMBER_OF_ENABLED_STATIC_RULESETS,
            staticRulesEnabledCount,
            staticRulesMaximumCount,
            staticRulesRegexpsEnabledCount: background_RulesLimitsService.getStaticRulesRegexpsCount(result, filters),
            staticRulesRegexpsMaxCount: background_MAX_NUMBER_OF_REGEX_RULES,
            actuallyEnabledFilters: await background_RulesLimitsService.getActuallyEnabledFilters(),
            expectedEnabledFilters: background_RulesLimitsService.getExpectedEnabledFilters(),
            areFilterLimitsExceeded: await background_RulesLimitsService.areFilterLimitsExceeded()
        };
    }
    /**
     * Checks whether the filter limits are exceeded:
     * - if we have cached enabled filters and they are not equal to the actually enabled filters
     * (when state was broken once before);
     * - if filters from current configuration are not equal to the actually enabled filters
     * (when state became broken right now).
     *
     * @returns True if the filter limits are exceeded, false otherwise.
     */ static async areFilterLimitsExceeded() {
        const filteringDisabled = background_settingsStorage.get(background_SettingOption.DisableFiltering);
        if (filteringDisabled) {
            return false;
        }
        const actuallyEnabledFilters = await background_RulesLimitsService.getActuallyEnabledFilters();
        if (actuallyEnabledFilters.length === 0) {
            return false;
        }
        // If there are some filters in storage - it means, that last used
        // configuration is damaged and we should notify user about them until
        // he will fix configuration or turn off this notification.
        // This case needed to save warning if service worker will restart and
        // after successful configuration update we will not notify user about
        // changed configuration or user paused and resumed protection.
        const cachedEnabledFilters = background_RulesLimitsService.getExpectedEnabledFilters();
        if (cachedEnabledFilters.length > 0 && !background_arraysAreEqual(actuallyEnabledFilters, cachedEnabledFilters)) {
            return true;
        }
        // Else we do a full check of the current configuration: if filters from
        // configuration are not same as enabled filters - it means that browser
        // declined update of the configuration and we should notify user about it.
        const expectedEnabledFilters = background_RulesLimitsService.getCurrentConfigurationEnabledFilters();
        return !background_arraysAreEqual(actuallyEnabledFilters, expectedEnabledFilters);
    }
    /**
     * Set configuration result to the service.
     *
     * @param result Configuration result.
     * @param isFilteringEnabled Is filtering enabled or not. If disabled -
     * service will turn off all checks for limitations.
     */ updateConfigurationResult(result, isFilteringEnabled) {
        this.configurationResult = result;
        this.isFilteringEnabled = isFilteringEnabled;
    }
    /**
     * Check if filters limits have changed and update filters state if needed.
     *
     * @param update Function to update filters state and configure tswebextension.
     */ static async checkFiltersLimitsChange(update) {
        const isStateBroken = await background_RulesLimitsService.areFilterLimitsExceeded();
        // If state is broken - disable filters that were expected to be enabled
        // and configure tswebextension without them to activate minimal possible
        // defense via saving last enabled filters in the separate storage to
        // show them in the UI.
        if (isStateBroken) {
            const expectedEnabledFilters = background_RulesLimitsService.getCurrentConfigurationEnabledFilters();
            const actuallyEnabledFilters = await background_RulesLimitsService.getActuallyEnabledFilters();
            const filtersToDisable = expectedEnabledFilters.filter((id)=>!actuallyEnabledFilters.includes(id));
            // Save last expected to be enabled filters to notify UI about them,
            // because we will disable them to run minimal possible configuration.
            // It should be done only if there are no filters in the storage,
            // otherwise previous filters list will be overwritten on successful filter enabling (AG-34194).
            if (background_RulesLimitsService.getExpectedEnabledFilters().length === 0) {
                await background_rulesLimitsStorage.setData(expectedEnabledFilters);
            }
            background_filterStateStorage.enableFilters(actuallyEnabledFilters);
            background_filterStateStorage.disableFilters(filtersToDisable);
            // Update tswebextension configuration without check limitations to
            // skip recursion.
            await update(true);
        } else {
            // If state is not broken - clear list of "broken" filters
            const prevExpectedEnabledFilters = background_RulesLimitsService.getExpectedEnabledFilters();
            if (prevExpectedEnabledFilters.length > 0) {
                await this.cleanExpectedEnabledFilters();
            }
        }
    }
    /**
     * Clean filters that were expected to be enabled.
     */ static async cleanExpectedEnabledFilters() {
        await background_rulesLimitsStorage.setData([]);
    }
    /**
     * Read stringified domains array from specified allowlist storage,
     * parse it and set memory cache.
     *
     * If data is not exist, set default data.
     */ static async initStorage() {
        try {
            const storageData = await background_rulesLimitsStorage.read();
            if (typeof storageData === 'string') {
                const validatedData = background_rulesLimitsStorageDataValidator.parse(JSON.parse(storageData));
                background_rulesLimitsStorage.setCache(validatedData);
            } else {
                await this.cleanExpectedEnabledFilters();
            }
        } catch (e) {
            // eslint-disable-next-line max-len
            background_logger_logger.warn(`Cannot parse data from "${background_rulesLimitsStorage.key}" storage, set default states. Origin error: `, e);
            await this.cleanExpectedEnabledFilters();
        }
    }
    /**
     * Returns current possible limitations of the rules for static filters
     * and dynamic rules based on the current configuration result.
     *
     * @returns Promise that resolves with possible limitations.
     */ async getRulesLimits() {
        const staticFiltersCheck = await this.getStaticFiltersLimitations();
        const dynamicRulesCheck = await this.getDynamicRulesLimitations();
        return {
            ok: staticFiltersCheck.ok && dynamicRulesCheck.ok,
            staticFiltersData: staticFiltersCheck.data,
            dynamicRulesData: dynamicRulesCheck.data
        };
    }
    /**
     * Returns limits for the dynamic section of rules.
     *
     * @returns Promise that resolves with possible limitations.
     */ async getStaticFiltersLimitations() {
        if (!this.isFilteringEnabled) {
            return {
                ok: true
            };
        }
        const enabledFiltersCount = background_RulesLimitsService.getStaticEnabledFiltersCount();
        if (enabledFiltersCount === background_MAX_NUMBER_OF_ENABLED_STATIC_RULESETS) {
            return {
                ok: false,
                data: {
                    type: 'static',
                    filtersCount: {
                        current: enabledFiltersCount,
                        maximum: background_MAX_NUMBER_OF_ENABLED_STATIC_RULESETS
                    }
                }
            };
        }
        const areFilterLimitsExceeded = await background_RulesLimitsService.areFilterLimitsExceeded();
        if (areFilterLimitsExceeded) {
            const actuallyEnabledFilters = await background_RulesLimitsService.getActuallyEnabledFilters();
            return {
                ok: false,
                data: {
                    type: 'static',
                    filtersCount: {
                        current: actuallyEnabledFilters.length,
                        expected: background_RulesLimitsService.getExpectedEnabledFilters().length
                    }
                }
            };
        }
        return {
            ok: true
        };
    }
    /**
     * Returns limits for the dynamic section of rules.
     *
     * @returns Promise that resolves with possible limitations.
     */ async getDynamicRulesLimitations() {
        if (!this.isFilteringEnabled) {
            return {
                ok: true
            };
        }
        const result = this.configurationResult;
        if (!result) {
            // sometimes configuration result may not be ready yet,
            // e.g. when service worker was not running and options page is opened from the context menu
            // TODO: consider returning something like NOT_READY status which can be handled later if needed
            background_logger_logger.debug('[canEnableDynamicRules] Configuration result is not ready yet');
            return {
                ok: true
            };
        }
        const dynamicRulesEnabledCount = background_RulesLimitsService.getDynamicRulesEnabledCount(result);
        const dynamicRulesExcludedCount = background_RulesLimitsService.getDynamicRulesExcludedCount(result);
        const dynamicRulesMaximumCount = background_RulesLimitsService.getDynamicRulesMaximumCount(result);
        const allRulesCount = dynamicRulesEnabledCount + dynamicRulesExcludedCount;
        if (allRulesCount > dynamicRulesMaximumCount) {
            return {
                ok: false,
                data: {
                    type: 'dynamic',
                    rulesCount: {
                        // return number of all rules (enabled + excluded)
                        // to show how many rules a user is trying to enable
                        current: dynamicRulesEnabledCount + dynamicRulesExcludedCount,
                        maximum: dynamicRulesMaximumCount
                    }
                }
            };
        }
        const dynamicRulesUnsafeEnabledCount = background_RulesLimitsService.getDynamicUnsafeRulesEnabledCount(result);
        const dynamicUnsafeRegexpsMaximumCount = background_RulesLimitsService.getDynamicUnsafeRulesMaximumCount(result);
        if (dynamicRulesUnsafeEnabledCount > dynamicUnsafeRegexpsMaximumCount) {
            return {
                ok: false,
                data: {
                    type: 'dynamic',
                    rulesUnsafeCount: {
                        current: dynamicRulesUnsafeEnabledCount,
                        maximum: dynamicUnsafeRegexpsMaximumCount
                    }
                }
            };
        }
        const dynamicRulesRegexpsEnabledCount = background_RulesLimitsService.getDynamicRegexpRulesEnabledCount(result);
        const dynamicRulesRegexpsMaximumCount = background_RulesLimitsService.getDynamicRegexpRulesMaximumCount(result);
        if (dynamicRulesRegexpsEnabledCount > dynamicRulesRegexpsMaximumCount) {
            return {
                ok: false,
                data: {
                    type: 'dynamic',
                    rulesRegexpsCount: {
                        current: dynamicRulesRegexpsEnabledCount,
                        maximum: dynamicRulesRegexpsMaximumCount
                    }
                }
            };
        }
        return {
            ok: true
        };
    }
    /**
     * Checks if the static filter can be enabled.
     *
     * @param filterId Filter id.
     *
     * @returns Promise that resolves with the result of the check.
     */ async doesStaticFilterFitsInLimits(filterId) {
        const result = this.configurationResult;
        /**
         * Usually, the configuration result should be ready, when this method is called.
         * But even if it's not ready, we should not block the filter enabling.
         * In any case, the filter will not be enabled if it doesn't fit in limits.
         */ if (!result) {
            background_logger_logger.error('[doesStaticFilterFitsInLimits]: configuration result is not ready yet');
            return {
                ok: true
            };
        }
        if (!this.isFilteringEnabled) {
            return {
                ok: true
            };
        }
        const enabledFiltersCount = background_RulesLimitsService.getStaticEnabledFiltersCount();
        if (enabledFiltersCount > background_MAX_NUMBER_OF_ENABLED_STATIC_RULESETS) {
            return {
                ok: false,
                data: {
                    type: 'static',
                    filtersCount: {
                        current: enabledFiltersCount,
                        maximum: background_MAX_NUMBER_OF_ENABLED_STATIC_RULESETS
                    }
                }
            };
        }
        const availableStaticRulesCount = await background_browser_polyfill_default().declarativeNetRequest.getAvailableStaticRuleCount();
        const filterStaticRulesCount = background_RulesLimitsService.getStaticRuleSetCounter(result, filterId);
        if (filterStaticRulesCount.rulesCount > availableStaticRulesCount) {
            return {
                ok: false,
                data: {
                    type: 'static',
                    rulesCount: {
                        current: filterStaticRulesCount.rulesCount,
                        maximum: availableStaticRulesCount
                    }
                }
            };
        }
        const enabledFilters = background_main_FiltersApi.getEnabledFiltersWithMetadata();
        const allEnabledRegexpRulesCount = background_RulesLimitsService.getStaticRulesRegexpsCount(result, enabledFilters);
        const allPossibleEnabledRegexpRulesCount = allEnabledRegexpRulesCount + filterStaticRulesCount.regexpRulesCount;
        if (allPossibleEnabledRegexpRulesCount > background_MAX_NUMBER_OF_REGEX_RULES) {
            return {
                ok: false,
                data: {
                    type: 'static',
                    rulesRegexpsCount: {
                        current: filterStaticRulesCount.regexpRulesCount,
                        maximum: background_MAX_NUMBER_OF_REGEX_RULES
                    }
                }
            };
        }
        return {
            ok: true
        };
    }
    /**
     * Checks if static filter can be enabled.
     *
     * @param message Message with filter id.
     *
     * @returns Promise that resolves with the result of the check — {@link StaticLimitsCheckResult}.
     */ async canEnableStaticFilter(message) {
        const { filterId } = message.data;
        if (background_custom_CustomFilterApi.isCustomFilter(filterId)) {
            throw new Error('Custom filters should be checked with canEnableDynamicRules method');
        }
        return this.doesStaticFilterFitsInLimits(filterId);
    }
    /**
     * Checks if the static filters can be enabled.
     *
     * @param filterIds Filter ids list.
     *
     * @returns Promise that resolves with the result of the check.
     */ async doStaticFiltersFitInLimits(filterIds) {
        const result = this.configurationResult;
        /**
         * Usually, the configuration result should be ready when this method is called.
         * But even if it's not ready, we should not block the filter enabling.
         * In any case, the filter will not be enabled if it doesn't fit in limits.
         */ if (!result) {
            background_logger_logger.error('[doStaticFiltersFitInLimits]: Configuration result is not ready yet.');
            return {
                ok: true
            };
        }
        if (!this.isFilteringEnabled) {
            return {
                ok: true
            };
        }
        const enabledFiltersCount = background_RulesLimitsService.getStaticEnabledFiltersCount();
        const isWithinRulesetsLimit = enabledFiltersCount + filterIds.length <= background_MAX_NUMBER_OF_ENABLED_STATIC_RULESETS;
        if (!isWithinRulesetsLimit) {
            return {
                ok: false,
                data: {
                    type: 'static',
                    filtersCount: {
                        current: enabledFiltersCount,
                        maximum: background_MAX_NUMBER_OF_ENABLED_STATIC_RULESETS
                    }
                }
            };
        }
        const availableStaticRulesCount = await background_browser_polyfill_default().declarativeNetRequest.getAvailableStaticRuleCount();
        const { totalStaticRulesCount, totalRegexpRulesCount } = filterIds.reduce((acc, filterId)=>{
            const filterStaticRulesCount = background_RulesLimitsService.getStaticRuleSetCounter(result, filterId);
            acc.totalStaticRulesCount += filterStaticRulesCount.rulesCount;
            acc.totalRegexpRulesCount += filterStaticRulesCount.regexpRulesCount;
            return acc;
        }, {
            totalStaticRulesCount: 0,
            totalRegexpRulesCount: 0
        });
        const isWithinStaticRulesLimit = availableStaticRulesCount >= totalStaticRulesCount;
        if (!isWithinStaticRulesLimit) {
            return {
                ok: false,
                data: {
                    type: 'static',
                    rulesCount: {
                        current: totalStaticRulesCount,
                        maximum: availableStaticRulesCount
                    }
                }
            };
        }
        const enabledFilters = background_main_FiltersApi.getEnabledFiltersWithMetadata();
        const allEnabledRegexpRulesCount = background_RulesLimitsService.getStaticRulesRegexpsCount(result, enabledFilters);
        const regexpRulesIfFiltersEnabled = allEnabledRegexpRulesCount + totalRegexpRulesCount;
        const isWithinRegexRulesLimit = regexpRulesIfFiltersEnabled <= background_MAX_NUMBER_OF_REGEX_RULES;
        if (!isWithinRegexRulesLimit) {
            return {
                ok: false,
                data: {
                    type: 'static',
                    rulesRegexpsCount: {
                        current: totalRegexpRulesCount,
                        maximum: background_MAX_NUMBER_OF_REGEX_RULES
                    }
                }
            };
        }
        return {
            ok: true
        };
    }
    /**
     * Checks if the static group can be enabled.
     *
     * @param message Message with group id.
     *
     * @returns Promise that resolves with the result of the check.
     */ async canEnableStaticGroup(message) {
        const { groupId } = message.data;
        const group = background_Categories.getGroupState(groupId);
        if (!group) {
            throw new Error(`There is no group with such id: ${groupId}`);
        }
        let filters = [];
        if (group.touched) {
            filters = background_Categories.getEnabledFiltersIdsByGroupId(groupId);
        } else {
            filters = background_Categories.getRecommendedFilterIdsByGroupId(groupId);
        }
        return this.doStaticFiltersFitInLimits(filters);
    }
    constructor(){
        background_rules_limits_service_mv3_define_property(this, "configurationResult", null);
        /**
     * Is filtering enabled or not. If disabled - service will turn off all
     * checks for limitations.
     */ background_rules_limits_service_mv3_define_property(this, "isFilteringEnabled", true);
    }
}
/**
     * Returns a map of ruleset counters.
     *
     * @param result Configuration result.
     *
     * @returns A map of ruleset counters.
     */ background_rules_limits_service_mv3_define_property(background_RulesLimitsService, "getRuleSetsCountersMap", (result)=>{
    const counters = result.staticFilters.reduce((acc, ruleset)=>{
        const filterId = Number(ruleset.getId().slice(background_RULESET_NAME_PREFIX.length));
        acc[filterId] = {
            filterId,
            rulesCount: ruleset.getRulesCount(),
            regexpRulesCount: ruleset.getRegexpRulesCount()
        };
        return acc;
    }, {});
    // TODO: Uncomment this block when Quick Fixes filter will be supported for MV3
    // // It is like "syntax sugar" for the quick fixes filter to emulate it
    // // like an "empty" ruleset, because it looks like usual filter
    // // in the UI, but it actually applied dynamically, so enabling it will
    // // never change quota of the used static rules.
    // counters[AntiBannerFiltersId.QuickFixesFilterId] = {
    //     filterId: AntiBannerFiltersId.QuickFixesFilterId,
    //     rulesCount: 0,
    //     regexpRulesCount: 0,
    // };
    return counters;
});
/**
     * Finds first found limitation error about unsafe rules limit.
     *
     * @param result Configuration result.
     *
     * @returns Limitation error.
     */ background_rules_limits_service_mv3_define_property(background_RulesLimitsService, "getUnsafeRulesLimitExceedErr", (result)=>{
    var _result_dynamicRules;
    return (_result_dynamicRules = result.dynamicRules) === null || _result_dynamicRules === void 0 ? void 0 : _result_dynamicRules.limitations.find((e)=>e instanceof background_TooManyUnsafeRulesError);
});
/**
     * Finds first found limitation error.
     *
     * @param result Configuration result.
     *
     * @returns Limitation error.
     */ background_rules_limits_service_mv3_define_property(background_RulesLimitsService, "getRegexpRulesLimitExceedErr", (result)=>{
    var _result_dynamicRules;
    return (_result_dynamicRules = result.dynamicRules) === null || _result_dynamicRules === void 0 ? void 0 : _result_dynamicRules.limitations.find((e)=>e instanceof background_TooManyRegexpRulesError);
});
/**
     * Finds first too many rules error.
     *
     * @param result Configuration result.
     *
     * @returns Too many rules error.
     */ background_rules_limits_service_mv3_define_property(background_RulesLimitsService, "getRulesLimitExceedErr", (result)=>{
    var _result_dynamicRules;
    return (_result_dynamicRules = result.dynamicRules) === null || _result_dynamicRules === void 0 ? void 0 : _result_dynamicRules.limitations.find((e)=>e instanceof background_TooManyRulesError);
});
const background_rulesLimitsService = new background_RulesLimitsService();

;// ./Extension/src/background/services/filtering-log.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 







// TODO (David): Add function to preprocess rule event data
/**
 * FilteringLogService collects all actions that extension doing to web requests
 * to record them and show.
 */ class background_FilteringLogService {
    /**
     * Creates handlers for all possible actions.
     */ static init() {
        /* eslint-disable max-len */ background_message_handler_messageHandler.addListener(background_constants_MessageType.GetFilteringLogData, background_FilteringLogService.onGetFilteringLogData);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.SynchronizeOpenTabs, background_FilteringLogService.onSyncOpenTabs);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.GetFilteringInfoByTabId, background_FilteringLogService.onGetFilteringLogInfoById);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.OnOpenFilteringLogPage, background_filteringLogApi.onOpenFilteringLogPage);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.OnCloseFilteringLogPage, background_filteringLogApi.onCloseFilteringLogPage);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.ClearEventsByTabId, background_FilteringLogService.onClearEventsByTabId);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.RefreshPage, background_FilteringLogService.onRefreshPage);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.SetPreserveLogState, background_FilteringLogService.onSetPreserveLogState);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.SetFilteringLogWindowState, background_FilteringLogService.onSetFilteringLogWindowState);
        background_tabsApi.onCreate.subscribe(background_FilteringLogService.onTabCreate);
        background_tabsApi.onUpdate.subscribe(background_FilteringLogService.onTabUpdate);
        background_tabsApi.onDelete.subscribe(background_FilteringLogService.onTabRemove);
        background_defaultFilteringLog.addEventListener(background_FilteringEventType.SendRequest, background_FilteringLogService.onSendRequest);
        background_defaultFilteringLog.addEventListener(background_FilteringEventType.TabReload, background_FilteringLogService.onTabReload);
        background_defaultFilteringLog.addEventListener(background_FilteringEventType.ReceiveResponse, background_FilteringLogService.onReceiveResponse);
        background_defaultFilteringLog.addEventListener(background_FilteringEventType.ApplyBasicRule, background_FilteringLogService.onApplyBasicRule);
        background_defaultFilteringLog.addEventListener(background_FilteringEventType.ApplyCspRule, background_FilteringLogService.onApplyCspRule);
        background_defaultFilteringLog.addEventListener(background_FilteringEventType.ApplyPermissionsRule, background_FilteringLogService.onApplyPermissionsRule);
        background_defaultFilteringLog.addEventListener(background_FilteringEventType.ApplyCosmeticRule, background_FilteringLogService.onApplyCosmeticRule);
        background_defaultFilteringLog.addEventListener(background_FilteringEventType.RemoveParam, background_FilteringLogService.onRemoveParam);
        background_defaultFilteringLog.addEventListener(background_FilteringEventType.RemoveHeader, background_FilteringLogService.onRemoveheader);
        background_defaultFilteringLog.addEventListener(background_FilteringEventType.Cookie, background_FilteringLogService.onCookie);
        background_defaultFilteringLog.addEventListener(background_FilteringEventType.JsInject, background_FilteringLogService.onScriptInjection);
        background_defaultFilteringLog.addEventListener(background_FilteringEventType.StealthAction, background_FilteringLogService.onStealthAction);
        background_defaultFilteringLog.addEventListener(background_FilteringEventType.StealthAllowlistAction, background_FilteringLogService.onStealthAllowlistAction);
        background_defaultFilteringLog.addEventListener(background_FilteringEventType.CspReportBlocked, background_FilteringLogService.onCspReportBlocked);
        // Will fire only in unpacked extension.
        background_defaultFilteringLog.addEventListener(background_FilteringEventType.MatchedDeclarativeRule, background_FilteringLogService.onMatchedDeclarativeRule);
        if (background_UserAgent.isFirefox) {
            background_defaultFilteringLog.addEventListener(background_FilteringEventType.ReplaceRuleApply, background_FilteringLogService.onReplaceRuleApply);
        }
    /* eslint-enable max-len */ }
    /**
     * Records the initiation of a request.
     *
     * @param sendRequestEvent Event with type {@link SendRequestEvent}.
     * @param sendRequestEvent.data Contains data about the request and the tab
     * from which the request was initiated.
     */ static onSendRequest({ data }) {
        const { tabId, ...eventData } = data;
        // TODO: fix `string | null` vs `string | undefined` inconsistency
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        background_filteringLogApi.addEventData(tabId, eventData);
    }
    /**
     * Records tab reload.
     *
     * @param event Event with type {@link TabReloadEvent} contains id
     * of the reloaded tab.
     */ static onTabReload(event) {
        const { tabId } = event.data;
        background_filteringLogApi.clearEventsByTabId(tabId);
    }
    /**
     * Records the application of a blocking rule, redirecting rule
     * or blocking of an open new tab.
     *
     * @param ruleEvent Item of {@link ApplyBasicRuleEvent}.
     * @param ruleEvent.data Data for this event: tabId, eventId and applied rule.
     */ static async onApplyBasicRule({ data }) {
        const { tabId, eventId, filterId, ruleIndex, isAllowlist, isImportant, isDocumentLevel, isCsp, isCookie, advancedModifier } = data;
        // This can happened only if event fired from webRequest.onErrorOccurred
        if (filterId === null || ruleIndex === null) {
            return;
        }
        background_filteringLogApi.updateEventData(tabId, eventId, {
            requestRule: {
                filterId,
                ruleIndex,
                allowlistRule: isAllowlist,
                isImportant,
                documentLevelRule: isDocumentLevel,
                isStealthModeRule: filterId === background_AntiBannerFiltersId.StealthModeFilterId,
                cspRule: isCsp,
                cookieRule: isCookie,
                modifierValue: advancedModifier !== null && advancedModifier !== void 0 ? advancedModifier : undefined
            }
        });
        if (!background_SettingsApi.getSetting(background_SettingOption.DisableCollectHits)) {
            background_HitStatsApi.addRuleHit(filterId, ruleIndex);
        }
    }
    /**
     * Records the application of declarative rule.
     *
     * @param ruleEvent Item of {@link matchedDeclarativeRule}.
     * @param ruleEvent.data Data for this event: tabId, eventId and applied declarative rule in JSON.
     */ static async onMatchedDeclarativeRule({ data }) {
        const { tabId, eventId, declarativeRuleInfo } = data;
        background_filteringLogApi.attachDeclarativeRuleToEventData(tabId, eventId, declarativeRuleInfo);
    }
    /**
     * Records the application of the cosmetic rule.
     *
     * @param ruleEvent Item of {@link ApplyCosmeticRuleEvent}.
     * @param ruleEvent.data Data for this event.
     */ static async onApplyCosmeticRule({ data }) {
        const { tabId, filterId, ruleIndex, cssRule, scriptRule, contentRule, ...eventData } = data;
        background_filteringLogApi.addEventData(tabId, {
            ...eventData,
            requestRule: {
                filterId,
                ruleIndex,
                cssRule,
                scriptRule,
                contentRule
            }
        });
        if (!background_SettingsApi.getSetting(background_SettingOption.DisableCollectHits)) {
            background_HitStatsApi.addRuleHit(filterId, ruleIndex);
        }
    }
    /**
     * Records the application of the rule with $csp modifier.
     *
     * @param ruleEvent Item of {@link ApplyCspRuleEvent}.
     * @param ruleEvent.data Data for this event.
     */ static async onApplyCspRule({ data }) {
        const { tabId, filterId, ruleIndex, isAllowlist, isImportant, isDocumentLevel, isCsp, isCookie, advancedModifier, frameDomain, ...eventData } = data;
        var _getDomain;
        background_filteringLogApi.addEventData(tabId, {
            ...eventData,
            // TODO: Fix `string | null` vs `string | undefined` inconsistency
            frameDomain: frameDomain !== null && frameDomain !== void 0 ? frameDomain : undefined,
            requestDomain: (_getDomain = background_getDomain(eventData.requestUrl)) !== null && _getDomain !== void 0 ? _getDomain : undefined,
            requestRule: {
                filterId,
                ruleIndex,
                allowlistRule: isAllowlist,
                isImportant,
                documentLevelRule: isDocumentLevel,
                isStealthModeRule: filterId === background_AntiBannerFiltersId.StealthModeFilterId,
                cspRule: isCsp,
                cookieRule: isCookie,
                modifierValue: advancedModifier !== null && advancedModifier !== void 0 ? advancedModifier : undefined
            }
        });
        if (!background_SettingsApi.getSetting(background_SettingOption.DisableCollectHits)) {
            background_HitStatsApi.addRuleHit(filterId, ruleIndex);
        }
    }
    /**
     * Records the application of the rule with $permissions modifier.
     *
     * @param ruleEvent Item of {@link ApplyPermissionsRuleEvent}.
     * @param ruleEvent.data Data for this event.
     */ static async onApplyPermissionsRule({ data }) {
        const { tabId, filterId, ruleIndex, isAllowlist, isImportant, isDocumentLevel, isCsp, isCookie, advancedModifier, frameDomain, ...eventData } = data;
        var _getDomain;
        background_filteringLogApi.addEventData(tabId, {
            ...eventData,
            // TODO: Fix `string | null` vs `string | undefined` inconsistency
            frameDomain: frameDomain !== null && frameDomain !== void 0 ? frameDomain : undefined,
            requestDomain: (_getDomain = background_getDomain(eventData.requestUrl)) !== null && _getDomain !== void 0 ? _getDomain : undefined,
            requestRule: {
                filterId,
                ruleIndex,
                allowlistRule: isAllowlist,
                isImportant,
                documentLevelRule: isDocumentLevel,
                isStealthModeRule: filterId === background_AntiBannerFiltersId.StealthModeFilterId,
                cspRule: isCsp,
                permissionsRule: true,
                cookieRule: isCookie,
                modifierValue: advancedModifier !== null && advancedModifier !== void 0 ? advancedModifier : undefined
            }
        });
        if (!background_SettingsApi.getSetting(background_SettingOption.DisableCollectHits)) {
            background_HitStatsApi.addRuleHit(filterId, ruleIndex);
        }
    }
    /**
     * Records the application of the rule with $removeparam modifier.
     *
     * @param ruleEvent Item of {@link RemoveParamEvent}.
     * @param ruleEvent.data Data for this event.
     */ static async onRemoveParam({ data }) {
        const { tabId, filterId, ruleIndex, isAllowlist, isImportant, isDocumentLevel, isCsp, isCookie, advancedModifier, ...eventData } = data;
        var _getDomain;
        background_filteringLogApi.addEventData(tabId, {
            ...eventData,
            requestDomain: (_getDomain = background_getDomain(eventData.requestUrl)) !== null && _getDomain !== void 0 ? _getDomain : undefined,
            requestRule: {
                filterId,
                ruleIndex,
                allowlistRule: isAllowlist,
                isImportant,
                documentLevelRule: isDocumentLevel,
                isStealthModeRule: filterId === background_AntiBannerFiltersId.StealthModeFilterId,
                cspRule: isCsp,
                cookieRule: isCookie,
                modifierValue: advancedModifier !== null && advancedModifier !== void 0 ? advancedModifier : undefined
            }
        });
        if (!background_SettingsApi.getSetting(background_SettingOption.DisableCollectHits)) {
            background_HitStatsApi.addRuleHit(filterId, ruleIndex);
        }
    }
    /**
     * Records the application of the rule with $removeheader modifier.
     *
     * @param ruleEvent Item of {@link RemoveHeaderEvent}.
     * @param ruleEvent.data Data for this event.
     */ static async onRemoveheader({ data }) {
        const { tabId, filterId, ruleIndex, isAllowlist, isImportant, isDocumentLevel, isCsp, isCookie, advancedModifier, ...eventData } = data;
        var _getDomain;
        background_filteringLogApi.addEventData(tabId, {
            ...eventData,
            requestDomain: (_getDomain = background_getDomain(eventData.requestUrl)) !== null && _getDomain !== void 0 ? _getDomain : undefined,
            requestRule: {
                filterId,
                ruleIndex,
                allowlistRule: isAllowlist,
                isImportant,
                documentLevelRule: isDocumentLevel,
                isStealthModeRule: filterId === background_AntiBannerFiltersId.StealthModeFilterId,
                cspRule: isCsp,
                cookieRule: isCookie,
                modifierValue: advancedModifier !== null && advancedModifier !== void 0 ? advancedModifier : undefined
            }
        });
        if (!background_SettingsApi.getSetting(background_SettingOption.DisableCollectHits)) {
            background_HitStatsApi.addRuleHit(filterId, ruleIndex);
        }
    }
    /**
     * Records receiving of web request.
     *
     * @param responseEvent Item of {@link ReceiveResponseEvent}.
     * @param responseEvent.data Data for this event: eventId, tabId
     * and status code.
     */ static onReceiveResponse({ data }) {
        const { eventId, tabId, statusCode } = data;
        background_filteringLogApi.updateEventData(tabId, eventId, {
            statusCode
        });
    }
    /**
     * Records cookie event on cookie filtering in onBeforeSendHeaders and
     * onHeadersReceived, but only if there is no cookie event registered.
     *
     * @param event Event with type {@link CookieEvent}.
     */ static async onCookie(event) {
        if (background_filteringLogApi.isExistingCookieEvent(event)) {
            return;
        }
        const { tabId, filterId, ruleIndex, isAllowlist, isImportant, isDocumentLevel, isCsp, isCookie, advancedModifier, ...eventData } = event.data;
        background_filteringLogApi.addEventData(tabId, {
            ...eventData,
            requestRule: {
                filterId,
                ruleIndex,
                allowlistRule: isAllowlist,
                isImportant,
                documentLevelRule: isDocumentLevel,
                isStealthModeRule: filterId === background_AntiBannerFiltersId.StealthModeFilterId,
                cspRule: isCsp,
                cookieRule: isCookie,
                modifierValue: advancedModifier !== null && advancedModifier !== void 0 ? advancedModifier : undefined
            }
        });
        if (!background_SettingsApi.getSetting(background_SettingOption.DisableCollectHits)) {
            background_HitStatsApi.addRuleHit(filterId, ruleIndex);
        }
    }
    /**
     * Records injection of script.
     *
     * @param event Event with type {@link JsInjectEvent}.
     * @param event.data Destructed data from {@link JsInjectEvent}.
     */ static async onScriptInjection({ data }) {
        const { tabId, filterId, ruleIndex, cssRule, scriptRule, contentRule, ...eventData } = data;
        background_filteringLogApi.addEventData(tabId, {
            ...eventData,
            requestRule: {
                filterId,
                ruleIndex,
                cssRule,
                scriptRule,
                contentRule
            }
        });
        if (!background_SettingsApi.getSetting(background_SettingOption.DisableCollectHits)) {
            background_HitStatsApi.addRuleHit(filterId, ruleIndex);
        }
    }
    /**
     * Records the application of the rule with $replace modifier.
     *
     * @param event Event with type {@link ReplaceRuleApplyEvent}.
     * @param event.data Destructed data from {@link ReplaceRuleApplyEvent}.
     */ static async onReplaceRuleApply({ data }) {
        const { tabId, rules, eventId } = data;
        background_filteringLogApi.updateEventData(tabId, eventId, {
            replaceRules: rules
        });
        if (!background_SettingsApi.getSetting(background_SettingOption.DisableCollectHits)) {
            rules.forEach(({ filterId, ruleIndex })=>{
                background_HitStatsApi.addRuleHit(filterId, ruleIndex);
            });
        }
    }
    /**
     * Records the application of an action from Tracking protection (formerly Stealth Mode).
     *
     * @param event Event with type {@link StealthActionEvent}.
     * @param event.data Destructed data from {@link StealthActionEvent}:
     * tab id, event id and stealthActions - last one is the bit-mask
     * of applied {@link StealthActions} from tswebextension.
     */ static onStealthAction({ data }) {
        const { tabId, eventId, stealthActions } = data;
        background_filteringLogApi.updateEventData(tabId, eventId, {
            stealthActions
        });
    }
    /**
     * Records prevention of an action from Tracking protection (formerly Stealth Mode).
     *
     * @param event Event with type {@link StealthAllowlistActionEvent}.
     * @param event.data Destructed data from {@link StealthAllowlistActionEvent}:
     * tab id, event id and allowlisting stealth network rule which
     * cancel application of {@link StealthActions} from tswebextension.
     */ static onStealthAllowlistAction({ data }) {
        const { tabId, rules, eventId } = data;
        background_filteringLogApi.updateEventData(tabId, eventId, {
            stealthAllowlistRules: rules.map((rule)=>{
                var _rule_advancedModifier;
                return {
                    filterId: rule.filterId,
                    ruleIndex: rule.ruleIndex,
                    allowlistRule: rule.isAllowlist,
                    isImportant: rule.isImportant,
                    documentLevelRule: rule.isDocumentLevel,
                    isStealthModeRule: true,
                    cspRule: rule.isCsp,
                    cookieRule: rule.isCookie,
                    modifierValue: (_rule_advancedModifier = rule.advancedModifier) !== null && _rule_advancedModifier !== void 0 ? _rule_advancedModifier : undefined
                };
            })
        });
        if (!background_SettingsApi.getSetting(background_SettingOption.DisableCollectHits)) {
            rules.forEach(({ filterId, ruleIndex })=>{
                background_HitStatsApi.addRuleHit(filterId, ruleIndex);
            });
        }
    }
    /**
     * Records the blocked csp report.
     *
     * @param event Event with type {@link CspReportBlocked}.
     * @param event.data Destructed data from {@link CspReportBlocked}:
     * tab id, event id and cspReportBlocked - last one is a boolean flag.
     */ static onCspReportBlocked({ data }) {
        const { tabId, eventId, cspReportBlocked } = data;
        background_filteringLogApi.updateEventData(tabId, eventId, {
            cspReportBlocked
        });
    }
    /**
     * Creates tab info.
     *
     * @param tabContext Item of {@link TabContext}.
     */ static onTabCreate(tabContext) {
        const { info, isSyntheticTab } = tabContext;
        background_filteringLogApi.createTabInfo(info, isSyntheticTab);
    }
    /**
     * Updates tab info.
     *
     * @param tabContext Item of {@link TabContext}.
     */ static onTabUpdate(tabContext) {
        const { info } = tabContext;
        background_filteringLogApi.updateTabInfo(info);
    }
    /**
     * Deletes a tab.
     *
     * @param tabContext Item of {@link TabContext}.
     */ static onTabRemove(tabContext) {
        const { info: { id } } = tabContext;
        if (id) {
            background_filteringLogApi.removeTabInfo(id);
        }
    }
    /**
     * Clears all messages for the specified tab.
     *
     * @param message Message with type {@link ClearEventsByTabIdMessage}.
     * @param message.data Destructed data from {@link ClearEventsByTabIdMessage}:
     * tab id and flag indicates that of ignoring preserve log (clear on the refresh).
     */ static onClearEventsByTabId({ data }) {
        const { tabId, ignorePreserveLog } = data;
        background_filteringLogApi.clearEventsByTabId(tabId, ignorePreserveLog);
    }
    /**
     * Enable or disable preserve log.
     *
     * @param message Message with type {@link SetPreserveLogStateMessage}.
     * @param message.data State for preserver log: enable or disable.
     */ static onSetPreserveLogState({ data }) {
        const { state } = data;
        background_filteringLogApi.setPreserveLogState(state);
    }
    /**
     * Refreshes tab with specified id.
     *
     * @param message Message with type {@link PageRefreshMessage}.
     * @param message.data Tab id from {@link PageRefreshMessage}.
     */ static async onRefreshPage({ data }) {
        const { tabId } = data;
        await background_TabsApi.reload(tabId);
    }
    /**
     * Returns {@link FilteringLogTabInfo} for specified tab id.
     *
     * @param message Message with type {@link GetFilteringInfoByTabIdMessage}.
     * @param message.data Tab id from {@link GetFilteringInfoByTabIdMessage}.
     *
     * @returns Item with type {@link FilteringLogTabInfo} for specified tab id
     * or undefined.
     */ static onGetFilteringLogInfoById({ data }) {
        const { tabId } = data;
        return background_filteringLogApi.getFilteringInfoByTabId(tabId);
    }
    /**
     * Calls {@link filteringLogApi} for synchronize list of the opened tabs.
     *
     * @returns List of the opened tabs.
     */ static async onSyncOpenTabs() {
        return background_filteringLogApi.synchronizeOpenTabs();
    }
    /**
     * Returns current settings of filtering log.
     *
     * @returns The {@link GetFilteringLogDataResponse} object, which contains
     * filter log parameters: metadata, settings, and save log state.
     */ static onGetFilteringLogData() {
        return {
            filtersMetadata: background_main_FiltersApi.getFiltersMetadata(),
            settings: background_SettingsApi.getData(),
            preserveLogEnabled: background_filteringLogApi.isPreserveLogEnabled()
        };
    }
    /**
     * Saves the parameters of the filtering log window: position, size, etc.
     *
     * @param message Message of type {@link SetFilteringLogWindowStateMessage}.
     * @param message.data Parameters of the filter log window {@link Windows#CreateCreateDataType}.
     */ static async onSetFilteringLogWindowState({ data }) {
        const { windowState } = data;
        await background_browserStorage.set(background_FILTERING_LOG_WINDOW_STATE, JSON.stringify(windowState));
    }
}

;// ./Extension/src/background/services/fullscreen-user-rules-editor.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_fullscreen_user_rules_editor_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}


/**
 * Module used to keep track of userrules editor opened in the fullscreen mode.
 */ class background_FullscreenUserRulesEditor {
    /**
     * Increases number of opened pages.
     */ onOpenPage() {
        this.openPagesCount += 1;
        this.onPagesCountChanged();
    }
    /**
     * Decreases number of opened pages.
     */ onClosePage() {
        if (this.openPagesCount <= 0) {
            return;
        }
        this.openPagesCount -= 1;
        this.onPagesCountChanged();
    }
    /**
     * Notifies listeners of changes in the open page counter.
     */ onPagesCountChanged() {
        background_notifier_notifier.notifyListeners(background_constants_NotifierType.FullscreenUserRulesEditorUpdated, this.isOpen());
    }
    /**
     * If there is more than one open page, the editor is open. Otherwise it is closed.
     *
     * @returns Status of editor.
     */ isOpen() {
        return this.openPagesCount > 0;
    }
    constructor(){
        background_fullscreen_user_rules_editor_define_property(this, "openPagesCount", 0);
    }
}
const background_fullscreenUserRulesEditor = new background_FullscreenUserRulesEditor();

;// ./Extension/src/background/services/settings/settings-service-mv3.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 












/**
 * SettingsService handles all setting-related messages and
 * calls {@link SettingsApi} to handle settings.
 *
 * TODO: gracefully handle errors for tswebextension events. AG-37301.
 */ class background_SettingsService {
    /**
     * Adds a listener for background messages about settings: load/apply settings
     * from JSON and change/reset/return of custom settings.
     * Adds a listener with the action of updating the engine when you change
     * any {@link SettingOption} parameter.
     * Adds a listener to enable or disable protection from the context menu.
     */ static init() {
        background_message_handler_messageHandler.addListener(background_constants_MessageType.GetOptionsData, background_SettingsService.getOptionsData);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.ResetSettings, background_SettingsService.reset);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.ChangeUserSettings, background_SettingsService.changeUserSettings);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.ApplySettingsJson, background_SettingsService.import);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.LoadSettingsJson, background_SettingsService.export);
        background_settingsEvents.addListener(background_SettingOption.DisableStealthMode, background_SettingsService.onDisableStealthModeStateChange);
        // TODO: revert when will be found a better way to add exclusions for $stealth=referrer
        // AG-34765
        // settingsEvents.addListener(SettingOption.HideReferrer, SettingsService.onHideReferrerStateChange);
        // TODO: revert when will be found a better way to add exclusions for $stealth=searchqueries
        // AG-34765
        // settingsEvents.addListener(SettingOption.HideSearchQueries, SettingsService.onHideSearchQueriesStateChange);
        background_settingsEvents.addListener(background_SettingOption.SendDoNotTrack, background_SettingsService.onSendDoNotTrackStateChange);
        background_settingsEvents.addListener(background_SettingOption.RemoveXClientData, background_SettingsService.onRemoveXClientDataStateChange);
        background_settingsEvents.addListener(background_SettingOption.BlockWebRTC, background_SettingsService.onBlockWebRTCStateChange);
        // TODO: Possibly can be implemented when https://github.com/w3c/webextensions/issues/439 will be implemented.
        // settingsEvents.addListener(
        //     SettingOption.SelfDestructThirdPartyCookies,
        //     SettingsService.onSelfDestructThirdPartyCookiesStateChange,
        // );
        // settingsEvents.addListener(
        //     SettingOption.SelfDestructThirdPartyCookiesTime,
        //     SettingsService.onSelfDestructThirdPartyCookiesTimeStateChange,
        // );
        // settingsEvents.addListener(
        //     SettingOption.SelfDestructFirstPartyCookies,
        //     SettingsService.onSelfDestructFirstPartyCookiesStateChange,
        // );
        // settingsEvents.addListener(
        //     SettingOption.SelfDestructFirstPartyCookiesTime,
        //     SettingsService.onSelfDestructFirstPartyCookiesTimeStateChange,
        // );
        background_settingsEvents.addListener(background_SettingOption.DisableFiltering, background_SettingsService.onDisableFilteringStateChange);
        background_contextMenuEvents.addListener(background_ContextMenuAction.EnableProtection, background_SettingsService.enableFiltering);
        background_contextMenuEvents.addListener(background_ContextMenuAction.DisableProtection, background_SettingsService.disableFiltering);
    }
    /**
     * Returns settings with some additional data: app version,
     * environment options, constants, filters info, filters metadata.
     *
     * @returns Item of {@link GetOptionsDataResponse}.
     */ static async getOptionsData() {
        const areFilterLimitsExceeded = await background_RulesLimitsService.areFilterLimitsExceeded();
        return {
            settings: background_SettingsApi.getData(),
            appVersion: background_Prefs.version,
            libVersions: background_Prefs.libVersions,
            environmentOptions: {
                isChrome: background_UserAgent.isChrome
            },
            constants: {
                AntiBannerFiltersId: background_AntiBannerFiltersId
            },
            filtersInfo: {
                rulesCount: background_engine_engine.api.getRulesCount()
            },
            filtersMetadata: background_Categories.getCategories(),
            fullscreenUserRulesEditorIsOpen: background_fullscreenUserRulesEditor.isOpen(),
            areFilterLimitsExceeded
        };
    }
    /**
     * Changes user settings.
     *
     * @param message Item of {@link ChangeUserSettingMessage}.
     */ static async changeUserSettings(message) {
        const { key, value } = message.data;
        await background_SettingsApi.setSetting(key, value);
    }
    /**
     * Resets user settings and updates engine.
     *
     * @returns Result of resetting.
     */ static async reset() {
        try {
            // Should enable default filters and their groups.
            await background_SettingsApi.reset(true);
            await background_engine_engine.update();
            return true;
        } catch (e) {
            return false;
        }
    }
    /**
     * Imports settings from JSON.
     *
     * @param message Message with JSON settings {@link ApplySettingsJsonMessage}.
     *
     * @returns Boolean result of importing.
     */ static async import(message) {
        const { json } = message.data;
        const isImported = await background_SettingsApi.import(json);
        await background_engine_engine.update();
        return isImported;
    }
    /**
     * Exports settings.
     *
     * @returns Promise with {@link ExportMessageResponse}.
     */ static async export() {
        return {
            content: await background_SettingsApi.export(),
            appVersion: background_browser_polyfill_default().runtime.getManifest().version
        };
    }
    /**
     * Called when {@link SettingOption.DisableFiltering} setting changed.
     *
     * @param isFilteringDisabled Changed {@link SettingOption.DisableFiltering} setting value.
     */ static async onDisableFilteringStateChange(isFilteringDisabled) {
        try {
            await background_engine_engine.setFilteringState(!isFilteringDisabled);
            const activeTab = await background_TabsApi.getActive();
            if (activeTab) {
                await background_TabsApi.reload(activeTab.id);
            }
        } catch (e) {
            background_logger_logger.error('Error while updating filtering state', e);
        }
    }
    /**
     * Called when {@link SettingOption.DisableStealthMode} setting changed.
     */ static async onDisableStealthModeStateChange() {
        try {
            await background_engine_engine.update();
        } catch (e) {
            background_logger_logger.error('Failed to change Tracking protection state', e);
        }
    }
    /**
     * Called when {@link SettingOption.HideSearchQueries} setting changed.
     *
     * @param isHideReferrerEnabled Changed {@link SettingOption.HideReferrer} setting value.
     */ static async onHideReferrerStateChange(isHideReferrerEnabled) {
        try {
            const appliedValue = await background_engine_engine.api.setHideReferrer(isHideReferrerEnabled);
            if (appliedValue !== isHideReferrerEnabled) {
                // If the setting was not applied, we need to revert it back for
                // the user in the UI and in the storage for configuration persistence.
                await background_SettingsApi.setSetting(background_SettingOption.HideReferrer, !isHideReferrerEnabled);
            }
        } catch (e) {
            background_logger_logger.error('Failed to change `hide referrer` option state', e);
        }
    }
    /**
     * Called when {@link SettingOption.HideSearchQueries} setting changed.
     *
     * @param isHideSearchQueriesEnabled Changed {@link SettingOption.HideSearchQueries} setting value.
     */ static async onHideSearchQueriesStateChange(isHideSearchQueriesEnabled) {
        try {
            const appliedValue = await background_engine_engine.api.setHideSearchQueries(isHideSearchQueriesEnabled);
            if (appliedValue !== isHideSearchQueriesEnabled) {
                // If the setting was not applied, we need to revert it back for
                // the user in the UI and in the storage for configuration persistence.
                await background_SettingsApi.setSetting(background_SettingOption.HideSearchQueries, !isHideSearchQueriesEnabled);
            }
        } catch (e) {
            background_logger_logger.error('Failed to change `hide search queries` option state', e);
        }
    }
    /**
     * Called when {@link SettingOption.RemoveXClientData} setting changed.
     *
     * @param isSendDoNotTrackEnabled Changed {@link SettingOption.RemoveXClientData} setting value.
     */ static async onSendDoNotTrackStateChange(isSendDoNotTrackEnabled) {
        try {
            const appliedValue = await background_engine_engine.api.setSendDoNotTrack(isSendDoNotTrackEnabled);
            if (appliedValue !== isSendDoNotTrackEnabled) {
                // If the setting was not applied, we need to revert it back for
                // the user in the UI and in the storage for configuration persistence.
                await background_SettingsApi.setSetting(background_SettingOption.SendDoNotTrack, !isSendDoNotTrackEnabled);
            }
        } catch (e) {
            background_logger_logger.error('Failed to change `send do not track` option state', e);
        }
    }
    /**
     * Called when {@link SettingOption.RemoveXClientData} setting changed.
     *
     * @param isRemoveXClientDataEnabled Changed {@link SettingOption.RemoveXClientData} setting value.
     */ static async onRemoveXClientDataStateChange(isRemoveXClientDataEnabled) {
        try {
            const appliedValue = await background_engine_engine.api.setBlockChromeClientData(isRemoveXClientDataEnabled);
            if (appliedValue !== isRemoveXClientDataEnabled) {
                // If the setting was not applied, we need to revert it back for
                // the user in the UI and in the storage for configuration persistence.
                await background_SettingsApi.setSetting(background_SettingOption.RemoveXClientData, !isRemoveXClientDataEnabled);
            }
        } catch (e) {
            background_logger_logger.error('Failed to change `remove x-client-data` option state', e);
        }
    }
    /**
     * Called when {@link SettingOption.BlockWebRTC} setting changed.
     *
     * @param isBlockWebRTCEnabled Changed {@link SettingOption.BlockWebRTC} setting value.
     */ static async onBlockWebRTCStateChange(isBlockWebRTCEnabled) {
        try {
            const appliedValue = await background_engine_engine.api.setBlockWebRTC(isBlockWebRTCEnabled);
            if (appliedValue !== isBlockWebRTCEnabled) {
                // If the setting was not applied, we need to revert it back for
                // the user in the UI and in the storage for configuration persistence.
                await background_SettingsApi.setSetting(background_SettingOption.BlockWebRTC, !isBlockWebRTCEnabled);
            }
        } catch (e) {
            background_logger_logger.error('Failed to change `block WebRTC` option state', e);
        }
    }
    // TODO: Possibly can be implemented when https://github.com/w3c/webextensions/issues/439 will be implemented.
    // /**
    //  * Called when {@link SettingOption.SelfDestructThirdPartyCookies} setting changed.
    //  *
    //  * {@link SettingOption.SelfDestructThirdPartyCookies} Setting value.
    //  *
    //  * @throws Error for mv3.
    //  */
    // static onSelfDestructThirdPartyCookiesStateChange(): void {
    //     throw new Error('onSelfDestructThirdPartyCookiesStateChange not implemented for mv3');
    // }
    // TODO: Possibly can be implemented when https://github.com/w3c/webextensions/issues/439 will be implemented.
    // /**
    //  * Called when {@link SettingOption.SelfDestructThirdPartyCookiesTime} setting changed.
    //  *
    //  * {@link SettingOption.SelfDestructThirdPartyCookiesTime} Setting value.
    //  *
    //  * @throws Error for mv3.
    //  */
    // static onSelfDestructThirdPartyCookiesTimeStateChange(): void {
    //     throw new Error('onSelfDestructThirdPartyCookiesTimeStateChange not implemented for mv3');
    // }
    // TODO: Possibly can be implemented when https://github.com/w3c/webextensions/issues/439 will be implemented.
    // /**
    //  * Called when {@link SettingOption.SelfDestructFirstPartyCookies} setting changed.
    //  *
    //  * {@link SettingOption.SelfDestructFirstPartyCookies} Setting value.
    //  *
    //  * @throws Error for mv3.
    //  */
    // static onSelfDestructFirstPartyCookiesStateChange(): void {
    //     throw new Error('onSelfDestructFirstPartyCookiesStateChange not implemented for mv3');
    // }
    // TODO: Possibly can be implemented when https://github.com/w3c/webextensions/issues/439 will be implemented.
    // /**
    //  * Called when {@link SettingOption.SelfDestructFirstPartyCookiesTime} setting changed.
    //  *
    //  * {@link SettingOption.SelfDestructFirstPartyCookiesTime} Setting value.
    //  *
    //  * @throws Error for mv3.
    //  */
    // static onSelfDestructFirstPartyCookiesTimeStateChange(): void {
    //     throw new Error('onSelfDestructFirstPartyCookiesTimeStateChange not implemented for mv3');
    // }
    /**
     * Called when protection enabling is requested.
     */ static async enableFiltering() {
        await background_SettingsApi.setSetting(background_SettingOption.DisableFiltering, false);
    }
    /**
     * Called when protection disabling is requested.
     */ static async disableFiltering() {
        await background_SettingsApi.setSetting(background_SettingOption.DisableFiltering, true);
    }
}

;// ./Extension/src/background/services/settings/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ // NOTE: Here important to use 'settings-service' without path, because
// it is an alias for manifest-specific implementation of the rules rules limits
// service. It will be replaced with mv2 or mv3 version during the build
// via webpack.
/**
 * SettingsService is a singleton instance of SettingsService which
 * will be replaced with mv2 or mv3 implementation during the build via webpack.
 *
 * By default, mv2 will be used.
 */ 

;// ./Extension/src/background/services/allowlist.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 







/**
 * Service for processing events with a allowlist.
 */ class background_AllowlistService {
    /**
     * Initialize handlers.
     */ static init() {
        background_message_handler_messageHandler.addListener(background_constants_MessageType.GetAllowlistDomains, background_AllowlistService.onGetAllowlistDomains);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.SaveAllowlistDomains, background_AllowlistService.handleDomainsSave);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.AddAllowlistDomain, background_AllowlistService.onAddAllowlistDomain);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.RemoveAllowlistDomain, background_AllowlistService.onRemoveAllowlistDomain);
        background_settingsEvents.addListener(background_SettingOption.AllowlistEnabled, background_AllowlistService.updateEngine);
        background_settingsEvents.addListener(background_SettingOption.DefaultAllowlistMode, background_AllowlistService.updateEngine);
        background_contextMenuEvents.addListener(background_ContextMenuAction.SiteFilteringOn, background_AllowlistService.enableSiteFilteringFromContextMenu);
        background_contextMenuEvents.addListener(background_ContextMenuAction.SiteFilteringOff, background_AllowlistService.disableSiteFilteringFromContextMenu);
    }
    /**
     * Returns domains depending on current allowlist mode.
     *
     * @returns Object of type {@link GetAllowlistDomainsResponse}.
     */ static onGetAllowlistDomains() {
        const domains = background_allowlist_AllowlistApi.isInverted() ? background_allowlist_AllowlistApi.getInvertedAllowlistDomains() : background_allowlist_AllowlistApi.getAllowlistDomains();
        const content = domains.join('\n');
        return {
            content,
            appVersion: background_Prefs.version
        };
    }
    /**
     * The listener for the allowlist domain addition event from popup.
     *
     * @param message Message of type {@link AddAllowlistDomainMessage}.
     */ static async onAddAllowlistDomain(message) {
        const { tabId } = message.data;
        await background_allowlist_AllowlistApi.disableTabFiltering(tabId);
    }
    /**
     * The listener for the allowlist domain deletion event.
     *
     * @param message Message of type {@link RemoveAllowlistDomainMessage}.
     */ static async onRemoveAllowlistDomain(message) {
        const { tabId, tabRefresh } = message.data;
        await background_allowlist_AllowlistApi.enableTabFiltering(tabId, tabRefresh);
    }
    /**
     * Stores domains depending on current allowlist mode.
     *
     * @param message Message data.
     */ static async handleDomainsSave(message) {
        const { value } = message.data;
        const domains = value.split(/[\r\n]+/);
        if (background_allowlist_AllowlistApi.isInverted()) {
            background_allowlist_AllowlistApi.setInvertedAllowlistDomains(domains);
        } else {
            background_allowlist_AllowlistApi.setAllowlistDomains(domains);
        }
        // update the engine only if the module is enabled
        if (background_allowlist_AllowlistApi.isEnabled()) {
            await background_engine_engine.update();
        }
    }
    /**
     * Listener for an event to enable site filtering from the context menu.
     */ static async enableSiteFilteringFromContextMenu() {
        const activeTab = await background_TabsApi.getActive();
        if (activeTab === null || activeTab === void 0 ? void 0 : activeTab.id) {
            await background_allowlist_AllowlistApi.enableTabFiltering(activeTab.id, true);
        } else {
            background_logger_logger.warn('Cannot open site report page for active tab');
        }
    }
    /**
     * Listener for an event to disable site filtering from the context menu.
     */ static async disableSiteFilteringFromContextMenu() {
        const activeTab = await background_TabsApi.getActive();
        if (activeTab === null || activeTab === void 0 ? void 0 : activeTab.id) {
            await background_allowlist_AllowlistApi.disableTabFiltering(activeTab.id);
        } else {
            background_logger_logger.warn('Cannot open site report page for active tab');
        }
    }
    /**
     * Updates the tswebextension engine on {@link SettingOption.AllowlistEnabled}
     * or {@link SettingOption.DefaultAllowlistMode} setting change.
     * This setting can be changed by the switch ui element, so it is important
     * to update the engine config via debounce function for MV2, as this
     * is a heavyweight call.
     * For MV3 we should wait for the engine to be ready and then check for
     * possible exceeding the limits.
     */ static async updateEngine() {
        if (true) {
            await background_engine_engine.update();
        } else {}
    }
}

;// ./Extension/src/background/services/custom-filters/custom-filters-service-mv2.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 





/**
 * Service for processing events with custom filters.
 */ class background_CustomFiltersService {
    /**
     * Init handlers.
     */ static init() {
        messageHandler.addListener(MessageType.LoadCustomFilterInfo, background_CustomFiltersService.onCustomFilterInfoLoad);
        // eslint-disable-next-line max-len
        messageHandler.addListener(MessageType.SubscribeToCustomFilter, background_CustomFiltersService.onCustomFilterSubscription);
        messageHandler.addListener(MessageType.RemoveAntiBannerFilter, background_CustomFiltersService.onCustomFilterRemove);
    }
    /**
     * Returns custom filter info for modal window.
     *
     * @param message Message data.
     *
     * @returns Custom filter info.
     */ static async onCustomFilterInfoLoad(message) {
        const { url, title } = message.data;
        return CustomFilterApi.getFilterInfo(url, title);
    }
    /**
     * Add new custom filter.
     *
     * @param message Message data.
     *
     * @returns Custom filter metadata.
     */ static async onCustomFilterSubscription(message) {
        const { filter } = message.data;
        const { customUrl, name, trusted } = filter;
        // Creates a filter and enables the group if necessary.
        const filterMetadata = await CustomFilterApi.createFilter({
            customUrl,
            title: name,
            trusted,
            enabled: true
        });
        engine.debounceUpdate();
        notifier.notifyListeners(NotifierType.CustomFilterAdded);
        return filterMetadata;
    }
    /**
     * Removes a custom filter.
     *
     * If the filter was enabled, the engine will be updated.
     *
     * @param message Message data.
     */ static async onCustomFilterRemove(message) {
        const { filterId } = message.data;
        const wasEnabled = await CustomFilterApi.removeFilter(filterId);
        if (wasEnabled) {
            engine.debounceUpdate();
        }
    }
}

;// ./Extension/src/background/services/event.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_event_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}




/**
 * The EventService class operates with event listeners: creates or removes them.
 */ class background_EventService {
    /**
     * Registers event listeners in the {@link messageHandler} with background messages.
     */ init() {
        background_message_handler_messageHandler.addListener(background_constants_MessageType.CreateEventListener, this.createEventListener);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.RemoveListener, this.removeEventListener);
    }
    /**
     * Creates new event listener and returs its id.
     *
     * @param message Item of {@link CreateEventListenerMessage}.
     * @param sender Item of {@link Runtime.MessageSender}.
     *
     * @returns The identifier of the event listener enclosed in the {@link CreateEventListenerResponse} type.
     */ createEventListener(message, sender) {
        const { events } = message.data;
        const listenerId = background_notifier_notifier.addSpecifiedListener(events, (...data)=>{
            const sender = this.eventListeners.get(listenerId);
            if (!sender) {
                return;
            }
            const message = {
                type: background_constants_MessageType.NotifyListeners,
                data
            };
            background_browser_polyfill_default().tabs.sendMessage(sender.tab.id, message);
        });
        this.eventListeners.set(listenerId, sender);
        return {
            listenerId
        };
    }
    /**
     * Removes listener for provided message.
     *
     * @param message Message of type {@link RemoveListenerMessage}.
     */ removeEventListener(message) {
        const { listenerId } = message.data;
        background_notifier_notifier.removeListener(listenerId);
        this.eventListeners.delete(listenerId);
    }
    /**
     * Creates new {@link EventService}.
     */ constructor(){
        // TODO: types
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        background_event_define_property(this, "eventListeners", new Map());
        this.createEventListener = this.createEventListener.bind(this);
        this.removeEventListener = this.removeEventListener.bind(this);
    }
}
const background_eventService = new background_EventService();

;// ./Extension/src/background/services/ui/main.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_services_ui_main_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}












/**
 * Service for processing extension UI events (navigation, popups, alerts etc.).
 */ class background_UiService {
    /**
     * Initializes **sync** UI services and registers listeners.
     *
     * For MV3, handlers should be registered on the top level in sync functions,
     * otherwise they may not work or work incorrectly.
     */ static syncInit() {
        // TODO add better handling for AdGuard for Firefox
        // Do not init context menu for mobile browsers
        if ((background_browser_polyfill_default()).contextMenus) {
            background_ContextMenuApi.init();
        }
        background_contextMenuEvents.addListener(background_ContextMenuAction.OpenSettings, background_PagesApi.openSettingsPage);
        background_contextMenuEvents.addListener(background_ContextMenuAction.OpenLog, background_PagesApi.openFilteringLogPage);
        background_contextMenuEvents.addListener(background_ContextMenuAction.ComplaintWebsite, background_UiService.openAbusePageForActiveTab);
        background_contextMenuEvents.addListener(background_ContextMenuAction.SecurityReport, background_UiService.openSiteReportPageForActiveTab);
        background_contextMenuEvents.addListener(background_ContextMenuAction.BlockSiteAds, background_AssistantApi.openAssistant);
    }
    /**
     * Initialize linked **async** services and register listeners.
     */ static async init() {
        await background_toasts.init();
        await background_UiApi.init();
        // TODO: consider moving the following to syncInit()
        background_message_handler_messageHandler.addListener(background_constants_MessageType.OpenSettingsTab, background_PagesApi.openSettingsPage);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.OpenFilteringLog, background_PagesApi.openFilteringLogPage);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.OpenAbuseTab, background_UiService.openAbusePage);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.OpenSiteReportTab, background_UiService.openSiteReportPage);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.OpenThankyouPage, background_PagesApi.openThankYouPage);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.OpenExtensionStore, background_PagesApi.openExtensionStorePage);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.OpenComparePage, background_PagesApi.openComparePage);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.OpenFullscreenUserRules, background_PagesApi.openFullscreenUserRulesPage);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.UpdateFullscreenUserRulesTheme, background_PagesApi.updateFullscreenUserRulesPageTheme);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.AddFilteringSubscription, background_PagesApi.openSettingsPageWithCustomFilterModal);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.OpenAssistant, background_AssistantApi.openAssistant);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.OpenRulesLimitsTab, background_PagesApi.openRulesLimitsPage);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.InitializeFrameScript, background_UiService.getPageInitAppData);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.ScriptletCloseWindow, background_PagesApi.closePage);
        background_tabsApi.onCreate.subscribe(background_UiApi.update);
        background_tabsApi.onUpdate.subscribe(background_UiApi.update);
        background_tabsApi.onActivate.subscribe(background_UiApi.update);
        background_defaultFilteringLog.addEventListener(background_FilteringEventType.ApplyBasicRule, background_UiService.onBasicRuleApply);
    }
    /**
     * Handles {@link OpenAbuseTabMessage} and opens abuse page for passed site url in new tab.
     *
     * @param message Incoming {@link OpenAbuseTabMessage}.
     * @param message.data Site url and {@link ForwardFrom} token for creating abuse page url params.
     */ static async openAbusePage({ data }) {
        const { url, from } = data;
        await background_PagesApi.openAbusePage(url, from);
    }
    /**
     * Opens abuse page for current active tab url in new tab.
     */ static async openAbusePageForActiveTab() {
        const activeTab = await background_TabsApi.getActive();
        if (activeTab === null || activeTab === void 0 ? void 0 : activeTab.url) {
            await background_PagesApi.openAbusePage(activeTab.url, background_ForwardFrom.ContextMenu);
        } else {
            background_logger_logger.warn('Cannot open abuse page for active tab');
        }
    }
    /**
     * Handles {@link OpenSiteReportTabMessage} and opens site report page for passed site url in new tab.
     *
     * @param message Incoming {@link OpenSiteReportTabMessage}.
     * @param message.data Site url and {@link ForwardFrom} token for creating site report url params.
     */ static async openSiteReportPage({ data }) {
        const { url, from } = data;
        await background_PagesApi.openSiteReportPage(url, from);
    }
    /**
     * Opens site report page for current active tab url in new tab.
     */ static async openSiteReportPageForActiveTab() {
        const activeTab = await background_TabsApi.getActive();
        if (activeTab === null || activeTab === void 0 ? void 0 : activeTab.url) {
            await background_PagesApi.openSiteReportPage(activeTab.url, background_ForwardFrom.ContextMenu);
        } else {
            background_logger_logger.warn('Cannot open site report page for active tab');
        }
    }
    /**
     * Returns {@link PageInitAppData} that uses on extension pages, like thankyou.html.
     *
     * @returns Init app data.
     */ static getPageInitAppData() {
        const enabledFilters = {};
        Object.values(background_AntiBannerFiltersId).forEach((filterId)=>{
            const enabled = background_main_FiltersApi.isFilterEnabled(Number(filterId));
            if (enabled) {
                enabledFilters[filterId] = true;
            }
        });
        return {
            userSettings: background_SettingsApi.getData(),
            enabledFilters,
            filtersMetadata: background_main_FiltersApi.getFiltersMetadata(),
            requestFilterInfo: {
                rulesCount: background_engine_engine.api.getRulesCount()
            },
            environmentOptions: {
                isMacOs: background_UserAgent.isMacOs,
                /**
                 * Browsers api doesn't allow to get optional permissions
                 * via chrome.permissions.getAll and we can't check privacy
                 * availability via `browser.privacy !== undefined` till permission
                 * isn't enabled by the user.
                 *
                 * That's why use edge browser detection
                 * Privacy methods are not working at all in the Edge.
                 */ canBlockWebRTC: !background_UserAgent.isEdge,
                isChrome: background_UserAgent.isChrome,
                Prefs: {
                    locale: background_browser_polyfill_default().i18n.getUILanguage(),
                    mobile: background_UserAgent.isAndroid
                },
                appVersion: background_browser_polyfill_default().runtime.getManifest().version
            },
            constants: {
                AntiBannerFiltersId: background_AntiBannerFiltersId,
                EventNotifierType: background_notifier_notifier.events
            }
        };
    }
    /**
     * Handles {@link ApplyBasicRuleEvent} and update blocking request stats and counter.
     *
     * @param event Handled {@link ApplyBasicRuleEvent}.
     * @param event.data Event data.
     */ static async onBasicRuleApply({ data }) {
        const { isAllowlist, tabId, companyCategoryName } = data;
        // If rule is not blocking, ignore it
        if (isAllowlist) {
            return;
        }
        if (companyCategoryName) {
            await background_PageStatsApi.updateStats(companyCategoryName, background_UiService.blockedCountIncrement);
            background_PageStatsApi.incrementTotalBlocked(background_UiService.blockedCountIncrement);
        }
        const tabContext = background_tabsApi.getTabContext(tabId);
        // If tab context is not found, do not update request blocking counter and icon badge for tab
        if (!tabContext) {
            return;
        }
        await background_UiApi.update(tabContext);
    }
}
/**
     * Increment value for request blocking counting and page stats collection.
     */ background_services_ui_main_define_property(background_UiService, "blockedCountIncrement", 1);

;// ./Extension/src/background/services/ui/popup.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 







/**
 * Handles work with popups.
 */ class background_PopupService {
    /**
     * Creates listeners for getter of tab info and for popup.
     */ static init() {
        background_message_handler_messageHandler.addListener(background_constants_MessageType.GetIsEngineStarted, background_PopupService.getIsAppInitialized);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.GetTabInfoForPopup, background_PopupService.getTabInfoForPopup);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.ChangeApplicationFilteringPaused, background_PopupService.onChangeFilteringPaused);
    }
    /**
     * Returns the state of the application initialization.
     *
     * @returns True if the application is initialized, false otherwise.
     */ static getIsAppInitialized() {
        return background_appContext.get(background_AppContextKey.IsInit);
    }
    /**
     * Returns tab info: frame info, stats form {@link PageStatsApi},
     * current settings and some other options.
     *
     * @param message Message of type {@link GetTabInfoForPopupMessage}.
     * @param message.data Contains tab id.
     *
     * @returns If found - tab context {@link GetTabInfoForPopupResponse},
     * or undefined if not found.
     */ static async getTabInfoForPopup({ data }) {
        const { tabId } = data;
        const tabContext = background_tabsApi.getTabContext(tabId);
        if (tabContext) {
            return {
                frameInfo: background_FramesApi.getMainFrameData(tabContext),
                stats: background_PageStatsApi.getStatisticsData(),
                settings: background_SettingsApi.getData(),
                areFilterLimitsExceeded:  true ? await background_RulesLimitsService.areFilterLimitsExceeded() : 0,
                options: {
                    showStatsSupported: true,
                    isFirefoxBrowser: background_UserAgent.isFirefox,
                    showInfoAboutFullVersion: !background_settingsStorage.get(background_SettingOption.DisableShowAdguardPromoInfo),
                    isMacOs: background_UserAgent.isMacOs,
                    isEdgeBrowser: background_UserAgent.isEdge || background_UserAgent.isEdgeChromium,
                    notification: await background_promoNotificationApi.getCurrentNotification(),
                    isDisableShowAdguardPromoInfo: background_settingsStorage.get(background_SettingOption.DisableShowAdguardPromoInfo),
                    hasUserRulesToReset: await background_UserRulesApi.hasRulesForUrl(tabContext.info.url)
                }
            };
        }
    }
    /**
     * Called when protection pausing or resuming is requested.
     *
     * @param message Message of {@link ChangeApplicationFilteringPausedMessage}.
     * @param message.data State of protection.
     */ static async onChangeFilteringPaused({ data }) {
        const { state } = data;
        await background_SettingsApi.setSetting(background_SettingOption.DisableFiltering, state);
    }
}

;// ./Extension/src/background/services/ui/promo-notification.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 


/**
 * Service that manages events for promo notifications.
 */ class background_PromoNotificationService {
    /**
     * Adds a listener to mark the promo notification as watched.
     */ static init() {
        background_promoNotificationApi.init();
        background_message_handler_messageHandler.addListener(background_constants_MessageType.SetNotificationViewed, background_PromoNotificationService.setNotificationViewed);
    }
    /**
     * Marks the promo notification as watched.
     *
     * @param message Message of type {@link SetNotificationViewedMessage}.
     * @param message.data Delay of hiding notification.
     */ static async setNotificationViewed({ data }) {
        // We don't need id of the notification, because we don't show several
        // notification at once.
        const { withDelay } = data;
        await background_promoNotificationApi.setNotificationViewed(withDelay);
    }
}

;// ./Extension/src/background/services/ui/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 



;// ./Extension/src/background/services/filters/filters-service-mv3.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 








/**
 * FiltersService creates handlers for messages that relate to filters.
 *
 * **MV3 version**.
 */ class background_FiltersService {
    /**
     * Adds a listener for background messages about working with filters:
     * disabling, enabling, adding, removing.
     * Adds a listener for updating filters from the context menu.
     * Adds a listener for changing the settings of optimized filters and
     * disabling hit collection.
     */ static async init() {
        background_message_handler_messageHandler.addListener(background_constants_MessageType.AddAndEnableFilter, background_FiltersService.onFilterEnable);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.DisableFilter, background_FiltersService.onFilterDisable);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.EnableFiltersGroup, background_FiltersService.onGroupEnable);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.DisableFiltersGroup, background_FiltersService.onGroupDisable);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.RestoreFiltersMv3, background_FiltersService.onRestoreFilters);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.ResetBlockedAdsCount, background_FiltersService.resetBlockedAdsCount);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.SetConsentedFilters, background_FiltersService.setConsentedFilters);
        background_message_handler_messageHandler.addListener(background_constants_MessageType.GetIsConsentedFilter, background_FiltersService.getIsConsentedFilter);
        background_settingsEvents.addListener(background_SettingOption.DisableCollectHits, background_FiltersService.onCollectHitsSwitch);
    }
    /**
     * Enables filter on {@link AddAndEnableFilterMessage} message via {@link FiltersService.enableFilter}.
     * If filter group has not been touched before, it will be activated.
     *
     * If filter group has been touched before and it is disabled now, the engine will not be updated.
     *
     * NOTE: we do not await of async task execution and returns group id optimistic.
     * TODO (v.zhelvis): handle enabling of group on frontend instead using this handler,
     * because this is UI edge case.
     *
     * @param message Message of {@link AddAndEnableFilterMessage} with filter
     * id to enable.
     *
     * @returns Id of the enabled filter group, if it has not been touched before, otherwise returns undefined.
     */ static async onFilterEnable(message) {
        const { filterId } = message.data;
        // FiltersService.enableFilter() method's second arg is 'true'
        // because it is needed to enable not touched group
        // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2776
        await background_FiltersService.enableFilter(filterId, true);
        const group = background_Categories.getGroupByFilterId(filterId);
        if (!group) {
            return;
        }
        const { groupId } = group;
        const groupState = background_Categories.getGroupState(groupId);
        if (!groupState) {
            return;
        }
        if (!groupState.touched) {
            return groupId;
        }
        if (groupState.enabled) {
            // update the engine only if the group is enabled
            await background_engine_engine.update();
        }
    }
    /**
     * Called at the request to disable filter.
     *
     * If filter group is disabled, the engine will not be updated.
     *
     * @param message Message of {@link DisableFilterMessage} with filter id to disable.
     */ static async onFilterDisable(message) {
        const { filterId } = message.data;
        background_main_FiltersApi.disableFilters([
            filterId
        ]);
        const group = background_Categories.getGroupByFilterId(filterId);
        if (!group) {
            return;
        }
        const groupState = background_Categories.getGroupState(group.groupId);
        if (groupState && groupState.enabled) {
            // update the engine only if the group is enabled
            await background_engine_engine.update();
        }
    }
    /**
     * Enables group on {@link EnableFiltersGroupMessage} message via {@link FiltersService.enableGroup}.
     *
     * If group is activated first time, provides list of recommended filters.
     * NOTE: we do not await of async task execution and returns array of recommended filters optimistic.
     * TODO (v.zhelvis): handle enabling of recommended filters on frontend instead using this handler,
     * because this is UI edge case.
     *
     * @param message {@link EnableFiltersGroupMessage} With specified group id.
     *
     * @returns Array of recommended filters on first group activation.
     */ static async onGroupEnable(message) {
        const { groupId } = message.data;
        const group = background_Categories.getGroupState(groupId);
        if (!group) {
            background_logger_logger.error(`Cannot find group with ${groupId} id`);
            return;
        }
        if (group.touched) {
            await background_FiltersService.enableGroup(groupId);
            return;
        }
        // If this is the first time the group has been activated - load and
        // enable the recommended filters.
        const recommendedFiltersIds = background_Categories.getRecommendedFilterIdsByGroupId(groupId);
        await background_FiltersService.enableGroup(groupId, recommendedFiltersIds);
        return recommendedFiltersIds;
    }
    /**
     * Called at the request to disable group of filters.
     *
     * @param message Message of {@link DisableFiltersGroupMessage} with group
     * id to disable.
     */ static async onGroupDisable(message) {
        const { groupId } = message.data;
        background_Categories.disableGroup(groupId);
        await background_engine_engine.update();
    }
    /**
     * Called when user tries to restore filters.
     */ static async onRestoreFilters() {
        const expectedEnabledFilters = background_RulesLimitsService.getExpectedEnabledFilters();
        await background_main_FiltersApi.loadAndEnableFilters(expectedEnabledFilters);
        await background_engine_engine.update();
    }
    /**
     * Called on a request to reset the counters of blocked ads.
     */ static async resetBlockedAdsCount() {
        await background_PageStatsApi.reset();
    }
    /**
     * Called on a request to add filter ids to consented filters list.
     *
     * @param message Message of {@link SetConsentedFiltersMessage} with filter ids to add.
     */ static async setConsentedFilters(message) {
        const { filterIds } = message.data;
        await background_annoyancesConsent.addFilterIds(filterIds);
    }
    /**
     * Called on a request to check if filter is consented.
     *
     * @param message Message of {@link GetIsConsentedFilterMessage} with filter id to check.
     *
     * @returns True if consent is granted for filter, otherwise false.
     */ static async getIsConsentedFilter(message) {
        const { filterId } = message.data;
        const isConsented = await background_annoyancesConsent.isConsentedFilter(filterId);
        return isConsented;
    }
    /**
     * Enables specified group and updates filter engine.
     *
     * On first group activation we provide recommended filters,
     * that will be loaded end enabled before update checking.
     *
     * @see Categories.enableGroup
     *
     * @param groupId Id of filter group.
     * @param recommendedFiltersIds Array of filters ids to enable on first time the group has been activated.
     */ static async enableGroup(groupId, recommendedFiltersIds = []) {
        await background_Categories.enableGroup(groupId, false, recommendedFiltersIds);
        await background_engine_engine.update();
    }
    /**
     * Loads and enables specified filter.
     * If filter group has not been touched before, it will be activated.
     *
     * Note: this method **does not update the engine**.
     *
     * @param filterId Id of filter.
     * @param shouldEnableGroup Flag for enabling the filter group if it has not been touched before.
     */ static async enableFilter(filterId, shouldEnableGroup = false) {
        // For quick fixes filter we have special logic with partially updating
        // metadata and then load filter from remote.
        if (filterId === background_AntiBannerFiltersId.QuickFixesFilterId) {
        // TODO: Uncomment this block when Quick Fixes filter will be supported for MV3
        // await QuickFixesRulesApi.loadAndEnableQuickFixesRules();
        } else {
            await background_main_FiltersApi.loadAndEnableFilters([
                filterId
            ], false, shouldEnableGroup);
        }
    }
    /**
     * Called when prompted to disable or enable hit collection.
     *
     * @param value Desired collecting status.
     */ static async onCollectHitsSwitch(value) {
        if (value) {
            background_HitStatsApi.cleanup();
        }
    }
}

;// ./Extension/src/background/services/filters/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ // NOTE: Here important to use 'filters-service' without path, because
// it is an alias for manifest-specific implementation of the rules rules limits
// service. It will be replaced with mv2 or mv3 version during the build
// via webpack.
/**
 * FiltersService is a singleton instance of FiltersService which
 * will be replaced with mv2 or mv3 implementation during the build via webpack.
 *
 * By default, mv2 will be used.
 */ 

;// ./Extension/src/background/services/locale-detect.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_locale_detect_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}













/**
 * This service is used to auto-enable language-specific filters.
 */ class background_LocaleDetect {
    /**
     * Adds listener for tab update message.
     */ init() {
        background_browser_polyfill_default().tabs.onUpdated.addListener(this.onTabUpdated);
    }
    /**
     * Called when tab is updated.
     *
     * @param tabId Tab id. Unused.
     * @param changeInfo Info about tab changed ({@link Tabs.OnUpdatedChangeInfoType}). Unused.
     * @param tab Item of {@link Tabs.Tab}.
     */ async onTabUpdated(tabId, changeInfo, tab) {
        if (tab.status === 'complete' && !true) {}
    }
    /**
     * Detects language for the specified tab.
     *
     * @param tab Tab details.
     */ async detectTabLanguage(tab) {
        const isDetectDisabled = background_settingsStorage.get(background_SettingOption.DisableDetectFilters);
        const isFilteringDisabled = background_settingsStorage.get(background_SettingOption.DisableFiltering);
        if (isDetectDisabled || isFilteringDisabled || !tab.url || !background_isHttpRequest(tab.url)) {
            return;
        }
        // tabs.detectLanguage doesn't work in Opera
        // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/997
        if (!background_UserAgent.isOpera) {
            if (tab.id && (background_browser_polyfill_default()).tabs && (background_browser_polyfill_default()).tabs.detectLanguage) {
                // https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/tabs/detectLanguage
                try {
                    const language = await background_browser_polyfill_default().tabs.detectLanguage(tab.id);
                    this.detectLanguage(language);
                } catch (e) {
                // do nothing
                }
                return;
            }
        }
        // Detecting language by top-level domain if extension API language detection is unavailable
        // Ignore hostnames which length is less or equal to 8
        // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/1354
        const host = background_getDomain(tab.url);
        if (host && host.length > 8) {
            const parts = host.split('.');
            const tld = parts.at(-1);
            if (!tld) {
                return;
            }
            const lang = background_LocaleDetect.domainToLanguagesMap[tld];
            if (!lang) {
                return;
            }
            await this.detectLanguage(lang);
        }
    }
    /**
     * Stores language in the special array containing languages of the last visited pages.
     * If user has visited enough pages with a specified language we call special callback
     * to auto-enable filter for this language.
     *
     * @param language Page language.
     *
     * @private
     */ async detectLanguage(language) {
        /**
         * For an unknown language "und" will be returned
         * https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/tabs/detectLanguage.
         */ if (!language || language === 'und') {
            return;
        }
        this.browsingLanguages.push({
            language,
            time: Date.now()
        });
        if (this.browsingLanguages.length > background_LocaleDetect.MAX_HISTORY_LENGTH) {
            this.browsingLanguages.shift();
        }
        const history = this.browsingLanguages.filter((h)=>{
            return h.language === language;
        });
        if (history.length >= background_LocaleDetect.SUCCESS_HIT_COUNT && !this.loadingLanguagesMutex[language]) {
            // Lock mutex to exclude double loading.
            this.loadingLanguagesMutex[language] = true;
            const filterIds = background_metadataStorage.getFilterIdsForLanguage(language);
            await background_LocaleDetect.onFilterDetectedByLocale(filterIds);
            // Free mutex for language.
            delete this.loadingLanguagesMutex[language];
        }
    }
    /**
     * Called when LocaleDetector has detected language-specific filters we can enable.
     *
     * @param filterIds List of detected language-specific filter identifiers.
     *
     * @private
     */ static async onFilterDetectedByLocale(filterIds) {
        if (!filterIds || filterIds.length === 0) {
            return;
        }
        const disabledFiltersIds = filterIds.filter((filterId)=>!background_main_FiltersApi.isFilterEnabled(filterId));
        // TODO: Check, do we really need always enable language group,
        // even if user disabled it manually?
        // Always enable language filters group.
        background_groupStateStorage.enableGroups([
            background_AntibannerGroupsId.LanguageFiltersGroupId
        ]);
        if (disabledFiltersIds.length === 0) {
            return;
        }
        const remote = !true;
        await background_main_FiltersApi.loadAndEnableFilters(disabledFiltersIds, remote);
        background_engine_engine.debounceUpdate();
        const filters = [];
        disabledFiltersIds.forEach((filterId)=>{
            const filter = background_CommonFilterApi.getFilterMetadata(filterId);
            if (filter) {
                filters.push(filter);
            }
        });
        background_toasts.showFiltersEnabledAlertMessage(filters);
    }
    /**
     * Creates new {@link LocaleDetect}.
     */ constructor(){
        background_locale_detect_define_property(this, "browsingLanguages", []);
        /**
     * Because listener for tab updates cannot be paused during filter loading,
     * we should save status of loading for each language to exclude double loading.
     */ background_locale_detect_define_property(this, "loadingLanguagesMutex", {});
        this.onTabUpdated = this.onTabUpdated.bind(this);
    }
}
background_locale_detect_define_property(background_LocaleDetect, "SUCCESS_HIT_COUNT", 3);
background_locale_detect_define_property(background_LocaleDetect, "MAX_HISTORY_LENGTH", 10);
background_locale_detect_define_property(background_LocaleDetect, "domainToLanguagesMap", {
    // Russian
    'ru': 'ru',
    'by': 'ru',
    'kz': 'ru',
    'uz': 'ru',
    'kg': 'ru',
    // Ukrainian
    'ua': 'uk',
    // English
    'com': 'en',
    'au': 'en',
    'uk': 'en',
    'nz': 'en',
    // German
    'de': 'de',
    'at': 'de',
    'li': 'de',
    // Japanese
    'jp': 'ja',
    // Dutch
    'nl': 'nl',
    // French
    'fr': 'fr',
    'mc': 'fr',
    'ht': 'fr',
    // Spanish
    'es': 'es',
    'mx': 'es',
    'ar': 'es',
    'cl': 'es',
    'uy': 'es',
    'pe': 'es',
    've': 'es',
    'ec': 'es',
    'bo': 'es',
    'py': 'es',
    'pa': 'es',
    'cr': 'es',
    'ni': 'es',
    'hn': 'es',
    'gt': 'es',
    'sv': 'es',
    'do': 'es',
    'pr': 'es',
    'cat': 'es',
    // Italian
    'it': 'it',
    'sm': 'it',
    // Portuguese
    'pt': 'pt',
    'br': 'pt',
    'ao': 'pt',
    'mz': 'pt',
    'cv': 'pt',
    // Polish
    'pl': 'pl',
    // Czech
    'cz': 'cs',
    // Bulgarian
    'bg': 'bg',
    // Lithuanian
    'lt': 'lt',
    // Latvian
    'lv': 'lv',
    // Arabic
    'eg': 'ar',
    'dz': 'ar',
    'kw': 'ar',
    'ae': 'ar',
    'ma': 'ar',
    'jo': 'ar',
    'lb': 'ar',
    'bh': 'ar',
    'qa': 'ar',
    'iq': 'ar',
    'tn': 'ar',
    // Slovakian
    'sk': 'sk',
    // Romanian
    'ro': 'ro',
    'md': 'ro',
    // Suomi
    'fi': 'fi',
    // Icelandic
    'is': 'is',
    // Norwegian
    'no': 'no',
    // Greek
    'gr': 'el',
    // Hungarian
    'hu': 'hu',
    // Hebrew
    'il': 'he',
    // Chinese
    'cn': 'zh',
    'tw': 'zh',
    // Indonesian
    'id': 'id',
    // Malaysian
    'my': 'id',
    // Turkish
    'tr': 'tr',
    // Serbian
    'sr': 'sr',
    'ba': 'sr',
    // Croatian
    'hr': 'hr',
    // Hindi
    'in': 'hi',
    // Bangla:
    'bd': 'hi',
    // Sri Lanka
    'lk': 'hi',
    // Nepal:
    'np': 'hi',
    // Estonian:
    'ee': 'et',
    // Persian:
    'ir': 'fa',
    // Tajik:
    'tj': 'fa',
    // Korean:
    'kr': 'ko',
    // Danish:
    'dk': 'da',
    // Faroese:
    'fo': 'fo',
    // Vietnamese:
    'vn': 'vi',
    // Thai:
    'th': 'th',
    // Swedish:
    'se': 'sv',
    'ax': 'sv'
});
const background_localeDetect = new background_LocaleDetect();

;// ./Extension/src/background/services/document-block.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 




/**
 * The DocumentBlockService controls events when an already blocked site
 * is excluded from the blocking mechanism for a period of time.
 */ class background_DocumentBlockService {
    /**
     * Initializes {@link DocumentBlockApi} and registers a listener for
     * the event of adding a domain to trusted domains.
     */ static async init() {
        await background_DocumentBlockApi.init();
        background_message_handler_messageHandler.addListener(background_constants_MessageType.AddUrlToTrusted, background_DocumentBlockService.onAddUrlToTrusted);
    }
    /**
     * Listener for the event of adding a domain to trusted domains.
     *
     * @param message Message of type {@link AddUrlToTrustedMessage}.
     * @param message.data Contains string url domain.
     */ static async onAddUrlToTrusted({ data }) {
        const { url } = data;
        await background_DocumentBlockApi.setTrustedDomain(url);
        await background_engine_engine.update();
        const tab = await background_TabsApi.getActive();
        if (tab === null || tab === void 0 ? void 0 : tab.id) {
            await background_browser_polyfill_default().tabs.update(tab.id, {
                url
            });
        }
    }
}

;// ./Extension/src/background/services/filter-update.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_filter_update_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}





/**
 * Service for scheduling filters update checks.
 *
 * After initialization scheduler checks filter updates
 * {@link CHECK_PERIOD_MS every 5 minutes}.
 */ class background_FilterUpdateService {
    /**
     * Initially starts checking filters update.
     */ async init() {
        await this.update();
    }
    /**
     * Checks every {@link CHECK_PERIOD_MS} period whether the enabled filters
     * should be updated with setTimeout which saved to {@link schedulerTimerId}.
     */ async update() {
        // eslint-disable-next-line no-restricted-globals
        self.clearTimeout(this.schedulerTimerId);
        const prevCheckTimeMs = await background_browserStorage.get(background_FilterUpdateService.STORAGE_KEY);
        /**
         * Check updates if prevCheckTimeMs is not set or
         * if it is set and last check was more than {@link CHECK_PERIOD_MS} ago.
         */ const shouldCheckUpdates = !prevCheckTimeMs || background_guards_isNumber(prevCheckTimeMs) && Date.now() - prevCheckTimeMs > background_FilterUpdateService.FILTER_UPDATE_PERIOD_MS;
        if (shouldCheckUpdates) {
            try {
                if (true) {
                // TODO: Uncomment this block when Quick Fixes filter will be supported for MV3
                // await QuickFixesRulesApi.updateQuickFixesFilter();
                } else {}
            } catch (e) {
                background_logger_logger.error('An error occurred during filters update:', e);
            }
            // Saving current time to storage is required in the cases
            // when background page is often unloaded,
            // for example, in the cases of service workers.
            await background_browserStorage.set(background_FilterUpdateService.STORAGE_KEY, Date.now());
        }
        // eslint-disable-next-line no-restricted-globals
        this.schedulerTimerId = self.setTimeout(async ()=>{
            await this.update();
        }, background_FilterUpdateService.CHECK_PERIOD_MS);
    }
    /**
     * Creates new {@link FilterUpdateService}.
     */ constructor(){
        /**
     * Stores scheduler timer id for checking update in every
     * {@link CHECK_PERIOD_MS} time.
     */ background_filter_update_define_property(this, "schedulerTimerId", void 0);
        this.update = this.update.bind(this);
    }
}
/**
     * Storage key for storing last update check time in the storage.
     */ background_filter_update_define_property(background_FilterUpdateService, "STORAGE_KEY", 'updateCheckTimeMs');
/**
     * Checking period
     * That timer should check every specified period of time if it is time to update filters.
     */ background_filter_update_define_property(background_FilterUpdateService, "CHECK_PERIOD_MS", 1000 * 60 * 5) // 5 min
;
/**
     * Filter update period.
     * This means that filters should be updated if it was updated more than the specified value.
     * We set 1 hour because currently we generate patches for our filter once an hour and
     * for third-party filters once every 4 hours.
     */ background_filter_update_define_property(background_FilterUpdateService, "FILTER_UPDATE_PERIOD_MS", 1000 * 60 * 60) // 1 hour
;
const background_filterUpdateService = new background_FilterUpdateService();

;// ./Extension/src/background/services/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 










 // Do not export SafebrowsingService here, because it will break MV3 build
 // because of dependencies with window object.

;// ./Extension/src/background/services/scripting/scripting-service-mv3.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

/**
 * Executes a script in the context of a given tab.
 *
 * @param tabId The tab ID.
 * @param options The options for the script execution.
 *
 * @throws Basic {@link Error} if passed options contains invalid or unsupported fields.
 */ const background_executeScript = async (tabId, options)=>{
    if (!tabId) {
        background_logger_logger.debug('Tab id is not provided');
        return;
    }
    const { frameId, allFrames, files = [], func } = options;
    const hasFiles = files.length !== 0;
    const hasFunc = func !== undefined;
    // Ensure that at least one and not both of the 'files' or 'func' is provided
    if (hasFiles === hasFunc) {
        throw new Error('Provide either "files" or "func", but not both.');
    }
    const frameIds = frameId !== undefined ? [
        frameId
    ] : undefined;
    const target = {
        tabId,
        allFrames,
        frameIds
    };
    let executeScriptOptions;
    if (hasFiles) {
        executeScriptOptions = {
            target,
            files
        };
    } else if (hasFunc) {
        executeScriptOptions = {
            target,
            func
        };
    }
    return new Promise((resolve, reject)=>{
        chrome.scripting.executeScript(executeScriptOptions, ()=>{
            if (chrome.runtime.lastError) {
                reject(new Error(chrome.runtime.lastError.message));
                return;
            }
            resolve();
        });
    });
};

;// ./Extension/src/background/keep-alive.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_keep_alive_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}







/**
 * Code which is injected into the page as content-script to keep the connection alive.
 */ const background_keepAliveCode = (/* unused pure expression or super */ null && (`
(() => {
    // used to avoid multiple connections from the same tab
    if (window.keepAlive) {
        return;
    }

    function connect() {
        browser.runtime.connect({ name: '${KEEP_ALIVE_PORT_NAME}' })
            .onDisconnect
            .addListener(() => {
                connect();
            });
    }

    // AG-37908
    window.addEventListener('pageshow', (event) => {
        if (event.persisted) {
            // The page is restored from BFCache, set up a new connection.
            connect();
        }
    });

    connect();

    window.keepAlive = true;
})();
`));
/**
 * Function to keep the connection alive by reconnecting if disconnected.
 */ function background_keepAliveFunc() {
    // We avoid adding a global type declaration to prevent confusion with the service worker,
    // as this will be used only on this page.
    // @ts-ignore
    if (window.keepAlive) {
        return;
    }
    /**
     * Connects to the background script and reconnects if disconnected.
     */ function connect() {
        // not in the constant, because it is injected into the page, and it will lose the context of this variable
        // @see KEEP_ALIVE_PORT_NAME
        chrome.runtime.connect({
            name: 'keep-alive'
        }).onDisconnect.addListener(()=>{
            connect();
        });
    }
    // AG-37908
    window.addEventListener('pageshow', (event)=>{
        if (event.persisted) {
            // The page is restored from BFCache, set up a new connection.
            connect();
        }
    });
    connect();
    // We avoid adding a global type declaration to prevent confusion with the service worker,
    // as this will be used only on this page.
    // @ts-ignore
    window.keepAlive = true;
}
/**
 * Class responsible for keeping the Chrome service worker or Firefox service worker page alive.
 * It connects to a port, with its handler located in {@link ConnectionHandler}.
 * This is used to prevent ad blinking caused by the termination of the service worker or event page.
 * This implementation is temporary and will be removed once a faster engine initialization mechanism is in place.
 */ class background_KeepAlive {
    /**
     * Adds listeners to tabs updates and finds the first tab to inject the script.
     */ static init() {
        if (background_UserAgent.isFirefox || true) {
            /**
             * When tab updates, we try to inject the content script to it.
             */ background_browser_polyfill_default().tabs.onUpdated.addListener(background_KeepAlive.onUpdate);
            background_KeepAlive.keepServiceWorkerAlive();
            background_KeepAlive.executeScriptOnTab();
        }
    }
    /**
     * Called after the background page has reloaded.
     * It is necessary for event page, which can reload,
     * but options page subscribes to events only once.
     * This function notifies all listeners to update by sending an UpdateListeners message.
     * TODO: can be removed after all pages connected via long living messages.
     */ static async resyncEventSubscriptions() {
        try {
            await background_messenger.updateListeners();
        } catch (e) {
            // This error occurs if there are no pages able to handle this listener.
            // It could happen if the background page reloaded when the options page was not open.
            background_logger_logger.debug(e);
        }
    }
    /**
     * Executes a script on one of the open tabs.
     *
     * @param tabs Tabs to execute a script on or null by default.
     */ static async executeScriptOnTab(tabs = null) {
        tabs = tabs || await background_browser_polyfill_default().tabs.query({
            url: '*://*/*'
        });
        // eslint-disable-next-line no-restricted-syntax
        for (const tab of tabs){
            try {
                if (true) {
                    // TODO - remove ts-ignore for mv3 version
                    // @ts-ignore
                    // eslint-disable-next-line no-await-in-loop
                    await background_executeScript(tab.id, {
                        func: background_keepAliveFunc
                    });
                } else {}
                return;
            } catch (e) {
                background_logger_logger.error(e);
            }
        }
    }
    /**
     * Prolongs the service worker's lifespan by periodically invoking a runtime API.
     *
     * Note:
     * - This is not an official solution and may be removed or become unsupported in the future.
     * - It does not restart the service worker if it has already been terminated.
     *   For that, a port connect/disconnect workaround is used.
     */ static keepServiceWorkerAlive() {
        // Usually a service worker dies after 30 seconds,
        // using 20 seconds should be enough to keep it alive.
        const KEEP_ALIVE_INTERVAL_MS = 20000;
        setInterval(async ()=>{
            await background_browser_polyfill_default().runtime.getPlatformInfo();
        }, KEEP_ALIVE_INTERVAL_MS);
    }
}
/**
     * On tab update event handler.
     *
     * @param tabId Tab id, not used in the code. Required by API.
     * @param info Tab update info.
     * @param tab Tab details.
     */ background_keep_alive_define_property(background_KeepAlive, "onUpdate", (tabId, info, tab)=>{
    if (info.url && background_isHttpRequest(info.url)) {
        background_KeepAlive.executeScriptOnTab([
            tab
        ]);
    }
});

;// ./Extension/src/background/connection-handler.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 









/**
 * ConnectionHandler manages long-lived connections to the {@link Runtime.Port}.
 */ class background_ConnectionHandler {
    /**
     * Initializes event listener for {@link browser.runtime.onConnect}.
     */ static init() {
        background_browser_polyfill_default().runtime.onConnect.addListener(background_ConnectionHandler.handleConnection);
    }
    /**
     * Handles long-live connection to the port with message {@link MessageType.AddLongLivedConnectionMessage}.
     *
     * @param port Object of {@link Runtime.Port}.
     */ static handleConnection(port) {
        let listenerId;
        background_logger_logger.info(`Port: "${port.name}" connected`);
        background_ConnectionHandler.onPortConnection(port);
        port.onMessage.addListener((message)=>{
            if (!background_messageHasTypeAndDataFields(message)) {
                // eslint-disable-next-line max-len
                background_logger_logger.error('Received message in ConnectionHandler.handleConnection has no type or data field: ', message);
                return;
            }
            if (message.type !== background_constants_MessageType.AddLongLivedConnection) {
                return;
            }
            const { data: { events } } = message;
            listenerId = background_notifier_notifier.addSpecifiedListener(events, async (...data)=>{
                try {
                    const message = {
                        type: background_constants_MessageType.NotifyListeners,
                        data
                    };
                    port.postMessage(message);
                } catch (e) {
                    background_logger_logger.error('Failed to send message to the port due to an error:', e);
                }
            });
        });
        port.onDisconnect.addListener(()=>{
            if (chrome.runtime.lastError) {
                background_logger_logger.debug('An error occurred on disconnect', (background_browser_polyfill_default()).runtime.lastError);
            }
            background_ConnectionHandler.onPortDisconnection(port);
            background_notifier_notifier.removeListener(listenerId);
            background_logger_logger.info(`Port: "${port.name}" disconnected`);
        });
    }
    /**
     * Handler for initial port connection.
     *
     * @param port Object of {@link Runtime.Port}.
     *
     * @throws Basic {@link Error} if the page specified in the port name
     * is not found.
     */ static onPortConnection(port) {
        switch(true){
            case port.name.startsWith(background_Page.FilteringLog):
                {
                    background_filteringLogApi.onOpenFilteringLogPage();
                    break;
                }
            case port.name.startsWith(background_Page.FullscreenUserRules):
                {
                    background_fullscreenUserRulesEditor.onOpenPage();
                    break;
                }
            case port.name === background_constants_KEEP_ALIVE_PORT_NAME:
                {
                    // This handler exists solely to prevent errors from the default case.
                    background_logger_logger.debug('Connected to the port');
                    break;
                }
            default:
                {
                    throw new Error(`There is no such pages ${port.name}`);
                }
        }
    }
    /**
     * Handler for port disconnection.
     *
     * @param port Object of {@link Runtime.Port}.
     *
     * @throws Basic {@link Error} if the page specified in the port name
     * is not found.
     */ static onPortDisconnection(port) {
        switch(true){
            case port.name.startsWith(background_Page.FilteringLog):
                {
                    background_filteringLogApi.onCloseFilteringLogPage();
                    break;
                }
            case port.name.startsWith(background_Page.FullscreenUserRules):
                {
                    background_fullscreenUserRulesEditor.onClosePage();
                    break;
                }
            case port.name === background_constants_KEEP_ALIVE_PORT_NAME:
                {
                    // when the port disconnects, we try to find a new tab to inject the content script
                    background_KeepAlive.executeScriptOnTab();
                    break;
                }
            default:
                {
                    throw new Error(`There is no such pages ${port.name}`);
                }
        }
    }
}

;// ./Extension/src/background/content-script-injector.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_content_script_injector_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}













/**
 * Helper class for injecting content script into tabs, opened before extension
 * initialization.
 */ class background_ContentScriptInjector {
    /**
     * Returns open tabs and injects content scripts into tab contexts.
     */ static async init() {
        const tabs = await background_TabsApi.getAll();
        const tasks = [];
        tabs.forEach((tab)=>{
            // Do not inject scripts into extension pages, browser internals and tabs without id
            if (typeof tab.id !== 'number' || !background_ContentScriptInjector.canInjectJs(tab)) {
                return;
            }
            const { id } = tab;
            tasks.push(background_ContentScriptInjector.inject(id, background_ContentScriptInjector.contentScripts));
        });
        // Loading order is not matter,
        // because all content-scripts are independent and tabs have been already loaded
        const promises = await Promise.allSettled(tasks);
        // Handles errors
        promises.forEach((promise)=>{
            if (promise.status === 'rejected') {
                background_logger_logger.error('Cannot inject scripts to tab due to: ', promise.reason);
            }
        });
    }
    /**
     * Inject content-script into specified tab.
     *
     * @param tabId The ID of the tab to inject the content script into.
     * @param files The path of the JS files to inject, relative to the extension's root directory.
     *
     * @throws Error if the content script injection times out or fails for another reason.
     */ static async inject(tabId, files) {
        try {
            /**
             * This implementation uses Promise.race() to prevent content script injection
             * from freezing the application when Chrome drops tabs.
             */ await background_createPromiseWithTimeout(background_executeScript(tabId, {
                allFrames: true,
                files
            }), background_ContentScriptInjector.INJECTION_LIMIT_MS, `Content script inject timeout because tab with id ${tabId} does not respond`);
        } catch (error) {
            // re-throw error with custom message
            throw new Error(`Cannot inject ${files.join(', ')} to tab with id ${tabId}. Error: ${background_error_getErrorMessage(error)}`);
        }
    }
    /**
     * Creates content-script relative url.
     *
     * @param output Content script output path.
     *
     * @returns Content-script relative url.
     */ static createContentScriptUrl(output) {
        return `/${output}.js`;
    }
    /**
     * Checks, if content script can be injected to specified tab.
     *
     * @param tab Tab browser details.
     *
     * @returns True, if content script can be injected, else returns false.
     */ static canInjectJs(tab) {
        if (typeof tab.url !== 'string' || !background_isHttpRequest(tab.url) || tab.status !== 'complete' || tab.discarded) {
            return false;
        }
        const hostname = (0,background_es6/* getHostname */.EW)(tab.url);
        if (!hostname) {
            return false;
        }
        const { jsInjectRestrictedHostnames } = background_ContentScriptInjector;
        if (background_UserAgent.isChromium && jsInjectRestrictedHostnames.chromium.includes(hostname)) {
            return false;
        }
        if (background_UserAgent.isFirefox && jsInjectRestrictedHostnames.firefox.includes(hostname)) {
            return false;
        }
        if (background_UserAgent.isOpera && jsInjectRestrictedHostnames.opera.includes(hostname)) {
            return false;
        }
        if (background_UserAgent.isEdge && jsInjectRestrictedHostnames.edge.includes(hostname)) {
            return false;
        }
        return true;
    }
    /**
     * Checks if session storage is available in the browser. If session storage
     * is available then we suppose that background (event page for firefox or
     * service worker for chromium) can die and we need to check if content
     * scripts were injected to exclude double injection.
     *
     * If session storage is not available (in MV2), we suppose that background
     * will not die and we don't need to check if content scripts were injected.
     *
     * @returns `true` if session storage is available, otherwise `false`.
     */ static isSessionStorageAvailable() {
        var _browser_storage;
        return ((_browser_storage = (background_browser_polyfill_default()).storage) === null || _browser_storage === void 0 ? void 0 : _browser_storage.session) !== undefined;
    }
    /**
     * Sets the injected flag in session storage.
     * This method updates the session storage to indicate that content scripts have been injected.
     */ static async setInjected() {
        if (!background_ContentScriptInjector.isSessionStorageAvailable()) {
            return;
        }
        try {
            await background_browser_polyfill_default().storage.session.set({
                [background_ContentScriptInjector.INJECTED_KEY]: true
            });
        } catch (e) {
            background_logger_logger.error('Cannot set injected flag in session storage', e);
        }
    }
    /**
     * Checks if content scripts have been injected.
     * Uses session storage since it is faster than sending a message to the content script.
     * As of November 25, 2025, Firefox v132.0.2 takes 1 second to send a message,
     * whereas reading from the session storage takes only 1 ms.
     *
     * @returns True if content scripts were injected; otherwise, false.
     */ static async isInjected() {
        if (!background_ContentScriptInjector.isSessionStorageAvailable()) {
            return false;
        }
        let isInjected = false;
        try {
            const result = await background_browser_polyfill_default().storage.session.get(background_ContentScriptInjector.INJECTED_KEY);
            isInjected = result[background_ContentScriptInjector.INJECTED_KEY] === true;
        } catch (e) {
            background_logger_logger.error('Cannot get injected flag from session storage', e);
        }
        return isInjected;
    }
}
/**
     * Key used to store the injected flag in session storage.
     */ background_content_script_injector_define_property(background_ContentScriptInjector, "INJECTED_KEY", 'content_script_injected');
background_content_script_injector_define_property(background_ContentScriptInjector, "INJECTION_LIMIT_MS", 1000);
/**
     * Content-scripts src relative paths.
     */ background_content_script_injector_define_property(background_ContentScriptInjector, "contentScripts", [
    background_ContentScriptInjector.createContentScriptUrl(background_CONTENT_SCRIPT_START_OUTPUT),
    background_ContentScriptInjector.createContentScriptUrl(background_CONTENT_SCRIPT_END_OUTPUT)
].concat( true ? [] : 0));
/**
     * Content scripts are blocked from executing on some websites by browsers
     * to protect users from extension escalating privileges.
     */ background_content_script_injector_define_property(background_ContentScriptInjector, "jsInjectRestrictedHostnames", {
    chromium: [
        'chrome.google.com',
        // https://chromium.googlesource.com/chromium/src/+/5d1f214db0f7996f3c17cd87093d439ce4c7f8f1/chrome/common/extensions/chrome_extensions_client.cc#232
        'chromewebstore.google.com'
    ],
    firefox: [
        'accounts-static.cdn.mozilla.net',
        'accounts.firefox.com',
        'addons.cdn.mozilla.net',
        'addons.mozilla.org',
        'api.accounts.firefox.com',
        'content.cdn.mozilla.net',
        'discovery.addons.mozilla.org',
        'install.mozilla.org',
        'oauth.accounts.firefox.com',
        'profile.accounts.firefox.com',
        'support.mozilla.org',
        'sync.services.mozilla.com'
    ],
    opera: [
        'addons.opera.com'
    ],
    edge: [
        'microsoftedge.microsoft.com'
    ]
});

;// ./Extension/src/background/app/app-mv3.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ function background_app_mv3_define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}


















/**
 * This class is app entry point.
 *
 * {@link App.init} Initializes all app services
 * and handle webextension API events for first install and update scenario.
 */ class background_App {
    /**
     * Initializes all app services
     * and handle webextension API events for first install and update scenario.
     *
     * First sync modules are initialized, then async modules.
     */ static async init() {
        // removes listeners on re-initialization, because new ones will be registered during process
        background_App.removeListeners();
        // First initialize critical sync event handlers.
        background_App.syncInit();
        // Then "lazy" call for all other stuff.
        await background_App.asyncInit();
    }
    /**
     * Initializes **sync** modules.
     *
     * Important: should be called before async part inside {@link App.init},
     * because in MV3 handlers should be registered on the top level in sync
     * functions.
     */ static syncInit() {
        background_UiService.syncInit();
    }
    // TODO: move other sync modules from App.asyncInit() to App.syncInit()
    /**
     * Initializes **async** modules.
     */ static async asyncInit() {
        // TODO: Remove after migration to MV3
        // This is a temporary solution to keep event pages alive in Firefox.
        // We will remove it once engine initialization becomes faster.
        background_KeepAlive.init();
        // Reads persisted data from session storage.
        await background_engine_engine.api.initStorage();
        // Initializes connection and message handler as soon as possible
        // to prevent connection errors from extension pages
        background_ConnectionHandler.init();
        background_message_handler_messageHandler.init();
        // get application run info
        const runInfo = await background_getRunInfo();
        const { previousAppVersion, currentAppVersion } = runInfo;
        const isAppVersionChanged = previousAppVersion !== currentAppVersion;
        const isInstall = isAppVersionChanged && !previousAppVersion;
        const isUpdate = isAppVersionChanged && !!previousAppVersion;
        if (isInstall) {
            await background_InstallApi.install(runInfo);
        }
        if (isUpdate) {
            await background_UpdateApi.update(runInfo);
        }
        // Initializes network settings.
        await background_network.waitForNetworkInit();
        // Initializes App storage data
        await background_App.initClientId();
        // Initializes Settings storage data
        await background_SettingsApi.init();
        await background_UiApi.init();
        await background_rulesLimitsService.init();
        /**
         * Injects content scripts into already opened tabs.
         *
         * Does injection when all requirements are met:
         * - Statistics collection is disabled - prevents conflicts from multiple
         * `cssHitCounters`;
         * - Content scripts have not been injected in the current session -
         * avoids unnecessary injections.
         */ if (background_SettingsApi.getSetting(background_SettingOption.DisableCollectHits) && !await background_ContentScriptInjector.isInjected()) {
            await background_ContentScriptInjector.init();
            await background_ContentScriptInjector.setInjected();
        }
        /**
         * Initializes Filters data:
         * - Loads app i18n metadata and caches it in i18n-metadata storage
         * - Loads app metadata, apply localization from i18n-metadata storage and caches it in metadata storage
         * - Initializes storages for userrules, allowlist, custom filters metadata and page-stats
         * - Initializes storages for filters state, groups state and filters versions, based on app metadata.
         */ await background_main_FiltersApi.init(isInstall);
        // Update the filters in the MV3 version for each extension update,
        // even for patches, because MV3 does not support remote filter updates
        // (either full or through diffs) and filters are updated only with
        // the update of the entire extension.
        if (isUpdate) {
            const filtersIds = await background_main_FiltersApi.reloadFiltersFromLocal();
            background_logger_logger.info('Following filters has been updated from local resources:', filtersIds);
        }
        await background_PageStatsApi.init();
        await background_HitStatsApi.init();
        /**
         * Initializes promo notifications:
         * - Initializes notifications storage
         * - Adds listeners for notification events.
         */ background_PromoNotificationService.init();
        // Adds listeners for settings events
        background_SettingsService.init();
        // Adds listeners for filter and group state events (enabling, updates)
        await background_FiltersService.init();
        // Adds listeners specified for custom filters
        // TODO: Uncomment this class when custom filters will be supported for MV3.
        // CustomFiltersService.init();
        // Adds listeners for allowlist events
        background_AllowlistService.init();
        // Adds listeners for userrules list events
        await background_UserRulesService.init(background_engine_engine);
        // Adds listeners for filtering log
        background_FilteringLogService.init();
        /**
         * Adds listeners for managing ui
         * (routing between extension pages, toasts, icon update).
         */ await background_UiService.init();
        // Adds listeners for popup events
        background_PopupService.init();
        // Initializes language detector for auto-enabling relevant filters
        background_localeDetect.init();
        /**
         * Adds listener for creating `notifier` events. Triggers by frontend.
         *
         * TODO: delete after frontend refactoring.
         */ background_eventService.init();
        /**
         * Called after eventService init, otherwise it won't handle messages.
         */ await background_KeepAlive.resyncEventSubscriptions();
        /**
         * Initializes Document block module
         * - Initializes persisted cache for trusted domains
         * - Adds listener for "add trusted domain" message.
         */ await background_DocumentBlockService.init();
        // Sets app uninstall url
        await background_App.setUninstallUrl();
        // First install additional scenario
        if (isInstall) {
            // Adds engine status listener for filters-download page
            background_message_handler_messageHandler.addListener(background_constants_MessageType.CheckRequestFilterReady, background_App.onCheckRequestFilterReady);
            // Opens filters-download page
            await background_PagesApi.openPostInstallPage();
            // Loads default filters
            await background_CommonFilterApi.initDefaultFilters(true);
            // Write the current version to the storage only after successful initialization of the extension
            await background_InstallApi.postSuccessInstall(currentAppVersion);
        }
        // Update additional scenario
        if (isUpdate) {
            if (!background_settingsStorage.get(background_SettingOption.DisableShowAppUpdatedNotification)) {
                // for isUpdate state previousAppVersion can't be null
                background_toasts.showApplicationUpdatedPopup(currentAppVersion, previousAppVersion);
            }
        }
        // Runs tswebextension
        await background_engine_engine.start();
        background_appContext.set(background_AppContextKey.IsInit, true);
        await background_sendMessage({
            type: background_constants_MessageType.AppInitialized
        });
        // In MV3 we need filters update service to update quick fixes filter,
        // we should await it before dispatching the event to exclude race
        // conditions.
        await background_filterUpdateService.init();
        // This event is used for integration tests (scripts/browser-test/index.ts)
        // and waitUntilExtensionInitialized() is adding a listener to the event
        // so the event should be dispatched eventually after all initialization
        // is done.
        dispatchEvent(new Event(background_EXTENSION_INITIALIZED_EVENT));
    }
    /**
     * Remove all registered app event listeners.
     */ static removeListeners() {
        background_message_handler_messageHandler.removeListeners();
        background_contextMenuEvents.removeListeners();
        background_settingsEvents.removeListeners();
    }
    /**
     * Handles engine status request from filters-download page.
     *
     * @returns True, if filter engine is initialized, else false.
     */ static onCheckRequestFilterReady() {
        const ready = background_engine_engine.api.isStarted;
        /**
         * If engine is ready, user will be redirected to thankyou page.
         *
         * CheckRequestFilterReady listener is not needed anymore.
         */ if (ready) {
            background_message_handler_messageHandler.removeListener(background_constants_MessageType.CheckRequestFilterReady);
        }
        return ready;
    }
    /**
     * Sets app uninstall url.
     */ static async setUninstallUrl() {
        try {
            await background_browser_polyfill_default().runtime.setUninstallURL(background_App.uninstallUrl);
        } catch (e) {
            background_logger_logger.error('Cannot set app uninstall url. Origin error: ', e);
        }
    }
    /**
     * Initializes App storage data.
     */ static async initClientId() {
        const storageClientId = await background_browserStorage.get(background_CLIENT_ID_KEY);
        let clientId;
        try {
            clientId = background_lib/* default.string */.Ay.string().parse(storageClientId);
        } catch (e) {
            background_logger_logger.warn('Error while parsing client id, generating a new one');
            clientId = background_InstallApi.genClientId();
            await background_browserStorage.set(background_CLIENT_ID_KEY, clientId);
        }
        background_appContext.set(background_AppContextKey.ClientId, clientId);
    }
}
background_app_mv3_define_property(background_App, "uninstallUrl", background_Forward.get({
    action: background_ForwardAction.UninstallExtension,
    from: background_ForwardFrom.Background
}));

;// ./Extension/src/background/index.ts
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 
// initialize background services
background_App.init();

;// ./Extension/pages/background/index.js
/**
 * @file
 * This file is part of AdGuard Browser Extension (https://github.com/AdguardTeam/AdguardBrowserExtension).
 *
 * AdGuard Browser Extension is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AdGuard Browser Extension is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AdGuard Browser Extension. If not, see <http://www.gnu.org/licenses/>.
 */ 

})();

/******/ })()
;