"use strict";
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 = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// node_modules/shiki/dist/engine-javascript.mjs
var engine_javascript_exports = {};
__export(engine_javascript_exports, {
  JavaScriptScanner: () => JavaScriptScanner,
  createJavaScriptRegexEngine: () => createJavaScriptRegexEngine,
  defaultJavaScriptRegexConstructor: () => 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) {
  const re = new RegExp(String.raw`${needle}|(?<$skip>\[\^?|\\?.)`, "gsu");
  const negated = [false];
  let numCharClassesOpen = 0;
  let result = "";
  for (const match of expression.matchAll(re)) {
    const { 0: m, groups: { $skip } } = match;
    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, pos = 0, context) {
  if (!new RegExp(needle, "su").test(expression)) {
    return null;
  }
  const re = new RegExp(`${needle}|(?<$skip>\\\\?.)`, "gsu");
  re.lastIndex = pos;
  let numCharClassesOpen = 0;
  let match;
  while (match = re.exec(expression)) {
    const { 0: m, groups: { $skip } } = match;
    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) {
  const token5 = /\\?./gsu;
  token5.lastIndex = contentsStartPos;
  let contentsEndPos = expression.length;
  let numCharClassesOpen = 0;
  let numGroupsOpen = 1;
  let match;
  while (match = token5.exec(expression)) {
    const [m] = match;
    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 = class {
  #value;
  /** @param {string} value */
  constructor(value) {
    this.#value = value;
  }
  /** @returns {string} */
  toString() {
    return String(this.#value);
  }
};
function pattern(first, ...substitutions) {
  if (Array.isArray(first?.raw)) {
    return new Pattern(
      // Intersperse raw template strings and substitutions
      first.raw.flatMap((raw, i) => 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, ...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 = (() => {
  try {
    new RegExp("(?i:)");
  } catch (e) {
    return false;
  }
  return true;
})();
var flagVSupported = (() => {
  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)`), (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, {
  regexContext = RegexContext.DEFAULT,
  charClassContext = CharClassContext.DEFAULT,
  charClassDepth = 0,
  lastPos = 0
} = {}) {
  contextToken.lastIndex = lastPos;
  let match;
  while (match = contextToken.exec(incompleteExpression)) {
    const { 0: m, groups: { groupN, enclosedPU, enclosedQ, intervalQ, incompleteT } } = match;
    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,
    charClassContext,
    charClassDepth,
    lastPos: incompleteExpression.length
  };
}
function countCaptures(expression) {
  let num = 0;
  forEachUnescaped(expression, capturingDelim, () => 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) {
  let newTemplate = { raw: [] };
  let newSubstitutions = [];
  let runningContext;
  template.raw.forEach((raw, i) => {
    const result = preprocessor(raw, { ...runningContext, lastPos: 0 }, options);
    newTemplate.raw.push(result.transformed);
    runningContext = result.runningContext;
    if (i < template.raw.length - 1) {
      const substitution = substitutions[i];
      if (substitution instanceof Pattern) {
        const result2 = preprocessor(substitution, { ...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);
  let expression = "";
  let transformed = "";
  for (const { 0: m, groups: { backrefNum } } of value.matchAll(token)) {
    expression += m;
    runningContext = getEndContextForIncompleteExpression(expression, runningContext);
    const { regexContext } = runningContext;
    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,
    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);
  let ignoringWs = false;
  let ignoringCharClassWs = false;
  let ignoringComment = false;
  let expression = "";
  let transformed = "";
  let lastSignificantToken = "";
  let lastSignificantCharClassContext = "";
  let separatorNeeded = false;
  const update = (str, { prefix = true, postfix = false } = {}) => {
    str = (separatorNeeded && prefix ? "(?:)" : "") + str + (postfix ? "(?:)" : "");
    separatorNeeded = false;
    return str;
  };
  for (const { 0: m, index } of value.matchAll(token2)) {
    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);
    const { regexContext, charClassContext } = runningContext;
    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) {
        const nextChar = value[index + 1] ?? "";
        let 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,
    runningContext
  };
}
function cleanPlugin(expression) {
  const sep = String.raw`\(\?:\)`;
  expression = replaceUnescaped(expression, `(?:${sep}){2,}`, "(?:)", Context.DEFAULT);
  const 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;
  }
  const aGDelim = "(?>";
  const emulatedAGDelim = `(?:(?=(${data.useEmulationGroups ? emulationGroupMarker : ""}`;
  const captureNumMap = [0];
  let numCapturesBeforeAG = 0;
  let numAGs = 0;
  let aGPos = NaN;
  let hasProcessedAG;
  do {
    hasProcessedAG = false;
    let numCharClassesOpen = 0;
    let numGroupsOpenInAG = 0;
    let inAG = false;
    let match;
    atomicPluginToken.lastIndex = Number.isNaN(aGPos) ? 0 : aGPos + emulatedAGDelim.length;
    while (match = atomicPluginToken.exec(expression)) {
      const { 0: m, index, groups: { capturingStart, noncapturingStart } } = match;
      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+)>`,
    ({ 0: m, groups: { backrefNum, wrappedBackrefNum } }) => {
      if (backrefNum) {
        const 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;
  }
  const openGroupIndices = [];
  let lastGroupIndex = null;
  let lastCharClassIndex = null;
  let lastToken = "";
  let numCharClassesOpen = 0;
  let match;
  possessivePluginToken.lastIndex = 0;
  while (match = possessivePluginToken.exec(expression)) {
    const { 0: m, index, groups: { qBase, qMod, invalidQ } } = match;
    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}"`);
        }
        let charsAdded = -1;
        if (/^\{\d+\}$/.test(qBase)) {
          expression = spliceStr(expression, index + qBase.length, qMod, "");
        } else {
          if (lastToken === ")" || lastToken === "]") {
            const 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) {
  const namedGroups = getNamedCapturingGroups(expression, { includeContents: true });
  const 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;
  }
  const hasBackrefs = hasUnescaped(expression, "\\\\(?:[1-9]|k<[^>]+>)", Context.DEFAULT);
  const subroutineWrapper = hasBackrefs ? `(${useEmulationGroups ? emulationGroupMarker : ""}` : "(?:";
  const openSubroutines = /* @__PURE__ */ new Map();
  const openSubroutinesStack = [];
  const captureNumMap = [0];
  let numCapturesPassedOutsideSubroutines = 0;
  let numCapturesPassedInsideSubroutines = 0;
  let numCapturesPassedInsideThisSubroutine = 0;
  let numSubroutineCapturesTrackedInRemap = 0;
  let numCharClassesOpen = 0;
  let result = expression;
  let match;
  token3.lastIndex = 0;
  while (match = token3.exec(result)) {
    const { 0: m, index, groups: { subroutineName, capturingStart, backrefNum, backrefName } } = match;
    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`);
        }
        const contents = namedGroups.get(subroutineName).contents;
        const 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) {
        const num = backrefNum ? +backrefNum : namedGroups.get(backrefName)?.groupNum;
        let isGroupFromThisSubroutine = false;
        for (const s of openSubroutinesStack) {
          const group = namedGroups.get(s);
          if (num >= group.groupNum && num <= group.groupNum + group.numCaptures) {
            isGroupFromThisSubroutine = true;
            break;
          }
        }
        if (isGroupFromThisSubroutine) {
          const group = namedGroups.get(lastOf(openSubroutinesStack));
          const subroutineNum = numCapturesPassedOutsideSubroutines + numCapturesPassedInsideSubroutines - numCapturesPassedInsideThisSubroutine;
          const 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) {
          const 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+)>)`,
      ({ 0: m, groups: { bNum, bNumSub, subNum, refNum, refCaps } }) => {
        if (bNum) {
          const backrefNum = +bNum;
          if (backrefNum > captureNumMap.length - 1) {
            throw new Error(`Backref "${m}" greater than number of captures`);
          }
          return `\\${captureNumMap[backrefNum]}`;
        }
        const backrefNumInSubroutine = +bNumSub;
        const subroutineGroupNum = +subNum;
        const refGroupNum = +refNum;
        const 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) {
  const defineMatch = execUnescaped(expression, String.raw`\(\?\(DEFINE\)`, 0, Context.DEFAULT);
  if (!defineMatch) {
    return expression;
  }
  const 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");
  }
  let match;
  defineGroupToken.lastIndex = 0;
  while (match = defineGroupToken.exec(defineGroup.contents)) {
    const { captureName, invalid } = match.groups;
    if (captureName) {
      const group = getGroup(defineGroup.contents, match);
      let duplicateName;
      if (!namedGroups.get(captureName).isUnique) {
        duplicateName = captureName;
      } else {
        const nestedNamedGroups = getNamedCapturingGroups(group.contents);
        for (const 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) {
  let num = 0;
  forEachUnescaped(expression, "\\(", () => num++, Context.DEFAULT);
  return num;
}
function getCaptureNum(expression, groupName) {
  let num = 0;
  let pos = 0;
  let match;
  while (match = execUnescaped(expression, capturingDelim, pos, Context.DEFAULT)) {
    const { 0: m, index, groups: { captureName } } = match;
    num++;
    if (captureName === groupName) {
      break;
    }
    pos = index + m.length;
  }
  return num;
}
function getGroup(expression, delimMatch) {
  const contentsStart = delimMatch.index + delimMatch[0].length;
  const contents = getGroupContents(expression, contentsStart);
  const afterPos = contentsStart + contents.length + 1;
  return {
    contents,
    afterPos
  };
}
function getNamedCapturingGroups(expression, { includeContents } = {}) {
  const namedGroups = /* @__PURE__ */ new Map();
  forEachUnescaped(
    expression,
    namedCapturingDelim,
    ({ 0: m, index, groups: { captureName } }) => {
      if (namedGroups.has(captureName)) {
        namedGroups.get(captureName).isUnique = false;
      } else {
        const group = { isUnique: true };
        if (includeContents) {
          const contents = getGroupContents(expression, index + m.length);
          Object.assign(group, {
            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) {
  const unescapedLiteralHyphenMsg = 'Invalid unescaped "-" in character class';
  let inCharClass = false;
  let result = "";
  for (const { 0: m, groups: { dp, vOnlyEscape } } of expression.matchAll(token4)) {
    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(expression = "", options = {}) {
  const 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) {
  const opts = {
    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");
  }
  const 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) {
  const preprocessors = [];
  if (!options.disable.x) {
    preprocessors.push(flagXPreprocessor);
  }
  if (!options.disable.n) {
    preprocessors.push(flagNPreprocessor);
  }
  for (const pp of preprocessors) {
    ({ template, substitutions } = preprocess(template, substitutions, pp, options));
  }
  return {
    template,
    substitutions
  };
}
function handlePlugins(expression, options) {
  const { flags, plugins, unicodeSetsPlugin, disable, subclass } = options;
  [
    ...plugins,
    // Run first, so provided plugins can output extended syntax
    ...disable.subroutines ? [] : [subroutinesPlugin],
    ...disable.atomic ? [] : [possessivePlugin, atomicPlugin],
    ...disable.x ? [] : [cleanPlugin],
    // Run last, so it doesn't have to worry about parsing extended syntax
    ...!unicodeSetsPlugin ? [] : [unicodeSetsPlugin]
  ].forEach((p) => expression = p(expression, { flags, useEmulationGroups: subclass }));
  return expression;
}

// node_modules/oniguruma-to-js/dist/shared/oniguruma-to-js.2969e22d.mjs
var __defProp2 = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => {
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};
var RegExpConversionError = class extends SyntaxError {
  constructor(message, options) {
    super(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;
  }
};
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, options = {}) {
  const {
    useRegex = false,
    preserveFlags = false,
    removePossessiveQuantifier = false,
    removeAtomicGroup = false,
    convertHexDigitsShorthand = false,
    convertUnicodeCategory = false,
    expandNestedCharacterClass = false
  } = options;
  let output = "";
  const flags = /* @__PURE__ */ new Set();
  const stack = [];
  const freeSpacingLocal = [];
  let freeSpacingGlobal = false;
  let isInNestedCharClass = false;
  let i = 0;
  try {
    while (i < input.length) {
      const char = input[i];
      while (freeSpacingLocal.length && freeSpacingLocal[0] > stack.length) {
        freeSpacingLocal.shift();
      }
      const head = stack[0];
      const freeSpacing = freeSpacingGlobal || freeSpacingLocal.length;
      if (char === "\\") {
        if (convertHexDigitsShorthand) {
          if (input[i + 1] === "h") {
            const 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] === "{") {
          const end = input.indexOf("}", i + 3);
          if (end === -1) {
            throw new RegExpConversionError(
              "Unmatched \\p{...}",
              { pattern: input, converted: output, cursor: i }
            );
          }
          const name = input.slice(i + 3, end);
          const 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 (let 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 (let 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])) {
            let end = i + 3;
            for (; end < input.length; end++) {
              if (!KNOWN_FLAGS.has(input[end]))
                break;
            }
            const flagStr2 = input.slice(i + 2, end);
            const hasX = flagStr2.includes("x") && flagStr2[0] !== "-";
            let remainFlags = [...flagStr2].filter((x) => x !== "x").join("");
            if (!preserveFlags) {
              if (remainFlags[0] === "-") {
                remainFlags = remainFlags.slice(1);
                for (const flag of flagStr2) {
                  flags.delete(flag);
                }
              } else {
                for (const 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] === ":") {
          let name = "";
          let negated = false;
          if (input[i + 2] === "^") {
            negated = true;
            i += 1;
          }
          for (let j = i + 2; j < input.length; j++) {
            if (input[j] === ":") {
              i = j + 2;
              break;
            }
            if (!input[j].match(/[a-z]/i)) {
              name = "";
              break;
            }
            name += input[j];
          }
          if (name) {
            let 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 }
    );
  }
  const flagStr = [...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, options = {}) {
  const {
    original = pattern2,
    flags = ["g"]
  } = options;
  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 }
    );
  }
  const 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, (m, hex) => `\\u${hex.padStart(4, "0")}`).replace(/\(\?(-)?(\w+):/g, (_, neg, flagStr) => {
    if (neg) {
      for (const flag of flagStr)
        flagSet.delete(flag);
    } else {
      for (const flag of flagStr)
        flagSet.add(flag);
    }
    return "(?:";
  }).replace(/\(\?(-)?(\w+)\)/g, (_, neg, flags2) => {
    if (neg) {
      for (const flag of flags2)
        flagSet.delete(flag);
    } else {
      for (const flag of flags2)
        flagSet.add(flag);
    }
    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, [...flagSet].join(""));
  } catch (e) {
    throw new RegExpConversionError(
      `Failed to construct RegExp`,
      {
        pattern: original,
        converted: pattern2,
        cause: e
      }
    );
  }
}
function onigurumaToRegexp(pattern2, options = {}) {
  const {
    pattern: converted,
    flags
  } = syntaxLowering(pattern2, {
    // removePossessiveQuantifier: false,
    // removeAtomicGroup: false,
    convertHexDigitsShorthand: true,
    convertUnicodeCategory: true,
    useRegex: true,
    expandNestedCharacterClass: true,
    ...options
  });
  return construct(converted, {
    original: pattern2,
    ...options,
    flags: [.../* @__PURE__ */ new Set([...flags, ...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 = (obj, key, value) => key in obj ? __defProp3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __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 = class {
  constructor(patterns, options = {}) {
    this.patterns = patterns;
    this.options = options;
    __publicField2(this, "regexps");
    __publicField2(this, "contiguousAnchorSimulation");
    const {
      forgiving = false,
      cache,
      simulation = true,
      regexConstructor = defaultJavaScriptRegexConstructor
    } = options;
    this.contiguousAnchorSimulation = Array.from({ length: patterns.length }, () => false);
    this.regexps = patterns.map((p, idx) => {
      if (simulation)
        p = p.replaceAll("(^|\\\uFFFF)", "(^|\\G)");
      if (simulation && (p.startsWith("(^|\\G)") || p.startsWith("(\\G|^)")))
        this.contiguousAnchorSimulation[idx] = true;
      const cached = cache?.get(p);
      if (cached) {
        if (cached instanceof RegExp) {
          return cached;
        }
        if (forgiving)
          return null;
        throw cached;
      }
      try {
        let pattern2 = p;
        if (simulation) {
          for (const [from, to] of replacements) {
            pattern2 = pattern2.replaceAll(from, to);
          }
        }
        const regex = regexConstructor(pattern2);
        cache?.set(p, regex);
        return regex;
      } catch (e) {
        cache?.set(p, e);
        if (forgiving)
          return null;
        throw e;
      }
    });
  }
  findNextMatchSync(string, startPosition) {
    const str = typeof string === "string" ? string : string.content;
    const pending = [];
    function toResult(index, match, offset = 0) {
      return {
        index,
        captureIndices: match.indices.map((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 (let i = 0; i < this.regexps.length; i++) {
      const regexp = this.regexps[i];
      if (!regexp)
        continue;
      try {
        let offset = 0;
        regexp.lastIndex = startPosition;
        let 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) {
      const minIndex = Math.min(...pending.map((m) => m[1].index));
      for (const [i, match, offset] of pending) {
        if (match.index === minIndex) {
          return toResult(i, match, offset);
        }
      }
    }
    return null;
  }
};
function createJavaScriptRegexEngine(options = {}) {
  const _options = {
    cache: /* @__PURE__ */ new Map(),
    ...options
  };
  return {
    createScanner(patterns) {
      return new JavaScriptScanner(patterns, _options);
    },
    createString(s) {
      return {
        content: s
      };
    }
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  JavaScriptScanner,
  createJavaScriptRegexEngine,
  defaultJavaScriptRegexConstructor
});
