"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _wrapNativeSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/wrapNativeSuper"));var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _classPrivateFieldLooseBase2 = _interopRequireDefault(require("@babel/runtime/helpers/classPrivateFieldLooseBase"));var _classPrivateFieldLooseKey2 = _interopRequireDefault(require("@babel/runtime/helpers/classPrivateFieldLooseKey"));var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _value;function _callSuper(t, o, e) {return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e));}function _isNativeReflectConstruct() {try {var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));} catch (t) {}return (_isNativeReflectConstruct = function _isNativeReflectConstruct() {return !!t;})();}
Object.defineProperty(exports, "__esModule", { value: true });

var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = function __export(target, all) {
  for (var name in all)
  __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = function __copyProps(to, from, except, desc) {
  if (from && typeof from === "object" || typeof from === "function") {var _loop = function _loop(key) {

      if (!__hasOwnProp.call(to, key) && key !== except)
      __defProp(to, key, { get: function get() {return from[key];}, enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });};for (var key of __getOwnPropNames(from)) {_loop(key);}
  }
  return to;
};
var __toCommonJS = function __toCommonJS(mod) {return __copyProps(__defProp({}, "__esModule", { value: true }), mod);};

// node_modules/shiki/dist/engine-javascript.mjs
var engine_javascript_exports = {};
__export(engine_javascript_exports, {
  JavaScriptScanner: function JavaScriptScanner() {return _JavaScriptScanner;},
  createJavaScriptRegexEngine: function createJavaScriptRegexEngine() {return _createJavaScriptRegexEngine;},
  defaultJavaScriptRegexConstructor: function defaultJavaScriptRegexConstructor() {return _defaultJavaScriptRegexConstructor;}
});
module.exports = __toCommonJS(engine_javascript_exports);

// node_modules/regex/dist/regex.mjs
var Context = Object.freeze({
  DEFAULT: "DEFAULT",
  CHAR_CLASS: "CHAR_CLASS"
});
function replaceUnescaped(expression, needle, replacement, context) {
  var re = new RegExp(String.raw`${needle}|(?<$skip>\[\^?|\\?.)`, "gsu");
  var negated = [false];
  var numCharClassesOpen = 0;
  var result = "";
  for (var match of expression.matchAll(re)) {
    var m = match[0],$skip = match.groups.$skip;
    if (!$skip && (!context || context === Context.DEFAULT === !numCharClassesOpen)) {
      if (replacement instanceof Function) {
        result += replacement(match, {
          context: numCharClassesOpen ? Context.CHAR_CLASS : Context.DEFAULT,
          negated: negated[negated.length - 1]
        });
      } else {
        result += replacement;
      }
      continue;
    }
    if (m[0] === "[") {
      numCharClassesOpen++;
      negated.push(m[1] === "^");
    } else if (m === "]" && numCharClassesOpen) {
      numCharClassesOpen--;
      negated.pop();
    }
    result += m;
  }
  return result;
}
function forEachUnescaped(expression, needle, callback, context) {
  replaceUnescaped(expression, needle, callback, context);
}
function execUnescaped(expression, needle) {var pos = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;var context = arguments.length > 3 ? arguments[3] : undefined;
  if (!new RegExp(needle, "su").test(expression)) {
    return null;
  }
  var re = new RegExp(`${needle}|(?<$skip>\\\\?.)`, "gsu");
  re.lastIndex = pos;
  var numCharClassesOpen = 0;
  var match;
  while (match = re.exec(expression)) {
    var _match = match,m = _match[0],$skip = _match.groups.$skip;
    if (!$skip && (!context || context === Context.DEFAULT === !numCharClassesOpen)) {
      return match;
    }
    if (m === "[") {
      numCharClassesOpen++;
    } else if (m === "]" && numCharClassesOpen) {
      numCharClassesOpen--;
    }
    if (re.lastIndex == match.index) {
      re.lastIndex++;
    }
  }
  return null;
}
function hasUnescaped(expression, needle, context) {
  return !!execUnescaped(expression, needle, 0, context);
}
function getGroupContents(expression, contentsStartPos) {
  var token5 = /\\?(?:[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/gs;
  token5.lastIndex = contentsStartPos;
  var contentsEndPos = expression.length;
  var numCharClassesOpen = 0;
  var numGroupsOpen = 1;
  var match;
  while (match = token5.exec(expression)) {
    var _match2 = match,_match3 = (0, _slicedToArray2.default)(_match2, 1),m = _match3[0];
    if (m === "[") {
      numCharClassesOpen++;
    } else if (!numCharClassesOpen) {
      if (m === "(") {
        numGroupsOpen++;
      } else if (m === ")") {
        numGroupsOpen--;
        if (!numGroupsOpen) {
          contentsEndPos = match.index;
          break;
        }
      }
    } else if (m === "]") {
      numCharClassesOpen--;
    }
  }
  return expression.slice(contentsStartPos, contentsEndPos);
}
var Pattern = (_value = /*#__PURE__*/(0, _classPrivateFieldLooseKey2.default)("value"), /*#__PURE__*/function () {

  /** @param {string} value */
  function Pattern(value) {(0, _classCallCheck2.default)(this, Pattern);Object.defineProperty(this, _value, { writable: true, value: void 0 });
    (0, _classPrivateFieldLooseBase2.default)(this, _value)[_value] = value;
  }
  /** @returns {string} */return (0, _createClass2.default)(Pattern, [{ key: "toString", value:
    function toString() {
      return String((0, _classPrivateFieldLooseBase2.default)(this, _value)[_value]);
    } }]);}());

function pattern(first) {for (var _len = arguments.length, substitutions = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {substitutions[_key - 1] = arguments[_key];}
  if (Array.isArray(first == null ? void 0 : first.raw)) {
    return new Pattern(
      // Intersperse raw template strings and substitutions
      first.raw.flatMap(function (raw, i) {return i < first.raw.length - 1 ? [raw, substitutions[i]] : raw;}).join("")
    );
  } else if (!substitutions.length) {
    return new Pattern(first === void 0 ? "" : first);
  }
  throw new Error(`Unexpected arguments: ${JSON.stringify([first].concat(substitutions))}`);
}
var RegexContext = {
  DEFAULT: "DEFAULT",
  CHAR_CLASS: "CHAR_CLASS",
  ENCLOSED_P: "ENCLOSED_P",
  ENCLOSED_U: "ENCLOSED_U",
  GROUP_NAME: "GROUP_NAME",
  INTERVAL_QUANTIFIER: "INTERVAL_QUANTIFIER",
  INVALID_INCOMPLETE_TOKEN: "INVALID_INCOMPLETE_TOKEN"
};
var CharClassContext = {
  DEFAULT: "DEFAULT",
  ENCLOSED_P: "ENCLOSED_P",
  ENCLOSED_Q: "ENCLOSED_Q",
  ENCLOSED_U: "ENCLOSED_U",
  INVALID_INCOMPLETE_TOKEN: "INVALID_INCOMPLETE_TOKEN",
  RANGE: "RANGE"
};
var enclosedTokenRegexContexts = /* @__PURE__ */new Set([
RegexContext.ENCLOSED_P,
RegexContext.ENCLOSED_U]
);
var enclosedTokenCharClassContexts = /* @__PURE__ */new Set([
CharClassContext.ENCLOSED_P,
CharClassContext.ENCLOSED_Q,
CharClassContext.ENCLOSED_U]
);
var patternModsSupported = function () {
  try {
    new RegExp("(?i:)");
  } catch (e) {
    return false;
  }
  return true;
}();
var flagVSupported = function () {
  try {
    new RegExp("", "v");
  } catch (e) {
    return false;
  }
  return true;
}();
var doublePunctuatorChars = "&!#$%*+,.:;<=>?@^`~";
var emulationGroupMarker = "$E$";
var namedCapturingDelim = String.raw`\(\?<(?![=!])(?<captureName>[^>]+)>`;
var capturingDelim = String.raw`\((?!\?)(?!(?<=\(\?\()DEFINE\))|${namedCapturingDelim}`;
var noncapturingDelim = String.raw`\(\?(?:[:=!>A-Za-z\-]|<[=!]|\(DEFINE\))`;
function sandboxLoneDoublePunctuatorChar(str) {
  return str.replace(new RegExp(`^([${doublePunctuatorChars}])(?!\\1)`), function (m, _, pos) {
    return `\\${m}${pos + 1 === str.length ? "" : m}`;
  });
}
function sandboxUnsafeNulls(str, context) {
  return replaceUnescaped(str, String.raw`\\0(?!\d)`, "\\x00", context);
}
var contextToken = new RegExp(String.raw`
(?<groupN>\(\?<(?![=!])|\\[gk]<)
| (?<enclosedPU>\\[pPu]\{)
| (?<enclosedQ>\\q\{)
| (?<intervalQ>\{)
| (?<incompleteT>\\(?: $
  | c(?![A-Za-z])
  | u(?![A-Fa-f\d]{4})[A-Fa-f\d]{0,3}
  | x(?![A-Fa-f\d]{2})[A-Fa-f\d]?
  )
)
| --
| \\?.
`.replace(/\s+/g, ""), "gsu");
function getEndContextForIncompleteExpression(incompleteExpression)




{var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},_ref$regexContext = _ref.regexContext,regexContext = _ref$regexContext === void 0 ? RegexContext.DEFAULT : _ref$regexContext,_ref$charClassContext = _ref.charClassContext,charClassContext = _ref$charClassContext === void 0 ? CharClassContext.DEFAULT : _ref$charClassContext,_ref$charClassDepth = _ref.charClassDepth,charClassDepth = _ref$charClassDepth === void 0 ? 0 : _ref$charClassDepth,_ref$lastPos = _ref.lastPos,lastPos = _ref$lastPos === void 0 ? 0 : _ref$lastPos;
  contextToken.lastIndex = lastPos;
  var match;
  while (match = contextToken.exec(incompleteExpression)) {
    var _match4 = match,m = _match4[0],_match4$groups = _match4.groups,groupN = _match4$groups.groupN,enclosedPU = _match4$groups.enclosedPU,enclosedQ = _match4$groups.enclosedQ,intervalQ = _match4$groups.intervalQ,incompleteT = _match4$groups.incompleteT;
    if (m === "[") {
      charClassDepth++;
      regexContext = RegexContext.CHAR_CLASS;
      charClassContext = CharClassContext.DEFAULT;
    } else if (m === "]" && regexContext === RegexContext.CHAR_CLASS) {
      if (charClassDepth) {
        charClassDepth--;
      }
      if (!charClassDepth) {
        regexContext = RegexContext.DEFAULT;
      }
      charClassContext = CharClassContext.DEFAULT;
    } else if (regexContext === RegexContext.CHAR_CLASS) {
      if (incompleteT) {
        charClassContext = CharClassContext.INVALID_INCOMPLETE_TOKEN;
      } else if (m === "-") {
        charClassContext = CharClassContext.RANGE;
      } else if (enclosedPU) {
        charClassContext = m[1] === "u" ? CharClassContext.ENCLOSED_U : CharClassContext.ENCLOSED_P;
      } else if (enclosedQ) {
        charClassContext = CharClassContext.ENCLOSED_Q;
      } else if (m === "}" && enclosedTokenCharClassContexts.has(charClassContext) || // Don't continue in these contexts since we've advanced another token
      charClassContext === CharClassContext.INVALID_INCOMPLETE_TOKEN || charClassContext === CharClassContext.RANGE) {
        charClassContext = CharClassContext.DEFAULT;
      }
    } else {
      if (incompleteT) {
        regexContext = RegexContext.INVALID_INCOMPLETE_TOKEN;
      } else if (groupN) {
        regexContext = RegexContext.GROUP_NAME;
      } else if (enclosedPU) {
        regexContext = m[1] === "u" ? RegexContext.ENCLOSED_U : RegexContext.ENCLOSED_P;
      } else if (intervalQ) {
        regexContext = RegexContext.INTERVAL_QUANTIFIER;
      } else if (m === ">" && regexContext === RegexContext.GROUP_NAME || m === "}" && (regexContext === RegexContext.INTERVAL_QUANTIFIER || enclosedTokenRegexContexts.has(regexContext)) || // Don't continue in this context since we've advanced another token
      regexContext === RegexContext.INVALID_INCOMPLETE_TOKEN) {
        regexContext = RegexContext.DEFAULT;
      }
    }
  }
  return {
    regexContext: regexContext,
    charClassContext: charClassContext,
    charClassDepth: charClassDepth,
    lastPos: incompleteExpression.length
  };
}
function countCaptures(expression) {
  var num = 0;
  forEachUnescaped(expression, capturingDelim, function () {return num++;}, Context.DEFAULT);
  return num;
}
function spliceStr(str, pos, oldValue, newValue) {
  return str.slice(0, pos) + newValue + str.slice(pos + oldValue.length);
}
var stringPropertyNames = [
"Basic_Emoji",
"Emoji_Keycap_Sequence",
"RGI_Emoji_Modifier_Sequence",
"RGI_Emoji_Flag_Sequence",
"RGI_Emoji_Tag_Sequence",
"RGI_Emoji_ZWJ_Sequence",
"RGI_Emoji"].
join("|");
var charClassUnionToken = new RegExp(String.raw`
\\(?: c[A-Za-z]
  | p\{(?<pStrProp>${stringPropertyNames})\}
  | [pP]\{[^\}]+\}
  | (?<qStrProp>q)
  | u(?:[A-Fa-f\d]{4}|\{[A-Fa-f\d]+\})
  | x[A-Fa-f\d]{2}
  | .
)
| --
| &&
| .
`.replace(/\s+/g, ""), "gsu");
function preprocess(template, substitutions, preprocessor, options) {
  var newTemplate = { raw: [] };
  var newSubstitutions = [];
  var runningContext;
  template.raw.forEach(function (raw, i) {
    var result = preprocessor(raw, Object.assign({}, runningContext, { lastPos: 0 }), options);
    newTemplate.raw.push(result.transformed);
    runningContext = result.runningContext;
    if (i < template.raw.length - 1) {
      var substitution = substitutions[i];
      if (substitution instanceof Pattern) {
        var result2 = preprocessor(substitution, Object.assign({}, runningContext, { lastPos: 0 }), options);
        newSubstitutions.push(pattern(result2.transformed));
        runningContext = result2.runningContext;
      } else {
        newSubstitutions.push(substitution);
      }
    }
  });
  return {
    template: newTemplate,
    substitutions: newSubstitutions
  };
}
var token = new RegExp(String.raw`
${noncapturingDelim}
| \(\?<
| (?<backrefNum>\\[1-9]\d*)
| \\?.
`.replace(/\s+/g, ""), "gsu");
function flagNPreprocessor(value, runningContext) {
  value = String(value);
  var expression = "";
  var transformed = "";
  for (var _ref2 of value.matchAll(token)) {var m = _ref2[0];var backrefNum = _ref2.groups.backrefNum;
    expression += m;
    runningContext = getEndContextForIncompleteExpression(expression, runningContext);
    var _runningContext = runningContext,regexContext = _runningContext.regexContext;
    if (regexContext === RegexContext.DEFAULT) {
      if (m === "(") {
        transformed += "(?:";
      } else if (backrefNum) {
        throw new Error(`Invalid decimal escape "${m}" with implicit flag n; replace with named backreference`);
      } else {
        transformed += m;
      }
    } else {
      transformed += m;
    }
  }
  return {
    transformed: transformed,
    runningContext: runningContext
  };
}
var ws = /^\s$/;
var escapedWsOrHash = /^\\[\s#]$/;
var charClassWs = /^[ \t]$/;
var escapedCharClassWs = /^\\[ \t]$/;
var token2 = new RegExp(String.raw`
\\(?: [gk]<
  | [pPu]\{
  | c[A-Za-z]
  | u[A-Fa-f\d]{4}
  | x[A-Fa-f\d]{2}
  | 0\d+
)
| \[\^
| ${noncapturingDelim}
| \(\?<
| (?<dp>[${doublePunctuatorChars}])\k<dp>
| --
| \\?.
`.replace(/\s+/g, ""), "gsu");
function flagXPreprocessor(value, runningContext, options) {
  value = String(value);
  var ignoringWs = false;
  var ignoringCharClassWs = false;
  var ignoringComment = false;
  var expression = "";
  var transformed = "";
  var lastSignificantToken = "";
  var lastSignificantCharClassContext = "";
  var separatorNeeded = false;
  var update = function update(str) {var _ref3 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},_ref3$prefix = _ref3.prefix,prefix = _ref3$prefix === void 0 ? true : _ref3$prefix,_ref3$postfix = _ref3.postfix,postfix = _ref3$postfix === void 0 ? false : _ref3$postfix;
    str = (separatorNeeded && prefix ? "(?:)" : "") + str + (postfix ? "(?:)" : "");
    separatorNeeded = false;
    return str;
  };
  for (var _ref4 of value.matchAll(token2)) {var m = _ref4[0];var index = _ref4.index;
    if (ignoringComment) {
      if (m === "\n") {
        ignoringComment = false;
        separatorNeeded = true;
      }
      continue;
    }
    if (ignoringWs) {
      if (ws.test(m)) {
        continue;
      }
      ignoringWs = false;
      separatorNeeded = true;
    } else if (ignoringCharClassWs) {
      if (charClassWs.test(m)) {
        continue;
      }
      ignoringCharClassWs = false;
    }
    expression += m;
    runningContext = getEndContextForIncompleteExpression(expression, runningContext);
    var _runningContext2 = runningContext,regexContext = _runningContext2.regexContext,charClassContext = _runningContext2.charClassContext;
    if (
    // `--` is matched in one step, so boundary chars aren't `-` unless separated by whitespace
    m === "-" && regexContext === RegexContext.CHAR_CLASS && lastSignificantCharClassContext === CharClassContext.RANGE && (options.flags.includes("v") || options.unicodeSetsPlugin))
    {
      throw new Error("Invalid unescaped hyphen as the end value for a range");
    }
    if (
    // `??` is matched in one step by the double punctuator token
    regexContext === RegexContext.DEFAULT && /^(?:[?*+]|\?\?)$/.test(m) || regexContext === RegexContext.INTERVAL_QUANTIFIER && m === "{")
    {
      transformed += update(m, { prefix: false, postfix: lastSignificantToken === "(" && m === "?" });
    } else if (regexContext === RegexContext.DEFAULT) {
      if (ws.test(m)) {
        ignoringWs = true;
      } else if (m.startsWith("#")) {
        ignoringComment = true;
      } else if (escapedWsOrHash.test(m)) {
        transformed += update(m[1], { prefix: false });
      } else {
        transformed += update(m);
      }
    } else if (regexContext === RegexContext.CHAR_CLASS && m !== "[" && m !== "[^") {
      if (charClassWs.test(m) && (charClassContext === CharClassContext.DEFAULT || charClassContext === CharClassContext.ENCLOSED_Q || charClassContext === CharClassContext.RANGE)) {
        ignoringCharClassWs = true;
      } else if (charClassContext === CharClassContext.INVALID_INCOMPLETE_TOKEN) {
        throw new Error(`Invalid incomplete token in character class: "${m}"`);
      } else if (escapedCharClassWs.test(m) && (charClassContext === CharClassContext.DEFAULT || charClassContext === CharClassContext.ENCLOSED_Q)) {
        transformed += update(m[1], { prefix: false });
      } else if (charClassContext === CharClassContext.DEFAULT) {var _value2;
        var nextChar = (_value2 = value[index + 1]) != null ? _value2 : "";
        var updated = sandboxUnsafeNulls(m);
        if (charClassWs.test(nextChar) || m === "^") {
          updated = sandboxLoneDoublePunctuatorChar(updated);
        }
        transformed += update(updated);
      } else {
        transformed += update(m);
      }
    } else {
      transformed += update(m);
    }
    if (!(ignoringWs || ignoringCharClassWs || ignoringComment)) {
      lastSignificantToken = m;
      lastSignificantCharClassContext = charClassContext;
    }
  }
  return {
    transformed: transformed,
    runningContext: runningContext
  };
}
function cleanPlugin(expression) {
  var sep = String.raw`\(\?:\)`;
  expression = replaceUnescaped(expression, `(?:${sep}){2,}`, "(?:)", Context.DEFAULT);
  var marker = emulationGroupMarker.replace(/\$/g, "\\$");
  expression = replaceUnescaped(
    expression,
    String.raw`(?:${sep}(?=[)|.[$\\]|\((?!DEFINE)|$)|(?<=[()|.\]^>]|\\[bBdDfnrsStvwW]|\(\?(?:[:=!]|<[=!])|^)${sep}(?![?*+{]))(?!${marker})`,
    "",
    Context.DEFAULT
  );
  return expression;
}
var atomicPluginToken = new RegExp(String.raw`(?<noncapturingStart>${noncapturingDelim})|(?<capturingStart>\((?:\?<[^>]+>)?)|\\?.`, "gsu");
function atomicPlugin(expression, data) {
  if (!/\(\?>/.test(expression)) {
    return expression;
  }
  var aGDelim = "(?>";
  var emulatedAGDelim = `(?:(?=(${data.useEmulationGroups ? emulationGroupMarker : ""}`;
  var captureNumMap = [0];
  var numCapturesBeforeAG = 0;
  var numAGs = 0;
  var aGPos = NaN;
  var hasProcessedAG;
  do {
    hasProcessedAG = false;
    var numCharClassesOpen = 0;
    var numGroupsOpenInAG = 0;
    var inAG = false;
    var match = void 0;
    atomicPluginToken.lastIndex = Number.isNaN(aGPos) ? 0 : aGPos + emulatedAGDelim.length;
    while (match = atomicPluginToken.exec(expression)) {
      var _match5 = match,m = _match5[0],index = _match5.index,_match5$groups = _match5.groups,capturingStart = _match5$groups.capturingStart,noncapturingStart = _match5$groups.noncapturingStart;
      if (m === "[") {
        numCharClassesOpen++;
      } else if (!numCharClassesOpen) {
        if (m === aGDelim && !inAG) {
          aGPos = index;
          inAG = true;
        } else if (inAG && noncapturingStart) {
          numGroupsOpenInAG++;
        } else if (capturingStart) {
          if (inAG) {
            numGroupsOpenInAG++;
          } else {
            numCapturesBeforeAG++;
            captureNumMap.push(numCapturesBeforeAG + numAGs);
          }
        } else if (m === ")" && inAG) {
          if (!numGroupsOpenInAG) {
            numAGs++;
            expression = `${expression.slice(0, aGPos)}${emulatedAGDelim}${expression.slice(aGPos + aGDelim.length, index)}))<$$${numAGs + numCapturesBeforeAG}>)${expression.slice(index + 1)}`;
            hasProcessedAG = true;
            break;
          }
          numGroupsOpenInAG--;
        }
      } else if (m === "]") {
        numCharClassesOpen--;
      }
    }
  } while (hasProcessedAG);
  expression = replaceUnescaped(
    expression,
    String.raw`\\(?<backrefNum>[1-9]\d*)|<\$\$(?<wrappedBackrefNum>\d+)>`,
    function (_ref5) {var m = _ref5[0],_ref5$groups = _ref5.groups,backrefNum = _ref5$groups.backrefNum,wrappedBackrefNum = _ref5$groups.wrappedBackrefNum;
      if (backrefNum) {
        var bNum = +backrefNum;
        if (bNum > captureNumMap.length - 1) {
          throw new Error(`Backref "${m}" greater than number of captures`);
        }
        return `\\${captureNumMap[bNum]}`;
      }
      return `\\${wrappedBackrefNum}`;
    },
    Context.DEFAULT
  );
  return expression;
}
var baseQuantifier = String.raw`(?:[?*+]|\{\d+(?:,\d*)?\})`;
var possessivePluginToken = new RegExp(String.raw`
\\(?: \d+
  | c[A-Za-z]
  | [gk]<[^>]+>
  | [pPu]\{[^\}]+\}
  | u[A-Fa-f\d]{4}
  | x[A-Fa-f\d]{2}
  )
| \((?: \? (?: [:=!>]
  | <(?:[=!]|[^>]+>)
  | [A-Za-z\-]+:
  | \(DEFINE\)
  ))?
| (?<qBase>${baseQuantifier})(?<qMod>[?+]?)(?<invalidQ>[?*+\{]?)
| \\?.
`.replace(/\s+/g, ""), "gsu");
function possessivePlugin(expression) {
  if (!new RegExp(`${baseQuantifier}\\+`).test(expression)) {
    return expression;
  }
  var openGroupIndices = [];
  var lastGroupIndex = null;
  var lastCharClassIndex = null;
  var lastToken = "";
  var numCharClassesOpen = 0;
  var match;
  possessivePluginToken.lastIndex = 0;
  while (match = possessivePluginToken.exec(expression)) {
    var _match6 = match,m = _match6[0],index = _match6.index,_match6$groups = _match6.groups,qBase = _match6$groups.qBase,qMod = _match6$groups.qMod,invalidQ = _match6$groups.invalidQ;
    if (m === "[") {
      if (!numCharClassesOpen) {
        lastCharClassIndex = index;
      }
      numCharClassesOpen++;
    } else if (m === "]") {
      if (numCharClassesOpen) {
        numCharClassesOpen--;
      } else {
        lastCharClassIndex = null;
      }
    } else if (!numCharClassesOpen) {
      if (qMod === "+" && lastToken && !lastToken.startsWith("(")) {
        if (invalidQ) {
          throw new Error(`Invalid quantifier "${m}"`);
        }
        var charsAdded = -1;
        if (/^\{\d+\}$/.test(qBase)) {
          expression = spliceStr(expression, index + qBase.length, qMod, "");
        } else {
          if (lastToken === ")" || lastToken === "]") {
            var nodeIndex = lastToken === ")" ? lastGroupIndex : lastCharClassIndex;
            if (nodeIndex === null) {
              throw new Error(`Invalid unmatched "${lastToken}"`);
            }
            expression = `${expression.slice(0, nodeIndex)}(?>${expression.slice(nodeIndex, index)}${qBase})${expression.slice(index + m.length)}`;
          } else {
            expression = `${expression.slice(0, index - lastToken.length)}(?>${lastToken}${qBase})${expression.slice(index + m.length)}`;
          }
          charsAdded += 4;
        }
        possessivePluginToken.lastIndex += charsAdded;
      } else if (m[0] === "(") {
        openGroupIndices.push(index);
      } else if (m === ")") {
        lastGroupIndex = openGroupIndices.length ? openGroupIndices.pop() : null;
      }
    }
    lastToken = m;
  }
  return expression;
}
function subroutinesPlugin(expression, data) {
  var namedGroups = getNamedCapturingGroups(expression, { includeContents: true });
  var transformed = processSubroutines(expression, namedGroups, data.useEmulationGroups);
  return processDefinitionGroup(transformed, namedGroups);
}
var subroutinePattern = String.raw`\\g<(?<subroutineName>[^>&]+)>`;
var token3 = new RegExp(String.raw`
${subroutinePattern}
| (?<capturingStart>${capturingDelim})
| \\(?<backrefNum>[1-9]\d*)
| \\k<(?<backrefName>[^>]+)>
| \\?.
`.replace(/\s+/g, ""), "gsu");
function processSubroutines(expression, namedGroups, useEmulationGroups) {
  if (!/\\g</.test(expression)) {
    return expression;
  }
  var hasBackrefs = hasUnescaped(expression, "\\\\(?:[1-9]|k<[^>]+>)", Context.DEFAULT);
  var subroutineWrapper = hasBackrefs ? `(${useEmulationGroups ? emulationGroupMarker : ""}` : "(?:";
  var openSubroutines = /* @__PURE__ */new Map();
  var openSubroutinesStack = [];
  var captureNumMap = [0];
  var numCapturesPassedOutsideSubroutines = 0;
  var numCapturesPassedInsideSubroutines = 0;
  var numCapturesPassedInsideThisSubroutine = 0;
  var numSubroutineCapturesTrackedInRemap = 0;
  var numCharClassesOpen = 0;
  var result = expression;
  var match;
  token3.lastIndex = 0;
  while (match = token3.exec(result)) {
    var _match7 = match,m = _match7[0],index = _match7.index,_match7$groups = _match7.groups,subroutineName = _match7$groups.subroutineName,capturingStart = _match7$groups.capturingStart,backrefNum = _match7$groups.backrefNum,backrefName = _match7$groups.backrefName;
    if (m === "[") {
      numCharClassesOpen++;
    } else if (!numCharClassesOpen) {
      if (subroutineName) {
        if (!namedGroups.has(subroutineName)) {
          throw new Error(`Invalid named capture referenced by subroutine ${m}`);
        }
        if (openSubroutines.has(subroutineName)) {
          throw new Error(`Subroutine ${m} followed a recursive reference`);
        }
        var contents = namedGroups.get(subroutineName).contents;
        var subroutineValue = `${subroutineWrapper}${contents})`;
        if (hasBackrefs) {
          numCapturesPassedInsideThisSubroutine = 0;
          numCapturesPassedInsideSubroutines++;
        }
        openSubroutines.set(subroutineName, {
          // Incrementally decremented to track when we've left the group
          unclosedGroupCount: countOpenParens(subroutineValue)
        });
        openSubroutinesStack.push(subroutineName);
        result = spliceStr(result, index, m, subroutineValue);
        token3.lastIndex -= m.length - subroutineWrapper.length;
      } else if (capturingStart) {
        if (openSubroutines.size) {
          if (hasBackrefs) {
            numCapturesPassedInsideThisSubroutine++;
            numCapturesPassedInsideSubroutines++;
          }
          if (m !== "(") {
            result = spliceStr(result, index, m, subroutineWrapper);
            token3.lastIndex -= m.length - subroutineWrapper.length;
          }
        } else if (hasBackrefs) {
          captureNumMap.push(
            lastOf(captureNumMap) + 1 + numCapturesPassedInsideSubroutines - numSubroutineCapturesTrackedInRemap
          );
          numSubroutineCapturesTrackedInRemap = numCapturesPassedInsideSubroutines;
          numCapturesPassedOutsideSubroutines++;
        }
      } else if ((backrefNum || backrefName) && openSubroutines.size) {var _namedGroups$get;
        var num = backrefNum ? +backrefNum : (_namedGroups$get = namedGroups.get(backrefName)) == null ? void 0 : _namedGroups$get.groupNum;
        var isGroupFromThisSubroutine = false;
        for (var s of openSubroutinesStack) {
          var group = namedGroups.get(s);
          if (num >= group.groupNum && num <= group.groupNum + group.numCaptures) {
            isGroupFromThisSubroutine = true;
            break;
          }
        }
        if (isGroupFromThisSubroutine) {
          var _group = namedGroups.get(lastOf(openSubroutinesStack));
          var subroutineNum = numCapturesPassedOutsideSubroutines + numCapturesPassedInsideSubroutines - numCapturesPassedInsideThisSubroutine;
          var metadata = `\\k<$$b${num}s${subroutineNum}r${_group.groupNum}c${_group.numCaptures}>`;
          result = spliceStr(result, index, m, metadata);
          token3.lastIndex += metadata.length - m.length;
        }
      } else if (m === ")") {
        if (openSubroutines.size) {
          var subroutine = openSubroutines.get(lastOf(openSubroutinesStack));
          subroutine.unclosedGroupCount--;
          if (!subroutine.unclosedGroupCount) {
            openSubroutines.delete(openSubroutinesStack.pop());
          }
        }
      }
    } else if (m === "]") {
      numCharClassesOpen--;
    }
  }
  if (hasBackrefs) {
    result = replaceUnescaped(
      result,
      String.raw`\\(?:(?<bNum>[1-9]\d*)|k<\$\$b(?<bNumSub>\d+)s(?<subNum>\d+)r(?<refNum>\d+)c(?<refCaps>\d+)>)`,
      function (_ref6) {var m = _ref6[0],_ref6$groups = _ref6.groups,bNum = _ref6$groups.bNum,bNumSub = _ref6$groups.bNumSub,subNum = _ref6$groups.subNum,refNum = _ref6$groups.refNum,refCaps = _ref6$groups.refCaps;
        if (bNum) {
          var _backrefNum = +bNum;
          if (_backrefNum > captureNumMap.length - 1) {
            throw new Error(`Backref "${m}" greater than number of captures`);
          }
          return `\\${captureNumMap[_backrefNum]}`;
        }
        var backrefNumInSubroutine = +bNumSub;
        var subroutineGroupNum = +subNum;
        var refGroupNum = +refNum;
        var numCapturesInRef = +refCaps;
        if (backrefNumInSubroutine < refGroupNum || backrefNumInSubroutine > refGroupNum + numCapturesInRef) {
          return `\\${captureNumMap[backrefNumInSubroutine]}`;
        }
        return `\\${subroutineGroupNum - refGroupNum + backrefNumInSubroutine}`;
      },
      Context.DEFAULT
    );
  }
  return result;
}
var defineGroupToken = new RegExp(String.raw`${namedCapturingDelim}|\(\?:\)|(?<invalid>\\?.)`, "gsu");
function processDefinitionGroup(expression, namedGroups) {
  var defineMatch = execUnescaped(expression, String.raw`\(\?\(DEFINE\)`, 0, Context.DEFAULT);
  if (!defineMatch) {
    return expression;
  }
  var defineGroup = getGroup(expression, defineMatch);
  if (defineGroup.afterPos < expression.length) {
    throw new Error("DEFINE group allowed only at the end of a regex");
  } else if (defineGroup.afterPos > expression.length) {
    throw new Error("DEFINE group is unclosed");
  }
  var match;
  defineGroupToken.lastIndex = 0;
  while (match = defineGroupToken.exec(defineGroup.contents)) {
    var _match$groups = match.groups,captureName = _match$groups.captureName,invalid = _match$groups.invalid;
    if (captureName) {
      var group = getGroup(defineGroup.contents, match);
      var duplicateName = void 0;
      if (!namedGroups.get(captureName).isUnique) {
        duplicateName = captureName;
      } else {
        var nestedNamedGroups = getNamedCapturingGroups(group.contents);
        for (var name of nestedNamedGroups.keys()) {
          if (!namedGroups.get(name).isUnique) {
            duplicateName = name;
            break;
          }
        }
      }
      if (duplicateName) {
        throw new Error(`Duplicate group name "${duplicateName}" within DEFINE`);
      }
      defineGroupToken.lastIndex = group.afterPos;
    } else if (invalid) {
      throw new Error(`DEFINE group includes unsupported syntax at top level`);
    }
  }
  return expression.slice(0, defineMatch.index);
}
function countOpenParens(expression) {
  var num = 0;
  forEachUnescaped(expression, "\\(", function () {return num++;}, Context.DEFAULT);
  return num;
}
function getCaptureNum(expression, groupName) {
  var num = 0;
  var pos = 0;
  var match;
  while (match = execUnescaped(expression, capturingDelim, pos, Context.DEFAULT)) {
    var _match8 = match,m = _match8[0],index = _match8.index,captureName = _match8.groups.captureName;
    num++;
    if (captureName === groupName) {
      break;
    }
    pos = index + m.length;
  }
  return num;
}
function getGroup(expression, delimMatch) {
  var contentsStart = delimMatch.index + delimMatch[0].length;
  var contents = getGroupContents(expression, contentsStart);
  var afterPos = contentsStart + contents.length + 1;
  return {
    contents: contents,
    afterPos: afterPos
  };
}
function getNamedCapturingGroups(expression) {var _ref7 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},includeContents = _ref7.includeContents;
  var namedGroups = /* @__PURE__ */new Map();
  forEachUnescaped(
    expression,
    namedCapturingDelim,
    function (_ref8) {var m = _ref8[0],index = _ref8.index,captureName = _ref8.groups.captureName;
      if (namedGroups.has(captureName)) {
        namedGroups.get(captureName).isUnique = false;
      } else {
        var group = { isUnique: true };
        if (includeContents) {
          var contents = getGroupContents(expression, index + m.length);
          Object.assign(group, {
            contents: contents,
            groupNum: getCaptureNum(expression, captureName),
            numCaptures: countCaptures(contents)
          });
        }
        namedGroups.set(captureName, group);
      }
    },
    Context.DEFAULT
  );
  return namedGroups;
}
function lastOf(arr) {
  return arr[arr.length - 1];
}
var incompatibleEscapeChars = "&!#%,:;<=>@`~";
var token4 = new RegExp(String.raw`
\[\^?-?
| --?\]
| (?<dp>[${doublePunctuatorChars}])\k<dp>
| --
| \\(?<vOnlyEscape>[${incompatibleEscapeChars}])
| \\[pPu]\{[^}]+\}
| \\?.
`.replace(/\s+/g, ""), "gsu");
function backcompatPlugin(expression) {
  var unescapedLiteralHyphenMsg = 'Invalid unescaped "-" in character class';
  var inCharClass = false;
  var result = "";
  for (var _ref9 of expression.matchAll(token4)) {var m = _ref9[0];var _ref9$groups = _ref9.groups;var dp = _ref9$groups.dp;var vOnlyEscape = _ref9$groups.vOnlyEscape;
    if (m[0] === "[") {
      if (inCharClass) {
        throw new Error("Invalid nested character class when flag v not supported; possibly from interpolation");
      }
      if (m.endsWith("-")) {
        throw new Error(unescapedLiteralHyphenMsg);
      }
      inCharClass = true;
    } else if (m.endsWith("]")) {
      if (m[0] === "-") {
        throw new Error(unescapedLiteralHyphenMsg);
      }
      inCharClass = false;
    } else if (inCharClass) {
      if (m === "&&" || m === "--") {
        throw new Error(`Invalid set operator "${m}" when flag v not supported`);
      } else if (dp) {
        throw new Error(`Invalid double punctuator "${m}", reserved by flag v`);
      } else if ("(){}/|".includes(m)) {
        throw new Error(`Invalid unescaped "${m}" in character class`);
      } else if (vOnlyEscape) {
        result += vOnlyEscape;
        continue;
      }
    }
    result += m;
  }
  return result;
}
function rewrite() {var expression = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var opts = getOptions(options);
  if (opts.subclass) {
    throw new Error("Cannot use option subclass");
  }
  return {
    expression: handlePlugins(
      handlePreprocessors({ raw: [expression] }, [], opts).template.raw[0],
      opts
    ),
    flags: opts.flags
  };
}
function getOptions(options) {
  var opts = Object.assign({
    flags: "",
    subclass: false,
    plugins: [],
    unicodeSetsPlugin: backcompatPlugin,
    disable: {

      /* n, v, x, atomic, subroutines */},
    force: {

      /* v */} },
  options);

  if (/[nuvx]/.test(opts.flags)) {
    throw new Error("Implicit flags v/u/x/n cannot be explicitly added");
  }
  var useFlagV = opts.force.v || (opts.disable.v ? false : flagVSupported);
  opts.flags += useFlagV ? "v" : "u";
  if (useFlagV) {
    opts.unicodeSetsPlugin = null;
  }
  return opts;
}
function handlePreprocessors(template, substitutions, options) {
  var preprocessors = [];
  if (!options.disable.x) {
    preprocessors.push(flagXPreprocessor);
  }
  if (!options.disable.n) {
    preprocessors.push(flagNPreprocessor);
  }
  for (var pp of preprocessors) {var _preprocess =
    preprocess(template, substitutions, pp, options);template = _preprocess.template;substitutions = _preprocess.substitutions;
  }
  return {
    template: template,
    substitutions: substitutions
  };
}
function handlePlugins(expression, options) {
  var flags = options.flags,plugins = options.plugins,unicodeSetsPlugin = options.unicodeSetsPlugin,disable = options.disable,subclass = options.subclass;
  [].concat((0, _toConsumableArray2.default)(
    plugins), (0, _toConsumableArray2.default)(

    disable.subroutines ? [] : [subroutinesPlugin]), (0, _toConsumableArray2.default)(
    disable.atomic ? [] : [possessivePlugin, atomicPlugin]), (0, _toConsumableArray2.default)(
    disable.x ? [] : [cleanPlugin]), (0, _toConsumableArray2.default)(

    !unicodeSetsPlugin ? [] : [unicodeSetsPlugin])).
  forEach(function (p) {return expression = p(expression, { flags: flags, useEmulationGroups: subclass });});
  return expression;
}

// node_modules/oniguruma-to-js/dist/shared/oniguruma-to-js.2969e22d.mjs
var __defProp2 = Object.defineProperty;
var __defNormalProp = function __defNormalProp(obj, key, value) {return key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value: value }) : obj[key] = value;};
var __publicField = function __publicField(obj, key, value) {
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};
var RegExpConversionError = /*#__PURE__*/function (_SyntaxError) {
  function RegExpConversionError(message, options) {var _this;(0, _classCallCheck2.default)(this, RegExpConversionError);
    _this = _callSuper(this, RegExpConversionError, [message, { cause: options.cause }]);
    __publicField(_this, "patternOriginal");
    __publicField(_this, "patternConverted");
    __publicField(_this, "cursorPosition");
    _this.patternOriginal = options.pattern;
    _this.patternConverted = options.converted;
    _this.cursorPosition = options.cursor;return _this;
  }(0, _inherits2.default)(RegExpConversionError, _SyntaxError);return (0, _createClass2.default)(RegExpConversionError);}(/*#__PURE__*/(0, _wrapNativeSuper2.default)(SyntaxError));

var UNNECESSARY_ESCAPE_CHAR_CLASS = new Set("!?:=+$(){}_><# ");
var UNNECESSARY_ESCAPE = new Set("-!:=_>< ");
var TABLE_POSIX = {
  alnum: "0-9A-Za-z",
  alpha: "A-Za-z",
  ascii: "\0-\x7F",
  blank: " \\t",
  cntrl: "\0-\x7F",
  digit: "\\d",
  graph: "!-~",
  lower: "a-z",
  print: " -~",
  punct: "!-/:-@[-`{-~",
  space: "\\s",
  upper: "A-Z",
  xdigit: "0-9A-Fa-f",
  word: "\\w"
};
var TABLE_SLASH_P = {
  alnum: "0-9A-Za-z",
  alpha: "A-Za-z",
  alphabetic: "A-Za-z",
  blank: "\\s",
  greek: "\\p{Script=Greek}",
  print: "\\p{L}\\p{N}\\p{P}\\p{S}\\p{Zs}",
  word: "\\w"
};
var KNOWN_FLAGS = /* @__PURE__ */new Set("gimsuyx");
function syntaxLowering(input) {var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var _options$useRegex =







    options.useRegex,useRegex = _options$useRegex === void 0 ? false : _options$useRegex,_options$preserveFlag = options.preserveFlags,preserveFlags = _options$preserveFlag === void 0 ? false : _options$preserveFlag,_options$removePosses = options.removePossessiveQuantifier,removePossessiveQuantifier = _options$removePosses === void 0 ? false : _options$removePosses,_options$removeAtomic = options.removeAtomicGroup,removeAtomicGroup = _options$removeAtomic === void 0 ? false : _options$removeAtomic,_options$convertHexDi = options.convertHexDigitsShorthand,convertHexDigitsShorthand = _options$convertHexDi === void 0 ? false : _options$convertHexDi,_options$convertUnico = options.convertUnicodeCategory,convertUnicodeCategory = _options$convertUnico === void 0 ? false : _options$convertUnico,_options$expandNested = options.expandNestedCharacterClass,expandNestedCharacterClass = _options$expandNested === void 0 ? false : _options$expandNested;
  var output = "";
  var flags = /* @__PURE__ */new Set();
  var stack = [];
  var freeSpacingLocal = [];
  var freeSpacingGlobal = false;
  var isInNestedCharClass = false;
  var i = 0;
  try {
    while (i < input.length) {
      var char = input[i];
      while (freeSpacingLocal.length && freeSpacingLocal[0] > stack.length) {
        freeSpacingLocal.shift();
      }
      var head = stack[0];
      var freeSpacing = freeSpacingGlobal || freeSpacingLocal.length;
      if (char === "\\") {
        if (convertHexDigitsShorthand) {
          if (input[i + 1] === "h") {
            var body = `0-9A-Fa-f`;
            if (head === "[") {
              output += body;
            } else {
              output += `[${body}]`;
            }
            i += 2;
            continue;
          }
          if (input[i + 1] === "H") {
            if (head === "[") {
              throw new RegExpConversionError(
                "Expending \\H in character class is not supported",
                { pattern: input, converted: output, cursor: i }
              );
            } else {
              output += `[^0-9A-Fa-f]`;
            }
            i += 2;
            continue;
          }
        }
        if (convertUnicodeCategory && input[i + 1] === "p" && input[i + 2] === "{") {
          var end = input.indexOf("}", i + 3);
          if (end === -1) {
            throw new RegExpConversionError(
              "Unmatched \\p{...}",
              { pattern: input, converted: output, cursor: i }
            );
          }
          var name = input.slice(i + 3, end);
          var resolved = TABLE_SLASH_P[name.toLowerCase()];
          if (resolved) {
            if (head === "[") {
              output += resolved;
            } else {
              output += `[${resolved}]`;
            }
            i = end + 1;
            continue;
          }
        }
        if (head === "[" && UNNECESSARY_ESCAPE_CHAR_CLASS.has(input[i + 1])) {
          output += input[i + 1];
          i += 2;
          continue;
        }
        if (head !== "[" && UNNECESSARY_ESCAPE.has(input[i + 1])) {
          output += input[i + 1];
          i += 2;
          continue;
        }
        output += char + input[i + 1];
        i += 2;
        continue;
      }
      if (char === "#" && freeSpacing && input[i - 1].match(/\s/) && head !== "[") {
        for (var j = i + 1; j <= input.length; j++) {
          if (input[j] === "\n" || j === input.length) {
            i = j;
            break;
          }
        }
        continue;
      }
      if (char === "(" && head !== "[") {
        if (input[i + 1] === "?") {
          if (input[i + 2] === "#") {
            for (var _j = i + 3; _j < input.length; _j++) {
              if (input[_j] === ")" && input[_j - 1] !== "\\") {
                i = _j + 1;
                break;
              }
            }
            continue;
          }
          if (removeAtomicGroup && input[i + 2] === ">") {
            output += "(?:";
            i += 3;
            continue;
          }
          if (KNOWN_FLAGS.has(input[i + 2])) {
            var _end = i + 3;
            for (; _end < input.length; _end++) {
              if (!KNOWN_FLAGS.has(input[_end]))
              break;
            }
            var flagStr2 = input.slice(i + 2, _end);
            var hasX = flagStr2.includes("x") && flagStr2[0] !== "-";
            var remainFlags = (0, _toConsumableArray2.default)(flagStr2).filter(function (x) {return x !== "x";}).join("");
            if (!preserveFlags) {
              if (remainFlags[0] === "-") {
                remainFlags = remainFlags.slice(1);
                for (var flag of flagStr2) {
                  flags.delete(flag);
                }
              } else {
                for (var _flag of remainFlags) {
                  flags.add(_flag);
                }
              }
              remainFlags = "";
            }
            if (input[_end] === ")") {
              i = _end + 1;
              if (hasX) {
                freeSpacingGlobal = true;
              }
              if (remainFlags.length) {
                output += `(?${remainFlags})`;
              }
              continue;
            } else if (input[_end] === ":") {
              i = _end + 1;
              stack.unshift(char);
              if (hasX) {
                freeSpacingLocal.unshift(stack.length);
              }
              output += `(?${remainFlags}:`;
              continue;
            }
          }
          stack.unshift(char);
          output += char + input[i + 1] + input[i + 2];
          i += 3;
        } else {
          stack.unshift(char);
          output += char;
          i += 1;
        }
        continue;
      }
      if (char === ")" && head !== "[") {
        if (head === "(")
        stack.shift();
        output += char;
        i += 1;
        continue;
      }
      if (char === "[") {
        if (input[i + 1] === ":") {
          var _name = "";
          var negated = false;
          if (input[i + 2] === "^") {
            negated = true;
            i += 1;
          }
          for (var _j2 = i + 2; _j2 < input.length; _j2++) {
            if (input[_j2] === ":") {
              i = _j2 + 2;
              break;
            }
            if (!input[_j2].match(/[a-z]/i)) {
              _name = "";
              break;
            }
            _name += input[_j2];
          }
          if (_name) {
            var _resolved = TABLE_POSIX[_name];
            if (!_resolved) {
              throw new RegExpConversionError(
                `Unknown posix class "${_name}"`,
                { pattern: input, converted: output, cursor: i }
              );
            }
            if (negated)
            _resolved = `^${_resolved}`;
            if (head === "[")
            output += _resolved;else

            output += `[${_resolved}]`;
            continue;
          }
        }
        if (head !== "[") {
          stack.unshift(char);
        }
        if (head === "[" && expandNestedCharacterClass) {
          isInNestedCharClass = true;
          i += 1;
          if (input[i] === "-") {
            output += "\\-";
            i += 1;
          }
          continue;
        }
        output += char;
        i += 1;
        continue;
      }
      if (char === "]") {
        if (isInNestedCharClass) {
          isInNestedCharClass = false;
          i += 1;
          continue;
        }
        if (head === "[")
        stack.shift();
        output += char;
        i += 1;
        continue;
      }
      if (removePossessiveQuantifier && char === "+" && head !== "[") {
        if ("?+}*".includes(input[i - 1])) {
          i += 1;
          continue;
        }
      }
      if (char === "*" && head !== "[" && input[i - 1] === "|" && input[i - 2] !== "\\") {
        output += "\\";
      }
      if (!(freeSpacing && head !== "[" && char.match(/\s/))) {
        output += char;
      }
      i += 1;
    }
  } catch (e) {
    if (e instanceof RegExpConversionError)
    throw e;
    throw new RegExpConversionError(
      `Error lowering regex at position ${i}`,
      { pattern: input, converted: output, cursor: i, cause: e }
    );
  }
  var flagStr = (0, _toConsumableArray2.default)(flags).join("");
  if (useRegex) {
    output = rewrite(
      output,
      {
        flags: flagStr,
        unicodeSetsPlugin: null,
        disable: {
          n: true,
          v: true,
          x: true
        }
      }
    ).expression;
  }
  return {
    pattern: output,
    flags: flagStr
  };
}

// node_modules/oniguruma-to-js/dist/index.mjs
function construct(pattern2) {var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var _options$original =


    options.original,original = _options$original === void 0 ? pattern2 : _options$original,_options$flags = options.flags,flags = _options$flags === void 0 ? ["g"] : _options$flags;
  if (pattern2.startsWith("(?x)") || pattern2.includes("(?x:")) {
    throw new RegExpConversionError(
      "RegExp Free-spacing mode `(?x)` is not supported, you might want to run syntaxLowering() first",
      { pattern: original, converted: pattern2 }
    );
  }
  if (pattern2.match(/\[:\w+:\]/)) {
    throw new RegExpConversionError(
      "POSIX character classes are not supported, you might want to run syntaxLowering() first",
      { pattern: original, converted: pattern2 }
    );
  }
  var flagSet = new Set(Array.isArray(flags) ? flags : flags.split(""));
  if (pattern2.includes("\\p{"))
  flagSet.add("u");
  pattern2 = pattern2.replace(/\\A/g, "^").replace(/\\Z/g, "(?=\\n?$)").replace(/\\z/g, "$").replace(/\\x\{([^}]*)\}/g, function (m, hex) {return `\\u${hex.padStart(4, "0")}`;}).replace(/\(\?(-)?(\w+):/g, function (_, neg, flagStr) {
    if (neg) {
      for (var flag of flagStr)
      flagSet.delete(flag);
    } else {
      for (var _flag2 of flagStr)
      flagSet.add(_flag2);
    }
    return "(?:";
  }).replace(/\(\?(-)?(\w+)\)/g, function (_, neg, flags2) {
    if (neg) {
      for (var flag of flags2)
      flagSet.delete(flag);
    } else {
      for (var _flag3 of flags2)
      flagSet.add(_flag3);
    }
    return "";
  });
  if (options.ignoreContiguousAnchors) {
    if (pattern2.includes("\\G")) {
      flagSet.add("y");
    }
    if (pattern2.startsWith("\\G")) {
      pattern2 = pattern2.slice(2);
    }
    pattern2 = pattern2.replace(/\|\\G(\||\))/g, "$1").replace(/(\(|\|)\\G\|/g, "$1").replace(/\\G/g, "");
  }
  if (flagSet.has("x")) {
    throw new RegExpConversionError(
      "JavaScript does not support extended mode (x flag), you might want to run syntaxLowering() first",
      { pattern: original, converted: pattern2 }
    );
  }
  try {
    return new RegExp(pattern2, (0, _toConsumableArray2.default)(flagSet).join(""));
  } catch (e) {
    throw new RegExpConversionError(
      `Failed to construct RegExp`,
      {
        pattern: original,
        converted: pattern2,
        cause: e
      }
    );
  }
}
function onigurumaToRegexp(pattern2) {var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var _syntaxLowering =


    syntaxLowering(pattern2, Object.assign({
      // removePossessiveQuantifier: false,
      // removeAtomicGroup: false,
      convertHexDigitsShorthand: true,
      convertUnicodeCategory: true,
      useRegex: true,
      expandNestedCharacterClass: true },
    options)
    ),converted = _syntaxLowering.pattern,flags = _syntaxLowering.flags;
  return construct(converted, Object.assign({
    original: pattern2 },
  options, {
    flags: (0, _toConsumableArray2.default)(/* @__PURE__ */new Set([].concat((0, _toConsumableArray2.default)(flags), (0, _toConsumableArray2.default)(options.flags || [])))).join("") })
  );
}

// node_modules/@shikijs/engine-javascript/dist/index.mjs
var replacements = [
[
"(?<square>[^\\[\\]\\\\]|\\\\.|\\[\\g<square>*+\\])",
"(?<square>[^\\[\\]\\\\]|\\\\.|\\[(?:[^\\[\\]\\\\]|\\\\.|\\[(?:[^\\[\\]\\\\]|\\\\.|\\[(?:[^\\[\\]\\\\])*+\\])*+\\])*+\\])"],

[
"(?<url>(?>[^\\s()]+)|\\(\\g<url>*\\))",
"(?<url>(?>[^\\s()]+)|\\((?:(?>[^\\s()]+)|\\((?:(?>[^\\s()]+)|\\((?>[^\\s()]+)*\\))*\\))*\\))"]];


var __defProp3 = Object.defineProperty;
var __defNormalProp2 = function __defNormalProp2(obj, key, value) {return key in obj ? __defProp3(obj, key, { enumerable: true, configurable: true, writable: true, value: value }) : obj[key] = value;};
var __publicField2 = function __publicField2(obj, key, value) {
  __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};
var MAX = 4294967295;
function _defaultJavaScriptRegexConstructor(pattern2) {
  return onigurumaToRegexp(
    pattern2,
    {
      flags: "dgm",
      ignoreContiguousAnchors: true
    }
  );
}
var _JavaScriptScanner = /*#__PURE__*/function () {
  function _JavaScriptScanner(patterns) {var _this2 = this;var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};(0, _classCallCheck2.default)(this, _JavaScriptScanner);
    this.patterns = patterns;
    this.options = options;
    __publicField2(this, "regexps");
    __publicField2(this, "contiguousAnchorSimulation");
    var _options$forgiving =




      options.forgiving,forgiving = _options$forgiving === void 0 ? false : _options$forgiving,cache = options.cache,_options$simulation = options.simulation,simulation = _options$simulation === void 0 ? true : _options$simulation,_options$regexConstru = options.regexConstructor,regexConstructor = _options$regexConstru === void 0 ? _defaultJavaScriptRegexConstructor : _options$regexConstru;
    this.contiguousAnchorSimulation = Array.from({ length: patterns.length }, function () {return false;});
    this.regexps = patterns.map(function (p, idx) {
      if (simulation)
      p = p.replaceAll("(^|\\\uFFFF)", "(^|\\G)");
      if (simulation && (p.startsWith("(^|\\G)") || p.startsWith("(\\G|^)")))
      _this2.contiguousAnchorSimulation[idx] = true;
      var cached = cache == null ? void 0 : cache.get(p);
      if (cached) {
        if (cached instanceof RegExp) {
          return cached;
        }
        if (forgiving)
        return null;
        throw cached;
      }
      try {
        var pattern2 = p;
        if (simulation) {
          for (var _ref10 of replacements) {var _ref11 = (0, _slicedToArray2.default)(_ref10, 2);var from = _ref11[0];var to = _ref11[1];
            pattern2 = pattern2.replaceAll(from, to);
          }
        }
        var regex = regexConstructor(pattern2);
        cache == null ? void 0 : cache.set(p, regex);
        return regex;
      } catch (e) {
        cache == null ? void 0 : cache.set(p, e);
        if (forgiving)
        return null;
        throw e;
      }
    });
  }return (0, _createClass2.default)(_JavaScriptScanner, [{ key: "findNextMatchSync", value:
    function findNextMatchSync(string, startPosition) {
      var str = typeof string === "string" ? string : string.content;
      var pending = [];
      function toResult(index, match) {var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
        return {
          index: index,
          captureIndices: match.indices.map(function (indice) {
            if (indice == null) {
              return {
                end: MAX,
                start: MAX,
                length: 0
              };
            }
            return {
              start: indice[0] + offset,
              length: indice[1] - indice[0],
              end: indice[1] + offset
            };
          })
        };
      }
      for (var i = 0; i < this.regexps.length; i++) {
        var regexp = this.regexps[i];
        if (!regexp)
        continue;
        try {
          var offset = 0;
          regexp.lastIndex = startPosition;
          var match = regexp.exec(str);
          if (!match && this.contiguousAnchorSimulation[i]) {
            offset = startPosition;
            regexp.lastIndex = 0;
            match = regexp.exec(str.slice(startPosition));
          }
          if (!match)
          continue;
          if (match.index === startPosition) {
            return toResult(i, match, offset);
          }
          pending.push([i, match, offset]);
        } catch (e) {
          if (this.options.forgiving)
          continue;
          throw e;
        }
      }
      if (pending.length) {
        var minIndex = Math.min.apply(Math, (0, _toConsumableArray2.default)(pending.map(function (m) {return m[1].index;})));
        for (var _ref12 of pending) {var _ref13 = (0, _slicedToArray2.default)(_ref12, 3);var _i = _ref13[0];var _match9 = _ref13[1];var _offset = _ref13[2];
          if (_match9.index === minIndex) {
            return toResult(_i, _match9, _offset);
          }
        }
      }
      return null;
    } }]);}();

function _createJavaScriptRegexEngine() {var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var _options = Object.assign({
    cache: /* @__PURE__ */new Map() },
  options);

  return {
    createScanner: function createScanner(patterns) {
      return new _JavaScriptScanner(patterns, _options);
    },
    createString: function createString(s) {
      return {
        content: s
      };
    }
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  JavaScriptScanner: _JavaScriptScanner,
  createJavaScriptRegexEngine: _createJavaScriptRegexEngine,
  defaultJavaScriptRegexConstructor: _defaultJavaScriptRegexConstructor
});
//# sourceMappingURL=engine-javascript.js.map