UNPKG

regex-colorizer

Version:
37 lines (36 loc) 10.4 kB
var RegexColorizer=(()=>{var R=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var F=Object.prototype.hasOwnProperty;var D=(a,n)=>{for(var o in n)R(a,o,{get:n[o],enumerable:!0})},k=(a,n,o,l)=>{if(n&&typeof n=="object"||typeof n=="function")for(let c of x(n))!F.call(a,c)&&c!==o&&R(a,c,{get:()=>n[c],enumerable:!(l=w(n,c))||l.enumerable});return a};var H=a=>k(R({},"__esModule",{value:!0}),a);var W={};D(W,{colorizeAll:()=>K,colorizePattern:()=>y,loadStyles:()=>Y});var q="[pP] { (?<property> (?: [A-Za-z_]+ = )? [A-Za-z_]+ ) }",S=String.raw`c [A-Za-z] | u (?: [\dA-Fa-f]{4} | { [\dA-Fa-f]+ } ) | x [\dA-Fa-f]{2}`,$="[0-3][0-7]{0,2}|[4-7][0-7]?",P=new RegExp(String.raw` \[\^?(?:[^\\\]]+|\\.?)*]? | \\(?:0(?:${$})?|[1-9]\d*|${S}|k(?:<(?<backrefName>\w+)>)?|${q}|.?) | \((?:\?(?:<(?:[=!]|(?<captureName>[A-Za-z_]\w*)>)|[:=!]))? | (?:[?*+]|\{\d+(?:,\d*)?\})\?? | [^.?*+^$[\]{}()|\\]+ | . `.replace(/\s+/g,""),"gs"),O=new RegExp(String.raw` [^\\-]+ | \\ (?: ${$} | ${S} | ${q} | .? ) | - `.replace(/\s+/g,""),"gs"),v=/^(?<opening>\[\^?)(?<content>(?:[^\\\]]+|\\.?)*)(?<closing>]?)$/s,U=/^(?:[?*+]|\{\d+(?:,\d*)?\})\??$/,f={NONE:0,RANGE_HYPHEN:1,SHORT_CLASS:2,ALTERNATOR:3},i={DUPLICATE_CAPTURE_NAME:"Duplicate capture name",EMPTY_TOP_ALTERNATIVE:"Empty alternative effectively truncates the regex here",INCOMPLETE_TOKEN:"Token is incomplete",INDEX_OVERFLOW:"Character index cannot use value over 10FFFF",INTERVAL_OVERFLOW:"Interval quantifier cannot use value over 65,535",INTERVAL_REVERSED:"Interval quantifier range is reversed",INVALID_BACKREF:"Backreference to missing or invalid group",INVALID_ESCAPE:"Deprecated escaped literal or octal",INVALID_RANGE:"Reversed or invalid range",REQUIRES_ESCAPE:"Must be escaped unless part of a valid token",UNBALANCED_LEFT_PAREN:"Unclosed grouping",UNBALANCED_RIGHT_PAREN:"No matching opening parenthesis",UNCLOSED_CLASS:"Unclosed character class",UNQUANTIFIABLE:"Preceding token is not quantifiable"},u=`rc-${(+new Date).toString(36).slice(-5)}`,r={alternator:(a,n)=>`<b${n?` class="g${n}"`:""}>${a}</b>`,backref:a=>`<b class="bref">${a}</b>`,charClass:a=>`<i>${a}</i>`,charClassBoundary:a=>`<span>${a}</span>`,error:(a,n)=>`<b class="err" title="${n}">${a}</b>`,escapedLiteral:a=>`<span>${a}</span>`,group:(a,n)=>`<b class="g${n}">${a}</b>`,metasequence:a=>`<b>${a}</b>`,quantifier:(a,n)=>`<b${n?` class="g${n}"`:""}>${a}</b>`,range:a=>`<u>${a}</u>`};r.group.openingTagLength=14;function p(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;")}function V(a){return a.replace(/&amp;/g,"&").replace(/&lt;/g,"<")}function C(a){if(a.length>1&&a.charAt(0)==="\\"){let n=a.slice(1);if(/^c[A-Za-z]$/.test(n))return"ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(n.charAt(1).toUpperCase())+1;if(/^(?:x[\dA-Fa-f]{2}|u[\dA-Fa-f]{4})$/.test(n))return parseInt(n.slice(1),16);if(/^u{[\dA-Fa-f]+}$/.test(n))return parseInt(n.slice(2,-1),16);if(new RegExp(`^(?:${$})$`).test(n))return parseInt(n,8);if(n.length===1&&"cuxDdSsWw".includes(n))return NaN;if(n.length===1)switch(n){case"b":return 8;case"f":return 12;case"n":return 10;case"r":return 13;case"t":return 9;case"v":return 11;default:return n.charCodeAt(0)}}return a!=="\\"?a.charCodeAt(0):NaN}function B(a,n){let o="",l={rangeable:!1,type:f.NONE},{opening:c,content:A,closing:g}=v.exec(a).groups,L=A.matchAll(O);for(let d of L){let t=d[0];if(t.charAt(0)==="\\")if(/^\\[cux]$/.test(t))o+=r.error(t,i.INCOMPLETE_TOKEN),l={rangeable:l.type!==f.RANGE_HYPHEN};else if(n.unicode&&/^\\p$/i.test(t))o+=r.error(t,i.INCOMPLETE_TOKEN),l={rangeable:l.type!==f.RANGE_HYPHEN,type:f.SHORT_CLASS};else if(/^\\[dsw]$/i.test(t))o+=r.metasequence(t),l={rangeable:l.type!==f.RANGE_HYPHEN,type:f.SHORT_CLASS};else if(t==="\\")o+=r.error(t,i.INCOMPLETE_TOKEN);else if(d.groups.property)n.unicode?(o+=r.metasequence(t),l={rangeable:l.type!==f.RANGE_HYPHEN,type:f.SHORT_CLASS}):(o+=r.metasequence(t.slice(0,2))+t.slice(2),l={rangeable:!0,charCode:C("}")});else if(n.unicode&&/^\\(?:[^\^$?*+.|(){}[\]\\/\-0bcdDfnpPrsStuvwWx]|0\d)/.test(t))o+=r.error(p(t),i.INVALID_ESCAPE),l={rangeable:l.type!==f.RANGE_HYPHEN};else if(t.startsWith("\\u{"))if(n.unicode){let s=C(t);o+=s<=1114111?r.metasequence(t):r.error(t,i.INDEX_OVERFLOW),l={rangeable:l.type!==f.RANGE_HYPHEN,charCode:s}}else o+=r.error("\\u",i.INCOMPLETE_TOKEN)+t.slice(2),l={rangeable:!0,charCode:C("}")};else o+=r.metasequence(p(t)),l={rangeable:l.type!==f.RANGE_HYPHEN,charCode:C(t)};else if(t==="-")if(l.rangeable){let s=new RegExp(O);s.lastIndex=d.index+d[0].length;let h=s.exec(A);if(h){let T=C(h[0]);!isNaN(T)&&l.charCode>T||l.type===f.SHORT_CLASS||/^\\[dsw]$/i.test(h[0])||n.unicode&&h.groups.property?o+=r.error("-",i.INVALID_RANGE):o+=r.range("-"),l={rangeable:!1,type:f.RANGE_HYPHEN}}else g?o+="-":o+=r.range("-")}else o+="-",l={rangeable:l.type!==f.RANGE_HYPHEN};else o+=p(t),l={rangeable:t.length>1||l.type!==f.RANGE_HYPHEN,charCode:t.charCodeAt(t.length-1)}}return g?o=r.charClassBoundary(c)+o+r.charClassBoundary(g):o=r.error(c,i.UNCLOSED_CLASS)+o,o}function G(a){let n=new Set,o=0,l=a.matchAll(P);for(let c of l){let A=c.groups.captureName;A&&n.add(A),/^\((?=\?<(?![=!])|$)/.test(c[0])&&o++}return{captureNames:n,totalCaptures:o}}function M(a){let n={d:"hasIndices",g:"global",i:"ignoreCase",m:"multiline",s:"dotAll",u:"unicode",v:"unicodeSets",y:"sticky"},o=Object.fromEntries(Object.values(n).map(c=>[c,!1])),l=new Set;for(let c of a){if(l.has(c))throw new Error(`Duplicate flag: ${c}`);if(!Object.hasOwn(n,c))throw new Error(`Unknown flag: ${c}`);l.add(c),o[n[c]]=!0}if(o.unicodeSets)throw new Error("Flag v is not yet supported");return o}function y(a,{flags:n=""}={}){let o=M(n),{captureNames:l,totalCaptures:c}=G(a),A=new Set,g=[],L=0,d=0,t={quantifiable:!1,type:f.NONE},s="",h=a.matchAll(P);for(let N of h){let e=N[0],_=e.charAt(0),b=e.charAt(1);if(_==="[")s+=r.charClass(B(e,o)),t={quantifiable:!0};else if(_==="("){let E=N.groups.captureName;d=d===5?1:d+1,A.has(E)?(g.push({valid:!1,opening:p(e)}),s+=r.error(p(e),i.DUPLICATE_CAPTURE_NAME)):((e==="("||E)&&(L++,E&&A.add(E)),g.push({valid:!0,opening:p(e),index:s.length+r.group.openingTagLength}),s+=r.group(p(e),d)),t={quantifiable:!1}}else if(e===")")!g.length||!g.at(-1).valid?(s+=r.error(e,i.UNBALANCED_RIGHT_PAREN),t={quantifiable:!1}):(s+=r.group(e,d),t={quantifiable:!/^\(\?<?[=!]/.test(V(g.at(-1).opening)),groupStyleDepth:d}),d=d===1?5:d-1,g.pop();else if(_==="\\")if(/^[1-9]/.test(b))if(+e.slice(1)<=c)s+=r.backref(e),t={quantifiable:!0};else if(o.unicode)s+=r.error(e,i.INVALID_BACKREF),t={quantifiable:!1};else{let{escapedNum:E,escapedLiteral:I,literal:m}=new RegExp(String.raw`^\\(?<escapedNum>${$}|(?<escapedLiteral>[89]))(?<literal>\d*)`).exec(e).groups;I?s+=`${r.escapedLiteral(`\\${I}`)}${m}`:s+=`${r.metasequence(`\\${E}`)}${m}`,t={quantifiable:!0}}else if(b==="k")l.size?l.has(N.groups.backrefName)?(s+=r.backref(p(e)),t={quantifiable:!0}):e.endsWith(">")?(s+=r.error(p(e),i.INVALID_BACKREF),t={quantifiable:!1}):(s+=r.error(e,i.INCOMPLETE_TOKEN),t={quantifiable:!1}):o.unicode?(s+=r.error(p(e),i.INVALID_BACKREF),t={quantifiable:!1}):(s+=r.escapedLiteral("\\k")+p(e.slice(2)),t={quantifiable:!0});else if(N.groups.property)o.unicode?s+=r.metasequence(e):s+=r.escapedLiteral(`\\${b}`)+e.slice(2),t={quantifiable:!0};else if(o.unicode&&"pP".includes(b))s+=r.error(e,i.INCOMPLETE_TOKEN),t={quantifiable:!1};else if(/^[0bBcdDfnrsStuvwWx]/.test(b))if(/^\\[cux]$/.test(e))s+=r.error(e,i.INCOMPLETE_TOKEN),t={quantifiable:!1};else if(e.startsWith("\\u{"))if(o.unicode){let E=C(e);s+=E<=1114111?r.metasequence(e):r.error(e,i.INDEX_OVERFLOW),t={quantifiable:!0}}else/^\\u{\d+}$/.test(e)?(s+=r.error("\\u",i.INCOMPLETE_TOKEN)+r.error(e.slice(2),i.UNQUANTIFIABLE),t={quantifiable:!1}):(s+=r.error("\\u",i.INCOMPLETE_TOKEN)+e.slice(2),t={quantifiable:!0});else"bB".includes(b)?(s+=r.metasequence(e),t={quantifiable:!1}):o.unicode&&/^\\0\d/.test(e)?(s+=r.error(e,i.INVALID_ESCAPE),t={quantifiable:!1}):(s+=r.metasequence(e),t={quantifiable:!0});else e==="\\"?s+=r.error(e,i.INCOMPLETE_TOKEN):o.unicode&&/^[^\^$?*+.|(){}[\]\\/]$/.test(b)?(s+=r.error(p(e),i.INVALID_ESCAPE),t={quantifiable:!1}):(s+=r.escapedLiteral(p(e)),t={quantifiable:!0});else if(U.test(e)){if(t.quantifiable){let E=/^\{(\d+)(?:,(\d*))?/.exec(e);E&&(+E[1]>65535||E[2]&&+E[2]>65535)?s+=r.error(e,i.INTERVAL_OVERFLOW):E&&E[2]&&+E[1]>+E[2]?s+=r.error(e,i.INTERVAL_REVERSED):s+=r.quantifier(e,t.groupStyleDepth??0)}else s+=r.error(e,i.UNQUANTIFIABLE);t={quantifiable:!1}}else e==="|"?(t.type===f.NONE||t.type===f.ALTERNATOR&&!g.length?s+=r.error(e,i.EMPTY_TOP_ALTERNATIVE):s+=r.alternator(e,g.length&&d),t={quantifiable:!1,type:f.ALTERNATOR}):e==="^"||e==="$"?(s+=r.metasequence(e),t={quantifiable:!1}):e==="."?(s+=r.metasequence(e),t={quantifiable:!0}):o.unicode&&"{}]".includes(e)?(s+=r.error(e,i.REQUIRES_ESCAPE),t={quantifiable:!1}):(s+=p(e),t={quantifiable:!0})}let T=0;for(let N of g){if(!N.valid)continue;let e=N.index+T;s=s.slice(0,e)+r.error(N.opening,i.UNBALANCED_LEFT_PAREN)+s.slice(e+N.opening.length),T+=r.error("",i.UNBALANCED_LEFT_PAREN).length}return s}function K({selector:a=".regex",flags:n=""}={}){document.querySelectorAll(a).forEach(l=>{l.classList.add(u),l.innerHTML=y(l.textContent,{flags:l.dataset.flags||n})})}function Y(){if(document.getElementById(u))return;let a=document.createElement("style");a.id=u,a.textContent=` .${u} {color: #000; font-family: Consolas, "Source Code Pro", Monospace; white-space: pre-wrap; word-break: break-all; overflow-wrap: anywhere;} .${u} b {font-weight: normal;} .${u} i {font-style: normal;} .${u} u {text-decoration: none;} .${u} * {border-radius: 0.25em;} .${u} span {background: #eee;} .${u} b {background: #80c0ff; color: #092e7f;} .${u} b.bref {background: #86e9ff; color: #0d47c4;} .${u} b.err {background: #e30000; color: #fff; font-style: normal;} .${u} i {background: #e3e3e3; font-style: italic;} .${u} i span {background: #c3c3c3; font-style: normal;} .${u} i b {background: #c3c3c3; color: #222;} .${u} i u {background: #d3d3d3;} .${u} b.g1 {background: #b4fa50; color: #074d0b;} .${u} b.g2 {background: #8cd400; color: #053c08;} .${u} b.g3 {background: #26b809; color: #fff;} .${u} b.g4 {background: #30ea60; color: #125824;} .${u} b.g5 {background: #0c8d15; color: #fff;} `,document.querySelector("head").appendChild(a)}return H(W);})(); /*! Regex Colorizer (c) 2010-2025 Steven Levithan MIT License */