diff --git a/README.md b/README.md index e0653ba..755e7e2 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,8 @@ Specifically, this option enables the following additional features, depending o 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. +Using a higher limit is not a problem if needed. Although it can add a slight performance cost, that's limited to regexes that actually use recursion. + *Default: `6`.* ### `optimize` diff --git a/dist/index.min.js b/dist/index.min.js index ee0c331..e6eb1b7 100644 --- a/dist/index.min.js +++ b/dist/index.min.js @@ -33,7 +33,7 @@ var OnigurumaToES=(()=>{var ne=Object.defineProperty;var wt=Object.getOwnPropert | . `.replace(/\s+/g,""),"gsu");function M(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),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=Ft(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===k.capturing?(i++,u.number=i):u.raw==="("&&a.push(u))}),i||a.forEach((u,p)=>{u.kind=k.capturing,u.number=p+1});let c=i||a.length;return n=n.map(u=>u.type===g.EscapedNumber?Ot(u,c):u).flat(),{tokens:n,flags:{ignoreCase:t.includes("i"),dotAll:t.includes("m"),extended:t.includes("x")}}}function Ft(e,t,r,s){let[n,o,a]=r;if(n==="["){let i=Pt(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:Oe(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:vt(r,e)};if(e.pushModX(e.getCurrentModX()),r==="("||r==="(?:")return{token:m(g.GroupOpen,r,{kind:k.group})};if(r==="(?>")return{token:m(g.GroupOpen,r,{kind:k.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:_.posix,negate:!!t.groups.negate,value:t.groups.name})}return e==="-"?m(g.CharacterClassHyphen,e):e==="&&"?m(g.CharacterClassIntersector,e):(Ge(e),m(g.Character,e,{value:e.codePointAt(0)}))}function Oe(e,{inCharClass:t}){let r=e[1];if(r==="c"||r==="C")return Lt(e);if("dDhHsSwW".includes(r))return Dt(e);if(/^\\[pP]\{/.test(e)){if(e.length===3)throw new Error("Incomplete or invalid Unicode property");return Ut(e)}if(r==="u"||r==="x")return m(g.Character,e,{value:Mt(e)});if(Fe.has(r))return m(g.Character,e,{value:Fe.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 Lt(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 vt(e,t){let{on:r,off:s}=/^\(\?(?[imx]*)(?:-(?[imx\-]*))?/.exec(e).groups;s??="";let n=(t.getCurrentModX()||r.includes("x"))&&!s.includes("x"),o=Pe(r),a=Pe(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);let c=m(g.GroupOpen,e,{kind:k.group});return(o||a)&&(c.flags=i),c}throw new Error(`Unexpected flag modifier "${e}"`)}function Rt(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 Dt(e){let t=e[1].toLowerCase();return m(g.CharacterSet,e,{kind:{d:_.digit,h:_.hex,s:_.space,w:_.word}[t],negate:e[1]!==t})}function Ut(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:_.property,negate:n,value:s})}function Mt(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 Pe(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 Ot(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[S]),w=d&&r[d],U=typeof w=="function"?w:w?.enter,T=w?.exit;if(U?.(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 T?.(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"},Ve={AnyGroup:"AnyGroup",AnyNode:"AnyNode"};function Be(e){let{type:t}=e,r=[Ve.AnyNode];return(R(e)||t===l.CapturingGroup||t===l.Group)&&r.push(Ve.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"},b=_,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 F();case g.Assertion:return ze(w);case g.Backreference:return Bt(n);case g.Character:return He(w.value);case g.CharacterClassHyphen:return Vt(n,d);case g.CharacterClassOpen:return jt(n,d);case g.CharacterSet:return Kt(n);case g.Directive:return Zt(w);case g.GroupOpen:return zt(n,d);case g.Quantifier:return Ht(n);case g.Subroutine:return Qt(n);case g.VariableLengthCharacterSet:return sr(w.kind);default:throw new Error(`Unexpected token type "${w.type}"`)}}let a=rr(er(),Yt(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 Bt(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 Vt(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(),Jt(o,i);throw new Error("Invalid character class range")}return He(45)}function jt(e,t){let{token:r,tokens:s,optimize:n,walk:o}=e,a=fe({negate:r.negate}),i=a.elements[0],c=je(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=je(s[e.current])}if(n&&cr(i),i.classes.length===1){let u=i.classes[0];u.negate=a.negate!==u.negate,a=u}return e.current++,a}function Kt({token:e,bypassPropertyNameCheck:t}){let{kind:r,negate:s,value:n}=e;if(r===_.property){let a=K(n);if(Ie.has(a))r=_.posix,n=a;else return ge(n,{negate:s,allowAnyName:t})}let o={type:l.CharacterSet,kind:y(b[r],`Unexpected character set kind "${r}"`)};return(r===_.digit||r===_.hex||r===_.posix||r===_.space||r===_.word)&&(o.negate=s,r===_.posix&&(o.value=n)),o}function zt(e,t){let{token:r,tokens:s,optimize:n,capturingGroups:o,namedGroupsByName:a,walk:i}=e,c=Wt(r);c.type===l.CapturingGroup&&(o.push(c),c.name&&L(a,c.name,[]).push(c));let u=Ke(s[e.current]);for(;u.type!==g.GroupClose;){if(u.type===g.Alternator)c.alternatives.push(F()),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=Ke(s[e.current])}return n&&(c=or(c)),e.current++,c}function Ht({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=tr(a,r,s,n,o);return t.elements.pop(),i}function Qt(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=nr(n);return s.push(a),a}function F(){return{type:l.Alternative,elements:[]}}function ze({type:e,kind:t,negate:r}){if(e===g.GroupOpen)return Q({behind:t===k.lookbehind,negate:r});let s=y({"^":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 Wt(e){let{kind:t,number:r,name:s,flags:n}=e;switch(t){case k.atomic:return I({atomic:!0});case k.capturing:return qt(r,s);case k.group:return I({flags:n});case k.lookahead:case k.lookbehind:return ze(e);default:throw new Error(`Unexpected group kind "${t}"`)}}function qt(e,t){let r=t!==void 0;if(r&&!ir(t))throw new Error(`Group name "${t}" invalid in Oniguruma`);return{type:l.CapturingGroup,number:e,...r&&{name:t},alternatives:[F()]}}function He(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?[]:[Xt()]}}function Xt(){return{type:l.CharacterClassIntersection,classes:[fe({negate:!1,baseOnly:!0})]}}function Jt(e,t){if(t.values[0].toUpperCase()+s.slice(1).toLowerCase())}function or(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 ir(e){return!/^(?:[-\d]|$)/.test(e)}function cr(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?.dotAll&&r?.dotAll&&delete t.dotAll,t?.ignoreCase&&r?.ignoreCase&&delete t.ignoreCase,t&&!Object.keys(t).length&&delete e.flags.enable},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=F();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(P(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}`:Ne().source;t(P(f`(?>\r\n|${o}|\P{M}\p{M}*)`,{bypassPropertyNameCheck:!0}))}else throw new Error(`Unexpected varcharset kind "${n}"`)}},We={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),w=c.has(h)||i.has(C),U=w&&!c.size;if(w&&!U)throw new Error("Unsupported indirect recursion");if(C?c.add(h):i.add(e),U){t(Qe(h)),r();return}let T=L(o,h,[]);for(let S=0;Sp.type===l.Group&&!!p.flags));u&&(c=W(I({flags:u}),[i]))}s(c),a||de(c,e,t,We)}},ur={CapturingGroup({node:e},t){e.number=++t.numCapturesToLeft,t.groupsWithDuplicateNamesToRemove.has(e)&&delete e.name},Backreference({node:e,replaceWith:t},{reffedNodesByBackreference:r}){let s=r.get(e),n=Xe(e,o=>o.type===l.CapturingGroup);if(s.length>1){let o=s.map(a=>ee(F(),[n.some(i=>i.number===a.number)?Q({negate:!0}):Z(a.number)]));t(ee(I(),o))}else n.some(o=>o.number===e.ref||o.name===e.ref)?t(Q({negate:!0})):e.ref=s[0].number}};function ee(e,t){return t.forEach(r=>r.parent=e),e[Je(e)]=t,e}function qe(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]=qe(a,t,n,r):(o==="type"&&a===l.CapturingGroup&&t.set(n,e),n[o]=a);return n}function Qe(e){if(typeof e=="number"&&e!==0)throw new Error("Unsupported recursion by number; use name instead");return{type:l.Recursion,ref:e}}function Xe(e,t){let r=[];for(;e=e.parent;)(!t||t(e))&&r.push(e);return r}function Je(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 Ze(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 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 P(e,{bypassPropertyNameCheck:t}={}){let s=O(M(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=Je(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 et(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 xr(d,p,h);case l.Pattern:return d.alternatives.map(h).join("|");case l.Quantifier:return h(d.element)+$r(d);case l.Recursion:return br(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?rt({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(),tt(e,{firstOnly:!0}).length&&r.setHasCasedChar()},CharacterSet({node:e},t){e.kind===b.property&&le.has(e.value)&&t.setHasCasedChar()}},fr=new Set(["$","(",")","*","+",".","?","[","\\","]","^","{","|","}"]),gr=new Set(["-","\\","]","^"]),hr=new Set(["(",")","-","/","[","\\","]","^","{","|","}","!","#","$","%","&","*","+",",",".",":",";","<","=",">","?","@","`","~"]),Ye=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=G(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=G(r,n),a=G(s,n),i="";if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase){let c=tt(e);yr(c).forEach(p=>{i+=Array.isArray(p)?`${G(p[0],n)}-${G(p[1],n)}`:G(p,n)})}return`${o}-${a}${i}`}function _r({kind:e,negate:t,value:r,key:s},n){if(e===b.any)return n.currentFlags.dotAll?n.appliedGlobalFlags.dotAll||n.useFlagMods?".":"[^]":f`[^\n]`;if(e===b.digit)return t?f`\D`:f`\d`;if(e===b.property){if(!n.usePostEs2018Properties&&$e.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===b.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 xr({atomic:e,flags:t,parent:r,alternatives:s},n,o){let a=n.currentFlags;t&&(n.currentFlags=rt(a,t));let i=s.map(o).join("|"),c=n.optimize&&s.length===1&&r.type!==l.Quantifier&&!e&&(!n.useFlagMods||!t)?i:`(?${Nr(e,t,n.useFlagMods)}${i})`;return n.currentFlags=a,c}function br({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 tt(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 G(e,{isAfterBackref:t,inCharClass:r,useFlagV:s}){if(Ye.has(e))return Ye.get(e);if(e<32||e>126&&e<160||e>262143||t&&Ir(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 rt(e,{enable:t,disable:r}){return{dotAll:!r?.dotAll&&!!(t?.dotAll||e.dotAll),ignoreCase:!r?.ignoreCase&&!!(t?.ignoreCase||e.ignoreCase)}}function $r({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 Ir(e){return e>47&&e<58}var x=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===x.DEFAULT==!a)){r instanceof Function?i+=r(c,{context:a?x.CHAR_CLASS:x.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 Fr(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===x.DEFAULT==!o))return a;i==="["?o++:i==="]"&&o&&o--,n.lastIndex==a.index&&n.lastIndex++}return null}function V(e,t,r){return!!Fr(e,t,0,r)}function nt(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 st={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([st.ENCLOSED_P,st.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})(),at="$E$";var Pr=String.raw`\(\?<(?![=!])(?[^>]+)>`,kn=String.raw`\((?!\?)(?!(?<=\(\?\()DEFINE\))|${Pr}`,ot=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("|"),xn=new RegExp(String.raw` +\v\f\r]`);i.negate=o,t(i)}},Directive(e,t){let{node:r,parent:s,ast:n,remove:o,replaceWith:a,removeAllPrevSiblings:i,removeAllNextSiblings:c}=e,{kind:u,flags:p}=r;if(u===D.flags)if(!p.enable&&!p.disable)o();else{let h=W(I({flags:p}),c());a(h),de(h,e,t,he)}else if(u===D.keep){if(s.parent!==n.pattern||n.pattern.alternatives.length>1)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?.dotAll&&r?.dotAll&&delete t.dotAll,t?.ignoreCase&&r?.ignoreCase&&delete t.ignoreCase,t&&!Object.keys(t).length&&delete e.flags.enable},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=F();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(P(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}`:Ne().source;t(P(f`(?>\r\n|${o}|\P{M}\p{M}*)`,{bypassPropertyNameCheck:!0}))}else throw new Error(`Unexpected varcharset kind "${n}"`)}},We={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),w=c.has(h)||i.has(C),U=w&&!c.size;if(w&&!U)throw new Error("Unsupported indirect recursion");if(C?c.add(h):i.add(e),U){t(Qe(h)),r();return}let T=L(o,h,[]);for(let S=0;Sp.type===l.Group&&!!p.flags));u&&(c=W(I({flags:u}),[i]))}s(c),a||de(c,e,t,We)}},ur={CapturingGroup({node:e},t){e.number=++t.numCapturesToLeft,t.groupsWithDuplicateNamesToRemove.has(e)&&delete e.name},Backreference({node:e,replaceWith:t},{reffedNodesByBackreference:r}){let s=r.get(e),n=Xe(e,o=>o.type===l.CapturingGroup);if(s.length>1){let o=s.map(a=>ee(F(),[n.some(i=>i.number===a.number)?Q({negate:!0}):Z(a.number)]));t(ee(I(),o))}else n.some(o=>o.number===e.ref||o.name===e.ref)?t(Q({negate:!0})):e.ref=s[0].number}};function ee(e,t){return t.forEach(r=>r.parent=e),e[Je(e)]=t,e}function qe(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]=qe(a,t,n,r):(o==="type"&&a===l.CapturingGroup&&t.set(n,e),n[o]=a);return n}function Qe(e){if(typeof e=="number"&&e!==0)throw new Error("Unsupported recursion by number; use name instead");return{type:l.Recursion,ref:e}}function Xe(e,t){let r=[];for(;e=e.parent;)(!t||t(e))&&r.push(e);return r}function Je(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 Ze(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 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 P(e,{bypassPropertyNameCheck:t}={}){let s=O(M(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=Je(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 et(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 xr(d,p,h);case l.Pattern:return d.alternatives.map(h).join("|");case l.Quantifier:return h(d.element)+$r(d);case l.Recursion:return br(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?rt({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(),tt(e,{firstOnly:!0}).length&&r.setHasCasedChar()},CharacterSet({node:e},t){e.kind===b.property&&le.has(e.value)&&t.setHasCasedChar()}},fr=new Set(["$","(",")","*","+",".","?","[","\\","]","^","{","|","}"]),gr=new Set(["-","\\","]","^"]),hr=new Set(["(",")","-","/","[","\\","]","^","{","|","}","!","#","$","%","&","*","+",",",".",":",";","<","=",">","?","@","`","~"]),Ye=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=G(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=G(r,n),a=G(s,n),i="";if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase){let c=tt(e);yr(c).forEach(p=>{i+=Array.isArray(p)?`${G(p[0],n)}-${G(p[1],n)}`:G(p,n)})}return`${o}-${a}${i}`}function _r({kind:e,negate:t,value:r,key:s},n){if(e===b.any)return n.currentFlags.dotAll?n.appliedGlobalFlags.dotAll||n.useFlagMods?".":"[^]":f`[^\n]`;if(e===b.digit)return t?f`\D`:f`\d`;if(e===b.property){if(!n.usePostEs2018Properties&&$e.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===b.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 xr({atomic:e,flags:t,parent:r,alternatives:s},n,o){let a=n.currentFlags;t&&(n.currentFlags=rt(a,t));let i=s.map(o).join("|"),c=n.optimize&&s.length===1&&r.type!==l.Quantifier&&!e&&(!n.useFlagMods||!t)?i:`(?${Nr(e,t,n.useFlagMods)}${i})`;return n.currentFlags=a,c}function br({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 tt(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 G(e,{isAfterBackref:t,inCharClass:r,useFlagV:s}){if(Ye.has(e))return Ye.get(e);if(e<32||e>126&&e<160||e>262143||t&&Ir(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 rt(e,{enable:t,disable:r}){return{dotAll:!r?.dotAll&&!!(t?.dotAll||e.dotAll),ignoreCase:!r?.ignoreCase&&!!(t?.ignoreCase||e.ignoreCase)}}function $r({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 Ir(e){return e>47&&e<58}var x=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===x.DEFAULT==!a)){r instanceof Function?i+=r(c,{context:a?x.CHAR_CLASS:x.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 Fr(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===x.DEFAULT==!o))return a;i==="["?o++:i==="]"&&o&&o--,n.lastIndex==a.index&&n.lastIndex++}return null}function V(e,t,r){return!!Fr(e,t,0,r)}function nt(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 st={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([st.ENCLOSED_P,st.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})(),at="$E$";var Pr=String.raw`\(\?<(?![=!])(?[^>]+)>`,kn=String.raw`\((?!\?)(?!(?<=\(\?\()DEFINE\))|${Pr}`,ot=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("|"),xn=new RegExp(String.raw` \\(?: c[A-Za-z] | p\{(?${Tr})\} | [pP]\{[^\}]+\} diff --git a/spec/match-backreference.spec.js b/spec/match-backreference.spec.js index 2e9ad4a..69b1cf4 100644 --- a/spec/match-backreference.spec.js +++ b/spec/match-backreference.spec.js @@ -17,6 +17,7 @@ describe('Backreference', () => { expect('').not.toFindMatch(r`(\1)`); expect('').not.toFindMatch(r`(((\2)))`); expect(['a', 'aa']).not.toFindMatch(r`(a\1)`); + expect('').not.toFindMatch(r`(\g<2>(\1))`); }); it('should throw if not enough captures to the left', () => { @@ -86,6 +87,7 @@ describe('Backreference', () => { expect('').not.toFindMatch(r`(\k<1>)`); expect('').not.toFindMatch(r`(((\k<2>)))`); expect(['a', 'aa']).not.toFindMatch(r`(a\k<1>)`); + expect('').not.toFindMatch(r`(\g<2>(\k<1>))`); }); it('should throw if not enough captures to the left', () => { @@ -167,6 +169,7 @@ describe('Backreference', () => { expect('').not.toFindMatch(r`(\k<-1>)`); expect('').not.toFindMatch(r`(((\k<-2>)))`); expect(['a', 'aa']).not.toFindMatch(r`(a\k<-1>)`); + expect('').not.toFindMatch(r`(\g<+1>(\k<-2>))`); }); it('should throw if not enough captures to the left', () => { @@ -255,12 +258,13 @@ describe('Backreference', () => { expect('').not.toFindMatch(r`(?\k)`); expect('').not.toFindMatch(r`(?(?(?\k)))`); expect(['a', 'aa']).not.toFindMatch(r`(?a\k)`); + expect('').not.toFindMatch(r`(?\g(?\k))`); expect('').not.toFindMatch(r`(?(?\k))`); expect('aa').toExactlyMatch(r`(?a)\k|(?b\k)`); expect(['a', 'b', 'ba', 'bb']).not.toFindMatch(r`(?a)\k|(?b\k)`); }); - it('should only preclude the not-yet-closed groups when multiplexing', () => { + it('should preclude only the not-yet-closed groups when multiplexing', () => { expect('aa').toExactlyMatch(r`(?a)(?\k)`); expect('aba').toExactlyMatch(r`(?a)(?b\k)`); expect(['aa', 'bcb']).toExactlyMatch(r`(?a)\k|(?b)(?c\k)`); @@ -306,6 +310,7 @@ describe('Backreference', () => { it('should increase multiplexing as duplicate names are added to the left', () => { expect(['aaba', 'aabb']).toExactlyMatch(r`(?a)\k(?b)\k`); + expect(['aaba', 'aabb']).toExactlyMatch(r`((?a)\k)(?b)\k`); expect(['abba', 'abbb']).not.toFindMatch(r`(?a)\k(?b)\k`); }); diff --git a/spec/match-subroutine.spec.js b/spec/match-subroutine.spec.js index 46f1968..c3491f7 100644 --- a/spec/match-subroutine.spec.js +++ b/spec/match-subroutine.spec.js @@ -7,6 +7,8 @@ beforeEach(() => { }); describe('Subroutine', () => { + // TODO: Test `\g'n'` syntax + describe('numbered', () => { it('should match the expression within the referenced group', () => { expect('aa').toExactlyMatch(r`(a)\g<1>`); diff --git a/src/transform.js b/src/transform.js index 8bae285..2f155eb 100644 --- a/src/transform.js +++ b/src/transform.js @@ -441,9 +441,9 @@ const SecondPassVisitor = { // named groups from their preceding siblings let upAlt = getParentAlternative(parentAlt); if (upAlt) { - while ((upAlt = getParentAlternative(upAlt))) { + do { getOrCreate(namedGroupsInScopeByAlt, upAlt, new Map()).set(name, node); - } + } while ((upAlt = getParentAlternative(upAlt))); } } },