diff --git a/README.md b/README.md
index 898097a..8b4908b 100644
--- a/README.md
+++ b/README.md
@@ -81,6 +81,8 @@ A string with `i`, `m`, and `x` in any order (all optional).
```ts
type CompileOptions = {
allowBestEffort?: boolean;
+ global?: boolean;
+ hasIndices?: boolean;
maxRecursionDepth?: number | null;
optimize?: boolean;
target?: 'ES2018' | 'ES2024' | 'ESNext';
@@ -96,13 +98,11 @@ Transpiles an Oniguruma regex pattern and flags and returns a native JavaScript
```ts
function toRegExp(
pattern: string,
- flags?: string,
+ flags?: OnigurumaFlags,
options?: CompileOptions
): RegExp;
```
-The `flags` string can be any combination of Oniguruma flags `i`, `m`, and `x`, plus JavaScript flags `d` and `g`. Oniguruma's flag `m` is equivalent to JavaScript's flag `s`. See [Options](#-options) for more details.
-
> [!TIP]
> Try it in the [demo REPL](https://slevithan.github.io/oniguruma-to-es/demo/).
@@ -128,7 +128,7 @@ function toRegexAst(
): RegexAst;
```
-`regex`'s syntax and behavior is a strict superset of native JavaScript, so the AST is very close to representing native ESNext JavaScript `RegExp` but with some added features (atomic groups, possessive quantifiers, recursion). The `regex` AST doesn't use some of `regex`'s extended features like flag `x` or subroutines because they follow PCRE behavior and work somewhat differently than in Oniguruma. The AST represents what's needed to precisely reproduce the Oniguruma behavior using `regex`.
+`regex`'s syntax and behavior is a strict superset of native JavaScript, so the AST is very close to representing native ESNext `RegExp` but with some added features (atomic groups, possessive quantifiers, recursion). The `regex` AST doesn't use some of `regex`'s extended features like flag `x` or subroutines because they follow PCRE behavior and work somewhat differently than in Oniguruma. The AST represents what's needed to precisely reproduce the Oniguruma behavior using `regex`.
## 🔩 Options
@@ -154,6 +154,18 @@ Specifically, this option enables the following additional features, depending o
- Enables use of POSIX classes `[:graph:]` and `[:print:]` using ASCII-based versions rather than the Unicode versions available for `ES2024` and later. Other POSIX classes always use Unicode.
+### `global`
+
+Include JavaScript flag `g` (`global`) in results.
+
+*Default: `false`.*
+
+### `hasIndices`
+
+Include JavaScript flag `d` (`hasIndices`) in results.
+
+*Default: `false`.*
+
### `maxRecursionDepth`
If `null`, any use of recursion throws. If an integer between `2` and `100` (and `allowBestEffort` is `true`), common recursion forms are supported and recurse up to the specified max depth.
@@ -745,7 +757,7 @@ Notice that nearly every feature below has at least subtle differences from Java
✅
● Same behavior as numbered
- ✔ Error if refs a duplicate name
+ ✔ Error if reffed group uses duplicate name
@@ -834,7 +846,7 @@ Notice that nearly every feature below has at least subtle differences from Java
✅
✅
- ✔ [\q{…}]
matches literal q
, etc.
+ ✔ [\q{…}]
matches one of literal q
, {
, etc.
✔ [a--b]
includes the invalid reversed range a
to -
diff --git a/demo/demo.js b/demo/demo.js
index 0e74530..ee0b82a 100644
--- a/demo/demo.js
+++ b/demo/demo.js
@@ -1,15 +1,18 @@
-let useFlagI = getValue('flag-i');
-let useFlagM = getValue('flag-m');
-let useFlagX = getValue('flag-x');
-let optionAllowBestEffortValue = getValue('option-allow-best-effort');
-let optionMaxRecursionDepthValue = getValue('option-max-recursion-depth');
-let optionOptimizeValue = getValue('option-optimize');
-let optionTargetValue = getValue('option-target');
-
-function getValue(id) {
- const el = document.getElementById(id);
- return el.type === 'checkbox' ? el.checked : el.value;
-}
+const state = {
+ flags: {
+ i: getValue('flag-i'),
+ m: getValue('flag-m'),
+ x: getValue('flag-x'),
+ },
+ opts: {
+ allowBestEffort: getValue('option-allow-best-effort'),
+ global: getValue('option-global'),
+ hasIndices: getValue('option-has-indices'),
+ maxRecursionDepth: getValue('option-max-recursion-depth'),
+ optimize: getValue('option-optimize'),
+ target: getValue('option-target'),
+ },
+};
const inputEl = document.getElementById('input');
autoGrow(inputEl);
@@ -17,7 +20,7 @@ showOutput(inputEl);
function showOutput(el) {
const input = el.value;
- const flags = `${useFlagI ? 'i' : ''}${useFlagM ? 'm' : ''}${useFlagX ? 'x' : ''}`;
+ const flags = `${state.flags.i ? 'i' : ''}${state.flags.m ? 'm' : ''}${state.flags.x ? 'x' : ''}`;
const outputEl = document.getElementById('output');
outputEl.classList.remove('error');
let output = '';
@@ -25,10 +28,8 @@ function showOutput(el) {
// Use `compile` but display output as if `toRegExp` was called. This avoids erroring when the
// selected `target` includes features that don't work in the user's browser
const re = OnigurumaToES.compile(input, flags, {
- allowBestEffort: optionAllowBestEffortValue,
- maxRecursionDepth: optionMaxRecursionDepthValue === '' ? null : +optionMaxRecursionDepthValue,
- optimize: optionOptimizeValue,
- target: optionTargetValue,
+ ...state.opts,
+ maxRecursionDepth: state.opts.maxRecursionDepth === '' ? null : +state.opts.maxRecursionDepth,
});
output = `/${getRegExpLiteralPattern(re.pattern)}/${re.flags}`;
} catch (e) {
@@ -51,31 +52,17 @@ function getRegExpLiteralPattern(str) {
return str ? str.replace(/\\?./gsu, m => m === '/' ? '\\/' : m) : '(?:)';
}
-function setFlagI(checked) {
- useFlagI = checked;
- showOutput(inputEl);
-}
-function setFlagM(checked) {
- useFlagM = checked;
- showOutput(inputEl);
-}
-function setFlagX(checked) {
- useFlagX = checked;
- showOutput(inputEl);
-}
-function setOptionAllowBestEffort(checked) {
- optionAllowBestEffortValue = checked;
- showOutput(inputEl);
-}
-function setOptionMaxRecursionDepth(value) {
- optionMaxRecursionDepthValue = value;
- showOutput(inputEl);
+function getValue(id) {
+ const el = document.getElementById(id);
+ return el.type === 'checkbox' ? el.checked : el.value;
}
-function setOptionOptimize(checked) {
- optionOptimizeValue = checked;
+
+function setFlag(flag, value) {
+ state.flags[flag] = value;
showOutput(inputEl);
}
-function setOptionTarget(value) {
- optionTargetValue = value;
+
+function setOption(option, value) {
+ state.opts[option] = value;
showOutput(inputEl);
}
diff --git a/demo/index.html b/demo/index.html
index 8995def..9bda7a3 100644
--- a/demo/index.html
+++ b/demo/index.html
@@ -17,25 +17,25 @@
This is a basic REPL for testing the output of Oniguruma-To-ES , an Oniguruma to JavaScript RegExp transpiler. See Oniguruma syntax for an overview, but there are many subtleties to Oniguruma's differences from JavaScript that aren't shown in the docs.
Try it
-
+
Flags:
-
+
i
-
+
m
(JS flag s
)
-
+
x
target
:
-
+
ES2018
ES2024
ESNext
@@ -45,17 +45,25 @@ Try it
More options
-
+
allowBestEffort
-
+
optimize
-
+
maxRecursionDepth
+
+
+ global
+
+
+
+ hasIndices
+
diff --git a/dist/index.min.js b/dist/index.min.js
index 7fc40c0..15390e2 100644
--- a/dist/index.min.js
+++ b/dist/index.min.js
@@ -32,8 +32,8 @@ var OnigurumaToES=(()=>{var ne=Object.defineProperty;var mt=Object.getOwnPropert
| &&
| .
`.replace(/\s+/g,""),"gsu");function G(e,t=""){if(typeof e!="string")throw new Error("String expected as pattern");if(!/^[imx]*$/.test(t))throw new Error(`Flags "${t}" unsupported in Oniguruma`);let r=[t.includes("x")],s={getCurrentModX:()=>r.at(-1),numOpenGroups:0,popModX(){r.pop()},pushModX(u){r.push(u)},replaceCurrentModX(u){r[r.length-1]=u}},n=[],o;for(J.lastIndex=0;o=J.exec(e);){let u=Nt(s,e,o[0],J.lastIndex);u.tokens?n.push(...u.tokens):u.token&&n.push(u.token),u.lastIndex!==void 0&&(J.lastIndex=u.lastIndex)}let a=[],i=0;n.forEach(u=>{u.type===g.GroupOpen&&(u.kind===_.capturing?(i++,u.number=i):u.raw==="("&&a.push(u))}),i||a.forEach((u,p)=>{u.kind=_.capturing,u.number=p+1});let c=i||a.length;return n=n.map(u=>u.type===g.EscapedNumber?Ut(u,c):u).flat(),{tokens:n,flags:{ignoreCase:t.includes("i"),dotAll:t.includes("m"),extended:t.includes("x")}}}function Nt(e,t,r,s){let[n,o,a]=r;if(n==="["){let i=$t(t,r,s);return{tokens:i.tokens,lastIndex:i.lastIndex}}if(n==="\\")return"AbBGzZ".includes(o)?{token:m(g.Assertion,r,{kind:r})}:/^\\g[<']/.test(r)?{token:m(g.Subroutine,r)}:/^\\k[<']/.test(r)?{token:m(g.Backreference,r)}:o==="K"?{token:m(g.Directive,r,{kind:z.keep})}:"RX".includes(o)?{token:m(g.VariableLengthCharacterSet,r,{kind:r})}:{token:Ge(r,{inCharClass:!1})};if(n==="("){if(a==="#"){if(t[s]!==")")throw new Error('Unclosed comment group "(?#"');return{lastIndex:s+1}}if("-imx".includes(a))return{token:Tt(r,e)};if(e.pushModX(e.getCurrentModX()),e.numOpenGroups++,r==="("||r==="(?:")return{token:m(g.GroupOpen,r,{kind:_.group})};if(r==="(?>")return{token:m(g.GroupOpen,r,{kind:_.atomic})};if(r==="(?="||r==="(?!"||r==="(?<="||r==="(?\^?)(?[a-z]+):\]/.exec(e);if(!t||!X.get(t.groups.name))throw new Error(`Invalid POSIX class "${e}"`);return m(g.CharacterSet,e,{kind:S.posix,negate:!!t.groups.negate,value:t.groups.name})}return e==="-"?m(g.CharacterClassHyphen,e):e==="&&"?m(g.CharacterClassIntersector,e):(Oe(e),m(g.Character,e,{value:e.codePointAt(0)}))}function Ge(e,{inCharClass:t}){let r=e[1];if(r==="c"||r==="C")return Pt(e);if("dDhHsSwW".includes(r))return vt(e);if(/^\\[pP]\{/.test(e)){if(e.length===3)throw new Error("Incomplete or invalid Unicode property");return Rt(e)}if(r==="u"||r==="x")return m(g.Character,e,{value:Dt(e)});if($e.has(r))return m(g.Character,e,{value:$e.get(r)});if(/\d/.test(r))return m(g.EscapedNumber,e,{inCharClass:t});if(e==="\\")throw new Error(f`Incomplete escape "\"`);if(r==="M")throw new Error(`Unsupported meta-code "${e}"`);if(e.length===2)return m(g.Character,e,{value:e.codePointAt(1)});throw new Error(`Invalid multibyte escape "${e}"`)}function m(e,t,r){return{type:e,raw:t,...r}}function Pt(e){let t=e[1]==="c"?e[2]:e[3];if(!t||!/[A-Za-z]/.test(t))throw new Error(`Unsupported control character "${e}"`);return m(g.Character,e,{value:t.toUpperCase().codePointAt(0)-64})}function Tt(e,t){let{on:r,off:s}=/^\(\?(?[imx]*)(?:-(?[imx\-]*))?/.exec(e).groups;s??="";let n=(t.getCurrentModX()||r.includes("x"))&&!s.includes("x"),o=Ie(r),a=Ie(s),i={};if(o&&(i.enable=o),a&&(i.disable=a),e.endsWith(")"))return t.replaceCurrentModX(n),m(g.Directive,e,{kind:z.flags,flags:i});if(e.endsWith(":")){t.pushModX(n),t.numOpenGroups++;let c=m(g.GroupOpen,e,{kind:_.group});return(o||a)&&(c.flags=i),c}throw new Error(`Unexpected flag modifier "${e}"`)}function Lt(e){let t={};if(e[0]==="{"){let{min:r,max:s}=/^\{(?\d+)(?:,(?\d*))?/.exec(e).groups,n=1e5;if(+r>n||+s>n)throw new Error("Quantifier value unsupported in Oniguruma");t.min=+r,t.max=s===void 0?+r:s===""?1/0:+s,t.greedy=!e.endsWith("?"),t.possessive=!1}else t.min=e[0]==="+"?1:0,t.max=e[0]==="?"?1:1/0,t.greedy=e[1]!=="?",t.possessive=e[1]==="+";return m(g.Quantifier,e,t)}function vt(e){let t=e[1].toLowerCase();return m(g.CharacterSet,e,{kind:{d:S.digit,h:S.hex,s:S.space,w:S.word}[t],negate:e[1]!==t})}function Rt(e){let{p:t,neg:r,value:s}=/^\\(?[pP])\{(?\^?)(?[ \w]+)/.exec(e).groups,n=t==="P"&&!r||t==="p"&&!!r;return m(g.CharacterSet,e,{kind:S.property,negate:n,value:s})}function Dt(e){if(/^(?:\\x$|\\u(?!\p{AHex}{4}|\{\s*\p{AHex}{1,6}\s*\}))/u.test(e))throw new Error(`Incomplete or invalid escape "${e}"`);let t=e[2]==="{"?/^\\u\{\s*(?\p{AHex}+)/u.exec(e).groups.hex:e.slice(2),r=parseInt(t,16);if(r>1114111)throw new Error(`Invalid escape out of range "${e}"`);return r}function Ie(e){let t={};return e.includes("i")&&(t.ignoreCase=!0),e.includes("m")&&(t.dotAll=!0),e.includes("x")&&(t.extended=!0),Object.keys(t).length?t:null}function Ut(e,t){let{raw:r,inCharClass:s}=e,n=r.slice(1);if(!s&&(n!=="0"&&n.length===1||n[0]!=="0"&&+n<=t))return[m(g.Backreference,r)];let o=[],a=n.match(/^[0-7]+|\d/g);for(let i=0;i!!r[F]),w=h&&r[h],y=typeof w=="function"?w:w?.enter,b=w?.exit;if(y?.(C,t),!d)switch(a.type){case l.Regex:o(a.pattern,a,"pattern"),o(a.flags,a,"flags");break;case l.Alternative:case l.CharacterClass:n(a.elements,a);break;case l.Assertion:R(a)&&n(a.alternatives,a);break;case l.Backreference:case l.Character:case l.CharacterSet:case l.Directive:case l.Flags:case l.Recursion:case l.Subroutine:case l.VariableLengthCharacterSet:break;case l.CapturingGroup:case l.Group:case l.Pattern:n(a.alternatives,a);break;case l.CharacterClassIntersection:n(a.classes,a);break;case l.CharacterClassRange:o(a.min,a,"min"),o(a.max,a,"max");break;case l.Quantifier:o(a.element,a,"element");break;default:throw new Error(`Unexpected node type "${a.type}"`)}return b?.(C,t),p}o(e.node,e.parent,e.key,e.container)}function Gt(e,t){"parent"in t&&(e.parent=t)}var l={Alternative:"Alternative",Assertion:"Assertion",Backreference:"Backreference",CapturingGroup:"CapturingGroup",Character:"Character",CharacterClass:"CharacterClass",CharacterClassIntersection:"CharacterClassIntersection",CharacterClassRange:"CharacterClassRange",CharacterSet:"CharacterSet",Directive:"Directive",Flags:"Flags",Group:"Group",Pattern:"Pattern",Quantifier:"Quantifier",Regex:"Regex",Subroutine:"Subroutine",VariableLengthCharacterSet:"VariableLengthCharacterSet",Recursion:"Recursion"},Be={AnyGroup:"AnyGroup",AnyNode:"AnyNode"};function Me(e){let{type:t}=e,r=[Be.AnyNode];return(R(e)||t===l.CapturingGroup||t===l.Group)&&r.push(Be.AnyGroup),r.push(t),r}var E={line_end:"line_end",line_start:"line_start",lookahead:"lookahead",lookbehind:"lookbehind",search_start:"search_start",string_end:"string_end",string_end_newline:"string_end_newline",string_start:"string_start",word_boundary:"word_boundary"},x=S,D=z,H={grapheme:"grapheme",newline:"newline"};function O({tokens:e,flags:t},r){let s={bypassPropertyNameCheck:!1,optimize:!0,...r},n={bypassPropertyNameCheck:s.bypassPropertyNameCheck,capturingGroups:[],current:0,hasNumberedRef:!1,namedGroupsByName:new Map,optimize:s.optimize,parent:null,subroutines:[],token:null,tokens:e,walk:o};function o(C,h){let w=e[n.current];switch(n.parent=C,n.token=w,n.current++,w.type){case g.Alternator:return P();case g.Assertion:return Ke(w);case g.Backreference:return Ot(n);case g.Character:return ze(w.value);case g.CharacterClassHyphen:return Mt(n,h);case g.CharacterClassOpen:return Bt(n,h);case g.CharacterSet:return Vt(n);case g.Directive:return Xt(w);case g.GroupOpen:return jt(n,h);case g.Quantifier:return Kt(n);case g.Subroutine:return zt(n);case g.VariableLengthCharacterSet:return rr(w.kind);default:throw new Error(`Unexpected token type "${w.type}"`)}}let a=er(Zt(),Jt(t)),i=a.pattern.alternatives[0];for(;n.currentc.length)throw new Error("Subroutine uses a group number that's not defined")}else if(p.has(C)){if(p.get(C).length>1)throw new Error(f`Subroutine uses a duplicate group name "\g<${C}>"`)}else throw new Error(f`Subroutine uses a group name that's not defined "\g<${C}>"`);return $({node:a},null,{AnyNode({node:C,parent:h}){C.parent=h}}),a}function Ot(e){let{raw:t}=e.token,r=/^\\k[<']/.test(t),s=r?t.slice(3,-1):t.slice(1),n=(o,a=!1)=>{let i=e.capturingGroups.length;if(o>i)throw new Error(`Not enough capturing groups defined to the left "${t}"`);return e.hasNumberedRef=!0,Z(a?i+1-o:o)};if(r){let o=/^(?-?)0*(?[1-9]\d*)$/.exec(s);if(o)return n(+o.groups.num,!!o.groups.sign);if(/[-+]/.test(s))throw new Error(`Invalid backref name "${t}"`);if(!e.namedGroupsByName.has(s))throw new Error(`Group name not defined to the left "${t}"`);return Z(s)}return n(+s)}function Mt(e,t){let{parent:r,tokens:s,walk:n}=e,o=r.elements.at(-1),a=s[e.current];if(o&&o.type!==l.CharacterClass&&a&&a.type!==g.CharacterClassOpen&&a.type!==g.CharacterClassClose&&a.type!==g.CharacterClassIntersector){let i=n(r,t);if(o.type===l.Character&&i.type===l.Character)return r.elements.pop(),qt(o,i);throw new Error("Invalid character class range")}return ze(45)}function Bt(e,t){let{token:r,tokens:s,optimize:n,walk:o}=e,a=fe({negate:r.negate}),i=a.elements[0],c=Ve(s[e.current]);for(;c.type!==g.CharacterClassClose;){if(c.type===g.CharacterClassIntersector)i.classes.push(fe({negate:!1,baseOnly:!0})),e.current++;else{let u=i.classes.at(-1);u.elements.push(o(u,t))}c=Ve(s[e.current])}if(n&&or(i),i.classes.length===1){let u=i.classes[0];u.negate=a.negate!==u.negate,a=u}return e.current++,a}function Vt({token:e,bypassPropertyNameCheck:t}){let{kind:r,negate:s,value:n}=e;if(r===S.property){let a=K(n);if(Ne.has(a))r=S.posix,n=a;else return ge(n,{negate:s,allowAnyName:t})}let o={type:l.CharacterSet,kind:N(x[r],`Unexpected character set kind "${r}"`)};return(r===S.digit||r===S.hex||r===S.posix||r===S.space||r===S.word)&&(o.negate=s,r===S.posix&&(o.value=n)),o}function jt(e,t){let{token:r,tokens:s,optimize:n,capturingGroups:o,namedGroupsByName:a,walk:i}=e,c=Ht(r);c.type===l.CapturingGroup&&(o.push(c),c.name&&L(a,c.name,[]).push(c));let u=je(s[e.current]);for(;u.type!==g.GroupClose;){if(u.type===g.Alternator)c.alternatives.push(P()),e.current++;else{let p=c.alternatives.at(-1);t.isInLookbehind||=c.kind===E.lookbehind;let d=i(p,t);if(p.elements.push(d),t.isInLookbehind&&d.type===l.Quantifier&&d.min!==d.max)throw new Error("Variable repetition within lookbehind unsupported in Oniguruma")}u=je(s[e.current])}return n&&(c=sr(c)),e.current++,c}function Kt({token:e,parent:t}){let{min:r,max:s,greedy:n,possessive:o}=e,a=t.elements.at(-1);if(!a||a.type===l.Directive)throw new Error("Quantifier requires a repeatable token");let i=Yt(a,r,s,n,o);return t.elements.pop(),i}function zt(e){let{token:t,capturingGroups:r,subroutines:s}=e,n=t.raw.slice(3,-1),o=/^(?[-+]?)0*(?[1-9]\d*)$/.exec(n);if(o){let i=+o.groups.num,c=r.length;if(e.hasNumberedRef=!0,n={"":i,"+":c+i,"-":c+1-i}[o.groups.sign],n<1)throw new Error("Invalid subroutine number")}else n==="0"&&(n=0);let a=tr(n);return s.push(a),a}function P(){return{type:l.Alternative,elements:[]}}function Ke({type:e,kind:t,negate:r}){if(e===g.GroupOpen)return Q({behind:t===_.lookbehind,negate:r});let s=N({"^":E.line_start,$:E.line_end,"\\A":E.string_start,"\\b":E.word_boundary,"\\B":E.word_boundary,"\\G":E.search_start,"\\z":E.string_end,"\\Z":E.string_end_newline}[t],`Unexpected assertion kind "${t}"`),n={type:l.Assertion,kind:s};return s===E.word_boundary&&(n.negate=t===f`\B`),n}function Z(e){return{type:l.Backreference,ref:e}}function Ht(e){let{kind:t,number:r,name:s,flags:n}=e;switch(t){case _.atomic:return I({atomic:!0});case _.capturing:return Qt(r,s);case _.group:return I({flags:n});case _.lookahead:case _.lookbehind:return Ke(e);default:throw new Error(`Unexpected group kind "${t}"`)}}function Qt(e,t){let r=t!==void 0;if(r&&!ar(t))throw new Error(`Group name "${t}" invalid in Oniguruma`);return{type:l.CapturingGroup,number:e,...r&&{name:t},alternatives:[P()]}}function ze(e){return{type:l.Character,value:e}}function fe(e){let t={baseOnly:!1,negate:!1,...e};return{type:l.CharacterClass,negate:t.negate,elements:t.baseOnly?[]:[Wt()]}}function Wt(){return{type:l.CharacterClassIntersection,classes:[fe({negate:!1,baseOnly:!0})]}}function qt(e,t){if(t.values[0].toUpperCase()+s.slice(1).toLowerCase())}function sr(e){let t=e.alternatives[0],r=t.elements[0];return e.type===l.Group&&e.alternatives.length===1&&t.elements.length===1&&r.type===l.Group&&!(e.atomic&&r.flags)&&!(e.flags&&(r.atomic||r.flags))?(e.atomic?r.atomic=!0:e.flags&&(r.flags=e.flags),r):e}function R({type:e,kind:t}){return e===l.Assertion&&(t===E.lookahead||t===E.lookbehind)}function ar(e){return!/^(?:[-\d]|$)/.test(e)}function or(e){for(let t=0;to.kind===D.flags);for(let o=r+1;o1)throw new Error(f`Uses "\K" in a way that's unsupported for conversion to JS`);a(W(Q({behind:!0}),i()))}},Flags({node:e,parent:t}){delete e.extended,Object.assign(e,{global:!1,hasIndices:!1,multiline:!1,sticky:e.sticky??!1}),t.options={disable:{x:!0,n:!0},force:{v:!0}}},Group({node:e}){if(!e.flags)return;let{enable:t,disable:r}=e.flags;t?.extended&&delete t.extended,r?.extended&&delete r.extended,t?.dotAll&&r?.dotAll&&delete t.dotAll,t?.ignoreCase&&r?.ignoreCase&&delete t.ignoreCase,t&&!Object.keys(t).length&&delete e.flags.enable,r&&!Object.keys(r).length&&delete e.flags.disable,!e.flags.enable&&!e.flags.disable&&delete e.flags},Pattern({node:e}){let t=!1,r=!1;for(let s of e.alternatives)s.elements.sort((n,o)=>n.kind===E.search_start&&o.kind===D.flags?-1:n.kind===D.flags&&o.kind===E.search_start?1:0),s.elements[0]?.kind===E.search_start?t=!0:r=!0;if(t&&r)throw new Error(f`Uses "\G" in a way that's unsupported for conversion to JS`)},Quantifier(e,t){let{node:r,remove:s,replaceWith:n,skip:o}=e,a=r.element;if(a.type===l.Quantifier){let i=W(I(),[r.element]);i.parent=r,r.element=i}else if(a.type===l.Assertion){let i=R(a);if(!r.min&&i){let c=P();c.parent=a,a.alternatives.push(c)}r.min||i?(n(a),he(a,e,t,de),o()):(s(),o())}},VariableLengthCharacterSet({node:e,replaceWith:t},{allowBestEffort:r,minTargetEs2024:s}){let{kind:n}=e;if(n===H.newline)t(T(f`(?>\r\n?|[\n\v\f\x85\u2028\u2029])`));else if(n===H.grapheme){if(!r)throw new Error(f`Use of "\X" requires option allowBestEffort`);let o=s?f`\p{RGI_Emoji}`:ye().source;t(T(f`(?>\r\n|${o}|\P{M}\p{M}*)`,{bypassPropertyNameCheck:!0}))}else throw new Error(`Unexpected varcharset kind "${n}"`)}},Qe={Alternative({node:e},{namedGroupsInScopeByAlt:t}){let r=Y(e);if(r){let s=t.get(r);s&&t.set(e,s)}},Backreference({node:e},{multiplexCapturesToLeftByRef:t,reffedNodesByBackreference:r}){let{ref:s}=e;r.set(e,[...t.get(s).map(({node:n})=>n)])},CapturingGroup:{enter({node:e,replaceWith:t,skip:r},{groupOriginByCopy:s,groupsWithDuplicateNamesToRemove:n,multiplexCapturesToLeftByRef:o,namedGroupsInScopeByAlt:a,openDirectCaptures:i,openSubroutineRefs:c}){let{name:u,number:p}=e,d=u??p,C=s.get(e),h=Y(e);if(c.has(d))throw new Error("Unsupported indirect recursion");if(C?c.add(d):i.add(e),i.has(C)){t(He(d)),r();return}let w=L(o,d,[]);for(let y=0;yd.type===l.Group&&!!d.flags)),p=u?U(t.globalFlags,u):t.globalFlags;cr(p,t.currentFlags)||(c=W(I({flags:ur(p)}),[i]))}s(c),a||he(c,e,t,Qe)}},ir={Backreference({node:e,replaceWith:t},{reffedNodesByBackreference:r}){let s=r.get(e),n=qe(e,o=>o.type===l.CapturingGroup);if(s.length>1){let o=s.map(a=>ee(P(),[n.some(i=>i.number===a.number)?Q({negate:!0}):Z(a.number)]));t(ee(I(),o))}else e.ref=s[0].number,n.some(o=>o.number===e.ref)&&t(Q({negate:!0}))},CapturingGroup({node:e},t){e.number=++t.numCapturesToLeft,t.groupsWithDuplicateNamesToRemove.has(e)&&delete e.name}};function ee(e,t){return t.forEach(r=>r.parent=e),e[Xe(e)]=t,e}function cr(e,t){return e.dotAll===t.dotAll&&e.ignoreCase===t.ignoreCase}function We(e,t,r,s){let n=Array.isArray(e)?[]:{};for(let[o,a]of Object.entries(e))o==="parent"?n.parent=Array.isArray(r)?s:r:a&&typeof a=="object"?n[o]=We(a,t,n,r):(o==="type"&&a===l.CapturingGroup&&t.set(n,t.get(e)??e),n[o]=a);return n}function He(e){if(typeof e=="number"&&e!==0)throw new Error("Unsupported recursion by number; use name instead");return{type:l.Recursion,ref:e}}function qe(e,t){let r=[];for(;e=e.parent;)(!t||t(e))&&r.push(e);return r}function Xe(e){if(e.alternatives)return"alternatives";if(e.elements)return"elements";if(e.classes)return"classes";throw new Error("Accessor for child container unknown")}function Je(e){let t=["dotAll","ignoreCase"],r={enable:{},disable:{}};return e.forEach(({flags:s})=>{t.forEach(n=>{s.enable?.[n]&&(delete r.disable[n],r.enable[n]=!0),s.disable?.[n]&&(r.disable[n]=!0)})}),Object.keys(r.enable).length||delete r.enable,Object.keys(r.disable).length||delete r.disable,r.enable||r.disable?r:null}function ur({dotAll:e,ignoreCase:t}){let r={};return(e||t)&&(r.enable={},e&&(r.enable.dotAll=!0),t&&(r.enable.ignoreCase=!0)),(!e||!t)&&(r.disable={},!e&&(r.disable.dotAll=!0),!t&&(r.disable.ignoreCase=!0)),r}function Y(e){for(;e=e.parent;)if(e.type===l.Alternative)return e;return null}function lr(e){return/^[$_\p{IDS}][$\u200C\u200D\p{IDC}]*$/u.test(e)}function T(e,{bypassPropertyNameCheck:t}={}){let s=O(G(e),{bypassPropertyNameCheck:t}).pattern.alternatives;return s.length>1||s[0].elements.length>1?ee(I(),s):s[0].elements[0]}function W(e,t){let r=Xe(e);return e[r][0].parent=e,t&&ee(e[r][0],t),e}function he(e,{parent:t,key:r,container:s},n,o){$({node:e,parent:t,key:r,container:s},n,o)}function Ye(e,t){let r=me(t),s=j(r.target,"ES2024"),n=j(r.target,"ESNext"),o=r.maxRecursionDepth;if(o!==null&&(!Number.isInteger(o)||o<2||o>100))throw new Error("Invalid maxRecursionDepth; use null or 2-100");let a=null,i=null;if(!n){let h=[e.flags.ignoreCase];$({node:e},{getCurrentModI:()=>h.at(-1),popModI(){h.pop()},pushModI(w){h.push(w)},setHasCasedChar(){h.at(-1)?a=!0:i=!0}},pr)}let c={dotAll:e.flags.dotAll,ignoreCase:!!((e.flags.ignoreCase||a)&&!i)},u=null,p={allowBestEffort:r.allowBestEffort,appliedGlobalFlags:c,captureFlagIMap:new Map,currentFlags:{dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},groupNames:new Set,inCharClass:!1,lastNode:u,maxRecursionDepth:o,optimize:r.optimize,useAppliedIgnoreCase:!!(!n&&a&&i),useDuplicateNames:n,useFlagMods:n,useFlagV:s,usePostEs2018Properties:s};function d(h){switch(p.lastNode=u,u=h,h.type){case l.Regex:return{pattern:d(h.pattern),flags:d(h.flags),options:{...h.options}};case l.Alternative:return h.elements.map(d).join("");case l.Assertion:return Cr(h,p,d);case l.Backreference:return mr(h,p);case l.CapturingGroup:return Er(h,p,d);case l.Character:return wr(h,p);case l.CharacterClass:return Ar(h,p,d);case l.CharacterClassIntersection:if(!p.useFlagV)throw new Error("Use of class intersection requires target ES2024 or later");return h.classes.map(d).join("&&");case l.CharacterClassRange:return Sr(h,p);case l.CharacterSet:return _r(h,p);case l.Flags:return kr(h,p);case l.Group:return br(h,p,d);case l.Pattern:return h.alternatives.map(d).join("|");case l.Quantifier:return d(h.element)+Nr(h);case l.Recursion:return xr(h,p);default:throw new Error(`Unexpected node type "${h.type}"`)}}let C=d(e);return s||(delete C.options.force.v,C.options.disable.v=!0,C.options.unicodeSetsPlugin=null),C}var pr={AnyGroup:{enter({node:e},t){let r=t.getCurrentModI();t.pushModI(e.flags?U({ignoreCase:r},e.flags).ignoreCase:r)},exit(e,t){t.popModI()}},Backreference(e,t){t.setHasCasedChar()},Character({node:e},t){Ce(A(e.value))&&t.setHasCasedChar()},CharacterClassRange({node:e,skip:t},r){t(),et(e,{firstOnly:!0}).length&&r.setHasCasedChar()},CharacterSet({node:e},t){e.kind===x.property&&le.has(e.value)&&t.setHasCasedChar()}},fr=new Set(["$","(",")","*","+",".","?","[","\\","]","^","{","|","}"]),gr=new Set(["-","\\","]","^"]),dr=new Set(["(",")","-","/","[","\\","]","^","{","|","}","!","#","$","%","&","*","+",",",".",":",";","<","=",">","?","@","`","~"]),Ze=new Map([[9,f`\t`],[10,f`\n`],[11,f`\v`],[12,f`\f`],[13,f`\r`],[8232,f`\u2028`],[8233,f`\u2029`]]),hr=/^\p{Cased}$/u;function Ce(e){return hr.test(e)}function Cr(e,t,r){let{kind:s,negate:n,alternatives:o}=e;if(R(e))return`(?${`${s===E.lookahead?"":"<"}${n?"!":"="}`}${o.map(r).join("|")})`;if(s===E.string_end)return"$";if(s===E.string_start)return"^";throw new Error(`Unexpected assertion kind "${s}"`)}function mr({ref:e},t){if(typeof e!="number")throw new Error("Unexpected named backref in transformed AST");if(!t.useFlagMods&&!t.allowBestEffort&&t.currentFlags.ignoreCase&&!t.captureFlagIMap.get(e))throw new Error("Use of case-insensitive backref to case-sensitive group requires option allowBestEffort or target ESNext");return"\\"+e}function Er({name:e,number:t,alternatives:r},s,n){return e&&(s.groupNames.has(e)?s.useDuplicateNames||(e=null):s.groupNames.add(e)),s.captureFlagIMap.set(t,s.currentFlags.ignoreCase),`(${e?`?<${e}>`:""}${r.map(n).join("|")})`}function wr({value:e},t){let r=A(e),s=M(e,{isAfterBackref:t.lastNode.type===l.Backreference,inCharClass:t.inCharClass,useFlagV:t.useFlagV});if(s!==r)return s;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&Ce(r)){let n=oe(r);return t.inCharClass?n.join(""):n.length>1?`[${n.join("")}]`:n[0]}return r}function Ar({negate:e,parent:t,elements:r},s,n){if(!e&&(!s.useFlagV||s.optimize)&&t.type===l.CharacterClass&&r[0].type!==l.CharacterClassIntersection||s.optimize&&t.type===l.CharacterClassIntersection&&r.length===1&&r[0].type!==l.CharacterClassRange)return r.map(n).join("");if(!s.useFlagV&&t.type===l.CharacterClass)throw new Error("Use of nested character class requires target ES2024 or later");s.inCharClass=!0;let o=`[${e?"^":""}${r.map(n).join("")}]`;return s.inCharClass=!1,o}function Sr(e,t){let r=e.min.value,s=e.max.value,n={isAfterBackref:!1,inCharClass:!0,useFlagV:t.useFlagV},o=M(r,n),a=M(s,n),i="";if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase){let c=et(e);yr(c).forEach(p=>{i+=Array.isArray(p)?`${M(p[0],n)}-${M(p[1],n)}`:M(p,n)})}return`${o}-${a}${i}`}function _r({kind:e,negate:t,value:r,key:s},n){if(e===x.any)return n.currentFlags.dotAll?n.appliedGlobalFlags.dotAll||n.useFlagMods?".":"[^]":f`[^\n]`;if(e===x.digit)return t?f`\D`:f`\d`;if(e===x.property){if(!n.usePostEs2018Properties&&Fe.has(r))throw new Error(`Unicode property "${r}" unavailable in target ES2018`);if(n.useAppliedIgnoreCase&&n.currentFlags.ignoreCase&&le.has(r))throw new Error(`Unicode property "${r}" can't be case-insensitive when other chars have specific case`);return`${t?f`\P`:f`\p`}{${s?`${s}=`:""}${r}}`}if(e===x.word)return t?f`\W`:f`\w`;throw new Error(`Unexpected character set kind "${e}"`)}function kr(e,t){return(t.appliedGlobalFlags.ignoreCase?"i":"")+(e.dotAll?"s":"")+(e.sticky?"y":"")}function br({atomic:e,flags:t,parent:r,alternatives:s},n,o){let a=n.currentFlags;t&&(n.currentFlags=U(a,t));let i=s.map(o).join("|"),c=n.optimize&&s.length===1&&r.type!==l.Quantifier&&!e&&(!n.useFlagMods||!t)?i:`(?${Fr(e,t,n.useFlagMods)}${i})`;return n.currentFlags=a,c}function xr({ref:e},t){let r=t.maxRecursionDepth;if(!r)throw new Error("Use of recursion disabled");if(!t.allowBestEffort)throw new Error("Use of recursion requires option allowBestEffort");return e===0?`(?R=${r})`:f`\g<${e}&R=${r}>`}function et(e,{firstOnly:t}={}){let r=e.min.value,s=e.max.value,n=[];if(r<65&&(s===65535||s>=131071)||r===65536&&s>=131071)return n;for(let o=r;o<=s;o++){let a=A(o);if(!Ce(a))continue;let i=oe(a).filter(c=>{let u=c.codePointAt(0);return us});if(i.length&&(n.push(...i),t))break}return n}function M(e,{isAfterBackref:t,inCharClass:r,useFlagV:s}){if(Ze.has(e))return Ze.get(e);if(e<32||e>126&&e<160||e>262143||t&&$r(e))return e>255?f`\u{${e.toString(16).toUpperCase()}}`:f`\x${e.toString(16).toUpperCase().padStart(2,"0")}`;let n=r?s?dr:gr:fr,o=A(e);return(n.has(o)?"\\":"")+o}function yr(e){let t=e.map(n=>n.codePointAt(0)).sort((n,o)=>n-o),r=[],s=null;for(let n=0;n";let s="";if(t&&r){let{enable:n,disable:o}=t;s=(n?.ignoreCase?"i":"")+(n?.dotAll?"s":"")+(o?"-":"")+(o?.ignoreCase?"i":"")+(o?.dotAll?"s":"")}return`${s}:`}function Nr({min:e,max:t,greedy:r,possessive:s}){let n;return!e&&t===1?n="?":!e&&t===1/0?n="*":e===1&&t===1/0?n="+":e===t?n=`{${e}}`:n=`{${e},${t===1/0?"":t}}`,n+(s?"+":r?"":"?")}function $r(e){return e>47&&e<58}var k=Object.freeze({DEFAULT:"DEFAULT",CHAR_CLASS:"CHAR_CLASS"});function B(e,t,r,s){let n=new RegExp(String.raw`${t}|(?<$skip>\[\^?|\\?.)`,"gsu"),o=[!1],a=0,i="";for(let c of e.matchAll(n)){let{0:u,groups:{$skip:p}}=c;if(!p&&(!s||s===k.DEFAULT==!a)){r instanceof Function?i+=r(c,{context:a?k.CHAR_CLASS:k.DEFAULT,negated:o[o.length-1]}):i+=r;continue}u[0]==="["?(a++,o.push(u[1]==="^")):u==="]"&&a&&(a--,o.pop()),i+=u}return i}function Ee(e,t,r,s){B(e,t,r,s)}function Ir(e,t,r=0,s){if(!new RegExp(t,"su").test(e))return null;let n=new RegExp(`${t}|(?<$skip>\\\\?.)`,"gsu");n.lastIndex=r;let o=0,a;for(;a=n.exec(e);){let{0:i,groups:{$skip:c}}=a;if(!c&&(!s||s===k.DEFAULT==!o))return a;i==="["?o++:i==="]"&&o&&o--,n.lastIndex==a.index&&n.lastIndex++}return null}function V(e,t,r){return!!Ir(e,t,0,r)}function tt(e,t){let r=/\\?./gsu;r.lastIndex=t;let s=e.length,n=0,o=1,a;for(;a=r.exec(e);){let[i]=a;if(i==="[")n++;else if(n)i==="]"&&n--;else if(i==="(")o++;else if(i===")"&&(o--,!o)){s=a.index;break}}return e.slice(t,s)}var rt={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"},we={DEFAULT:"DEFAULT",ENCLOSED_P:"ENCLOSED_P",ENCLOSED_Q:"ENCLOSED_Q",ENCLOSED_U:"ENCLOSED_U",INVALID_INCOMPLETE_TOKEN:"INVALID_INCOMPLETE_TOKEN",RANGE:"RANGE"},wn=new Set([rt.ENCLOSED_P,rt.ENCLOSED_U]),An=new Set([we.ENCLOSED_P,we.ENCLOSED_Q,we.ENCLOSED_U]),Sn=(()=>{try{new RegExp("(?i:)")}catch{return!1}return!0})(),_n=(()=>{try{new RegExp("","v")}catch{return!1}return!0})(),nt="$E$";var Pr=String.raw`\(\?<(?![=!])(?[^>]+)>`,kn=String.raw`\((?!\?)(?!(?<=\(\?\()DEFINE\))|${Pr}`,st=String.raw`\(\?(?:[:=!>A-Za-z\-]|<[=!]|\(DEFINE\))`;var Tr=["Basic_Emoji","Emoji_Keycap_Sequence","RGI_Emoji_Modifier_Sequence","RGI_Emoji_Flag_Sequence","RGI_Emoji_Tag_Sequence","RGI_Emoji_ZWJ_Sequence","RGI_Emoji"].join("|"),bn=new RegExp(String.raw`
+`,s);return{lastIndex:i===-1?t.length:i}}if(/^\s$/.test(r)&&e.getCurrentModX()){let i=/\s+/y;return i.lastIndex=s,{lastIndex:i.exec(t)?i.lastIndex:s}}return r==="."?{token:m(g.CharacterSet,r,{kind:S.any})}:r==="^"||r==="$"?{token:m(g.Assertion,r,{kind:r})}:r==="|"?{token:m(g.Alternator,r)}:Ue.test(r)?{token:Lt(r)}:(Oe(r),{token:m(g.Character,r,{value:r.codePointAt(0)})})}function $t(e,t,r){Pe(t);let s=[m(g.CharacterClassOpen,t,{negate:t[1]==="^"})],n=1,o;for(pe.lastIndex=r;o=pe.exec(e);){let a=o[0];if(a[0]==="["&&a[1]!==":")Pe(a),n++,s.push(m(g.CharacterClassOpen,a,{negate:a[1]==="^"}));else if(a==="]"){if(n--,s.push(m(g.CharacterClassClose,a)),!n)break}else s.push(It(a))}return{tokens:s,lastIndex:pe.lastIndex||e.length}}function It(e){if(e[0]==="\\")return Ge(e,{inCharClass:!0});if(e[0]==="["){let t=/\[:(?\^?)(?[a-z]+):\]/.exec(e);if(!t||!X.get(t.groups.name))throw new Error(`Invalid POSIX class "${e}"`);return m(g.CharacterSet,e,{kind:S.posix,negate:!!t.groups.negate,value:t.groups.name})}return e==="-"?m(g.CharacterClassHyphen,e):e==="&&"?m(g.CharacterClassIntersector,e):(Oe(e),m(g.Character,e,{value:e.codePointAt(0)}))}function Ge(e,{inCharClass:t}){let r=e[1];if(r==="c"||r==="C")return Pt(e);if("dDhHsSwW".includes(r))return vt(e);if(/^\\[pP]\{/.test(e)){if(e.length===3)throw new Error("Incomplete or invalid Unicode property");return Rt(e)}if(r==="u"||r==="x")return m(g.Character,e,{value:Dt(e)});if($e.has(r))return m(g.Character,e,{value:$e.get(r)});if(/\d/.test(r))return m(g.EscapedNumber,e,{inCharClass:t});if(e==="\\")throw new Error(f`Incomplete escape "\"`);if(r==="M")throw new Error(`Unsupported meta-code "${e}"`);if(e.length===2)return m(g.Character,e,{value:e.codePointAt(1)});throw new Error(`Invalid multibyte escape "${e}"`)}function m(e,t,r){return{type:e,raw:t,...r}}function Pt(e){let t=e[1]==="c"?e[2]:e[3];if(!t||!/[A-Za-z]/.test(t))throw new Error(`Unsupported control character "${e}"`);return m(g.Character,e,{value:t.toUpperCase().codePointAt(0)-64})}function Tt(e,t){let{on:r,off:s}=/^\(\?(?[imx]*)(?:-(?[imx\-]*))?/.exec(e).groups;s??="";let n=(t.getCurrentModX()||r.includes("x"))&&!s.includes("x"),o=Ie(r),a=Ie(s),i={};if(o&&(i.enable=o),a&&(i.disable=a),e.endsWith(")"))return t.replaceCurrentModX(n),m(g.Directive,e,{kind:z.flags,flags:i});if(e.endsWith(":")){t.pushModX(n),t.numOpenGroups++;let c=m(g.GroupOpen,e,{kind:_.group});return(o||a)&&(c.flags=i),c}throw new Error(`Unexpected flag modifier "${e}"`)}function Lt(e){let t={};if(e[0]==="{"){let{min:r,max:s}=/^\{(?\d+)(?:,(?\d*))?/.exec(e).groups,n=1e5;if(+r>n||+s>n)throw new Error("Quantifier value unsupported in Oniguruma");t.min=+r,t.max=s===void 0?+r:s===""?1/0:+s,t.greedy=!e.endsWith("?"),t.possessive=!1}else t.min=e[0]==="+"?1:0,t.max=e[0]==="?"?1:1/0,t.greedy=e[1]!=="?",t.possessive=e[1]==="+";return m(g.Quantifier,e,t)}function vt(e){let t=e[1].toLowerCase();return m(g.CharacterSet,e,{kind:{d:S.digit,h:S.hex,s:S.space,w:S.word}[t],negate:e[1]!==t})}function Rt(e){let{p:t,neg:r,value:s}=/^\\(?[pP])\{(?\^?)(?[ \w]+)/.exec(e).groups,n=t==="P"&&!r||t==="p"&&!!r;return m(g.CharacterSet,e,{kind:S.property,negate:n,value:s})}function Dt(e){if(/^(?:\\x$|\\u(?!\p{AHex}{4}|\{\s*\p{AHex}{1,6}\s*\}))/u.test(e))throw new Error(`Incomplete or invalid escape "${e}"`);let t=e[2]==="{"?/^\\u\{\s*(?\p{AHex}+)/u.exec(e).groups.hex:e.slice(2),r=parseInt(t,16);if(r>1114111)throw new Error(`Invalid escape out of range "${e}"`);return r}function Ie(e){let t={};return e.includes("i")&&(t.ignoreCase=!0),e.includes("m")&&(t.dotAll=!0),e.includes("x")&&(t.extended=!0),Object.keys(t).length?t:null}function Ut(e,t){let{raw:r,inCharClass:s}=e,n=r.slice(1);if(!s&&(n!=="0"&&n.length===1||n[0]!=="0"&&+n<=t))return[m(g.Backreference,r)];let o=[],a=n.match(/^[0-7]+|\d/g);for(let i=0;i!!r[F]),w=d&&r[d],y=typeof w=="function"?w:w?.enter,b=w?.exit;if(y?.(C,t),!h)switch(a.type){case l.Regex:o(a.pattern,a,"pattern"),o(a.flags,a,"flags");break;case l.Alternative:case l.CharacterClass:n(a.elements,a);break;case l.Assertion:R(a)&&n(a.alternatives,a);break;case l.Backreference:case l.Character:case l.CharacterSet:case l.Directive:case l.Flags:case l.Recursion:case l.Subroutine:case l.VariableLengthCharacterSet:break;case l.CapturingGroup:case l.Group:case l.Pattern:n(a.alternatives,a);break;case l.CharacterClassIntersection:n(a.classes,a);break;case l.CharacterClassRange:o(a.min,a,"min"),o(a.max,a,"max");break;case l.Quantifier:o(a.element,a,"element");break;default:throw new Error(`Unexpected node type "${a.type}"`)}return b?.(C,t),p}o(e.node,e.parent,e.key,e.container)}function Gt(e,t){"parent"in t&&(e.parent=t)}var l={Alternative:"Alternative",Assertion:"Assertion",Backreference:"Backreference",CapturingGroup:"CapturingGroup",Character:"Character",CharacterClass:"CharacterClass",CharacterClassIntersection:"CharacterClassIntersection",CharacterClassRange:"CharacterClassRange",CharacterSet:"CharacterSet",Directive:"Directive",Flags:"Flags",Group:"Group",Pattern:"Pattern",Quantifier:"Quantifier",Regex:"Regex",Subroutine:"Subroutine",VariableLengthCharacterSet:"VariableLengthCharacterSet",Recursion:"Recursion"},Be={AnyGroup:"AnyGroup",AnyNode:"AnyNode"};function Me(e){let{type:t}=e,r=[Be.AnyNode];return(R(e)||t===l.CapturingGroup||t===l.Group)&&r.push(Be.AnyGroup),r.push(t),r}var E={line_end:"line_end",line_start:"line_start",lookahead:"lookahead",lookbehind:"lookbehind",search_start:"search_start",string_end:"string_end",string_end_newline:"string_end_newline",string_start:"string_start",word_boundary:"word_boundary"},x=S,D=z,H={grapheme:"grapheme",newline:"newline"};function O({tokens:e,flags:t},r){let s={bypassPropertyNameCheck:!1,optimize:!0,...r},n={bypassPropertyNameCheck:s.bypassPropertyNameCheck,capturingGroups:[],current:0,hasNumberedRef:!1,namedGroupsByName:new Map,optimize:s.optimize,parent:null,subroutines:[],token:null,tokens:e,walk:o};function o(C,d){let w=e[n.current];switch(n.parent=C,n.token=w,n.current++,w.type){case g.Alternator:return P();case g.Assertion:return Ke(w);case g.Backreference:return Ot(n);case g.Character:return ze(w.value);case g.CharacterClassHyphen:return Mt(n,d);case g.CharacterClassOpen:return Bt(n,d);case g.CharacterSet:return Vt(n);case g.Directive:return Xt(w);case g.GroupOpen:return jt(n,d);case g.Quantifier:return Kt(n);case g.Subroutine:return zt(n);case g.VariableLengthCharacterSet:return rr(w.kind);default:throw new Error(`Unexpected token type "${w.type}"`)}}let a=er(Zt(),Jt(t)),i=a.pattern.alternatives[0];for(;n.currentc.length)throw new Error("Subroutine uses a group number that's not defined")}else if(p.has(C)){if(p.get(C).length>1)throw new Error(f`Subroutine uses a duplicate group name "\g<${C}>"`)}else throw new Error(f`Subroutine uses a group name that's not defined "\g<${C}>"`);return $({node:a},null,{AnyNode({node:C,parent:d}){C.parent=d}}),a}function Ot(e){let{raw:t}=e.token,r=/^\\k[<']/.test(t),s=r?t.slice(3,-1):t.slice(1),n=(o,a=!1)=>{let i=e.capturingGroups.length;if(o>i)throw new Error(`Not enough capturing groups defined to the left "${t}"`);return e.hasNumberedRef=!0,Z(a?i+1-o:o)};if(r){let o=/^(?-?)0*(?[1-9]\d*)$/.exec(s);if(o)return n(+o.groups.num,!!o.groups.sign);if(/[-+]/.test(s))throw new Error(`Invalid backref name "${t}"`);if(!e.namedGroupsByName.has(s))throw new Error(`Group name not defined to the left "${t}"`);return Z(s)}return n(+s)}function Mt(e,t){let{parent:r,tokens:s,walk:n}=e,o=r.elements.at(-1),a=s[e.current];if(o&&o.type!==l.CharacterClass&&a&&a.type!==g.CharacterClassOpen&&a.type!==g.CharacterClassClose&&a.type!==g.CharacterClassIntersector){let i=n(r,t);if(o.type===l.Character&&i.type===l.Character)return r.elements.pop(),qt(o,i);throw new Error("Invalid character class range")}return ze(45)}function Bt(e,t){let{token:r,tokens:s,optimize:n,walk:o}=e,a=fe({negate:r.negate}),i=a.elements[0],c=Ve(s[e.current]);for(;c.type!==g.CharacterClassClose;){if(c.type===g.CharacterClassIntersector)i.classes.push(fe({negate:!1,baseOnly:!0})),e.current++;else{let u=i.classes.at(-1);u.elements.push(o(u,t))}c=Ve(s[e.current])}if(n&&or(i),i.classes.length===1){let u=i.classes[0];u.negate=a.negate!==u.negate,a=u}return e.current++,a}function Vt({token:e,bypassPropertyNameCheck:t}){let{kind:r,negate:s,value:n}=e;if(r===S.property){let a=K(n);if(Ne.has(a))r=S.posix,n=a;else return ge(n,{negate:s,allowAnyName:t})}let o={type:l.CharacterSet,kind:N(x[r],`Unexpected character set kind "${r}"`)};return(r===S.digit||r===S.hex||r===S.posix||r===S.space||r===S.word)&&(o.negate=s,r===S.posix&&(o.value=n)),o}function jt(e,t){let{token:r,tokens:s,optimize:n,capturingGroups:o,namedGroupsByName:a,walk:i}=e,c=Ht(r);c.type===l.CapturingGroup&&(o.push(c),c.name&&L(a,c.name,[]).push(c));let u=je(s[e.current]);for(;u.type!==g.GroupClose;){if(u.type===g.Alternator)c.alternatives.push(P()),e.current++;else{let p=c.alternatives.at(-1);t.isInLookbehind||=c.kind===E.lookbehind;let h=i(p,t);if(p.elements.push(h),t.isInLookbehind&&h.type===l.Quantifier&&h.min!==h.max)throw new Error("Variable repetition within lookbehind unsupported in Oniguruma")}u=je(s[e.current])}return n&&(c=sr(c)),e.current++,c}function Kt({token:e,parent:t}){let{min:r,max:s,greedy:n,possessive:o}=e,a=t.elements.at(-1);if(!a||a.type===l.Directive)throw new Error("Quantifier requires a repeatable token");let i=Yt(a,r,s,n,o);return t.elements.pop(),i}function zt(e){let{token:t,capturingGroups:r,subroutines:s}=e,n=t.raw.slice(3,-1),o=/^(?[-+]?)0*(?[1-9]\d*)$/.exec(n);if(o){let i=+o.groups.num,c=r.length;if(e.hasNumberedRef=!0,n={"":i,"+":c+i,"-":c+1-i}[o.groups.sign],n<1)throw new Error("Invalid subroutine number")}else n==="0"&&(n=0);let a=tr(n);return s.push(a),a}function P(){return{type:l.Alternative,elements:[]}}function Ke({type:e,kind:t,negate:r}){if(e===g.GroupOpen)return Q({behind:t===_.lookbehind,negate:r});let s=N({"^":E.line_start,$:E.line_end,"\\A":E.string_start,"\\b":E.word_boundary,"\\B":E.word_boundary,"\\G":E.search_start,"\\z":E.string_end,"\\Z":E.string_end_newline}[t],`Unexpected assertion kind "${t}"`),n={type:l.Assertion,kind:s};return s===E.word_boundary&&(n.negate=t===f`\B`),n}function Z(e){return{type:l.Backreference,ref:e}}function Ht(e){let{kind:t,number:r,name:s,flags:n}=e;switch(t){case _.atomic:return I({atomic:!0});case _.capturing:return Qt(r,s);case _.group:return I({flags:n});case _.lookahead:case _.lookbehind:return Ke(e);default:throw new Error(`Unexpected group kind "${t}"`)}}function Qt(e,t){let r=t!==void 0;if(r&&!ar(t))throw new Error(`Group name "${t}" invalid in Oniguruma`);return{type:l.CapturingGroup,number:e,...r&&{name:t},alternatives:[P()]}}function ze(e){return{type:l.Character,value:e}}function fe(e){let t={baseOnly:!1,negate:!1,...e};return{type:l.CharacterClass,negate:t.negate,elements:t.baseOnly?[]:[Wt()]}}function Wt(){return{type:l.CharacterClassIntersection,classes:[fe({negate:!1,baseOnly:!0})]}}function qt(e,t){if(t.values[0].toUpperCase()+s.slice(1).toLowerCase())}function sr(e){let t=e.alternatives[0],r=t.elements[0];return e.type===l.Group&&e.alternatives.length===1&&t.elements.length===1&&r.type===l.Group&&!(e.atomic&&r.flags)&&!(e.flags&&(r.atomic||r.flags))?(e.atomic?r.atomic=!0:e.flags&&(r.flags=e.flags),r):e}function R({type:e,kind:t}){return e===l.Assertion&&(t===E.lookahead||t===E.lookbehind)}function ar(e){return!/^(?:[-\d]|$)/.test(e)}function or(e){for(let t=0;to.kind===D.flags);for(let o=r+1;o1)throw new Error(f`Uses "\K" in a way that's unsupported for conversion to JS`);a(W(Q({behind:!0}),i()))}},Flags({node:e,parent:t}){delete e.extended,Object.assign(e,{global:!1,hasIndices:!1,multiline:!1,sticky:e.sticky??!1}),t.options={disable:{x:!0,n:!0},force:{v:!0}}},Group({node:e}){if(!e.flags)return;let{enable:t,disable:r}=e.flags;t?.extended&&delete t.extended,r?.extended&&delete r.extended,t?.dotAll&&r?.dotAll&&delete t.dotAll,t?.ignoreCase&&r?.ignoreCase&&delete t.ignoreCase,t&&!Object.keys(t).length&&delete e.flags.enable,r&&!Object.keys(r).length&&delete e.flags.disable,!e.flags.enable&&!e.flags.disable&&delete e.flags},Pattern({node:e}){let t=!1,r=!1;for(let s of e.alternatives)s.elements.sort((n,o)=>n.kind===E.search_start&&o.kind===D.flags?-1:n.kind===D.flags&&o.kind===E.search_start?1:0),s.elements[0]?.kind===E.search_start?t=!0:r=!0;if(t&&r)throw new Error(f`Uses "\G" in a way that's unsupported for conversion to JS`)},Quantifier(e,t){let{node:r,remove:s,replaceWith:n,skip:o}=e,a=r.element;if(a.type===l.Quantifier){let i=W(I(),[r.element]);i.parent=r,r.element=i}else if(a.type===l.Assertion){let i=R(a);if(!r.min&&i){let c=P();c.parent=a,a.alternatives.push(c)}r.min||i?(n(a),de(a,e,t,he),o()):(s(),o())}},VariableLengthCharacterSet({node:e,replaceWith:t},{allowBestEffort:r,minTargetEs2024:s}){let{kind:n}=e;if(n===H.newline)t(T(f`(?>\r\n?|[\n\v\f\x85\u2028\u2029])`));else if(n===H.grapheme){if(!r)throw new Error(f`Use of "\X" requires option allowBestEffort`);let o=s?f`\p{RGI_Emoji}`:ye().source;t(T(f`(?>\r\n|${o}|\P{M}\p{M}*)`,{bypassPropertyNameCheck:!0}))}else throw new Error(`Unexpected varcharset kind "${n}"`)}},Qe={Alternative({node:e},{namedGroupsInScopeByAlt:t}){let r=Y(e);if(r){let s=t.get(r);s&&t.set(e,s)}},Backreference({node:e},{multiplexCapturesToLeftByRef:t,reffedNodesByBackreference:r}){let{ref:s}=e;r.set(e,[...t.get(s).map(({node:n})=>n)])},CapturingGroup:{enter({node:e,replaceWith:t,skip:r},{groupOriginByCopy:s,groupsWithDuplicateNamesToRemove:n,multiplexCapturesToLeftByRef:o,namedGroupsInScopeByAlt:a,openDirectCaptures:i,openSubroutineRefs:c}){let{name:u,number:p}=e,h=u??p,C=s.get(e),d=Y(e);if(c.has(h))throw new Error("Unsupported indirect recursion");if(C?c.add(h):i.add(e),i.has(C)){t(He(h)),r();return}let w=L(o,h,[]);for(let y=0;yh.type===l.Group&&!!h.flags)),p=u?U(t.globalFlags,u):t.globalFlags;cr(p,t.currentFlags)||(c=W(I({flags:ur(p)}),[i]))}s(c),a||de(c,e,t,Qe)}},ir={Backreference({node:e,replaceWith:t},{reffedNodesByBackreference:r}){let s=r.get(e),n=qe(e,o=>o.type===l.CapturingGroup);if(s.length>1){let o=s.map(a=>ee(P(),[n.some(i=>i.number===a.number)?Q({negate:!0}):Z(a.number)]));t(ee(I(),o))}else e.ref=s[0].number,n.some(o=>o.number===e.ref)&&t(Q({negate:!0}))},CapturingGroup({node:e},t){e.number=++t.numCapturesToLeft,t.groupsWithDuplicateNamesToRemove.has(e)&&delete e.name}};function ee(e,t){return t.forEach(r=>r.parent=e),e[Xe(e)]=t,e}function cr(e,t){return e.dotAll===t.dotAll&&e.ignoreCase===t.ignoreCase}function We(e,t,r,s){let n=Array.isArray(e)?[]:{};for(let[o,a]of Object.entries(e))o==="parent"?n.parent=Array.isArray(r)?s:r:a&&typeof a=="object"?n[o]=We(a,t,n,r):(o==="type"&&a===l.CapturingGroup&&t.set(n,t.get(e)??e),n[o]=a);return n}function He(e){if(typeof e=="number"&&e!==0)throw new Error("Unsupported recursion by number; use name instead");return{type:l.Recursion,ref:e}}function qe(e,t){let r=[];for(;e=e.parent;)(!t||t(e))&&r.push(e);return r}function Xe(e){if(e.alternatives)return"alternatives";if(e.elements)return"elements";if(e.classes)return"classes";throw new Error("Accessor for child container unknown")}function Je(e){let t=["dotAll","ignoreCase"],r={enable:{},disable:{}};return e.forEach(({flags:s})=>{t.forEach(n=>{s.enable?.[n]&&(delete r.disable[n],r.enable[n]=!0),s.disable?.[n]&&(r.disable[n]=!0)})}),Object.keys(r.enable).length||delete r.enable,Object.keys(r.disable).length||delete r.disable,r.enable||r.disable?r:null}function ur({dotAll:e,ignoreCase:t}){let r={};return(e||t)&&(r.enable={},e&&(r.enable.dotAll=!0),t&&(r.enable.ignoreCase=!0)),(!e||!t)&&(r.disable={},!e&&(r.disable.dotAll=!0),!t&&(r.disable.ignoreCase=!0)),r}function Y(e){for(;e=e.parent;)if(e.type===l.Alternative)return e;return null}function lr(e){return/^[$_\p{IDS}][$\u200C\u200D\p{IDC}]*$/u.test(e)}function T(e,{bypassPropertyNameCheck:t}={}){let s=O(G(e),{bypassPropertyNameCheck:t}).pattern.alternatives;return s.length>1||s[0].elements.length>1?ee(I(),s):s[0].elements[0]}function W(e,t){let r=Xe(e);return e[r][0].parent=e,t&&ee(e[r][0],t),e}function de(e,{parent:t,key:r,container:s},n,o){$({node:e,parent:t,key:r,container:s},n,o)}function Ye(e,t){let r=me(t),s=j(r.target,"ES2024"),n=j(r.target,"ESNext"),o=r.maxRecursionDepth;if(o!==null&&(!Number.isInteger(o)||o<2||o>100))throw new Error("Invalid maxRecursionDepth; use null or 2-100");let a=null,i=null;if(!n){let d=[e.flags.ignoreCase];$({node:e},{getCurrentModI:()=>d.at(-1),popModI(){d.pop()},pushModI(w){d.push(w)},setHasCasedChar(){d.at(-1)?a=!0:i=!0}},pr)}let c={dotAll:e.flags.dotAll,ignoreCase:!!((e.flags.ignoreCase||a)&&!i)},u=null,p={allowBestEffort:r.allowBestEffort,appliedGlobalFlags:c,captureFlagIMap:new Map,currentFlags:{dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},groupNames:new Set,inCharClass:!1,lastNode:u,maxRecursionDepth:o,optimize:r.optimize,useAppliedIgnoreCase:!!(!n&&a&&i),useDuplicateNames:n,useFlagMods:n,useFlagV:s,usePostEs2018Properties:s};function h(d){switch(p.lastNode=u,u=d,d.type){case l.Regex:return{pattern:h(d.pattern),flags:h(d.flags),options:{...d.options}};case l.Alternative:return d.elements.map(h).join("");case l.Assertion:return Cr(d,p,h);case l.Backreference:return mr(d,p);case l.CapturingGroup:return Er(d,p,h);case l.Character:return wr(d,p);case l.CharacterClass:return Ar(d,p,h);case l.CharacterClassIntersection:if(!p.useFlagV)throw new Error("Use of class intersection requires target ES2024 or later");return d.classes.map(h).join("&&");case l.CharacterClassRange:return Sr(d,p);case l.CharacterSet:return _r(d,p);case l.Flags:return kr(d,p);case l.Group:return br(d,p,h);case l.Pattern:return d.alternatives.map(h).join("|");case l.Quantifier:return h(d.element)+Nr(d);case l.Recursion:return xr(d,p);default:throw new Error(`Unexpected node type "${d.type}"`)}}let C=h(e);return s||(delete C.options.force.v,C.options.disable.v=!0,C.options.unicodeSetsPlugin=null),C}var pr={AnyGroup:{enter({node:e},t){let r=t.getCurrentModI();t.pushModI(e.flags?U({ignoreCase:r},e.flags).ignoreCase:r)},exit(e,t){t.popModI()}},Backreference(e,t){t.setHasCasedChar()},Character({node:e},t){Ce(A(e.value))&&t.setHasCasedChar()},CharacterClassRange({node:e,skip:t},r){t(),et(e,{firstOnly:!0}).length&&r.setHasCasedChar()},CharacterSet({node:e},t){e.kind===x.property&&le.has(e.value)&&t.setHasCasedChar()}},fr=new Set(["$","(",")","*","+",".","?","[","\\","]","^","{","|","}"]),gr=new Set(["-","\\","]","^"]),hr=new Set(["(",")","-","/","[","\\","]","^","{","|","}","!","#","$","%","&","*","+",",",".",":",";","<","=",">","?","@","`","~"]),Ze=new Map([[9,f`\t`],[10,f`\n`],[11,f`\v`],[12,f`\f`],[13,f`\r`],[8232,f`\u2028`],[8233,f`\u2029`]]),dr=/^\p{Cased}$/u;function Ce(e){return dr.test(e)}function Cr(e,t,r){let{kind:s,negate:n,alternatives:o}=e;if(R(e))return`(?${`${s===E.lookahead?"":"<"}${n?"!":"="}`}${o.map(r).join("|")})`;if(s===E.string_end)return"$";if(s===E.string_start)return"^";throw new Error(`Unexpected assertion kind "${s}"`)}function mr({ref:e},t){if(typeof e!="number")throw new Error("Unexpected named backref in transformed AST");if(!t.useFlagMods&&!t.allowBestEffort&&t.currentFlags.ignoreCase&&!t.captureFlagIMap.get(e))throw new Error("Use of case-insensitive backref to case-sensitive group requires option allowBestEffort or target ESNext");return"\\"+e}function Er({name:e,number:t,alternatives:r},s,n){return e&&(s.groupNames.has(e)?s.useDuplicateNames||(e=null):s.groupNames.add(e)),s.captureFlagIMap.set(t,s.currentFlags.ignoreCase),`(${e?`?<${e}>`:""}${r.map(n).join("|")})`}function wr({value:e},t){let r=A(e),s=M(e,{isAfterBackref:t.lastNode.type===l.Backreference,inCharClass:t.inCharClass,useFlagV:t.useFlagV});if(s!==r)return s;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&Ce(r)){let n=oe(r);return t.inCharClass?n.join(""):n.length>1?`[${n.join("")}]`:n[0]}return r}function Ar({negate:e,parent:t,elements:r},s,n){if(!e&&(!s.useFlagV||s.optimize)&&t.type===l.CharacterClass&&r[0].type!==l.CharacterClassIntersection||s.optimize&&t.type===l.CharacterClassIntersection&&r.length===1&&r[0].type!==l.CharacterClassRange)return r.map(n).join("");if(!s.useFlagV&&t.type===l.CharacterClass)throw new Error("Use of nested character class requires target ES2024 or later");s.inCharClass=!0;let o=`[${e?"^":""}${r.map(n).join("")}]`;return s.inCharClass=!1,o}function Sr(e,t){let r=e.min.value,s=e.max.value,n={isAfterBackref:!1,inCharClass:!0,useFlagV:t.useFlagV},o=M(r,n),a=M(s,n),i="";if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase){let c=et(e);yr(c).forEach(p=>{i+=Array.isArray(p)?`${M(p[0],n)}-${M(p[1],n)}`:M(p,n)})}return`${o}-${a}${i}`}function _r({kind:e,negate:t,value:r,key:s},n){if(e===x.any)return n.currentFlags.dotAll?n.appliedGlobalFlags.dotAll||n.useFlagMods?".":"[^]":f`[^\n]`;if(e===x.digit)return t?f`\D`:f`\d`;if(e===x.property){if(!n.usePostEs2018Properties&&Fe.has(r))throw new Error(`Unicode property "${r}" unavailable in target ES2018`);if(n.useAppliedIgnoreCase&&n.currentFlags.ignoreCase&&le.has(r))throw new Error(`Unicode property "${r}" can't be case-insensitive when other chars have specific case`);return`${t?f`\P`:f`\p`}{${s?`${s}=`:""}${r}}`}if(e===x.word)return t?f`\W`:f`\w`;throw new Error(`Unexpected character set kind "${e}"`)}function kr(e,t){return(t.appliedGlobalFlags.ignoreCase?"i":"")+(e.dotAll?"s":"")+(e.sticky?"y":"")}function br({atomic:e,flags:t,parent:r,alternatives:s},n,o){let a=n.currentFlags;t&&(n.currentFlags=U(a,t));let i=s.map(o).join("|"),c=n.optimize&&s.length===1&&r.type!==l.Quantifier&&!e&&(!n.useFlagMods||!t)?i:`(?${Fr(e,t,n.useFlagMods)}${i})`;return n.currentFlags=a,c}function xr({ref:e},t){let r=t.maxRecursionDepth;if(!r)throw new Error("Use of recursion disabled");if(!t.allowBestEffort)throw new Error("Use of recursion requires option allowBestEffort");return e===0?`(?R=${r})`:f`\g<${e}&R=${r}>`}function et(e,{firstOnly:t}={}){let r=e.min.value,s=e.max.value,n=[];if(r<65&&(s===65535||s>=131071)||r===65536&&s>=131071)return n;for(let o=r;o<=s;o++){let a=A(o);if(!Ce(a))continue;let i=oe(a).filter(c=>{let u=c.codePointAt(0);return us});if(i.length&&(n.push(...i),t))break}return n}function M(e,{isAfterBackref:t,inCharClass:r,useFlagV:s}){if(Ze.has(e))return Ze.get(e);if(e<32||e>126&&e<160||e>262143||t&&$r(e))return e>255?f`\u{${e.toString(16).toUpperCase()}}`:f`\x${e.toString(16).toUpperCase().padStart(2,"0")}`;let n=r?s?hr:gr:fr,o=A(e);return(n.has(o)?"\\":"")+o}function yr(e){let t=e.map(n=>n.codePointAt(0)).sort((n,o)=>n-o),r=[],s=null;for(let n=0;n";let s="";if(t&&r){let{enable:n,disable:o}=t;s=(n?.ignoreCase?"i":"")+(n?.dotAll?"s":"")+(o?"-":"")+(o?.ignoreCase?"i":"")+(o?.dotAll?"s":"")}return`${s}:`}function Nr({min:e,max:t,greedy:r,possessive:s}){let n;return!e&&t===1?n="?":!e&&t===1/0?n="*":e===1&&t===1/0?n="+":e===t?n=`{${e}}`:n=`{${e},${t===1/0?"":t}}`,n+(s?"+":r?"":"?")}function $r(e){return e>47&&e<58}var k=Object.freeze({DEFAULT:"DEFAULT",CHAR_CLASS:"CHAR_CLASS"});function B(e,t,r,s){let n=new RegExp(String.raw`${t}|(?<$skip>\[\^?|\\?.)`,"gsu"),o=[!1],a=0,i="";for(let c of e.matchAll(n)){let{0:u,groups:{$skip:p}}=c;if(!p&&(!s||s===k.DEFAULT==!a)){r instanceof Function?i+=r(c,{context:a?k.CHAR_CLASS:k.DEFAULT,negated:o[o.length-1]}):i+=r;continue}u[0]==="["?(a++,o.push(u[1]==="^")):u==="]"&&a&&(a--,o.pop()),i+=u}return i}function Ee(e,t,r,s){B(e,t,r,s)}function Ir(e,t,r=0,s){if(!new RegExp(t,"su").test(e))return null;let n=new RegExp(`${t}|(?<$skip>\\\\?.)`,"gsu");n.lastIndex=r;let o=0,a;for(;a=n.exec(e);){let{0:i,groups:{$skip:c}}=a;if(!c&&(!s||s===k.DEFAULT==!o))return a;i==="["?o++:i==="]"&&o&&o--,n.lastIndex==a.index&&n.lastIndex++}return null}function V(e,t,r){return!!Ir(e,t,0,r)}function tt(e,t){let r=/\\?./gsu;r.lastIndex=t;let s=e.length,n=0,o=1,a;for(;a=r.exec(e);){let[i]=a;if(i==="[")n++;else if(n)i==="]"&&n--;else if(i==="(")o++;else if(i===")"&&(o--,!o)){s=a.index;break}}return e.slice(t,s)}var rt={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"},we={DEFAULT:"DEFAULT",ENCLOSED_P:"ENCLOSED_P",ENCLOSED_Q:"ENCLOSED_Q",ENCLOSED_U:"ENCLOSED_U",INVALID_INCOMPLETE_TOKEN:"INVALID_INCOMPLETE_TOKEN",RANGE:"RANGE"},wn=new Set([rt.ENCLOSED_P,rt.ENCLOSED_U]),An=new Set([we.ENCLOSED_P,we.ENCLOSED_Q,we.ENCLOSED_U]),Sn=(()=>{try{new RegExp("(?i:)")}catch{return!1}return!0})(),_n=(()=>{try{new RegExp("","v")}catch{return!1}return!0})(),nt="$E$";var Pr=String.raw`\(\?<(?![=!])(?[^>]+)>`,kn=String.raw`\((?!\?)(?!(?<=\(\?\()DEFINE\))|${Pr}`,st=String.raw`\(\?(?:[:=!>A-Za-z\-]|<[=!]|\(DEFINE\))`;var Tr=["Basic_Emoji","Emoji_Keycap_Sequence","RGI_Emoji_Modifier_Sequence","RGI_Emoji_Flag_Sequence","RGI_Emoji_Tag_Sequence","RGI_Emoji_ZWJ_Sequence","RGI_Emoji"].join("|"),bn=new RegExp(String.raw`
\\(?: c[A-Za-z]
| p\{(?${Tr})\}
| [pP]\{[^\}]+\}
@@ -58,7 +58,7 @@ var OnigurumaToES=(()=>{var ne=Object.defineProperty;var mt=Object.getOwnPropert
)
| --
| \\?.
-`.replace(/\s+/g,""),"gsu");function at(e,t,r,s){return e.slice(0,t)+s+e.slice(t+r.length)}var ot=new RegExp(String.raw`(?${st})|(?\((?:\?<[^>]+>)?)|\\?.`,"gsu");function it(e,t){if(!/\(\?>/.test(e))return e;let r="(?>",s=`(?:(?=(${t?.useEmulationGroups?nt:""}`,n=[0],o=0,a=0,i=NaN,c;do{c=!1;let u=0,p=0,d=!1,C;for(ot.lastIndex=Number.isNaN(i)?0:i+s.length;C=ot.exec(e);){let{0:h,index:w,groups:{capturingStart:y,noncapturingStart:b}}=C;if(h==="[")u++;else if(u)h==="]"&&u--;else if(h===r&&!d)i=w,d=!0;else if(d&&b)p++;else if(y)d?p++:(o++,n.push(o+a));else if(h===")"&&d){if(!p){a++,e=`${e.slice(0,i)}${s}${e.slice(i+r.length,w)}))<$$${a+o}>)${e.slice(w+1)}`,c=!0;break}p--}}}while(c);return e=B(e,String.raw`\\(?[1-9]\d*)|<\$\$(?\d+)>`,({0:u,groups:{backrefNum:p,wrappedBackrefNum:d}})=>{if(p){let C=+p;if(C>n.length-1)throw new Error(`Backref "${u}" greater than number of captures`);return`\\${n[C]}`}return`\\${d}`},k.DEFAULT),e}var ct=String.raw`(?:[?*+]|\{\d+(?:,\d*)?\})`,Ae=new RegExp(String.raw`
+`.replace(/\s+/g,""),"gsu");function at(e,t,r,s){return e.slice(0,t)+s+e.slice(t+r.length)}var ot=new RegExp(String.raw`(?${st})|(?\((?:\?<[^>]+>)?)|\\?.`,"gsu");function it(e,t){if(!/\(\?>/.test(e))return e;let r="(?>",s=`(?:(?=(${t?.useEmulationGroups?nt:""}`,n=[0],o=0,a=0,i=NaN,c;do{c=!1;let u=0,p=0,h=!1,C;for(ot.lastIndex=Number.isNaN(i)?0:i+s.length;C=ot.exec(e);){let{0:d,index:w,groups:{capturingStart:y,noncapturingStart:b}}=C;if(d==="[")u++;else if(u)d==="]"&&u--;else if(d===r&&!h)i=w,h=!0;else if(h&&b)p++;else if(y)h?p++:(o++,n.push(o+a));else if(d===")"&&h){if(!p){a++,e=`${e.slice(0,i)}${s}${e.slice(i+r.length,w)}))<$$${a+o}>)${e.slice(w+1)}`,c=!0;break}p--}}}while(c);return e=B(e,String.raw`\\(?[1-9]\d*)|<\$\$(?\d+)>`,({0:u,groups:{backrefNum:p,wrappedBackrefNum:h}})=>{if(p){let C=+p;if(C>n.length-1)throw new Error(`Backref "${u}" greater than number of captures`);return`\\${n[C]}`}return`\\${h}`},k.DEFAULT),e}var ct=String.raw`(?:[?*+]|\{\d+(?:,\d*)?\})`,Ae=new RegExp(String.raw`
\\(?: \d+
| c[A-Za-z]
| [gk]<[^>]+>
@@ -73,5 +73,5 @@ var OnigurumaToES=(()=>{var ne=Object.defineProperty;var mt=Object.getOwnPropert
))?
| (?${ct})(?[?+]?)(?[?*+\{]?)
| \\?.
-`.replace(/\s+/g,""),"gsu");function ut(e){if(!new RegExp(`${ct}\\+`).test(e))return e;let t=[],r=null,s=null,n="",o=0,a;for(Ae.lastIndex=0;a=Ae.exec(e);){let{0:i,index:c,groups:{qBase:u,qMod:p,invalidQ:d}}=a;if(i==="[")o||(s=c),o++;else if(i==="]")o?o--:s=null;else if(!o)if(p==="+"&&n&&!n.startsWith("(")){if(d)throw new Error(`Invalid quantifier "${i}"`);let C=-1;if(/^\{\d+\}$/.test(u))e=at(e,c+u.length,p,"");else{if(n===")"||n==="]"){let h=n===")"?r:s;if(h===null)throw new Error(`Invalid unmatched "${n}"`);e=`${e.slice(0,h)}(?>${e.slice(h,c)}${u})${e.slice(c+i.length)}`}else e=`${e.slice(0,c-n.length)}(?>${n}${u})${e.slice(c+i.length)}`;C+=4}Ae.lastIndex+=C}else i[0]==="("?t.push(c):i===")"&&(r=t.length?t.pop():null);n=i}return e}var dt=String.raw`\\g<(?[^>&]+)&R=(?\d+)>`,Se=String.raw`\(\?R=(?\d+)\)|${dt}`,_e=String.raw`\(\?<(?![=!])(?[^>]+)>`,re=new RegExp(String.raw`${_e}|${Se}|\\?.`,"gsu");function ht(e){if(!V(e,Se,k.DEFAULT))return e;if(V(e,String.raw`\\[1-9]`,k.DEFAULT))throw new Error("Numbered backrefs cannot be used with recursion; use named backref");if(V(e,String.raw`\(\?\(DEFINE\)`,k.DEFAULT))throw new Error("DEFINE groups cannot be used with recursion");let t=new Map,r=0,s;for(re.lastIndex=0;s=re.exec(e);){let{0:n,groups:{captureName:o,rDepth:a,gRName:i,gRDepth:c}}=s;if(n==="[")r++;else if(r)n==="]"&&r--;else if(o)t.set(o,re.lastIndex);else if(a){let u=+a;lt(u);let p=e.slice(0,s.index),d=e.slice(re.lastIndex);return pt(d),ft(p,d,u,!1)}else if(i){let u=+c;lt(u);let p=`Recursion via \\g<${i}&R=${c}> must be used within the referenced group`;if(!t.has(i))throw new Error(p);let d=t.get(i),C=tt(e,d);if(!V(C,dt,k.DEFAULT))throw new Error(p);let h=e.slice(d,s.index),w=C.slice(h.length+n.length);return pt(w),e.slice(0,d)+ft(h,w,u,!0)+e.slice(d+C.length)}}throw new Error("Unexpected error; recursion was not processed")}function lt(e){if(e<2||e>100)throw new Error(`Max depth must be between 2 and 100; used ${e}`)}function pt(e){if(V(e,Se,k.DEFAULT))throw new Error("Recursion can only be used once per regex")}function ft(e,t,r,s){let n=new Set;s&&Ee(e+t,_e,({groups:{captureName:a}})=>{n.add(a)},k.DEFAULT);let o=r-1;return`${e}${gt(`(?:${e}`,o,s?n:null)}(?:)${gt(`${t})`,o,s?n:null,"backward")}${t}`}function gt(e,t,r,s="forward"){let o=i=>s==="backward"?t-i+2-1:i+2,a="";for(let i=0;i[^>]+)>`,({0:u,groups:{captureName:p,backref:d}})=>{if(d&&r&&!r.has(d))return u;let C=`_$${c}`;return p?`(?<${p}${C}>`:`\\k<${d}${C}>`},k.DEFAULT)}return a}function ke(e,t,r){let s=me(r),n=G(e,t),o=O(n,{optimize:s.optimize}),a=te(o,{allowBestEffort:s.allowBestEffort,bestEffortTarget:s.target}),i=Ye(a,s);return{pattern:it(ut(ht(i.pattern))),flags:`${i.flags}${i.options.disable.v?"u":"v"}`}}function me(e){if(e?.target!==void 0&&!q[e.target])throw new Error(`Unexpected target "${e.target}"`);return{allowBestEffort:!0,maxRecursionDepth:6,optimize:!0,target:"ES2024",...e}}function Ct(e,t){return O(G(e,t))}function Lr(e,t){return te(Ct(e,t))}function vr(e,t="",r){let s=t.replace(/[^dg]+/g,"");t=t.replace(/[dg]+/g,"");let n=ke(e,t,r);return new RegExp(n.pattern,`${s}${n.flags}`)}return _t(Rr);})();
+`.replace(/\s+/g,""),"gsu");function ut(e){if(!new RegExp(`${ct}\\+`).test(e))return e;let t=[],r=null,s=null,n="",o=0,a;for(Ae.lastIndex=0;a=Ae.exec(e);){let{0:i,index:c,groups:{qBase:u,qMod:p,invalidQ:h}}=a;if(i==="[")o||(s=c),o++;else if(i==="]")o?o--:s=null;else if(!o)if(p==="+"&&n&&!n.startsWith("(")){if(h)throw new Error(`Invalid quantifier "${i}"`);let C=-1;if(/^\{\d+\}$/.test(u))e=at(e,c+u.length,p,"");else{if(n===")"||n==="]"){let d=n===")"?r:s;if(d===null)throw new Error(`Invalid unmatched "${n}"`);e=`${e.slice(0,d)}(?>${e.slice(d,c)}${u})${e.slice(c+i.length)}`}else e=`${e.slice(0,c-n.length)}(?>${n}${u})${e.slice(c+i.length)}`;C+=4}Ae.lastIndex+=C}else i[0]==="("?t.push(c):i===")"&&(r=t.length?t.pop():null);n=i}return e}var ht=String.raw`\\g<(?[^>&]+)&R=(?\d+)>`,Se=String.raw`\(\?R=(?\d+)\)|${ht}`,_e=String.raw`\(\?<(?![=!])(?[^>]+)>`,re=new RegExp(String.raw`${_e}|${Se}|\\?.`,"gsu");function dt(e){if(!V(e,Se,k.DEFAULT))return e;if(V(e,String.raw`\\[1-9]`,k.DEFAULT))throw new Error("Numbered backrefs cannot be used with recursion; use named backref");if(V(e,String.raw`\(\?\(DEFINE\)`,k.DEFAULT))throw new Error("DEFINE groups cannot be used with recursion");let t=new Map,r=0,s;for(re.lastIndex=0;s=re.exec(e);){let{0:n,groups:{captureName:o,rDepth:a,gRName:i,gRDepth:c}}=s;if(n==="[")r++;else if(r)n==="]"&&r--;else if(o)t.set(o,re.lastIndex);else if(a){let u=+a;lt(u);let p=e.slice(0,s.index),h=e.slice(re.lastIndex);return pt(h),ft(p,h,u,!1)}else if(i){let u=+c;lt(u);let p=`Recursion via \\g<${i}&R=${c}> must be used within the referenced group`;if(!t.has(i))throw new Error(p);let h=t.get(i),C=tt(e,h);if(!V(C,ht,k.DEFAULT))throw new Error(p);let d=e.slice(h,s.index),w=C.slice(d.length+n.length);return pt(w),e.slice(0,h)+ft(d,w,u,!0)+e.slice(h+C.length)}}throw new Error("Unexpected error; recursion was not processed")}function lt(e){if(e<2||e>100)throw new Error(`Max depth must be between 2 and 100; used ${e}`)}function pt(e){if(V(e,Se,k.DEFAULT))throw new Error("Recursion can only be used once per regex")}function ft(e,t,r,s){let n=new Set;s&&Ee(e+t,_e,({groups:{captureName:a}})=>{n.add(a)},k.DEFAULT);let o=r-1;return`${e}${gt(`(?:${e}`,o,s?n:null)}(?:)${gt(`${t})`,o,s?n:null,"backward")}${t}`}function gt(e,t,r,s="forward"){let o=i=>s==="backward"?t-i+2-1:i+2,a="";for(let i=0;i[^>]+)>`,({0:u,groups:{captureName:p,backref:h}})=>{if(h&&r&&!r.has(h))return u;let C=`_$${c}`;return p?`(?<${p}${C}>`:`\\k<${h}${C}>`},k.DEFAULT)}return a}function ke(e,t,r){let s=me(r),n=G(e,t),o=O(n,{optimize:s.optimize}),a=te(o,{allowBestEffort:s.allowBestEffort,bestEffortTarget:s.target}),i=Ye(a,s);return{pattern:it(ut(dt(i.pattern))),flags:`${s.hasIndices?"d":""}${s.global?"g":""}${i.flags}${i.options.disable.v?"u":"v"}`}}function me(e){if(e?.target!==void 0&&!q[e.target])throw new Error(`Unexpected target "${e.target}"`);return{allowBestEffort:!0,global:!1,hasIndices:!1,maxRecursionDepth:6,optimize:!0,target:"ES2024",...e}}function Ct(e,t){return O(G(e,t))}function Lr(e,t){return te(Ct(e,t))}function vr(e,t,r){let s=ke(e,t,r);return new RegExp(s.pattern,s.flags)}return _t(Rr);})();
//# sourceMappingURL=index.min.js.map
diff --git a/spec/match-assertion.spec.js b/spec/match-assertion.spec.js
index 8e6a806..2fbb26c 100644
--- a/spec/match-assertion.spec.js
+++ b/spec/match-assertion.spec.js
@@ -88,7 +88,7 @@ describe('Assertion', () => {
});
it('should match only at the start of the search when applied repeatedly', () => {
- expect('abbcbb'.match(toRegExp(r`\G[ab]`, 'g'))).toEqual(['a', 'b', 'b']);
+ expect('abbcbb'.match(toRegExp(r`\G[ab]`, '', {global: true}))).toEqual(['a', 'b', 'b']);
});
it('should apply with positive min quantification', () => {
diff --git a/spec/match-recursion.spec.js b/spec/match-recursion.spec.js
index 9f9e30a..b3599a8 100644
--- a/spec/match-recursion.spec.js
+++ b/spec/match-recursion.spec.js
@@ -36,7 +36,7 @@ describe('Recursion', () => {
'<>', '<<>>', 'd>e>', '<<<<< >>bc>>>',
]).toExactlyMatch(pattern);
expect(
- 'test > >> <> <> < '.match(toRegExp(pattern, 'g'))
+ 'test > >> <> <> < '.match(toRegExp(pattern, '', {global: true}))
).toEqual(['>>', '<>', '<>', '']);
});
diff --git a/src/compile.js b/src/compile.js
index 4a2ac00..b460a0d 100644
--- a/src/compile.js
+++ b/src/compile.js
@@ -9,6 +9,8 @@ import {recursion} from 'regex-recursion';
/**
@typedef {{
allowBestEffort?: boolean;
+ global?: boolean;
+ hasIndices?: boolean;
maxRecursionDepth?: number | null;
optimize?: boolean;
target?: keyof Target;
@@ -17,7 +19,7 @@ import {recursion} from 'regex-recursion';
/**
Transpiles an Oniguruma regex pattern and flags to native JS.
@param {string} pattern Oniguruma regex pattern.
-@param {import('./tokenize.js').OnigurumaFlags} [flags] Oniguruma flags. Flag `m` is equivalent to JS's flag `s`.
+@param {import('./tokenize.js').OnigurumaFlags} [flags] Oniguruma flags. Flag `m` is equivalent to JS flag `s`.
@param {CompileOptions} [options]
@returns {{
pattern: string;
@@ -37,7 +39,7 @@ function compile(pattern, flags, options) {
const generated = generate(regexAst, opts);
return {
pattern: atomic(possessive(recursion(generated.pattern))),
- flags: `${generated.flags}${generated.options.disable.v ? 'u' : 'v'}`,
+ flags: `${opts.hasIndices ? 'd' : ''}${opts.global ? 'g' : ''}${generated.flags}${generated.options.disable.v ? 'u' : 'v'}`,
};
}
@@ -53,16 +55,20 @@ function getOptions(options) {
// Set default values
return {
// Allows results that differ from Oniguruma in rare cases. If `false`, throws if the pattern
- // can't be emulated with identical behavior.
+ // can't be emulated with identical behavior
allowBestEffort: true,
+ // Include JS flag `g` in results
+ global: false,
+ // Include JS flag `d` in results
+ hasIndices: false,
// If `null`, any use of recursion throws. If an integer between `2` and `100` (and
// `allowBestEffort` is on), common recursion forms are supported and recurse up to the
- // specified max depth.
+ // specified max depth
maxRecursionDepth: 6,
- // Simplify the generated pattern when it doesn't change the meaning.
+ // Simplify the generated pattern when it doesn't change the meaning
optimize: true,
// Sets the JavaScript language version for generated patterns and flags. Later targets allow
- // faster processing, simpler generated source, and support for additional features.
+ // faster processing, simpler generated source, and support for additional features
target: 'ES2024',
...options,
};
diff --git a/src/index.js b/src/index.js
index c4ff98d..fb7ac36 100644
--- a/src/index.js
+++ b/src/index.js
@@ -19,7 +19,7 @@ import {tokenize} from './tokenize.js';
/**
Generates an Oniguruma AST from an Oniguruma pattern and flags.
@param {string} pattern Oniguruma regex pattern.
-@param {import('./tokenize.js').OnigurumaFlags} [flags] Oniguruma flags. Flag `m` is equivalent to JS's flag `s`.
+@param {import('./tokenize.js').OnigurumaFlags} [flags] Oniguruma flags. Flag `m` is equivalent to JS flag `s`.
@returns {import('./parse.js').OnigurumaAst}
*/
function toOnigurumaAst(pattern, flags) {
@@ -29,7 +29,7 @@ function toOnigurumaAst(pattern, flags) {
/**
Generates a `regex` AST from an Oniguruma pattern and flags.
@param {string} pattern Oniguruma regex pattern.
-@param {import('./tokenize.js').OnigurumaFlags} [flags] Oniguruma flags. Flag `m` is equivalent to JS's flag `s`.
+@param {import('./tokenize.js').OnigurumaFlags} [flags] Oniguruma flags. Flag `m` is equivalent to JS flag `s`.
@returns {import('./transform.js').RegexAst}
*/
function toRegexAst(pattern, flags) {
@@ -39,16 +39,13 @@ function toRegexAst(pattern, flags) {
/**
Transpiles an Oniguruma regex pattern and flags and returns a native JS RegExp.
@param {string} pattern Oniguruma regex pattern.
-@param {string} [flags] Any combination of Oniguruma flags `imx` and JS flags `dg`. Flag `m` is
- equivalent to JS's flag `s`.
+@param {import('./tokenize.js').OnigurumaFlags} [flags] Oniguruma flags. Flag `m` is equivalent to JS flag `s`.
@param {import('./compile.js').CompileOptions} [options]
@returns {RegExp}
*/
-function toRegExp(pattern, flags = '', options) {
- const allowedJsFlags = flags.replace(/[^dg]+/g, '');
- flags = flags.replace(/[dg]+/g, '');
+function toRegExp(pattern, flags, options) {
const result = compile(pattern, flags, options);
- return new RegExp(result.pattern, `${allowedJsFlags}${result.flags}`);
+ return new RegExp(result.pattern, result.flags);
}
export {
diff --git a/src/tokenize.js b/src/tokenize.js
index 81a6cfc..9cce2fb 100644
--- a/src/tokenize.js
+++ b/src/tokenize.js
@@ -16,7 +16,7 @@ const TokenTypes = /** @type {const} */ ({
GroupOpen: 'GroupOpen',
Subroutine: 'Subroutine',
Quantifier: 'Quantifier',
- // These aren't allowed in char classes, so they aren't equivalent to JS's `[\q{}]`
+ // These aren't allowed in char classes, so they aren't equivalent to JS `[\q{}]`
VariableLengthCharacterSet: 'VariableLengthCharacterSet',
// Intermediate representation not included in results
EscapedNumber: 'EscapedNumber',
@@ -122,7 +122,7 @@ const charClassTokenRe = new RegExp(r`
*/
/**
@param {string} pattern
-@param {OnigurumaFlags} [flags] Oniguruma flags. Flag `m` is equivalent to JS's flag `s`.
+@param {OnigurumaFlags} [flags] Oniguruma flags. Flag `m` is equivalent to JS flag `s`.
@returns {TokenizerResult}
*/
function tokenize(pattern, flags = '') {