UNPKG

fast-xml-parser

Version:

Validate XML, Parse XML, Build XML without C/C++ based libraries

1 lines 75.9 kB
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.fxp=e():t.fxp=e()}(this,()=>(()=>{"use strict";var t={d:(e,i)=>{for(var r in i)t.o(i,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:i[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{XMLBuilder:()=>ve,XMLParser:()=>Kt,XMLValidator:()=>ye});var i=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",r=new RegExp("^["+i+"]["+i+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function n(t,e){for(var i=[],r=e.exec(t);r;){var n=[];n.startIndex=e.lastIndex-r[0].length;for(var s=r.length,o=0;o<s;o++)n.push(r[o]);i.push(n),r=e.exec(t)}return i}var s=function(t){return!(null==r.exec(t))},o=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],a=["__proto__","constructor","prototype"],l={allowBooleanAttributes:!1,unpairedTags:[]};function p(t,e){e=Object.assign({},l,e);var i=[],r=!1,n=!1;"\ufeff"===t[0]&&(t=t.substr(1));for(var s=0;s<t.length;s++)if("<"===t[s]&&"?"===t[s+1]){if((s=h(t,s+=2)).err)return s}else{if("<"!==t[s]){if(c(t[s]))continue;return v("InvalidChar","char '"+t[s]+"' is not expected.",E(t,s))}var o=s;if("!"===t[++s]){s=d(t,s);continue}var a=!1;"/"===t[s]&&(a=!0,s++);for(var p="";s<t.length&&">"!==t[s]&&" "!==t[s]&&"\t"!==t[s]&&"\n"!==t[s]&&"\r"!==t[s];s++)p+=t[s];if("/"===(p=p.trim())[p.length-1]&&(p=p.substring(0,p.length-1),s--),!N(p))return v("InvalidTag",0===p.trim().length?"Invalid space after '<'.":"Tag '"+p+"' is an invalid name.",E(t,s));var u=g(t,s);if(!1===u)return v("InvalidAttr","Attributes for '"+p+"' have open quote.",E(t,s));var f=u.value;if(s=u.index,"/"===f[f.length-1]){var m=s-f.length,y=x(f=f.substring(0,f.length-1),e);if(!0!==y)return v(y.err.code,y.err.msg,E(t,m+y.err.line));r=!0}else if(a){if(!u.tagClosed)return v("InvalidTag","Closing tag '"+p+"' doesn't have proper closing.",E(t,s));if(f.trim().length>0)return v("InvalidTag","Closing tag '"+p+"' can't have attributes or invalid starting.",E(t,o));if(0===i.length)return v("InvalidTag","Closing tag '"+p+"' has not been opened.",E(t,o));var w=i.pop();if(p!==w.tagName){var S=E(t,w.tagStartPos);return v("InvalidTag","Expected closing tag '"+w.tagName+"' (opened in line "+S.line+", col "+S.col+") instead of closing tag '"+p+"'.",E(t,o))}0==i.length&&(n=!0)}else{var A=x(f,e);if(!0!==A)return v(A.err.code,A.err.msg,E(t,s-f.length+A.err.line));if(!0===n)return v("InvalidXml","Multiple possible root nodes found.",E(t,s));-1!==e.unpairedTags.indexOf(p)||i.push({tagName:p,tagStartPos:o}),r=!0}for(s++;s<t.length;s++)if("<"===t[s]){if("!"===t[s+1]){s=d(t,++s);continue}if("?"!==t[s+1])break;if((s=h(t,++s)).err)return s}else if("&"===t[s]){var T=b(t,s);if(-1==T)return v("InvalidChar","char '&' is not expected.",E(t,s));s=T}else if(!0===n&&!c(t[s]))return v("InvalidXml","Extra text at the end",E(t,s));"<"===t[s]&&s--}return r?1==i.length?v("InvalidTag","Unclosed tag '"+i[0].tagName+"'.",E(t,i[0].tagStartPos)):!(i.length>0)||v("InvalidXml","Invalid '"+JSON.stringify(i.map(function(t){return t.tagName}),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):v("InvalidXml","Start tag expected.",1)}function c(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function h(t,e){for(var i=e;e<t.length;e++)if("?"!=t[e]&&" "!=t[e]);else{var r=t.substr(i,e-i);if(e>5&&"xml"===r)return v("InvalidXml","XML declaration allowed only at the start of the document.",E(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}}return e}function d(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e<t.length;e++)if("-"===t[e]&&"-"===t[e+1]&&">"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){var i=1;for(e+=8;e<t.length;e++)if("<"===t[e])i++;else if(">"===t[e]&&0===--i)break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e<t.length;e++)if("]"===t[e]&&"]"===t[e+1]&&">"===t[e+2]){e+=2;break}return e}var u='"',f="'";function g(t,e){for(var i="",r="",n=!1;e<t.length;e++){if(t[e]===u||t[e]===f)""===r?r=t[e]:r!==t[e]||(r="");else if(">"===t[e]&&""===r){n=!0;break}i+=t[e]}return""===r&&{value:i,index:e,tagClosed:n}}var m=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function x(t,e){for(var i=n(t,m),r={},s=0;s<i.length;s++){if(0===i[s][1].length)return v("InvalidAttr","Attribute '"+i[s][2]+"' has no space in starting.",w(i[s]));if(void 0!==i[s][3]&&void 0===i[s][4])return v("InvalidAttr","Attribute '"+i[s][2]+"' is without value.",w(i[s]));if(void 0===i[s][3]&&!e.allowBooleanAttributes)return v("InvalidAttr","boolean attribute '"+i[s][2]+"' is not allowed.",w(i[s]));var o=i[s][2];if(!y(o))return v("InvalidAttr","Attribute '"+o+"' is an invalid name.",w(i[s]));if(Object.prototype.hasOwnProperty.call(r,o))return v("InvalidAttr","Attribute '"+o+"' is repeated.",w(i[s]));r[o]=1}return!0}function b(t,e){if(";"===t[++e])return-1;if("#"===t[e])return function(t,e){var i=/\d/;for("x"===t[e]&&(e++,i=/[\da-fA-F]/);e<t.length;e++){if(";"===t[e])return e;if(!t[e].match(i))break}return-1}(t,++e);for(var i=0;e<t.length;e++,i++)if(!(t[e].match(/\w/)&&i<20)){if(";"===t[e])break;return-1}return e}function v(t,e,i){return{err:{code:t,msg:e,line:i.line||i,col:i.col}}}function y(t){return s(t)}function N(t){return s(t)}function E(t,e){var i=t.substring(0,e).split(/\r?\n/);return{line:i.length,col:i[i.length-1].length+1}}function w(t){return t.startIndex+t[1].length}var S=function(t){return o.includes(t)?"__"+t:t},A={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0,unicode:!1},tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},stopNodes:[],alwaysCreateTextNode:!1,isArray:function(){return!1},commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,entityDecoder:null,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,i){return t},captureMetaData:!1,maxNestedTags:100,strictReservedNames:!0,jPath:!0,onDangerousProperty:S};function T(t,e){if("string"==typeof t){var i=t.toLowerCase();if(o.some(function(t){return i===t.toLowerCase()}))throw new Error("[SECURITY] Invalid "+e+': "'+t+'" is a reserved JavaScript keyword that could cause prototype pollution');if(a.some(function(t){return i===t.toLowerCase()}))throw new Error("[SECURITY] Invalid "+e+': "'+t+'" is a reserved JavaScript keyword that could cause prototype pollution')}}function _(t,e){return"boolean"==typeof t?{enabled:t,maxEntitySize:1e4,maxExpansionDepth:1e4,maxTotalExpansions:1/0,maxExpandedLength:1e5,maxEntityCount:1e3,allowedTags:null,tagFilter:null,appliesTo:"all"}:"object"==typeof t&&null!==t?{enabled:!1!==t.enabled,maxEntitySize:Math.max(1,null!=(i=t.maxEntitySize)?i:1e4),maxExpansionDepth:Math.max(1,null!=(r=t.maxExpansionDepth)?r:1e4),maxTotalExpansions:Math.max(1,null!=(n=t.maxTotalExpansions)?n:1/0),maxExpandedLength:Math.max(1,null!=(s=t.maxExpandedLength)?s:1e5),maxEntityCount:Math.max(1,null!=(o=t.maxEntityCount)?o:1e3),allowedTags:null!=(a=t.allowedTags)?a:null,tagFilter:null!=(l=t.tagFilter)?l:null,appliesTo:null!=(p=t.appliesTo)?p:"all"}:_(!0);var i,r,n,s,o,a,l,p}var C,O=function(t){for(var e=Object.assign({},A,t),i=0,r=[{value:e.attributeNamePrefix,name:"attributeNamePrefix"},{value:e.attributesGroupName,name:"attributesGroupName"},{value:e.textNodeName,name:"textNodeName"},{value:e.cdataPropName,name:"cdataPropName"},{value:e.commentPropName,name:"commentPropName"}];i<r.length;i++){var n=r[i],s=n.value,o=n.name;s&&T(s,o)}return null===e.onDangerousProperty&&(e.onDangerousProperty=S),e.processEntities=_(e.processEntities,e.htmlEntities),e.unpairedTagsSet=new Set(e.unpairedTags),e.stopNodes&&Array.isArray(e.stopNodes)&&(e.stopNodes=e.stopNodes.map(function(t){return"string"==typeof t&&t.startsWith("*.")?".."+t.substring(2):t})),e};C="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");var j=function(){function t(t){this.tagname=t,this.child=[],this[":@"]=Object.create(null)}var e=t.prototype;return e.add=function(t,e){var i;"__proto__"===t&&(t="#__proto__"),this.child.push(((i={})[t]=e,i))},e.addChild=function(t,e){var i,r;"__proto__"===t.tagname&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push(((i={})[t.tagname]=t.child,i[":@"]=t[":@"],i)):this.child.push(((r={})[t.tagname]=t.child,r)),void 0!==e&&(this.child[this.child.length-1][C]={startIndex:e})},t.getMetaDataSymbol=function(){return C},t}();const P=":A-Za-z_À-ÖØ-öø-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�",$=":A-Za-z_À-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",I=$+"\\-\\.\\d·̀-ͯ҇‿-⁀",k=(t,e,i="")=>{const r=`[${t.replace(":","")}][${e.replace(":","")}]*`;return{name:new RegExp(`^[${t}][${e}]*$`,i),ncName:new RegExp(`^${r}$`,i),qName:new RegExp(`^${r}(?::${r})?$`,i),nmToken:new RegExp(`^[${e}]+$`,i),nmTokens:new RegExp(`^[${e}]+(?:\\s+[${e}]+)*$`,i)}},L=k(P,P+"\\-\\.\\d·̀-ͯ‿-⁀"),D=k($,I,"u"),R=(t,{xmlVersion:e="1.0"}={})=>((t="1.0")=>"1.1"===t?D:L)(e).qName.test(t);var M=function(){function t(t,e){this.suppressValidationErr=!t,this.options=t,this.xmlVersion=e||1}var e=t.prototype;return e.setXmlVersion=function(t){void 0===t&&(t=1),this.xmlVersion=t},e.readDocType=function(t,e){var i=Object.create(null),r=0;if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");e+=9;for(var n=1,s=!1,o=!1;e<t.length;e++)if("<"!==t[e]||o)if(">"===t[e]){if(o?"-"===t[e-1]&&"-"===t[e-2]&&(o=!1,n--):n--,0===n)break}else"["===t[e]?s=!0:t[e];else{if(s&&q(t,"!ENTITY",e)){e+=7;var a,l=void 0,p=this.readEntityExp(t,e+1,this.suppressValidationErr);if(a=p[0],l=p[1],e=p[2],-1===l.indexOf("&")){if(!1!==this.options.enabled&&null!=this.options.maxEntityCount&&r>=this.options.maxEntityCount)throw new Error("Entity count ("+(r+1)+") exceeds maximum allowed ("+this.options.maxEntityCount+")");i[a]=l,r++}}else if(s&&q(t,"!ELEMENT",e))e+=8,e=this.readElementExp(t,e+1).index;else if(s&&q(t,"!ATTLIST",e))e+=8;else if(s&&q(t,"!NOTATION",e))e+=9,e=this.readNotationExp(t,e+1,this.suppressValidationErr).index;else{if(!q(t,"!--",e))throw new Error("Invalid DOCTYPE");o=!0}n++}if(0!==n)throw new Error("Unclosed DOCTYPE");return{entities:i,i:e}},e.readEntityExp=function(t,e){for(var i=e=V(t,e);e<t.length&&!/\s/.test(t[e])&&'"'!==t[e]&&"'"!==t[e];)e++;var r=t.substring(i,e);if(F(r,{xmlVersion:this.xmlVersion}),e=V(t,e),!this.suppressValidationErr){if("SYSTEM"===t.substring(e,e+6).toUpperCase())throw new Error("External entities are not supported");if("%"===t[e])throw new Error("Parameter entities are not supported")}var n,s=this.readIdentifierVal(t,e,"entity");if(e=s[0],n=s[1],!1!==this.options.enabled&&null!=this.options.maxEntitySize&&n.length>this.options.maxEntitySize)throw new Error('Entity "'+r+'" size ('+n.length+") exceeds maximum allowed size ("+this.options.maxEntitySize+")");return[r,n,--e]},e.readNotationExp=function(t,e){for(var i=e=V(t,e);e<t.length&&!/\s/.test(t[e]);)e++;var r=t.substring(i,e);!this.suppressValidationErr&&F(r,{xmlVersion:this.xmlVersion}),e=V(t,e);var n=t.substring(e,e+6).toUpperCase();if(!this.suppressValidationErr&&"SYSTEM"!==n&&"PUBLIC"!==n)throw new Error('Expected SYSTEM or PUBLIC, found "'+n+'"');e+=n.length,e=V(t,e);var s=null,o=null;if("PUBLIC"===n){var a=this.readIdentifierVal(t,e,"publicIdentifier");if(e=a[0],s=a[1],'"'===t[e=V(t,e)]||"'"===t[e]){var l=this.readIdentifierVal(t,e,"systemIdentifier");e=l[0],o=l[1]}}else if("SYSTEM"===n){var p=this.readIdentifierVal(t,e,"systemIdentifier");if(e=p[0],o=p[1],!this.suppressValidationErr&&!o)throw new Error("Missing mandatory system identifier for SYSTEM notation")}return{notationName:r,publicIdentifier:s,systemIdentifier:o,index:--e}},e.readIdentifierVal=function(t,e,i){var r,n=t[e];if('"'!==n&&"'"!==n)throw new Error('Expected quoted string, found "'+n+'"');for(var s=++e;e<t.length&&t[e]!==n;)e++;if(r=t.substring(s,e),t[e]!==n)throw new Error("Unterminated "+i+" value");return[++e,r]},e.readElementExp=function(t,e){for(var i=e=V(t,e);e<t.length&&!/\s/.test(t[e]);)e++;var r=t.substring(i,e);if(!this.suppressValidationErr&&!R(r,{xmlVersion:this.xmlVersion}))throw new Error('Invalid element name: "'+r+'"');var n="";if("E"===t[e=V(t,e)]&&q(t,"MPTY",e))e+=4;else if("A"===t[e]&&q(t,"NY",e))e+=2;else if("("===t[e]){for(var s=++e;e<t.length&&")"!==t[e];)e++;if(n=t.substring(s,e),")"!==t[e])throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error('Invalid Element Expression, found "'+t[e]+'"');return{elementName:r,contentModel:n.trim(),index:e}},e.readAttlistExp=function(t,e){for(var i=e=V(t,e);e<t.length&&!/\s/.test(t[e]);)e++;var r=t.substring(i,e);for(F(r,{xmlVersion:this.xmlVersion}),i=e=V(t,e);e<t.length&&!/\s/.test(t[e]);)e++;var n=t.substring(i,e);if(!F(n,{xmlVersion:this.xmlVersion}))throw new Error('Invalid attribute name: "'+n+'"');e=V(t,e);var s="";if("NOTATION"===t.substring(e,e+8).toUpperCase()){if(s="NOTATION","("!==t[e=V(t,e+=8)])throw new Error("Expected '(', found \""+t[e]+'"');e++;for(var o=[];e<t.length&&")"!==t[e];){for(var a=e;e<t.length&&"|"!==t[e]&&")"!==t[e];)e++;var l=t.substring(a,e);if(!F(l=l.trim(),{xmlVersion:this.xmlVersion}))throw new Error('Invalid notation name: "'+l+'"');o.push(l),"|"===t[e]&&(e++,e=V(t,e))}if(")"!==t[e])throw new Error("Unterminated list of notations");e++,s+=" ("+o.join("|")+")"}else{for(var p=e;e<t.length&&!/\s/.test(t[e]);)e++;if(s+=t.substring(p,e),!this.suppressValidationErr&&!["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"].includes(s.toUpperCase()))throw new Error('Invalid attribute type: "'+s+'"')}e=V(t,e);var c="";if("#REQUIRED"===t.substring(e,e+8).toUpperCase())c="#REQUIRED",e+=8;else if("#IMPLIED"===t.substring(e,e+7).toUpperCase())c="#IMPLIED",e+=7;else{var h=this.readIdentifierVal(t,e,"ATTLIST");e=h[0],c=h[1]}return{elementName:r,attributeName:n,attributeType:s,defaultValue:c,index:e}},t}(),V=function(t,e){for(;e<t.length&&/\s/.test(t[e]);)e++;return e};function q(t,e,i){for(var r=0;r<e.length;r++)if(e[r]!==t[i+r+1])return!1;return!0}function F(t,e){if(R(t,{xmlVersion:e}))return t;throw new Error("Invalid entity name "+t)}const U=[48,1632,1776,2406,2534,2662,2790,2918,3046,3174,3302,3430,3558,3664,3792,3872,4160,4240,6112,6160,6470,6608,6784,6800,6992,7088,7232,7248,65296,120782,120792,120802,120812,120822,66720,68912,69734,69872,69942,70096,70384,70736,70864,71248,71360,71472,71904,72016,72688,72784,73040,73120,73552,92768,92864,93008,123200,123632,124144,125264,130032],G=new Map,B=1632,W=new Uint8Array(63904).fill(255);for(const t of U)for(let e=0;e<10;e++){const i=t+e;i<=65535?W[i-B]=e:G.set(i,e)}const X=new Set([8722,65293,65123]),Y=/^[-+]?0x[a-fA-F0-9]+$/,z=/^0b[01]+$/,H=/^0o[0-7]+$/,Q=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,J={hex:!0,binary:!1,octal:!1,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original",unicode:!1};function Z(t,e={}){if(e=Object.assign({},J,e),!t||"string"!=typeof t)return t;let i=t.trim();if(0===i.length)return t;if(void 0!==e.skipLike&&e.skipLike.test(i))return t;if("0"===i)return 0;if(e.unicode&&(i=function(t){if("string"!=typeof t)return t;const e=t.length;if(0===e)return t;let i=-1;for(let r=0;r<e;r++){const n=t.charCodeAt(r);if(!(n>=48&&n<=57||45===n))if(n<B){if(X.has(n)){i=r;break}}else if(n>=55296&&n<=56319){if(r+1<e){const e=t.charCodeAt(r+1);if(e>=56320&&e<=57343){const t=65536+(n-55296<<10)+(e-56320);if(G.has(t)){i=r;break}}}}else if(255!==W[n-B]||X.has(n)){i=r;break}}if(-1===i)return t;const r=[];i>0&&r.push(t.slice(0,i));for(let n=i;n<e;n++){const i=t.charCodeAt(n);if(i>=48&&i<=57||45===i){r.push(t[n]);continue}if(i<B){r.push(X.has(i)?"-":t[n]);continue}if(i>=55296&&i<=56319){if(n+1<e){const e=t.charCodeAt(n+1);if(e>=56320&&e<=57343){const t=65536+(i-55296<<10)+(e-56320),s=G.get(t);if(void 0!==s){r.push(String.fromCharCode(s+48)),n++;continue}}}r.push(t[n]);continue}if(X.has(i)){r.push("-");continue}const s=W[i-B];r.push(255!==s?String.fromCharCode(s+48):t[n])}return r.join("")}(i),"0"===i))return 0;if(e.hex&&Y.test(i))return tt(i,16);if(e.binary&&z.test(i))return tt(i,2);if(e.octal&&H.test(i))return tt(i,8);if(isFinite(i)){if(i.includes("e")||i.includes("E"))return function(t,e,i){if(!i.eNotation)return t;const r=e.match(K);if(r){let n=r[1]||"";const s=-1===r[3].indexOf("e")?"E":"e",o=r[2],a=n?t[o.length+1]===s:t[o.length]===s;return o.length>1&&a?t:(1!==o.length||!r[3].startsWith(`.${s}`)&&r[3][0]!==s)&&o.length>0?i.leadingZeros&&!a?(e=(r[1]||"")+r[3],Number(e)):t:Number(e)}return t}(t,i,e);{const n=Q.exec(i);if(n){const s=n[1]||"",o=n[2];let a=(r=n[3])&&-1!==r.indexOf(".")?("."===(r=r.replace(/0+$/,""))?r="0":"."===r[0]?r="0"+r:"."===r[r.length-1]&&(r=r.substring(0,r.length-1)),r):r;const l=s?"."===t[o.length+1]:"."===t[o.length];if(!e.leadingZeros&&(o.length>1||1===o.length&&!l))return t;{const r=Number(i),n=String(r);if(0===r)return r;if(-1!==n.search(/[eE]/))return e.eNotation?r:t;if(-1!==i.indexOf("."))return"0"===n||n===a||n===`${s}${a}`?r:t;let l=o?a:i;return o?l===n||s+l===n?r:t:l===n||l===s+n?r:t}}return t}}var r;return function(t,e,i){const r=e===1/0;switch(i.infinity.toLowerCase()){case"null":return null;case"infinity":return e;case"string":return r?"Infinity":"-Infinity";default:return t}}(t,Number(i),e)}const K=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function tt(t,e){const i=t.trim();if(2!==e&&8!==e||(t=i.substring(2)),parseInt)return parseInt(t,e);if(Number.parseInt)return Number.parseInt(t,e);if(window&&window.parseInt)return window.parseInt(t,e);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}function et(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,r=Array(e);i<e;i++)r[i]=t[i];return r}class it{constructor(t){this._matcher=t}get separator(){return this._matcher.separator}getCurrentTag(){const t=this._matcher.path;return t.length>0?t[t.length-1].tag:void 0}getCurrentNamespace(){const t=this._matcher.path;return t.length>0?t[t.length-1].namespace:void 0}getAttrValue(t){const e=this._matcher.path;if(0!==e.length)return e[e.length-1].values?.[t]}hasAttr(t){const e=this._matcher.path;if(0===e.length)return!1;const i=e[e.length-1];return void 0!==i.values&&t in i.values}getPosition(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].position??0}getCounter(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(t,e=!0){return this._matcher.toString(t,e)}toArray(){return this._matcher.path.map(t=>t.tag)}matches(t){return this._matcher.matches(t)}matchesAny(t){return t.matchesAny(this._matcher)}}class rt{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new it(this)}push(t,e=null,i=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const r=this.path.length;this.siblingStacks[r]||(this.siblingStacks[r]=new Map);const n=this.siblingStacks[r],s=i?`${i}:${t}`:t,o=n.get(s)||0;let a=0;for(const t of n.values())a+=t;n.set(s,o+1);const l={tag:t,position:a,counter:o};null!=i&&(l.namespace=i),null!=e&&(l.values=e),this.path.push(l)}pop(){if(0===this.path.length)return;this._pathStringCache=null;const t=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),t}updateCurrent(t){if(this.path.length>0){const e=this.path[this.path.length-1];null!=t&&(e.values=t)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){if(0!==this.path.length)return this.path[this.path.length-1].values?.[t]}hasAttr(t){if(0===this.path.length)return!1;const e=this.path[this.path.length-1];return void 0!==e.values&&t in e.values}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,e=!0){const i=t||this.separator;if(i===this.separator&&!0===e){if(null!==this._pathStringCache)return this._pathStringCache;const t=this.path.map(t=>t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(i);return this._pathStringCache=t,t}return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(i)}toArray(){return this.path.map(t=>t.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[]}matches(t){const e=t.segments;return 0!==e.length&&(t.hasDeepWildcard()?this._matchWithDeepWildcard(e):this._matchSimple(e))}_matchSimple(t){if(this.path.length!==t.length)return!1;for(let e=0;e<t.length;e++)if(!this._matchSegment(t[e],this.path[e],e===this.path.length-1))return!1;return!0}_matchWithDeepWildcard(t){let e=this.path.length-1,i=t.length-1;for(;i>=0&&e>=0;){const r=t[i];if("deep-wildcard"===r.type){if(i--,i<0)return!0;const r=t[i];let n=!1;for(let t=e;t>=0;t--)if(this._matchSegment(r,this.path[t],t===this.path.length-1)){e=t-1,i--,n=!0;break}if(!n)return!1}else{if(!this._matchSegment(r,this.path[e],e===this.path.length-1))return!1;e--,i--}}return i<0}_matchSegment(t,e,i){if("*"!==t.tag&&t.tag!==e.tag)return!1;if(void 0!==t.namespace&&"*"!==t.namespace&&t.namespace!==e.namespace)return!1;if(void 0!==t.attrName){if(!i)return!1;if(!e.values||!(t.attrName in e.values))return!1;if(void 0!==t.attrValue&&String(e.values[t.attrName])!==String(t.attrValue))return!1}if(void 0!==t.position){if(!i)return!1;const r=e.counter??0;if("first"===t.position&&0!==r)return!1;if("odd"===t.position&&r%2!=1)return!1;if("even"===t.position&&r%2!=0)return!1;if("nth"===t.position&&r!==t.positionValue)return!1}return!0}matchesAny(t){return t.matchesAny(this)}snapshot(){return{path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>new Map(t))}}restore(t){this._pathStringCache=null,this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>new Map(t))}readOnly(){return this._view}}class nt{constructor(t,e={},i){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this.data=i,this._hasDeepWildcard=this.segments.some(t=>"deep-wildcard"===t.type),this._hasAttributeCondition=this.segments.some(t=>void 0!==t.attrName),this._hasPositionSelector=this.segments.some(t=>void 0!==t.position)}_parse(t){const e=[];let i=0,r="";for(;i<t.length;)t[i]===this.separator?i+1<t.length&&t[i+1]===this.separator?(r.trim()&&(e.push(this._parseSegment(r.trim())),r=""),e.push({type:"deep-wildcard"}),i+=2):(r.trim()&&e.push(this._parseSegment(r.trim())),r="",i++):(r+=t[i],i++);return r.trim()&&e.push(this._parseSegment(r.trim())),e}_parseSegment(t){const e={type:"tag"};let i=null,r=t;const n=t.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);if(n&&(r=n[1]+n[3],n[2])){const t=n[2].slice(1,-1);t&&(i=t)}let s,o,a=r;if(r.includes("::")){const e=r.indexOf("::");if(s=r.substring(0,e).trim(),a=r.substring(e+2).trim(),!s)throw new Error(`Invalid namespace in pattern: ${t}`)}let l=null;if(a.includes(":")){const t=a.lastIndexOf(":"),e=a.substring(0,t).trim(),i=a.substring(t+1).trim();["first","last","odd","even"].includes(i)||/^nth\(\d+\)$/.test(i)?(o=e,l=i):o=a}else o=a;if(!o)throw new Error(`Invalid segment pattern: ${t}`);if(e.tag=o,s&&(e.namespace=s),i)if(i.includes("=")){const t=i.indexOf("=");e.attrName=i.substring(0,t).trim(),e.attrValue=i.substring(t+1).trim()}else e.attrName=i.trim();if(l){const t=l.match(/^nth\((\d+)\)$/);t?(e.position="nth",e.positionValue=parseInt(t[1],10)):e.position=l}return e}get length(){return this.segments.length}hasDeepWildcard(){return this._hasDeepWildcard}hasAttributeCondition(){return this._hasAttributeCondition}hasPositionSelector(){return this._hasPositionSelector}toString(){return this.pattern}}class st{constructor(){this._byDepthAndTag=new Map,this._wildcardByDepth=new Map,this._deepWildcards=[],this._patterns=new Set,this._sealed=!1}add(t){if(this._sealed)throw new TypeError("ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.");if(this._patterns.has(t.pattern))return this;if(this._patterns.add(t.pattern),t.hasDeepWildcard())return this._deepWildcards.push(t),this;const e=t.length,i=t.segments[t.segments.length-1],r=i?.tag;if(r&&"*"!==r){const i=`${e}:${r}`;this._byDepthAndTag.has(i)||this._byDepthAndTag.set(i,[]),this._byDepthAndTag.get(i).push(t)}else this._wildcardByDepth.has(e)||this._wildcardByDepth.set(e,[]),this._wildcardByDepth.get(e).push(t);return this}addAll(t){for(const e of t)this.add(e);return this}has(t){return this._patterns.has(t.pattern)}get size(){return this._patterns.size}seal(){return this._sealed=!0,this}get isSealed(){return this._sealed}matchesAny(t){return null!==this.findMatch(t)}findMatch(t){const e=t.getDepth(),i=`${e}:${t.getCurrentTag()}`,r=this._byDepthAndTag.get(i);if(r)for(let e=0;e<r.length;e++)if(t.matches(r[e]))return r[e];const n=this._wildcardByDepth.get(e);if(n)for(let e=0;e<n.length;e++)if(t.matches(n[e]))return n[e];for(let e=0;e<this._deepWildcards.length;e++)if(t.matches(this._deepWildcards[e]))return this._deepWildcards[e];return null}}const ot={cent:"¢",pound:"£",curren:"¤",yen:"¥",euro:"€",dollar:"$",fnof:"ƒ",inr:"₹",af:"؋",birr:"ብር",peso:"₱",rub:"₽",won:"₩",yuan:"¥",cedil:"¸"},at={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'},lt={nbsp:" ",copy:"©",reg:"®",trade:"™",mdash:"—",ndash:"–",hellip:"…",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",bull:"•",para:"¶",sect:"§",deg:"°",frac12:"½",frac14:"¼",frac34:"¾"},pt=Object.freeze({ALLOW:"allow",BLOCK:"block",THROW:"throw"}),ct=new Set("!?\\\\/[]$%{}^&*()<>|+");function ht(t){if("#"===t[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${t}"`);for(const e of t)if(ct.has(e))throw new Error(`[EntityReplacer] Invalid character '${e}' in entity name: "${t}"`);return t}function dt(...t){const e=Object.create(null);for(const i of t)if(i)for(const t of Object.keys(i)){const r=i[t];if("string"==typeof r)e[t]=r;else if(r&&"object"==typeof r&&void 0!==r.val){const i=r.val;"string"==typeof i&&(e[t]=i)}}return e}const ut="external",ft="base",gt="all",mt=Object.freeze({allow:0,leave:1,remove:2,throw:3}),xt=new Set([9,10,13]);class bt{constructor(t={}){var e;this._limit=t.limit||{},this._maxTotalExpansions=this._limit.maxTotalExpansions||0,this._maxExpandedLength=this._limit.maxExpandedLength||0,this._postCheck="function"==typeof t.postCheck?t.postCheck:t=>t,this._limitTiers=(e=this._limit.applyLimitsTo??ut)&&e!==ut?e===gt?new Set([gt]):e===ft?new Set([ft]):Array.isArray(e)?new Set(e):new Set([ut]):new Set([ut]),this._numericAllowed=t.numericAllowed??!0,this._baseMap=dt(at,t.namedEntities||null),this._externalMap=Object.create(null),this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this._removeSet=new Set(t.remove&&Array.isArray(t.remove)?t.remove:[]),this._leaveSet=new Set(t.leave&&Array.isArray(t.leave)?t.leave:[]);const i=function(t){if(!t)return{xmlVersion:1,onLevel:mt.allow,nullLevel:mt.remove};const e=1.1===t.xmlVersion?1.1:1,i=mt[t.onNCR]??mt.allow,r=mt[t.nullNCR]??mt.remove;return{xmlVersion:e,onLevel:i,nullLevel:Math.max(r,mt.remove)}}(t.ncr);this._ncrXmlVersion=i.xmlVersion,this._ncrOnLevel=i.onLevel,this._ncrNullLevel=i.nullLevel,this._onExternalEntity="function"==typeof t.onExternalEntity?t.onExternalEntity:null,this._onInputEntity="function"==typeof t.onInputEntity?t.onInputEntity:null}_applyRegistrationHook(t,e,i,r){if(!t)return!0;const n=t(e,i);if(n===pt.BLOCK)return!1;if(n===pt.THROW)throw new Error(`[EntityDecoder] Registration of ${r} entity "&${e};" was rejected by hook`);return!0}setExternalEntities(t){if(t)for(const e of Object.keys(t))ht(e);if(!this._onExternalEntity)return void(this._externalMap=dt(t));const e=dt(t),i=Object.create(null);for(const[t,r]of Object.entries(e))this._applyRegistrationHook(this._onExternalEntity,t,r,"external")&&(i[t]=r);this._externalMap=i}addExternalEntity(t,e){ht(t),"string"==typeof e&&-1===e.indexOf("&")&&this._applyRegistrationHook(this._onExternalEntity,t,e,"external")&&(this._externalMap[t]=e)}addInputEntities(t){if(this._totalExpansions=0,this._expandedLength=0,!this._onInputEntity)return void(this._inputMap=dt(t));const e=dt(t),i=Object.create(null);for(const[t,r]of Object.entries(e))this._applyRegistrationHook(this._onInputEntity,t,r,"input")&&(i[t]=r);this._inputMap=i}reset(){return this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this}setXmlVersion(t){this._ncrXmlVersion=1.1===t?1.1:1}decode(t){if("string"!=typeof t||0===t.length)return t;if(-1===t.indexOf("&"))return t;const e=t,i=[],r=t.length;let n=0,s=0;const o=this._maxTotalExpansions>0,a=this._maxExpandedLength>0,l=o||a;for(;s<r;){if(38!==t.charCodeAt(s)){s++;continue}let e=s+1;for(;e<r&&59!==t.charCodeAt(e)&&e-s<=32;)e++;if(e>=r||59!==t.charCodeAt(e)){s++;continue}const p=t.slice(s+1,e);if(0===p.length){s++;continue}let c,h;if(this._removeSet.has(p))c="",void 0===h&&(h=ut);else{if(this._leaveSet.has(p)){s++;continue}if(35===p.charCodeAt(0)){const t=this._resolveNCR(p);if(void 0===t){s++;continue}c=t,h=ft}else{const t=this._resolveName(p);c=t?.value,h=t?.tier}}if(void 0!==c){if(s>n&&i.push(t.slice(n,s)),i.push(c),n=e+1,s=n,l&&this._tierCounts(h)){if(o&&(this._totalExpansions++,this._totalExpansions>this._maxTotalExpansions))throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`);if(a){const t=c.length-(p.length+2);if(t>0&&(this._expandedLength+=t,this._expandedLength>this._maxExpandedLength))throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}}}else s++}n<r&&i.push(t.slice(n));const p=0===i.length?t:i.join("");return this._postCheck(p,e)}_tierCounts(t){return!!this._limitTiers.has(gt)||this._limitTiers.has(t)}_resolveName(t){return t in this._inputMap?{value:this._inputMap[t],tier:ut}:t in this._externalMap?{value:this._externalMap[t],tier:ut}:t in this._baseMap?{value:this._baseMap[t],tier:ft}:void 0}_classifyNCR(t){return 0===t?this._ncrNullLevel:t>=55296&&t<=57343||1===this._ncrXmlVersion&&t>=1&&t<=31&&!xt.has(t)?mt.remove:-1}_applyNCRAction(t,e,i){switch(t){case mt.allow:return String.fromCodePoint(i);case mt.remove:return"";case mt.leave:return;case mt.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference &${e}; (U+${i.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(i)}}_resolveNCR(t){const e=t.charCodeAt(1);let i;if(i=120===e||88===e?parseInt(t.slice(2),16):parseInt(t.slice(1),10),Number.isNaN(i)||i<0||i>1114111)return;const r=this._classifyNCR(i);if(!this._numericAllowed&&r<mt.remove)return;const n=-1===r?this._ncrOnLevel:Math.max(this._ncrOnLevel,r);return this._applyNCRAction(n,t,i)}}const vt=[{id:"sql-block-comment-open",description:"SQL block comment open: /* ... */ — unusual in legitimate user text",pattern:/\/\*/},{id:"sql-union-select",description:"UNION SELECT — most common SQL injection aggregation attack",pattern:/\bUNION\s{1,20}(?:ALL\s{1,20})?SELECT\b/i},{id:"sql-drop-table",description:"DROP TABLE — destructive DDL injection",pattern:/\bDROP\s{1,20}TABLE\b/i},{id:"sql-drop-database",description:"DROP DATABASE — destructive DDL injection",pattern:/\bDROP\s{1,20}DATABASE\b/i},{id:"sql-insert-into",description:"INSERT INTO — data injection",pattern:/\bINSERT\s{1,20}INTO\b/i},{id:"sql-delete-from",description:"DELETE FROM — data deletion injection",pattern:/\bDELETE\s{1,20}FROM\b/i},{id:"sql-update-set",description:"UPDATE ... SET — data modification injection",pattern:/\bUPDATE\b[\s\S]{1,60}\bSET\b/i},{id:"sql-exec-xp",description:"EXEC xp_ — MSSQL extended stored procedure execution",pattern:/\bEXEC(?:UTE)?\s{1,20}xp_/i},{id:"sql-tautology-string",description:'Classic string tautology: \' OR \'1\'=\'1 or " OR "1"="1"',pattern:/'\s{0,10}OR\s{0,10}'[^']{0,20}'\s*=\s*'[^']{0,20}/i},{id:"sql-tautology-numeric",description:"Numeric tautology: OR 1=1",pattern:/\bOR\s{1,10}1\s*=\s*1\b/i},{id:"sql-always-true-zero",description:"Numeric tautology: OR 0=0",pattern:/\bOR\s{1,10}0\s*=\s*0\b/i},{id:"sql-sleep-benchmark",description:"Time-based blind injection: SLEEP() or BENCHMARK()",pattern:/\b(?:SLEEP|BENCHMARK)\s*\(/i},{id:"sql-waitfor-delay",description:"MSSQL time-based blind injection: WAITFOR DELAY",pattern:/\bWAITFOR\s{1,20}DELAY\b/i},{id:"sql-char-function",description:"CHAR() function — used to obfuscate injected strings",pattern:/\bCHAR\s*\(\s*\d{1,3}/i},{id:"sql-information-schema",description:"INFORMATION_SCHEMA — reconnaissance query for table/column enumeration",pattern:/\bINFORMATION_SCHEMA\b/i}],yt="[\"'\\s]*:",Nt={HTML:[{id:"html-script-open",description:"<script opening tag",pattern:/<script[\s>/]/i},{id:"html-script-close",description:"<\/script closing tag",pattern:/<\/script[\s>]/i},{id:"html-javascript-protocol",description:"javascript: URI scheme (with optional whitespace/encoding)",pattern:/j[\t\n\r ]*a[\t\n\r ]*v[\t\n\r ]*a[\t\n\r ]*s[\t\n\r ]*c[\t\n\r ]*r[\t\n\r ]*i[\t\n\r ]*p[\t\n\r ]*t[\t\n\r ]*:/i},{id:"html-vbscript-protocol",description:"vbscript: URI scheme",pattern:/vbscript[\t\n\r ]*:/i},{id:"html-data-html",description:"data:text/html URI — can execute scripts in browsers",pattern:/data[\t\n\r ]*:[\t\n\r ]*text\/html/i},{id:"html-data-xhtml",description:"data:application/xhtml+xml URI",pattern:/data[\t\n\r ]*:[\t\n\r ]*application\/xhtml/i},{id:"html-data-svg",description:"data:image/svg+xml URI — can execute scripts",pattern:/data[\t\n\r ]*:[\t\n\r ]*image\/svg\+xml/i},{id:"html-inline-event-handler",description:"Inline event handler attributes: onclick=, onerror=, onload=, etc.",pattern:/\bon\w{1,30}\s*=/i},{id:"html-entity-obfuscated-script",description:"HTML-entity-encoded <script (e.g. &#x3C;script or &lt;script)",pattern:/(?:&#x0*3[Cc];?|&#0*60;?|&lt;)\s*script/i},{id:"html-entity-obfuscated-javascript",description:'HTML-entity-encoded javascript: (partial — catches common &#106; or &#x6a; for "j")',pattern:/(?:&#x0*6[Aa];?|&#0*106;?)\s*(?:&#x0*61;?|a)[\s\S]{0,80}script\s*:/i},{id:"html-style-expression",description:"CSS expression() — IE-era code execution in style attributes",pattern:/style[\s\S]{0,20}expression\s*\(/i},{id:"html-object-embed",description:"<object or <embed tags that can load active content",pattern:/<(?:object|embed)[\s>/]/i},{id:"html-base-tag",description:"<base href= — can hijack all relative URLs on a page",pattern:/<base[\s>]/i},{id:"html-meta-refresh",description:'<meta http-equiv="refresh" — can redirect users',pattern:/<meta[\s\S]{0,40}http-equiv[\s\S]{0,20}refresh/i},{id:"html-srcdoc",description:"srcdoc= attribute on iframes — embeds HTML that can run scripts",pattern:/srcdoc\s*=/i},{id:"html-iframe",description:"<iframe tag",pattern:/<iframe[\s>/]/i},{id:"html-form",description:"<form tag — can be used for phishing / credential harvesting injection",pattern:/<form[\s>/]/i}],XML:[{id:"xml-cdata-injection",description:"CDATA section injection: <![CDATA[ breaks out of text node context",pattern:/<!\[CDATA\[/i},{id:"xml-cdata-close",description:"CDATA close sequence: ]]> can terminate an enclosing CDATA section",pattern:/\]\]>/},{id:"xml-processing-instruction",description:"XML processing instruction: <?xml-stylesheet or <?php etc.",pattern:/<\?(?:xml[\- ]|php|asp)/i},{id:"xml-doctype-injection",description:"DOCTYPE declaration embedded in content — can define entities",pattern:/<!DOCTYPE(?:[\s[]|$)/i},{id:"xml-entity-system",description:"SYSTEM keyword — used in external entity declarations (XXE)",pattern:/\bSYSTEM\s+["']/i},{id:"xml-entity-public",description:"PUBLIC keyword — used in external entity declarations (XXE)",pattern:/\bPUBLIC\s+["']/i},{id:"xml-entity-declaration",description:"<!ENTITY declaration — defines entities, potential XXE or entity expansion",pattern:/<!ENTITY[\s%]/i},{id:"xml-billion-laughs",description:"Entity reference chaining / billion laughs: repeated &eX; style references",pattern:/(?:&\w{1,20};){3,}/},{id:"xml-namespace-confusion",description:"xmlns: attribute injection — can redefine namespaces to confuse parsers",pattern:/\bxmlns\s*(?::\w{1,40})?\s*=/i},{id:"xml-comment-injection",description:"\x3c!-- comment injection — can hide content from some parsers",pattern:/<!--/},{id:"xml-comment-close",description:"--\x3e closes an enclosing XML comment",pattern:/-->/},{id:"xml-pi-close",description:"?> closes an enclosing processing instruction",pattern:/\?>/}],SVG:[{id:"svg-script-element",description:"<script element inside SVG executes JavaScript",pattern:/<script[\s>/]/i},{id:"svg-xlink-href-javascript",description:"xlink:href with javascript: — classic SVG XSS via <a> or <use>",pattern:/xlink\s*:\s*href\s*=\s*["']?\s*javascript\s*:/i},{id:"svg-href-javascript",description:"href= with javascript: in SVG context (<a>, <animate>, etc.)",pattern:/href\s*=\s*["']?\s*javascript\s*:/i},{id:"svg-foreignobject",description:"<foreignObject embeds HTML inside SVG — can execute scripts",pattern:/<foreignObject[\s>/]/i},{id:"svg-use-external",description:"<use xlink:href or href pointing to external resource (non-fragment URL)",pattern:/<use[\s\S]{0,60}(?:xlink\s*:\s*)?href\s*=\s*(?:["'][^#]|[^"'#\s>])/i},{id:"svg-animate-href",description:'<animate attributeName="href" — can dynamically change href to javascript:',pattern:/<animate[\s\S]{0,80}attributeName\s*=\s*["'][\s]*href["']/i},{id:"svg-animate-xlinkhref",description:'<animate attributeName="xlink:href"',pattern:/<animate[\s\S]{0,80}attributeName\s*=\s*["'][\s]*xlink\s*:\s*href["']/i},{id:"svg-set-javascript",description:'<set to="javascript:..." — sets an attribute to a javascript: URI',pattern:/<set[\s\S]{0,80}to\s*=\s*["']?\s*javascript\s*:/i},{id:"svg-event-handler",description:"SVG-specific event handler attributes: onload=, onerror=, onactivate=, etc.",pattern:/\bon(?:load|error|activate|begin|end|repeat|focus|blur|click|mouse\w{1,20}|key\w{1,20})\s*=/i},{id:"svg-handler-generic",description:"Generic on* handler catch-all for SVG attributes",pattern:/\bon\w{1,30}\s*=/i},{id:"svg-filter-feimage",description:"<feImage href= — filter primitive that can load external resources",pattern:/<feImage[\s\S]{0,80}(?:xlink\s*:\s*)?href\s*=/i},{id:"svg-image-external",description:"<image xlink:href with http/https or javascript protocol",pattern:/<image[\s\S]{0,80}(?:xlink\s*:\s*)?href\s*=\s*["']?\s*(?:https?|javascript)\s*:/i},{id:"svg-style-javascript",description:"style= attribute containing javascript: (e.g. background:url(javascript:...))",pattern:/style\s*=[\s\S]{0,60}javascript\s*:/i}],SQL:vt,"SQL-STRICT":[...vt,{id:"sql-line-comment",description:"SQL line comment: -- followed by whitespace or end of string",pattern:/--(?:\s|$)/},{id:"sql-stacked-query",description:"Stacked queries: semicolon immediately followed by a SQL keyword",pattern:/;\s{0,10}(?:SELECT|INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|EXEC)\b/i},{id:"sql-hex-encoding",description:"Hex-encoded string injection: 0x41414141 style (MySQL)",pattern:/\b0x[0-9a-f]{4,}/i}],SHELL:[{id:"shell-path-traversal-unix",description:"Unix path traversal: ../ — climbing the directory tree",pattern:/\.\.\//},{id:"shell-path-traversal-windows",description:"Windows path traversal: ..\\ — climbing the directory tree",pattern:/\.\.\\/},{id:"shell-path-traversal-encoded",description:"URL-encoded path traversal: %2e%2e or %2f variants",pattern:/%2e%2e|%2f\.\.|\.\.%2f/i},{id:"shell-null-byte",description:"Null byte injection: \\x00 or %00 — truncates strings in C-backed functions",pattern:/\x00|%00/},{id:"shell-semicolon",description:"Semicolon command separator: cmd1; cmd2",pattern:/;/},{id:"shell-pipe",description:"Pipe operator: cmd1 | cmd2",pattern:/\|/},{id:"shell-and-operator",description:"AND operator: cmd1 && cmd2",pattern:/&&/},{id:"shell-or-operator",description:"OR operator: cmd1 || cmd2",pattern:/\|\|/},{id:"shell-backtick",description:"Backtick command substitution: `cmd`",pattern:/`/},{id:"shell-dollar-paren",description:"Dollar-paren command substitution: $(cmd)",pattern:/\$\(/},{id:"shell-dollar-brace",description:"Dollar-brace variable expansion: ${var} — can be abused for injection",pattern:/\$\{/},{id:"shell-redirect-out",description:"Output redirection: cmd > file or cmd >> file",pattern:/>{1,2}/},{id:"shell-redirect-in",description:"Input redirection: cmd < file",pattern:/</},{id:"shell-newline-injection",description:"Newline injection: \\n or \\r — can inject new shell commands",pattern:/[\n\r]/},{id:"shell-glob-star",description:"Glob expansion: * or ? — can expand to unintended files",pattern:/[/\\][*?]/},{id:"shell-absolute-root",description:"Absolute root path injection: string starting with / or \\ (Windows UNC)",pattern:/^(?:\/|\\\\)/},{id:"shell-windows-drive",description:"Windows drive letter path injection: C:\\ or D:/",pattern:/^[a-zA-Z]:[/\\]/},{id:"shell-curl-wget",description:"curl/wget with URL or flags — can exfiltrate data or download payloads",pattern:/\b(?:curl|wget)\s+(?:https?:\/\/|ftp:\/\/|-)/i}],REDOS:[{id:"redos-nested-quantifier-plus",description:"Nested + quantifier inside a group with outer quantifier: (a+)+, (.+b)*, etc.",pattern:/\([^)]*\+[^)]*\)[+*]/},{id:"redos-nested-quantifier-star",description:"Nested * quantifier: (a*)* or (a*)+ — catastrophic backtracking",pattern:/\([^)]*\*[^)]*\)[*+]/},{id:"redos-nested-groups",description:"Doubly nested quantified groups: ((a+)+) — guaranteed catastrophic",pattern:/\(\([^)]{0,40}\)[+*]\)[+*]/},{id:"redos-alternation-overlap",description:"Overlapping alternation under quantifier: (a|a)+ — ambiguous NFA paths",pattern:/\(([^|()]{1,20})\|(?:\1)(?:\|[^|()]{1,20}){0,5}\)[+*?]{1,2}/},{id:"redos-star-plus-concat",description:"(x*x)+ pattern — triggers super-linear backtracking",pattern:/\([^)]{0,10}\*[^)]{0,10}\)[+*]/},{id:"redos-dot-star-greedy",description:"(.*){n,} or (.+){n,} — repeated greedy dot quantifiers",pattern:/\(\.[*+]\)\{?\d/},{id:"redos-large-repetition",description:"Very large fixed or range repetition count {1000,} or {1000,n} — denial of service via backtracking",pattern:/\{\d{4,}(?:,\d*)?\}/},{id:"redos-catastrophic-alternation",description:"Long alternation with many similar branches — polynomial backtracking risk",pattern:/\([^)]{0,200}(?:\|[^|)]{0,50}){9,}\)/}],NOSQL:[{id:"nosql-where-operator",description:"$where — executes arbitrary JavaScript server-side in MongoDB",pattern:new RegExp(`\\$where${yt}`,"i")},{id:"nosql-ne-operator",description:'$ne — "not equal" operator used to bypass equality checks',pattern:new RegExp(`\\$ne${yt}`,"i")},{id:"nosql-gt-operator",description:'$gt — "greater than" used to bypass password/value checks',pattern:new RegExp(`\\$gte?${yt}`,"i")},{id:"nosql-lt-operator",description:'$lt / $lte — "less than" bypass variants',pattern:new RegExp(`\\$lte?${yt}`,"i")},{id:"nosql-regex-operator",description:"$regex — can be used to extract data character by character (blind injection)",pattern:new RegExp(`\\$regex${yt}`,"i")},{id:"nosql-or-operator",description:"$or — logical OR; used to create always-true conditions",pattern:new RegExp(`\\$or${yt}\\s*\\[`,"i")},{id:"nosql-and-operator",description:"$and — logical AND operator injection",pattern:new RegExp(`\\$and${yt}\\s*\\[`,"i")},{id:"nosql-nor-operator",description:"$nor — logical NOR operator injection",pattern:new RegExp(`\\$nor${yt}\\s*\\[`,"i")},{id:"nosql-exists-operator",description:"$exists — can enumerate fields to determine schema",pattern:new RegExp(`\\$exists${yt}`,"i")},{id:"nosql-in-operator",description:"$in — matches any value in a list; can enumerate values",pattern:new RegExp(`\\$in${yt}\\s*\\[`,"i")},{id:"nosql-expr-operator",description:"$expr — allows aggregation expressions in queries (MongoDB 3.6+)",pattern:new RegExp(`\\$expr${yt}`,"i")},{id:"nosql-function-operator",description:"$function — executes arbitrary JavaScript in MongoDB 4.4+",pattern:new RegExp(`\\$function${yt}`,"i")},{id:"nosql-accumulator-operator",description:"$accumulator — custom aggregation with arbitrary JS execution",pattern:new RegExp(`\\$accumulator${yt}`,"i")},{id:"nosql-proto-pollution",description:"__proto__ — prototype pollution via object key injection",pattern:/__proto__/},{id:"nosql-constructor-prototype",description:"constructor.prototype — alternative prototype pollution vector (dot notation or JSON key)",pattern:/constructor[\s"':.,{\[]*prototype/i},{id:"nosql-proto-bracket",description:'["__proto__"] — bracket-notation prototype pollution',pattern:/\[["']__proto__["']\]/}],LOG:[{id:"log-crlf-injection",description:"CRLF injection: literal \\r or \\n embeds fake log lines",pattern:/[\r\n]/},{id:"log-url-encoded-crlf",description:"URL-encoded CRLF: %0d, %0a, %0D, %0A — decoded by some log parsers",pattern:/%0[dDaA]/},{id:"log-unicode-newline",description:"Unicode newline variants: U+2028 (line separator), U+2029 (paragraph separator)",pattern:/[\u2028\u2029]/},{id:"log-log4shell-jndi",description:"Log4Shell: ${jndi:...} triggers remote code execution in Apache Log4j",pattern:/\$\{jndi\s*:/i},{id:"log-log4shell-obfuscated",description:"Obfuscated Log4Shell: ${::-j}... lookup-bypass prefix used to evade WAF detection",pattern:/\$\{::-/},{id:"log-log4j-lookup",description:"Log4j lookup syntax: ${env:...}, ${sys:...}, ${ctx:...} — data exfiltration",pattern:/\$\{(?:env|sys|ctx|main|map|sd|web|docker|k8s|spring)\s*:/i},{id:"log-ssti-double-brace",description:"SSTI double-brace: {{expression}} — Jinja2, Twig, Handlebars, etc.",pattern:/\{\{[\s\S]{0,80}\}\}/},{id:"log-ssti-hash-brace",description:"SSTI hash-brace: #{expression} — Thymeleaf, Velocity, Ruby ERB",pattern:/#\{[\s\S]{0,80}\}/},{id:"log-ssti-dollar-brace",description:"SSTI/EL injection: ${expression with operators or method calls} — JSP EL, Freemarker, SpEL",pattern:/\$\{[^}]*(?:\.|\(|\*|\+|\bclass\b|\bruntime\b|\bprocess\b|\bexec\b)[^}]{0,80}\}/i},{id:"log-ssti-percent-tag",description:"SSTI ERB/ASP tag: <%= expression %> — Ruby ERB, ASP",pattern:/<%=[\s\S]{0,80}%>/},{id:"log-null-byte",description:"Null byte: \\x00 or %00 — can truncate log entries in C-backed loggers",pattern:/\x00|%00/},{id:"log-ansi-escape",description:"ANSI escape sequence: ESC[ — can manipulate terminal output when logs are tailed",pattern:/\x1b\[/}]},Et=Nt,wt=Object.freeze(Object.fromEntries(Object.keys(Nt).map(t=>[t,t])));function St(t,e){const i=Et[e];for(const r of i)if(r.pattern.test(t))return{context:e,id:r.id,description:r.description,pattern:r.pattern};return null}function At(t,e){if(function(t){if("string"!=typeof t)throw new TypeError("is-unsafe: first argument must be a string, got "+typeof t)}(t),function(t){if(!(t instanceof RegExp))if("string"!=typeof t){if(!Array.isArray(t))throw new TypeError("is-unsafe: second argument must be a context string, array of context strings, or RegExp. Got: "+typeof t);if(0===t.length)throw new TypeError("is-unsafe: context array must not be empty");for(const e of t)if("string"!=typeof e||!Et[e])throw new TypeError(`is-unsafe: unknown context "${e}" in array. Valid contexts: ${Object.keys(wt).join(", ")}`)}else if(!Et[t])throw new TypeError(`is-unsafe: unknown context "${t}". Valid contexts: ${Object.keys(wt).join(", ")}`)}(e),e instanceof RegExp)return e.test(t);if("string"==typeof e)return null!==St(t,e);for(const i of e)if(null!==St(t,i))return!0;return!1}function Tt(){return Tt=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var r in i)({}).hasOwnProperty.call(i,r)&&(t[r]=i[r])}return t},Tt.apply(null,arguments)}function _t(t,e){if(!t)return{};var i=e.attributesGroupName?t[e.attributesGroupName]:t;if(!i)return{};var r={};for(var n in i)n.startsWith(e.attributeNamePrefix)?r[n.substring(e.attributeNamePrefix.length)]=i[n]:r[n]=i[n];return r}function Ct(t){if(t&&"string"==typeof t){var e=t.indexOf(":");if(-1!==e&&e>0){var i=t.substring(0,e);if("xmlns"!==i)return i}}}var Ot=function(t,e){var i;this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.parseXml=kt,this.parseTextData=jt,this.resolveNameSpace=Pt,this.buildAttributesMap=It,this.isItStopNode=Mt,this.replaceEntitiesValue=Dt,this.readStopNodeData=Ut,this.saveTextToParentTag=Rt,this.addChild=Lt,this.ignoreAttributesFn="function"==typeof(i=this.options.ignoreAttributes)?i:Array.isArray(i)?function(t){for(var e,r=function(t,e){var i="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(i)return(i=i.call(t)).next.bind(i);if(Array.isArray(t)||(i=function(t,e){if(t){if("string"==typeof t)return et(t,e);var i={}.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?et(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){i&&(t=i);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(i);!(e=r()).done;){var n=e.value;if("string"==typeof n&&t===n)return!0;if(n instanceof RegExp&&n.test(t))return!0}}:function(){return!1},this.entityE