fast-xml-validator 1.4.0 → 1.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/fxv.cjs +1 -1
- package/lib/fxv.d.cts +1 -1
- package/lib/fxv.min.js +1 -1
- package/lib/fxv.min.js.map +1 -1
- package/package.json +2 -2
- package/src/fxv.d.ts +1 -1
- package/src/validators/AttributeStringValidator.js +101 -4
- package/src/validators/DocTypeValidator.js +13 -1
- package/src/validators/XmlDeclarationValidator.js +97 -10
- package/src/DocTypeValidator.js +0 -280
- package/src/validator.js +0 -539
package/lib/fxv.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{"use strict";var t={d:(e,r)=>{for(var s in r)t.o(r,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:r[s]})},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,{BusinessRulesValidator:()=>pr,SyntaxValidator:()=>$});class r extends Error{constructor(t,e,r,s){super(t),this.name=this.constructor.name,this.code=e,this.line=r,this.col=s,Error.captureStackTrace?.(this,this.constructor)}}function s(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function n(t){return t<=8||11===t||12===t||t>=14&&t<=31}function i(t,e){const r=t.substring(0,e).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function a(t){return t.startIndex+t[1].length}const o=":A-Za-z_À-ÖØ-öø-˿Ͱ-ͽͿ-҆҈--⁰-Ⰰ-、-豈-﷏ﷰ-�",l=":A-Za-z_À-˿Ͱ-ͽͿ-҆҈--⁰-Ⰰ-、-豈-﷏ﷰ-�𐀀-",c=l+"\\-\\.\\d·̀-ͯ҇‿-⁀",h=(t,e,r="")=>{const s=`[${t.replace(":","")}][${e.replace(":","")}]*`;return{name:new RegExp(`^[${t}][${e}]*$`,r),ncName:new RegExp(`^${s}$`,r),qName:new RegExp(`^${s}(?::${s})?$`,r),nmToken:new RegExp(`^[${e}]+$`,r),nmTokens:new RegExp(`^[${e}]+(?:\\s+[${e}]+)*$`,r)}},d=h(o,o+"\\-\\.\\d·̀-ͯ‿-⁀"),u=h(l,c,"u"),p=":A-Za-z_",f=h(p,p+"\\-\\.\\d"),g=(t="1.0",e=!1)=>e?f:"1.1"===t?u:d,m=(t,{xmlVersion:e="1.0",asciiOnly:r=!1}={})=>g(e,r).name.test(t),_=["name","ncName","qName","nmToken","nmTokens"],E=(t,{xmlVersion:e="1.0",asciiOnly:r=!1,maxCacheSize:s=2048}={})=>{if(!_.includes(t))throw new TypeError(`Unknown production "${t}". Must be one of: ${_.join(", ")}`);const n=g(e,r)[t];let i=new Map;const a=t=>{const e=i.get(t);if(void 0!==e)return e;const r=n.test(t);return i.size<s&&i.set(t,r),r};return a.reset=()=>{i=new Map},a};class x{constructor(t="1.0"){this.xmlVersion=t,this.qName=E("qName",{xmlVersion:t}),this.name=E("name",{xmlVersion:t})}isValidQName(t){return this.qName(t)}isValidName(t){return this.name(t)}}class b{constructor(t={},e){this.optional=void 0===t.optional||t.optional,this.argPosition=void 0!==t.argPosition?t.argPosition:void 0===t.argPostion||t.argPostion,this._throwError=e}validate(t){if(!t.startsWith("<?xml"))return this.optional||this._throwError("InvalidXml","XML declaration is required but missing.",{line:1,col:1}),{version:"1.0",end:0};const e=t.indexOf("?>");-1===e&&this._throwError("InvalidXml",'XML declaration is not closed with "?>".',{line:1,col:1});const r=t.substring(5,e),s=e+2,n=["version","encoding","standalone"],i=/\s+([\w]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;let a,o="1.0",l=-1;for(;null!==(a=i.exec(r));){const t=a[1],e=void 0!==a[2]?a[2]:a[3],r=a.index,s=n.indexOf(t);-1===s&&this._throwError("InvalidXml",'XML declaration contains unknown attribute "'+t+'". Allowed: version, encoding, standalone.',{line:1,col:6+r}),this.argPosition&&s<=l&&this._throwError("InvalidXml",'XML declaration attribute "'+t+'" is out of order. Required order: version, encoding, standalone.',{line:1,col:6+r}),l=s,"version"===t?("1.0"!==e&&"1.1"!==e&&this._throwError("InvalidXml",'XML declaration version "'+e+'" is not supported. Must be "1.0" or "1.1".',{line:1,col:6+r}),o=e):"standalone"===t&&"yes"!==e&&"no"!==e&&this._throwError("InvalidXml",'XML declaration standalone "'+e+'" is invalid. Must be "yes" or "no".',{line:1,col:6+r})}const c=r.replace(/\s+[\w]+\s*=\s*(?:"[^"]*"|'[^']*')/g,"").trim();return c.length>0&&this._throwError("InvalidXml",'XML declaration contains invalid content: "'+c+'".',{line:1,col:1}),{version:o,end:s}}}class T{static findIllegalIndex(t){const e=t.length;for(let r=0;r<e;r++)if(n(t.charCodeAt(r)))return r;return-1}static hasIllegalChar(t){return-1!==this.findIllegalIndex(t)}static describe(t){return`0x${t.toString(16).padStart(2,"0")}`}}const y=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");class w{constructor(t,e,r){this.options=t,this.nameValidator=e,this.xmlVersion=r}validate(t){const e=function(t,e){const r=[];let s=e.exec(t);for(;s;){const n=[];n.startIndex=e.lastIndex-s[0].length;const i=s.length;for(let t=0;t<i;t++)n.push(s[t]);r.push(n),s=e.exec(t)}return r}(t,y),r={},s=!0===this.options.invalidCharSequence?.attrLt;for(let t=0;t<e.length;t++){const n=e[t];if(0===n[1].length)return this._err("InvalidAttr","Attribute '"+n[2]+"' has no space in starting.",n);const i=void 0!==n[3],a=void 0!==n[4];if(i&&!a)return this._err("UnquotedAttributeValue","Attribute '"+n[2]+"' is without value.",n);if(!i&&!this.options.allowBooleanAttributes)return this._err("InvalidAttr","boolean attribute '"+n[2]+"' is not allowed.",n);const o=n[2];if(!this.nameValidator.isValidQName(o))return this._err("InvalidAttr","Attribute '"+o+"' is an invalid name.",n);const l=n[6]||"";if(a){const t=T.findIllegalIndex(l);if(-1!==t){const e=l.charCodeAt(t);return this._err("IllegalCharacter",`Illegal control character ${T.describe(e)} in attribute '${o}' value.`,n)}if(s&&-1!==l.indexOf("<"))return this._err("InvalidAttr",`Attribute '${o}' value must not contain '<'.`,n)}if(o.startsWith("xmlns:")&&""===n[6]&&"1.0"===this.xmlVersion)return this._err("InvalidAttr",`Undeclaring the prefixed namespace ${o}="" is only permitted in XML 1.1 documents.`,n);if(Object.prototype.hasOwnProperty.call(r,o))return this._err("InvalidAttr","Attribute '"+o+"' is repeated.",n);r[o]=1}return!0}_err(t,e,r){return{err:{code:t,msg:e,line:a(r)}}}}class I{constructor(t={}){this.checkCommentDashes=!0===t.invalidCharSequence?.comment}read(t,e,r){if(t.length>e+2&&"-"===t[e+1]&&"-"===t[e+2])return this._readComment(t,e);if(t.length>e+7&&"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])return r.validateDocType(t,e-1);if(t.length>e+8&&"["===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])return this._readCdata(t,e);throw new Error("Invalid construct starting with '<!'.")}_readComment(t,e){const r=e+3;for(e=r;e<t.length;e++)if("-"===t[e]&&"-"===t[e+1]&&">"===t[e+2]){e+=2;break}if(">"!==t[e])throw new Error('Comment is not closed with "--\x3e".');const s=t.substring(r,e-2),n=T.findIllegalIndex(s);if(-1!==n){const t=s.charCodeAt(n);throw new Error(`Illegal control character ${T.describe(t)} in comment.`)}if(this.checkCommentDashes&&-1!==s.indexOf("--"))throw new Error("Comment must not contain '--'.");return e}_readCdata(t,e){const r=e+8;for(e=r;e<t.length;e++)if("]"===t[e]&&"]"===t[e+1]&&">"===t[e+2]){e+=2;break}if(">"!==t[e])throw new Error('CDATA section is not closed with "]]>".');const s=t.substring(r,e-2),n=T.findIllegalIndex(s);if(-1!==n){const t=s.charCodeAt(n);throw new Error(`Illegal control character ${T.describe(t)} in CDATA section.`)}return e}}class A{constructor(t,e={},r){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this.data=r,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 r=0,s="";for(;r<t.length;)t[r]===this.separator?r+1<t.length&&t[r+1]===this.separator?(s.trim()&&(e.push(this._parseSegment(s.trim())),s=""),e.push({type:"deep-wildcard"}),r+=2):(s.trim()&&e.push(this._parseSegment(s.trim())),s="",r++):(s+=t[r],r++);return s.trim()&&e.push(this._parseSegment(s.trim())),e}_parseSegment(t){const e={type:"tag"};let r=null,s=t;const n=t.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);if(n&&(s=n[1]+n[3],n[2])){const t=n[2].slice(1,-1);t&&(r=t)}let i,a,o=s;if(s.includes("::")){const e=s.indexOf("::");if(i=s.substring(0,e).trim(),o=s.substring(e+2).trim(),!i)throw new Error(`Invalid namespace in pattern: ${t}`)}let l=null;if(o.includes(":")){const t=o.lastIndexOf(":"),e=o.substring(0,t).trim(),r=o.substring(t+1).trim();["first","last","odd","even"].includes(r)||/^nth\(\d+\)$/.test(r)?(a=e,l=r):a=o}else a=o;if(!a)throw new Error(`Invalid segment pattern: ${t}`);if(e.tag=a,i&&(e.namespace=i),r)if(r.includes("=")){const t=r.indexOf("=");e.attrName=r.substring(0,t).trim(),e.attrValue=r.substring(t+1).trim()}else e.attrName=r.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 N{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 r=e[e.length-1];return void 0!==r.values&&t in r.values}getAnyParentAttr(t){return this._matcher.getAnyParentAttr(t)}hasAnyParentAttr(t){return this._matcher.hasAnyParentAttr(t)}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 v{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new N(this),this._keptAttrs=[]}push(t,e=null,r=null,s=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const n=this.path.length;let i=this.siblingStacks[n];i||(i={counts:new Map,total:0},this.siblingStacks[n]=i);const a=r?`${r}:${t}`:t,o=i.counts.get(a)||0,l=i.total;i.counts.set(a,o+1),i.total++;const c={tag:t,position:l,counter:o};null!=r&&(c.namespace=r),null!=e&&(c.values=e),this.path.push(c);const h=this.path.length,d=null!==s?s.keep:null;if(null!=d&&d.length>0&&e)for(let t=0;t<d.length;t++){const r=d[t];void 0!==e[r]&&this._keptAttrs.push({depth:h,name:r,value:e[r]})}}pop(){if(0===this.path.length)return;this._pathStringCache=null;const t=this.path.pop();this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1);const e=this.path.length+1;for(;this._keptAttrs.length>0&&this._keptAttrs[this._keptAttrs.length-1].depth>=e;)this._keptAttrs.pop();return 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}getAnyParentAttr(t){const e=this._keptAttrs;for(let r=e.length-1;r>=0;r--)if(e[r].name===t)return e[r].value}hasAnyParentAttr(t){const e=this._keptAttrs;for(let r=e.length-1;r>=0;r--)if(e[r].name===t)return!0;return!1}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 r=t||this.separator;if(r===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(r);return this._pathStringCache=t,t}return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(r)}toArray(){return this.path.map(t=>t.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[],this._keptAttrs=[]}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,r=t.length-1;for(;r>=0&&e>=0;){const s=t[r];if("deep-wildcard"===s.type){if(r--,r<0)return!0;const s=t[r];let n=!1;for(let t=e;t>=0;t--)if(this._matchSegment(s,this.path[t],t===this.path.length-1)){e=t-1,r--,n=!0;break}if(!n)return!1}else{if(!this._matchSegment(s,this.path[e],e===this.path.length-1))return!1;e--,r--}}return r<0}_matchSegment(t,e,r){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(!r)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(!r)return!1;const s=e.counter??0;if("first"===t.position&&0!==s)return!1;if("odd"===t.position&&s%2!=1)return!1;if("even"===t.position&&s%2!=0)return!1;if("nth"===t.position&&s!==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=>t?{counts:new Map(t.counts),total:t.total}:t),keptAttrs:this._keptAttrs.map(t=>({...t}))}}restore(t){this._pathStringCache=null,this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>t?{counts:new Map(t.counts),total:t.total}:t),this._keptAttrs=(t.keptAttrs||[]).map(t=>({...t}))}readOnly(){return this._view}}class S{constructor(t=[]){this._expressions=t.map(t=>new A(t)),this._matcher=new v,this._enabled=this._expressions.length>0}get enabled(){return this._enabled}push(t,e){if(!this._enabled)return!1;this._matcher.push(t,e||null);for(let t=0;t<this._expressions.length;t++)if(this._matcher.matches(this._expressions[t]))return!0;return!1}pop(){this._enabled&&this._matcher.pop()}}class C{static consume(t,e,r){const s="</"+e;let n=r;for(;;){const r=t.indexOf(s,n);if(-1===r)throw new Error(`Unclosed skipped tag '${e}'.`);let i=r+s.length;for(;i<t.length&&/\s/.test(t[i]);)i++;if(">"===t[i])return i;n=r+s.length}}}const D={maxEntityCount:1/0,maxEntitySize:1/0};class O{constructor(t,e="1.0"){this.options=Object.assign({},D,t),this.suppressValidationErr=!t,this.xmlVersion=e}validateDocType(t,e){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;let r=1,s=!1,n=!1,i=0;for(;e<t.length;e++)if("<"!==t[e]||n)if(">"===t[e]){if(n?"-"===t[e-1]&&"-"===t[e-2]&&(n=!1,r--):r--,0===r)break}else"["===t[e]&&(s=!0);else{if(s&&P(t,"!ENTITY",e))e+=7,[i,e]=this._validateEntityExp(t,e+1,i);else if(s&&P(t,"!ELEMENT",e))e+=8,e=this._validateElementExp(t,e+1);else{if(s&&P(t,"!ATTLIST",e)){e+=8,e=this._validateAttlistExp(t,e+1);continue}if(s&&P(t,"!NOTATION",e))e+=9,e=this._validateNotationExp(t,e+1);else{if(!P(t,"!--",e))throw new Error("Invalid DOCTYPE");n=!0}}r++}if(0!==r)throw new Error("Unclosed DOCTYPE");return e}_validateEntityExp(t,e,r){const s=e=k(t,e);for(;e<t.length&&!/\s/.test(t[e])&&'"'!==t[e]&&"'"!==t[e];)e++;const n=t.substring(s,e);if(L(n,this.xmlVersion),e=k(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")}let i;[e,i]=U(t,e,"entity");const{maxEntitySize:a,maxEntityCount:o}=this.options;if(i.length>a)throw new Error(`Entity "${n}" size (${i.length}) exceeds maximum allowed size (${a})`);if(-1===i.indexOf("&")&&++r>o)throw new Error(`Entity count (${r}) exceeds maximum allowed (${o})`);return[r,e-1]}_validateNotationExp(t,e){const r=e=k(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;const s=t.substring(r,e);!this.suppressValidationErr&&L(s,this.xmlVersion),e=k(t,e);const n=t.substring(e,e+6).toUpperCase();if(!this.suppressValidationErr&&"SYSTEM"!==n&&"PUBLIC"!==n)throw new Error(`Expected SYSTEM or PUBLIC, found "${n}"`);return e=k(t,e+=n.length),"PUBLIC"===n?([e]=U(t,e,"publicIdentifier"),'"'!==t[e=k(t,e)]&&"'"!==t[e]||([e]=U(t,e,"systemIdentifier"))):"SYSTEM"===n&&([e]=U(t,e,"systemIdentifier")),--e}_validateElementExp(t,e){const r=e=k(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;const s=t.substring(r,e);if(!this.suppressValidationErr&&!m(s,{xmlVersion:this.xmlVersion}))throw new Error(`Invalid element name: "${s}"`);if("E"===t[e=k(t,e)]&&P(t,"MPTY",e))e+=4;else if("A"===t[e]&&P(t,"NY",e))e+=2;else if("("===t[e]){for(e++;e<t.length&&")"!==t[e];)e++;if(")"!==t[e])throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error(`Invalid Element Expression, found "${t[e]}"`);return e}_validateAttlistExp(t,e){const r=e=k(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;L(t.substring(r,e),this.xmlVersion);const s=e=k(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;if(L(t.substring(s,e),this.xmlVersion),e=k(t,e),"NOTATION"===t.substring(e,e+8).toUpperCase()){if("("!==t[e=k(t,e+=8)])throw new Error(`Expected '(', found "${t[e]}"`);for(e++;e<t.length&&")"!==t[e];){const r=e;for(;e<t.length&&"|"!==t[e]&&")"!==t[e];)e++;L(t.substring(r,e).trim(),this.xmlVersion),"|"===t[e]&&(e=k(t,++e))}if(")"!==t[e])throw new Error("Unterminated list of notations");e++}else{const r=e;for(;e<t.length&&!/\s/.test(t[e]);)e++;const s=t.substring(r,e),n=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!n.includes(s.toUpperCase()))throw new Error(`Invalid attribute type: "${s}"`)}return e=k(t,e),"#REQUIRED"===t.substring(e,e+9).toUpperCase()?e+=9:"#IMPLIED"===t.substring(e,e+8).toUpperCase()?e+=8:[e]=U(t,e,"ATTLIST default value"),e}}function k(t,e){for(;e<t.length&&/\s/.test(t[e]);)e++;return e}function P(t,e,r){for(let s=0;s<e.length;s++)if(e[s]!==t[r+s+1])return!1;return!0}function L(t,e="1.0"){if(!m(t,{xmlVersion:e}))throw new Error(`Invalid entity name "${t}"`)}function U(t,e,r){const s=t[e];if('"'!==s&&"'"!==s)throw new Error(`Expected quoted string for ${r}, found "${s}"`);const n=++e;for(;e<t.length&&t[e]!==s;)e++;if(t[e]!==s)throw new Error(`Unterminated ${r} value`);const i=t.substring(n,e);return[++e,i]}const M={allowBooleanAttributes:!1,unpairedTags:[],docType:{maxEntityCount:1/0,maxEntitySize:1/0},invalidCharSequence:{comment:!1,tagValue:!1,attrLt:!1},xmlDeclaraion:{optional:!0,argPosition:!0},multipleRoots:!0,skipTags:[]};class ${constructor(t){this.options=function(t,e){const r=Object.assign({},t,e);return r.docType=Object.assign({},t.docType,e?.docType),r.invalidCharSequence=Object.assign({},t.invalidCharSequence,e?.invalidCharSequence),r.xmlDeclaraion=Object.assign({},t.xmlDeclaraion,e?.xmlDeclaraion,e?.xmlDeclaration),r.skipTags=e?.skipTags||t.skipTags,r}(M,t)}static validate(t,e){return new $(e).validate(t)}validate(t){const e=this.options,a=[];let o=!1,l=!1,c=!1;"\ufeff"===t[0]&&(t=t.substr(1));const h=(t,e,s)=>{throw new r(e,t,s.line||s,s.col)},d=new b(e.xmlDeclaraion,h).validate(t),u=d.version;t=t.substring(d.end);const p=new O(e.docType,u),f=new I(e),g=new x(u),m=new w(e,g,u),_=new S(e.skipTags),E=!0===e.invalidCharSequence?.tagValue,y=e=>{"<!DOCTYPE"===t.substring(e,e+9).toUpperCase()&&(c&&h("InvalidXml","Multiple DOCTYPE declarations found.",i(t,e)),(o||a.length>0)&&h("InvalidXml","DOCTYPE must appear before the root element.",i(t,e)),c=!0)};for(let r=0;r<t.length;r++)if("<"===t[r]&&"?"===t[r+1])r+=2,r=this._readPI(t,r,g,h);else if("<"===t[r]){let c=r;if(r++,"!"===t[r]){try{y(c),r=f.read(t,r,p)}catch(e){h("InvalidDocType",e.message,i(t,r-1))}continue}{let d=!1;"/"===t[r]&&(d=!0,r++);let u="";for(;r<t.length&&">"!==t[r]&&" "!==t[r]&&"\t"!==t[r]&&"\n"!==t[r]&&"\r"!==t[r];r++)u+=t[r];if(u=u.trim(),"/"===u[u.length-1]&&(u=u.substring(0,u.length-1),r--),!g.isValidQName(u)){let e;e=0===u.trim().length?"Invalid space after '<'.":"Tag '"+u+"' is an invalid name.",h("InvalidTag",e,i(t,c))}const x=this._readAttributeStr(t,r);!1===x&&h("InvalidAttr","Attributes for '"+u+"' have open quote.",i(t,r));let b=x.value;if(r=x.index,"/"===b[b.length-1]){const s=r-b.length;b=b.substring(0,b.length-1);const n=m.validate(b);!0===n?(!0!==l||e.multipleRoots||h("InvalidXml","Multiple possible root nodes found.",i(t,c)),o=!0,0===a.length&&(l=!0),_.push(u),_.pop()):h(n.err.code,n.err.msg,i(t,s+n.err.line))}else if(d)if(x.tagClosed)if(b.trim().length>0)h("InvalidTag","Closing tag '"+u+"' can't have attributes or invalid starting.",i(t,c));else if(0===a.length)h("InvalidTag","Closing tag '"+u+"' has not been opened.",i(t,c));else{const e=a.pop();if(u!==e.tagName){let r=i(t,e.tagStartPos);h("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+r.line+", col "+r.col+") instead of closing tag '"+u+"'.",i(t,c))}_.pop(),0===a.length&&(l=!0)}else h("InvalidTag","Closing tag '"+u+"' doesn't have proper closing.",i(t,r));else{const s=_.push(u);if(!s){const e=m.validate(b);!0!==e&&h(e.err.code,e.err.msg,i(t,r-b.length+e.err.line))}if(!0!==l||e.multipleRoots)if(-1!==e.unpairedTags.indexOf(u))_.pop();else{if(s){r=C.consume(t,u,r+1),_.pop(),0===a.length&&(l=!0),o=!0;continue}a.push({tagName:u,tagStartPos:c})}else h("InvalidXml","Multiple possible root nodes found.",i(t,r));o=!0}let w="";for(r++;r<t.length;r++)if("<"===t[r]){if("!"===t[r+1]){r++;try{y(r-1),r=f.read(t,r,p)}catch(e){h("InvalidDocType",e.message,i(t,r-1))}w="";continue}if("?"!==t[r+1])break;r+=2,r=this._readPI(t,r,g,h),w=""}else if("&"===t[r]){const e=this._validateAmpersand(t,r);-1===e&&h("InvalidChar","char '&' is not expected.",i(t,r)),r=e,w=""}else{const e=t.charCodeAt(r);n(e)&&h("IllegalCharacter",`Illegal control character ${T.describe(e)} in document content.`,i(t,r)),!0!==l||0!==a.length||s(t[r])||h("InvalidXml","Extra text at the end",i(t,r)),E&&(w=(w+t[r]).slice(-2),"]]"===w&&">"===t[r+1]&&h("InvalidXml","Element text content must not contain ']]>'.",i(t,r-1)))}"<"===t[r]&&r--}}else{if(s(t[r]))continue;l&&h("InvalidXml","Extra text at the end: '"+t[r]+"' is not expected.",i(t,r)),h("InvalidChar","char '"+t[r]+"' is not expected.",i(t,r))}return o?1===a.length?h("InvalidTag","Unclosed tag '"+a[0].tagName+"'.",i(t,a[0].tagStartPos)):a.length>0&&h("InvalidXml","Invalid '"+JSON.stringify(a.map(t=>t.tagName)).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):h("InvalidXml","Start tag expected.",{line:1,col:1}),!0}_readPI(t,e,r,s){const n=e,a=e;let o=!1;for(;e<t.length;e++){const l=t[e];if(!o&&(" "===l||"?"===l)){const l=t.substr(a,e-a);o=!0,"xml"===l.toLowerCase()?s("InvalidXml","XML declaration allowed only at the start of the document.",i(t,n-2)):r.isValidName(l)||s("InvalidXml",`Processing instruction target "${l}" is not a valid XML Name.`,i(t,n-2))}if("?"===l&&">"===t[e+1])return++e}s("InvalidXml",'Processing instruction is not closed with "?>".',i(t,n-2))}_readAttributeStr(t,e){let r="",s="",n=!1;for(;e<t.length;e++){if('"'===t[e]||"'"===t[e])""===s?s=t[e]:s!==t[e]||(s="");else if(">"===t[e]&&""===s){n=!0;break}r+=t[e]}return""===s&&{value:r,index:e,tagClosed:n}}_validateNumberAmpersand(t,e){let r=/\d/;for("x"===t[e]&&(e++,r=/[\da-fA-F]/);e<t.length;e++){if(";"===t[e])return e;if(!t[e].match(r))break}return-1}_validateAmpersand(t,e){if(";"===t[++e])return-1;if("#"===t[e])return e++,this._validateNumberAmpersand(t,e);let r=0;for(;e<t.length;e++,r++)if(!(t[e].match(/\w/)&&r<20)){if(";"===t[e])break;return-1}return e}}class B{constructor(){this._byDepthAndTag=new Map,this._wildcardByDepth=new Map,this._deepWildcards=[],this._deepByTerminalTag=new Map,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()){const e=t.segments[t.segments.length-1];if(e&&"deep-wildcard"!==e.type&&"*"!==e.tag){const r=e.tag;this._deepByTerminalTag.has(r)||this._deepByTerminalTag.set(r,[]),this._deepByTerminalTag.get(r).push(t)}else this._deepWildcards.push(t);return this}const e=t.length,r=t.segments[t.segments.length-1],s=r?.tag;if(s&&"*"!==s){const r=`${e}:${s}`;this._byDepthAndTag.has(r)||this._byDepthAndTag.set(r,[]),this._byDepthAndTag.get(r).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(),r=t.getCurrentTag(),s=`${e}:${r}`,n=this._byDepthAndTag.get(s);if(n)for(let e=0;e<n.length;e++)if(t.matches(n[e]))return n[e];const i=this._wildcardByDepth.get(e);if(i)for(let e=0;e<i.length;e++)if(t.matches(i[e]))return i[e];const a=this._deepByTerminalTag.get(r);if(a)for(let e=0;e<a.length;e++)if(t.matches(a[e]))return a[e];for(let e=0;e<this._deepWildcards.length;e++)if(t.matches(this._deepWildcards[e]))return this._deepWildcards[e];return null}}const R={nameFor:{},skip:{},tags:{valueParsers:[]},attributes:{valueParsers:[]},textJoint:"",alwaysArray:[],forceArray:null,forceTextNode:!1},V=["ws","entity","boolean","number"],j=["entity","number","boolean"];function X(t){const e=q(R);t&&void 0!==t.tags?.valueParsers||(e.tags.valueParsers=[...V]),t&&void 0!==t.attributes?.valueParsers||(e.attributes.valueParsers=[...j]);const r=Array.isArray(t?.alwaysArray)?t.alwaysArray:e.alwaysArray,s=new B;for(const t of r)Y(t,"alwaysArray",s);return s.seal(),e._alwaysArraySet=s,t&&F(e,t),e}function q(t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map(q);const e={};for(const r of Object.keys(t))e[r]=q(t[r]);return e}function F(t,e){for(const r of Object.keys(e))"__proto__"!==r&&"constructor"!==r&&"prototype"!==r&&("function"==typeof e[r]||Array.isArray(e[r])?t[r]=e[r]:"object"==typeof e[r]&&null!==e[r]?("object"==typeof t[r]&&null!==t[r]||(t[r]={}),F(t[r],e[r])):t[r]=e[r])}function Y(t,e,r){let s;if("string"==typeof t){if(0===t.length)throw new Error(`${e} expression cannot be empty`);s=t}else{if(!("string"==typeof t?.pattern&&t.pattern.length>0&&Array.isArray(t?.segments)))throw new Error(`Invalid ${e} entry: expected a string, or Expression.`);s=t.toString()}const n=new A(s);return r.add(n),n}const z={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'},G=Object.freeze({ALLOW:"allow",BLOCK:"block",THROW:"throw"}),H=new Set("!?\\\\/[]$%{}^&*()<>|+");function W(t){if("#"===t[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${t}"`);for(const e of t)if(H.has(e))throw new Error(`[EntityReplacer] Invalid character '${e}' in entity name: "${t}"`);return t}function Q(...t){const e=Object.create(null);for(const r of t)if(r)for(const t of Object.keys(r)){const s=r[t];if("string"==typeof s)e[t]=s;else if(s&&"object"==typeof s&&void 0!==s.val){const r=s.val;"string"==typeof r&&(e[t]=r)}}return e}const J="external",Z="base",K="all",tt=Object.freeze({allow:0,leave:1,remove:2,throw:3}),et=new Set([9,10,13]);class rt{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??J)&&e!==J?e===K?new Set([K]):e===Z?new Set([Z]):Array.isArray(e)?new Set(e):new Set([J]):new Set([J]),this._numericAllowed=t.numericAllowed??!0,this._baseMap=Q(z,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 r=function(t){if(!t)return{xmlVersion:1,onLevel:tt.allow,nullLevel:tt.remove};const e=1.1===t.xmlVersion?1.1:1,r=tt[t.onNCR]??tt.allow,s=tt[t.nullNCR]??tt.remove;return{xmlVersion:e,onLevel:r,nullLevel:Math.max(s,tt.remove)}}(t.ncr);this._ncrXmlVersion=r.xmlVersion,this._ncrOnLevel=r.onLevel,this._ncrNullLevel=r.nullLevel,this._onExternalEntity="function"==typeof t.onExternalEntity?t.onExternalEntity:null,this._onInputEntity="function"==typeof t.onInputEntity?t.onInputEntity:null}_applyRegistrationHook(t,e,r,s){if(!t)return!0;const n=t(e,r);if(n===G.BLOCK)return!1;if(n===G.THROW)throw new Error(`[EntityDecoder] Registration of ${s} entity "&${e};" was rejected by hook`);return!0}setExternalEntities(t){if(t)for(const e of Object.keys(t))W(e);if(!this._onExternalEntity)return void(this._externalMap=Q(t));const e=Q(t),r=Object.create(null);for(const[t,s]of Object.entries(e))this._applyRegistrationHook(this._onExternalEntity,t,s,"external")&&(r[t]=s);this._externalMap=r}addExternalEntity(t,e){W(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=Q(t));const e=Q(t),r=Object.create(null);for(const[t,s]of Object.entries(e))this._applyRegistrationHook(this._onInputEntity,t,s,"input")&&(r[t]=s);this._inputMap=r}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,r=[],s=t.length;let n=0,i=0;const a=this._maxTotalExpansions>0,o=this._maxExpandedLength>0,l=a||o;for(;i<s;){if(38!==t.charCodeAt(i)){i++;continue}let e=i+1;for(;e<s&&59!==t.charCodeAt(e)&&e-i<=32;)e++;if(e>=s||59!==t.charCodeAt(e)){i++;continue}const c=t.slice(i+1,e);if(0===c.length){i++;continue}let h,d;if(this._removeSet.has(c))h="",void 0===d&&(d=J);else{if(this._leaveSet.has(c)){i++;continue}if(35===c.charCodeAt(0)){const t=this._resolveNCR(c);if(void 0===t){i++;continue}h=t,d=Z}else{const t=this._resolveName(c);h=t?.value,d=t?.tier}}if(void 0!==h){if(i>n&&r.push(t.slice(n,i)),r.push(h),n=e+1,i=n,l&&this._tierCounts(d)){if(a&&(this._totalExpansions++,this._totalExpansions>this._maxTotalExpansions))throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`);if(o){const t=h.length-(c.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 i++}n<s&&r.push(t.slice(n));const c=0===r.length?t:r.join("");return this._postCheck(c,e)}_tierCounts(t){return!!this._limitTiers.has(K)||this._limitTiers.has(t)}_resolveName(t){return t in this._inputMap?{value:this._inputMap[t],tier:J}:t in this._externalMap?{value:this._externalMap[t],tier:J}:t in this._baseMap?{value:this._baseMap[t],tier:Z}:void 0}_classifyNCR(t){return 0===t?this._ncrNullLevel:t>=55296&&t<=57343||1===this._ncrXmlVersion&&t>=1&&t<=31&&!et.has(t)?tt.remove:-1}_applyNCRAction(t,e,r){switch(t){case tt.allow:return String.fromCodePoint(r);case tt.remove:return"";case tt.leave:return;case tt.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference &${e}; (U+${r.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(r)}}_resolveNCR(t){const e=t.charCodeAt(1);let r;if(r=120===e||88===e?parseInt(t.slice(2),16):parseInt(t.slice(1),10),Number.isNaN(r)||r<0||r>1114111)return;const s=this._classifyNCR(r);if(!this._numericAllowed&&s<tt.remove)return;const n=-1===s?this._ncrOnLevel:Math.max(this._ncrOnLevel,s);return this._applyNCRAction(n,t,r)}}const st=[{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}],nt="[\"'\\s]*:",it={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. <script or <script)",pattern:/(?:�*3[Cc];?|�*60;?|<)\s*script/i},{id:"html-entity-obfuscated-javascript",description:'HTML-entity-encoded javascript: (partial — catches common j or j for "j")',pattern:/(?:�*6[Aa];?|�*106;?)\s*(?:�*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:st,"SQL-STRICT":[...st,{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${nt}`,"i")},{id:"nosql-ne-operator",description:'$ne — "not equal" operator used to bypass equality checks',pattern:new RegExp(`\\$ne${nt}`,"i")},{id:"nosql-gt-operator",description:'$gt — "greater than" used to bypass password/value checks',pattern:new RegExp(`\\$gte?${nt}`,"i")},{id:"nosql-lt-operator",description:'$lt / $lte — "less than" bypass variants',pattern:new RegExp(`\\$lte?${nt}`,"i")},{id:"nosql-regex-operator",description:"$regex — can be used to extract data character by character (blind injection)",pattern:new RegExp(`\\$regex${nt}`,"i")},{id:"nosql-or-operator",description:"$or — logical OR; used to create always-true conditions",pattern:new RegExp(`\\$or${nt}\\s*\\[`,"i")},{id:"nosql-and-operator",description:"$and — logical AND operator injection",pattern:new RegExp(`\\$and${nt}\\s*\\[`,"i")},{id:"nosql-nor-operator",description:"$nor — logical NOR operator injection",pattern:new RegExp(`\\$nor${nt}\\s*\\[`,"i")},{id:"nosql-exists-operator",description:"$exists — can enumerate fields to determine schema",pattern:new RegExp(`\\$exists${nt}`,"i")},{id:"nosql-in-operator",description:"$in — matches any value in a list; can enumerate values",pattern:new RegExp(`\\$in${nt}\\s*\\[`,"i")},{id:"nosql-expr-operator",description:"$expr — allows aggregation expressions in queries (MongoDB 3.6+)",pattern:new RegExp(`\\$expr${nt}`,"i")},{id:"nosql-function-operator",description:"$function — executes arbitrary JavaScript in MongoDB 4.4+",pattern:new RegExp(`\\$function${nt}`,"i")},{id:"nosql-accumulator-operator",description:"$accumulator — custom aggregation with arbitrary JS execution",pattern:new RegExp(`\\$accumulator${nt}`,"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\[/}]},at=it,ot=Object.freeze(Object.fromEntries(Object.keys(it).map(t=>[t,t])));function lt(t,e){const r=at[e];for(const s of r)if(s.pattern.test(t))return{context:e,id:s.id,description:s.description,pattern:s.pattern};return null}function ct(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||!at[e])throw new TypeError(`is-unsafe: unknown context "${e}" in array. Valid contexts: ${Object.keys(ot).join(", ")}`)}else if(!at[t])throw new TypeError(`is-unsafe: unknown context "${t}". Valid contexts: ${Object.keys(ot).join(", ")}`)}(e),e instanceof RegExp)return e.test(t);if("string"==typeof e)return null!==lt(t,e);for(const r of e)if(null!==lt(t,r))return!0;return!1}class ht{constructor(t=!1){this.IS_FINAL=t}init(t){this.ctx=t}reset(){}parse(t,e){throw new Error("You must implement parse() in a value parser.")}}const dt={namedEntities:{...z},numericAllowed:!0,onInputEntity:(t,e)=>ct(e,[ot.XML])?G.BLOCK:G.ALLOW},ut=[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],pt=new Map,ft=1632,gt=new Uint8Array(63904).fill(255);for(const t of ut)for(let e=0;e<10;e++){const r=t+e;r<=65535?gt[r-ft]=e:pt.set(r,e)}const mt=new Set([8722,65293,65123]),_t=/^[-+]?0x[a-fA-F0-9]+$/,Et=/^0b[01]+$/,xt=/^0o[0-7]+$/,bt=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Tt={hex:!0,binary:!1,octal:!1,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original",unicode:!1};function yt(t,e={}){if(e=Object.assign({},Tt,e),!t||"string"!=typeof t)return t;let r=t.trim();if(0===r.length)return t;if(void 0!==e.skipLike&&e.skipLike.test(r))return t;if("0"===r)return 0;if(e.unicode&&(r=function(t){if("string"!=typeof t)return t;const e=t.length;if(0===e)return t;let r=-1;for(let s=0;s<e;s++){const n=t.charCodeAt(s);if(!(n>=48&&n<=57||45===n))if(n<ft){if(mt.has(n)){r=s;break}}else if(n>=55296&&n<=56319){if(s+1<e){const e=t.charCodeAt(s+1);if(e>=56320&&e<=57343){const t=65536+(n-55296<<10)+(e-56320);if(pt.has(t)){r=s;break}}}}else if(255!==gt[n-ft]||mt.has(n)){r=s;break}}if(-1===r)return t;const s=[];r>0&&s.push(t.slice(0,r));for(let n=r;n<e;n++){const r=t.charCodeAt(n);if(r>=48&&r<=57||45===r){s.push(t[n]);continue}if(r<ft){s.push(mt.has(r)?"-":t[n]);continue}if(r>=55296&&r<=56319){if(n+1<e){const e=t.charCodeAt(n+1);if(e>=56320&&e<=57343){const t=65536+(r-55296<<10)+(e-56320),i=pt.get(t);if(void 0!==i){s.push(String.fromCharCode(i+48)),n++;continue}}}s.push(t[n]);continue}if(mt.has(r)){s.push("-");continue}const i=gt[r-ft];s.push(255!==i?String.fromCharCode(i+48):t[n])}return s.join("")}(r),"0"===r))return 0;if(e.hex&&_t.test(r))return It(r,16);if(e.binary&&Et.test(r))return It(r,2);if(e.octal&&xt.test(r))return It(r,8);if(isFinite(r)){if(r.includes("e")||r.includes("E"))return function(t,e,r){if(!r.eNotation)return t;const s=e.match(wt);if(s){let n=s[1]||"";const i=-1===s[3].indexOf("e")?"E":"e",a=s[2],o=n?t[a.length+1]===i:t[a.length]===i;return a.length>1&&o?t:(1!==a.length||!s[3].startsWith(`.${i}`)&&s[3][0]!==i)&&a.length>0?r.leadingZeros&&!o?(e=(s[1]||"")+s[3],Number(e)):t:Number(e)}return t}(t,r,e);{const n=bt.exec(r);if(n){const i=n[1]||"",a=n[2];let o=(s=n[3])&&-1!==s.indexOf(".")?("."===(s=s.replace(/0+$/,""))?s="0":"."===s[0]?s="0"+s:"."===s[s.length-1]&&(s=s.substring(0,s.length-1)),s):s;const l=i?"."===t[a.length+1]:"."===t[a.length];if(!e.leadingZeros&&(a.length>1||1===a.length&&!l))return t;{const s=Number(r),n=String(s);if(0===s)return s;if(-1!==n.search(/[eE]/))return e.eNotation?s:t;if(-1!==r.indexOf("."))return"0"===n||n===o||n===`${i}${o}`?s:t;let l=a?o:r;return a?l===n||i+l===n?s:t:l===n||l===i+n?s:t}}return t}}var s;return function(t,e,r){const s=e===1/0;switch(r.infinity.toLowerCase()){case"null":return null;case"infinity":return e;case"string":return s?"Infinity":"-Infinity";default:return t}}(t,Number(r),e)}const wt=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function It(t,e){const r=t.trim();if(2!==e&&8!==e||(t=r.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")}class At extends ht{constructor(t,e=!1){super(e),this.options=t||{}}parse(t){if("string"==typeof t){const e=yt(t,this.options);if(typeof e!==t)return this.IS_FINAL?new Ct(e):e}return t}}const Nt={entity:new class extends ht{#t=!1;#e=null;#r=null;constructor(t,e=!1){super(e),this.#r={...dt,...t||{},namedEntities:{...dt.namedEntities,...t?.namedEntities||{}}}}#s(){if(this.#e||(this.#e=new rt(this.#r)),!this.#t){const t=this.ctx?.get("xmlVersion"),e=this.ctx?.get("inputEntities");t&&this.#e.setXmlVersion(t),e&&this.#e.addInputEntities(e),this.#t=!0}}reset(){this.#t=!1,this.#e&&this.#e.reset()}parse(t){return"string"!=typeof t?t:(this.#s(),this.#e.decode(t))}},trim:new class extends ht{parse(t){return"string"==typeof t?t.trim():t}},ws:new class extends ht{constructor(t,e=!1){super(e);const r=t?.exclude??[],s=new B;for(const t of r)s.add("string"==typeof t?new A(t):t);s.seal(),this._excludeSet=s}parse(t,e){if("string"!=typeof t)return t;if(e){if(e.isAttribute)return t;if(e.matcher){if("preserve"===e.matcher.getAnyParentAttr("xml:space"))return t;if(this._excludeSet.size>0&&this._excludeSet.matchesAny(e.matcher))return t}}return t.replace(/[ \t\r\n]+/g," ").trim()}},boolean:new class extends ht{constructor(t,e,r=!1){super(r),this.trueList=t||["true"],this.falseList=e||["false"]}parse(t){if("string"==typeof t){const e=t.toLowerCase();if(-1!==this.trueList.indexOf(e))return!this.IS_FINAL||new Ct(!0);if(-1!==this.falseList.indexOf(e))return!!this.IS_FINAL&&new Ct(!1)}return t}},number:new At({hex:!0,leadingZeros:!0,eNotation:!0})};class vt{constructor(){this.registered={...Nt}}register(t,e){if(!t||"string"!=typeof t)throw new Error("name must be a string");if(!e)throw new Error("parser is required");if(!e.reset||"function"!=typeof e.reset)throw new Error("parser must implement reset()");if(!e.parse||"function"!=typeof e.parse)throw new Error("parser must implement parse()");this.registered[t]=e}reset(t){this.registered[t]?.reset()}resetAll(){for(const t in this.registered)this.registered[t]?.reset()}get(t){const e=this.registered[t];if(!e)throw new Error("parser not found: "+t);return e}}class St{constructor(t,e,r,s=!1){this.elementName=t,this.matcher=e,this.isLeafNode=r,this.isAttribute=s}}class Ct{constructor(t){this.value=t}}class Dt{#n={};set(t,e){this.#n[t]=e}get(t){return this.#n[t]}clear(){this.#n={}}}class Ot{constructor(t=[],e,r=null){this.valParsers=t,this.registry=e,this.sharedContext=r||new Dt,this._initAll(t)}run(t,e){for(let r=0;r<this.valParsers.length;r++){let s=this.valParsers[r];if("string"==typeof s&&(s=this.registry.get(s)),s){const r=s.parse(t,e);if(r instanceof Ct)return r.value;t=r}}return t}resetAll(){for(let t=0;t<this.valParsers.length;t++){let e=this.valParsers[t];"string"==typeof e&&(e=this.registry.get(e)),e&&e.reset&&"function"==typeof e.reset&&e.reset()}}register(t,e){this.registry.register(t,e),e.init&&e.init(this.sharedContext)}_initAll(t){if(!this.sharedContext)return;const e=new Set;for(const r of t){let t=r;"string"==typeof r&&(t=this.registry.get(r)),t&&"function"==typeof t.init&&!e.has(t)&&(e.add(t),t.init(this.sharedContext))}}}const kt=["ws","entity","boolean","number"],Pt=["entity","boolean","number"];class Lt{constructor(t,e,r,s,n=!0){this.matcher=r,this._rootName="^",this.parserOptions=t,this.builderOptions=e,this.registry=s;const i=e?.tags?.valueParsers??kt,a=e?.attributes?.valueParsers??Pt;this.sharedContext=new Dt,this.tagsPipeline=new Ot(i,this.registry,this.sharedContext),this.attrsPipeline=new Ot(a,this.registry,this.sharedContext),n&&(this.tagsPipeline.resetAll(),this.attrsPipeline.resetAll()),this._pendingStopNode=!1}addAttribute(t,e,r){"version"===t&&this.tagName===this._rootName&&this.sharedContext?.set("xmlVersion",+e);const s=`${this.parserOptions.attributes.prefix}${t}${this.parserOptions.attributes.suffix}`,n=new St(t,r,!0,!0);this.attributes[s]=this.attrsPipeline.run(e,n)}_addChild(t,e){}addComment(t){this.parserOptions.skip.comment||this.parserOptions.nameFor.comment&&this._addChild(this.parserOptions.nameFor.comment,t)}addLiteral(t){this.parserOptions.skip.cdata||(this.parserOptions.nameFor.cdata?this._addChild(this.parserOptions.nameFor.cdata,t):this.addRawValue(t||""))}addRawValue(t){this.addValue(t)}addInputEntities(t){this.sharedContext?.set("inputEntities",t)}addDeclaration(t){this.addInstruction(t)}addInstruction(t){}onStopNode(t,e){this._pendingStopNode=!0,"function"==typeof this.parserOptions.onStopNode&&this.parserOptions.onStopNode(t,e,this.matcher)}onExit(t){}}class Ut{constructor(t={}){this.builderOptions=t,this.registry=new vt}registerValueParser(t,e){this.registry.register(t,e)}getInstance(t,e){throw new Error("getInstance is not implemented")}}class Mt extends Ut{constructor(t={}){super(),this.builderOptions=X(t)}getInstance(t,e){return new $t(t,this.builderOptions,e,this.registry)}}class $t extends Lt{constructor(t,e,r,s){super(t,e,r,s),this.parserOptions=t,this.builderOptions=e,this.tagsStack=[],this.root={},this.parent=this.root,this.tagName=this._rootName,this.value={},this.textValue="",this.attributes={},this.hasAttributes=!1}_buildAttributeValue(){return Bt(this.attributes)?(this.hasAttributes=!1,""):(this.hasAttributes=!0,this.parserOptions.attributes.groupBy?{[this.parserOptions.attributes.groupBy]:this.attributes}:this.attributes)}addElement(t){const e=this._buildAttributeValue();this.tagsStack.push([this.tagName,this.textValue,this.value,this.hasAttributes]),this.tagName=t.name,this.value=e,this.textValue="",this.attributes={}}_resolveForceArray(t){let e,r;if(this.builderOptions._alwaysArraySet.matchesAny(this.matcher)&&(e=!0),"function"==typeof this.builderOptions.forceArray){const e=this.builderOptions.forceArray(this.matcher,t);!0===e?r=!0:!1===e&&(r=!1)}return!1!==e&&!1!==r&&(!0===e||!0===r)}closeElement(){const t=this.tagName;let e=this.value;const r=this.textValue,s=this.hasAttributes,n="object"!=typeof e||Array.isArray(e)||Bt(e)||s,i=new St(t,this.matcher,n,!1);if(n){const t=this._pendingStopNode?r:this.tagsPipeline.run(r,i);s?(""!==t&&null!=t||this.builderOptions.forceTextNode)&&(e[this.parserOptions.nameFor.text]=t):e=this.builderOptions.forceTextNode?{[this.parserOptions.nameFor.text]:t}:t}else if(r.length>0||this.builderOptions.forceTextNode){const t=this._pendingStopNode?r:this.tagsPipeline.run(r,i);e[this.parserOptions.nameFor.text]=t}let a={tagName:t,value:e};const o=this.tagsStack.pop();let l=o[2];const c=this._resolveForceArray(n);l=this._addChildTo(a.tagName,a.value,l,c),this.tagName=o[0],this.textValue=o[1],this.value=l,this.hasAttributes=o[3],this._pendingStopNode=!1}_addChild(t,e){"string"==typeof this.value&&(this.value={[this.parserOptions.nameFor.text]:this.value}),this._addChildTo(t,e,this.value,!1),this.attributes={}}_addChildTo(t,e,r,s){return"string"==typeof r&&(r={}),Object.prototype.hasOwnProperty.call(r,t)?(Array.isArray(r[t])||(r[t]=[r[t]]),r[t].push(e)):r[t]=s?[e]:e,r}addValue(t){this.textValue.length>0?this.textValue+=`${this.builderOptions.textJoint}${t}`:this.textValue=t}addInstruction(t){const e=this._buildAttributeValue();this._addChild(t,e),this.attributes={}}onExit(t){}getOutput(){return this.value}}function Bt(t){return 0===Object.keys(t).length}class Rt extends Error{constructor(t,e,r={}){super(t),this.name="ParseError",this.code=e,this.index=r.index??void 0}toString(){const t=this._posStr();return t?`${this.name} [${this.code}] at ${t}: ${this.message}`:`${this.name} [${this.code}]: ${this.message}`}_posStr(){return void 0!==this.index?`index ${this.index}`:null}}const Vt=Object.freeze({INVALID_INPUT:"INVALID_INPUT",INVALID_STREAM:"INVALID_STREAM",ALREADY_STREAMING:"ALREADY_STREAMING",NOT_STREAMING:"NOT_STREAMING",DATA_MUST_BE_STRING:"DATA_MUST_BE_STRING",UNEXPECTED_END:"UNEXPECTED_END",UNEXPECTED_CLOSE_TAG:"UNEXPECTED_CLOSE_TAG",MISMATCHED_CLOSE_TAG:"MISMATCHED_CLOSE_TAG",UNEXPECTED_TRAILING_DATA:"UNEXPECTED_TRAILING_DATA",INVALID_TAG:"INVALID_TAG",UNCLOSED_QUOTE:"UNCLOSED_QUOTE",INVALID_ATTRIBUTE_NAME:"INVALID_ATTRIBUTE_NAME",MULTIPLE_NAMESPACES:"MULTIPLE_NAMESPACES",ILLEGAL_CHARACTER:"ILLEGAL_CHARACTER",DUPLICATE_ATTRIBUTE:"DUPLICATE_ATTRIBUTE",UNQUOTED_ATTRIBUTE_VALUE:"UNQUOTED_ATTRIBUTE_VALUE",BOOLEAN_ATTRIBUTE_REJECTED:"BOOLEAN_ATTRIBUTE_REJECTED",SECURITY_PROTOTYPE_POLLUTION:"SECURITY_PROTOTYPE_POLLUTION",SECURITY_RESERVED_OPTION:"SECURITY_RESERVED_OPTION",SECURITY_RESTRICTED_NAME:"SECURITY_RESTRICTED_NAME",LIMIT_MAX_NESTED_TAGS:"LIMIT_MAX_NESTED_TAGS",LIMIT_MAX_ATTRIBUTES:"LIMIT_MAX_ATTRIBUTES",ENTITY_MAX_COUNT:"ENTITY_MAX_COUNT",ENTITY_MAX_SIZE:"ENTITY_MAX_SIZE",ENTITY_MAX_EXPANSIONS:"ENTITY_MAX_EXPANSIONS",ENTITY_MAX_EXPANDED_LENGTH:"ENTITY_MAX_EXPANDED_LENGTH",ENTITY_INVALID_KEY:"ENTITY_INVALID_KEY",ENTITY_INVALID_VALUE:"ENTITY_INVALID_VALUE",UNSUPPORTED_ENCODING:"UNSUPPORTED_ENCODING",INVALID_DECODER:"INVALID_DECODER",ENCODING_MISMATCH:"ENCODING_MISMATCH"});function jt(t){return" "===t||"\t"===t||"\n"===t||"\r"===t||"\f"===t}function Xt(t){return 32===t||9===t||10===t||13===t||12===t}const qt=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","toLocaleString","isPrototypeOf","propertyIsEnumerable"],Ft=["__proto__","constructor","prototype"];function Yt(t){return t.startIndex+(t._baseOffset||0)}function zt(t){return{index:Yt(t)}}function Gt(t){return t<=8||11===t||12===t||t>=14&&t<=31}function Ht(t,e){const r=t.length;let s=!1;for(let n=0;n<r;n++){const r=t.charCodeAt(n);if(Gt(r))throw new Rt(`Illegal control character 0x${r.toString(16).padStart(2,"0")} in document content`,Vt.ILLEGAL_CHARACTER,e?zt(e):{});13===r&&(s=!0)}if(!s)return t;let n="",i=0;for(let e=0;e<r;e++)13===t.charCodeAt(e)&&(n+=t.substring(i,e)+"\n",10===t.charCodeAt(e+1)&&e++,i=e+1);return n+=t.substring(i),n}function Wt(t,e,r,s=!1){const n=e.length;if(!t.canRead(n))throw new Rt(`Unexpected end of source reading ${r}`,Vt.UNEXPECTED_END,zt(t));if(!0!==t.matchAhead(e,s))throw new Rt(`Invalid ${r}`,Vt.INVALID_TAG,zt(t));t.updateBufferBoundary(n)}function Qt(t,e,r){if(!t.canRead(e))throw new Rt(`Unexpected end of source reading ${r}`,Vt.UNEXPECTED_END,zt(t))}const Jt=t=>qt.includes(t)?"__"+t:t,Zt={skip:{declaration:!1,pi:!1,attributes:!0,cdata:!1,comment:!1,nsPrefix:!1,tags:[],whitespaceText:!0},nameFor:{text:"#text",cdata:"",comment:""},attributes:{booleanType:"allow",duplicate:"overwrite",groupBy:"",prefix:"@_",suffix:""},tags:{unpaired:[],stopNodes:[]},strictReservedNames:!1,onDangerousProperty:Jt,sanitizeNames:!0,only:[],doctypeOptions:{enabled:!1,maxEntityCount:100,maxEntitySize:1e4},autoClose:null,limits:{maxNestedTags:null,maxAttributesPerTag:null},feedable:{maxBufferSize:10485760,autoFlush:!0,flushThreshold:1024,bufferSize:256},exitIf:()=>!1,OutputBuilder:null,decoding:{encoding:"auto",customDecoders:null}},Kt=new Set([...Ft,...qt]);function te(t,e){if("string"==typeof t&&""!==t&&Kt.has(t))throw new Rt(`SECURITY: '${t}' is a reserved JavaScript keyword and cannot be used as ${e}`,Vt.SECURITY_RESERVED_OPTION)}const ee=function(t){if(t&&(t.nameFor?.text&&te(t.nameFor.text,"nameFor.text"),t.nameFor?.cdata&&te(t.nameFor.cdata,"nameFor.cdata"),t.nameFor?.comment&&te(t.nameFor.comment,"nameFor.comment"),t.attributes?.prefix&&te(t.attributes.prefix,"attributes.prefix"),t.attributes?.groupBy&&te(t.attributes.groupBy,"attributes.groupBy"),void 0!==t.limits&&null!==t.limits)){if("object"!=typeof t.limits)throw new Rt("'limits' must be an object, got "+typeof t.limits,Vt.INVALID_INPUT);const{maxNestedTags:e,maxAttributesPerTag:r}=t.limits;if(null!=e&&("number"!=typeof e||!Number.isInteger(e)||e<1))throw new Rt(`'limits.maxNestedTags' must be a positive integer, got ${e}`,Vt.INVALID_INPUT);if(null!=r&&("number"!=typeof r||!Number.isInteger(r)||r<0))throw new Rt(`'limits.maxAttributesPerTag' must be a non-negative integer, got ${r}`,Vt.INVALID_INPUT)}const e=ne(Zt);if(t&&ie(e,t),e.OutputBuilder||(e.OutputBuilder=new Mt),Array.isArray(e.tags?.stopNodes)){const t=new B;e.tags.stopNodes=e.tags.stopNodes.map(e=>se(e,"stopNodes",t)),t.seal(),e.tags.stopNodesSet=t}if(Array.isArray(e.skip?.tags)){const t=new B;e.skip.tags=e.skip.tags.map(e=>se(e,"skip.tags",t)),t.seal(),e.skip.tagsSet=t}if(null===e.onDangerousProperty&&(e.onDangerousProperty=Jt),null!==e.exitIf&&void 0!==e.exitIf&&"function"!=typeof e.exitIf)throw new Rt("'exitIf' must be a function, got "+typeof e.exitIf,Vt.INVALID_INPUT);return e.autoClose=function(t,e){if(!t)return null;if("html"===t){const t=e.tags.unpaired||[],r=[...new Set([...t,...re])];return e.tags={...e.tags,unpaired:r},{onEof:"closeAll",onMismatch:"discard",collectErrors:!0}}return"string"==typeof t?{onEof:t,onMismatch:"throw",collectErrors:!1}:"object"==typeof t?{onEof:t.onEof||"throw",onMismatch:t.onMismatch||"throw",collectErrors:t.collectErrors||!1}:null}(e.autoClose,e),e},re=["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"];function se(t,e,r){let s,n,i;if("string"==typeof t){if(0===t.length)throw new Rt(`${e} expression cannot be empty`,Vt.INVALID_INPUT);s=t,n=!1,i=[]}else if(t instanceof A)s=t.toString(),n=t.data?.nested??!1,i=t.data?.skipEnclosures??[];else{if(!t||"object"!=typeof t||void 0===t.expression)throw new Rt(`Invalid ${e} entry: expected a string, Expression, or { expression, nested?, skipEnclosures? } object.`,Vt.INVALID_INPUT);{const r=t.expression;if("string"==typeof r){if(0===r.length)throw new Rt(`${e} expression cannot be empty`,Vt.INVALID_INPUT);s=r}else{if(!(r instanceof A))throw new Rt(`${e} expression must be a string or Expression instance`,Vt.INVALID_INPUT);s=r.toString()}n=!0===t.nested,i=Array.isArray(t.skipEnclosures)?t.skipEnclosures:[]}}const a=new A(s,{},{nested:n,skipEnclosures:i});return r.add(a),a}function ne(t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map(ne);if(t instanceof RegExp)return t;if(t instanceof A)return t;const e={};for(const r of Object.keys(t))e[r]="function"==typeof t[r]?t[r]:ne(t[r]);return e}function ie(t,e){for(const r of Object.keys(e))"__proto__"!==r&&"constructor"!==r&&"prototype"!==r&&("OutputBuilder"===r||"function"==typeof e[r]||e[r]instanceof RegExp||Array.isArray(e[r])?t[r]=e[r]:"object"==typeof e[r]&&null!==e[r]?("object"==typeof t[r]&&null!==t[r]||(t[r]={}),ie(t[r],e[r])):t[r]=e[r])}function ae(){const t=this.buffer,e=t.length,r=this.startIndex,s=this._quotePairs,n=s.length;let i=0,a=!1,o=!1;for(let l=r;l<e;l++){const e=t[l];if("'"===e)o||(a=!a,i<n&&(s[i++]=l-r));else if('"'===e)a||(o=!o,i<n&&(s[i++]=l-r));else if(">"===e&&!a&&!o)return this._quotePairsLen=i,l-r}return this._quotePairsLen=i,-1}function oe(){const t=this.buffer,e=t.length,r=this.startIndex;let s=!1,n=!1;for(let i=r;i<e;i++){const e=t[i];if("'"===e)n||(s=!s);else if('"'===e)s||(n=!n);else if(">"===e&&!s&&!n)return i-r}return-1}class le{constructor(t,e={}){this.buffer=t,this.startIndex=0,this._baseOffset=0,this.autoFlush=!1!==e.autoFlush,this.flushThreshold=e.flushThreshold??1024,this._marks=[-1,-1],this._quotePairs=new Int32Array(128),this._quotePairsLen=0}markTokenStart(t=0){this._marks[t]=this.startIndex}rewindToMark(){}clearMark(){this._marks[0]=-1,this._marks[1]=-1}flush(){let t=this.startIndex;for(const e of this._marks)e>=0&&e<t&&(t=e);if(t>0){this.buffer=this.buffer.substring(t);const e=this._marks.length;for(let r=0;r<e;r++)this._marks[r]>=0&&(this._marks[r]-=t);this.startIndex-=t,this._baseOffset+=t}}readCh(){return this.buffer[this.startIndex++]}readChAt(t){return this.buffer[this.startIndex+t]}readStr(t,e){return void 0===e&&(e=this.startIndex),this.buffer.substring(e,e+t)}matchAhead(t,e=!1){const r=t.length;for(let s=0;s<r;s++){let r=this.buffer[this.startIndex+s];if(void 0===r)return null;if(e&&(r=r.toLowerCase()),r!==t[s])return!1}return!0}scanTagExpEnd=ae;scanTagExpEndFast=oe;readUpto(t){const e=this.buffer.length,r=t.length;for(let s=this.startIndex;s<e;s++){let e=!0;for(let n=0;n<r;n++)if(this.buffer[s+n]!==t[n]){e=!1;break}if(e){const t=this.buffer.substring(this.startIndex,s);return this.startIndex=s+r,t}}throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END)}readUptoChar(t){const e=this.buffer.indexOf(t,this.startIndex);if(-1===e)throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END);const r=this.buffer.substring(this.startIndex,e);return this.startIndex=e+1,r}readUptoCloseTag(t){const e=this.buffer.length,r=t.length;let s=-1,n=0;for(let i=this.startIndex;i<e;i++){if(1===n){const t=this.buffer[i];if(jt(t))continue;">"===t?n=2:(n=0,s=-1)}else{let e=!0;for(let s=0;s<r;s++)if(this.buffer[i+s]!==t[s]){e=!1;break}e&&(n=1,s=i,i+=r-1)}if(2===n){const t=this.buffer.substring(this.startIndex,s);return this.startIndex=i+1,t}}throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END)}readFromBuffer(t,e){const r=1===t?this.buffer[this.startIndex]:this.buffer.substring(this.startIndex,this.startIndex+t);return e&&this.updateBufferBoundary(t),r}updateBufferBoundary(t=1){this.startIndex+=t,this.autoFlush&&this.startIndex>=this.flushThreshold&&this.flush()}canRead(t=0){return this.startIndex+t<this.buffer.length}}function ce(t,e="utf8",r=()=>!1){return{readCh(){const{char:e,width:r}=t(this.buffer,this.startIndex);return this.startIndex+=r,e},readChAt(e){return t(this.buffer,this.startIndex+e).char},readStr(t,r){return void 0===r&&(r=this.startIndex),this.buffer.slice(r,r+t).toString(e)},matchAhead(t,e=!1){const r=t.length;for(let s=0;s<r;s++){const r=this.buffer[this.startIndex+s];if(void 0===r)return null;let n=r;if(e&&n>=65&&n<=90&&(n+=32),n!==t.charCodeAt(s))return!1}return!0},scanTagExpEnd(){const t=this.buffer,e=t.length,r=this.startIndex,s=this._quotePairs,n=s.length;let i=0,a=!1,o=!1;for(let l=r;l<e;l++){const e=t[l];if(39===e)o||(a=!a,i<n&&(s[i++]=l-r));else if(34===e)a||(o=!o,i<n&&(s[i++]=l-r));else if(62===e&&!a&&!o)return this._quotePairsLen=i,l-r}return this._quotePairsLen=i,-1},scanTagExpEndFast(){const t=this.buffer,e=t.length,r=this.startIndex;let s=!1,n=!1;for(let i=r;i<e;i++){const e=t[i];if(39===e)n||(s=!s);else if(34===e)s||(n=!n);else if(62===e&&!s&&!n)return i-r}return-1},readUpto(t){const r=this.buffer.length,s=t.length,n=Buffer.from(t);for(let t=this.startIndex;t<r;t++){let r=!0;for(let e=0;e<s;e++)if(this.buffer[t+e]!==n[e]){r=!1;break}if(r){const r=this.buffer.slice(this.startIndex,t).toString(e);return this.startIndex=t+s,r}}throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END)},readUptoChar(t){const r=t.charCodeAt(0),s=this.buffer,n=s.length;for(let t=this.startIndex;t<n;t++)if(s[t]===r){const r=s.slice(this.startIndex,t).toString(e);return this.startIndex=t+1,r}throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END)},readUptoCloseTag(t){const r=this.buffer.length,s=t.length,n=Buffer.from(t);let i=-1,a=0;for(let t=this.startIndex;t<r;t++){const r=this.buffer[t];if(1===a){if(Xt(r))continue;62===r?a=2:(a=0,i=-1)}else{let e=!0;for(let r=0;r<s;r++)if(this.buffer[t+r]!==n[r]){e=!1;break}e&&(a=1,i=t,t+=s-1)}if(2===a){const r=this.buffer.slice(this.startIndex,i).toString(e);return this.startIndex=t+1,r}}throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END)},readFromBuffer(r,s){if(1===r){const{char:e,width:r}=t(this.buffer,this.startIndex);return s&&this.updateBufferBoundary(r),e}const n=this.buffer.slice(this.startIndex,this.startIndex+r).toString(e);return s&&this.updateBufferBoundary(r),n},updateBufferBoundary(t=1){this.startIndex+=t,this.autoFlush&&this.startIndex>=this.flushThreshold&&this._tokenStart<0&&this.flush()},canRead(t=0){return this.startIndex+t<this.buffer.length}}}function he(t,e){return{char:String.fromCharCode(t[e]),width:1}}function de(t,e){const r=t[e];let s=1;return 128&r?192==(224&r)?s=2:224==(240&r)?s=3:240==(248&r)&&(s=4):s=1,e+s>t.length&&(s=t.length-e),{char:t.toString("utf8",e,e+s),width:s}}const ue=ce(de,"utf8");class pe{constructor(t,e={},r=null){if(this.buffer=r?.bomLength?t.subarray(r.bomLength):t,r?.decodeFirst){const t=r.descriptor.createDecoder();this.buffer=t.write(this.buffer)+t.end()}this.startIndex=0,this._baseOffset=0,this.autoFlush=!1!==e.autoFlush,this.flushThreshold=e.flushThreshold??1024,this._tokenStart=-1,this._quotePairs=new Int32Array(128),this._quotePairsLen=0;const s=r?.scanStrategy??ue;Object.assign(this,s),this.encodingName=r?.descriptor?.name??"utf8",this._quotePairsUsable=!!r&&!1!==r.quotePairsUsable}markTokenStart(){this._tokenStart=this.startIndex}rewindToMark(){}flush(){const t=this._tokenStart>=0?this._tokenStart:this.startIndex;t>0&&(this.buffer=Buffer.from(this.buffer.subarray(t)),this._tokenStart>=0?(this.startIndex-=t,this._tokenStart=0):this.startIndex=0,this._baseOffset+=t)}}function fe(t,e){const r=function(t,e){for(const r of e.bomCandidates()){const e=r.bomBytes;if(t.length>=e.length&&e.equals(t.subarray(0,e.length)))return{descriptor:r,bomLength:e.length}}return null}(t,e),s=function(t,e){const r=t.subarray(e,Math.min(t.length,e+200)).toString("latin1").match(/^\s*<\?xml\s+[^?]*\?>/);if(!r)return null;const s=r[0].match(/encoding\s*=\s*["']([^"']+)["']/i);return s?s[1].toLowerCase():null}(t,r?r.bomLength:0);if(r&&s&&!function(t,e,r){try{return r.resolve(t).name===r.resolve(e).name}catch{return!1}}(r.descriptor.name,s,e))throw new Rt(`Byte-order mark indicates "${r.descriptor.name}" but the XML declaration says encoding="${s}"`,Vt.ENCODING_MISMATCH);return r?{encoding:r.descriptor.name,bomLength:r.bomLength,declaredEncoding:s}:s?{encoding:s,bomLength:0,declaredEncoding:s}:{encoding:"utf8",bomLength:0,declaredEncoding:null}}function ge(t){const e=new TextDecoder(t,{fatal:!1,ignoreBOM:!0});return{write:t=>e.decode(t,{stream:!0}),end:()=>e.decode()}}class me{constructor(){this._byName=new Map,this._seedDefaults()}_seedDefaults(){this.register({name:"utf8",aliases:["utf-8"],bomBytes:Buffer.from([239,187,191]),selfSynchronizing:!0,variableWidth:!0,createDecoder:()=>ge("utf-8")}),this.register({name:"ascii",aliases:[],bomBytes:null,selfSynchronizing:!0,variableWidth:!1,createDecoder:()=>ge("windows-1252")}),this.register({name:"latin1",aliases:["iso-8859-1","binary"],bomBytes:null,selfSynchronizing:!0,variableWidth:!1,createDecoder:()=>ge("iso-8859-1")}),this.register({name:"utf16le",aliases:["utf-16le","ucs2","ucs-2"],bomBytes:Buffer.from([255,254]),selfSynchronizing:!1,variableWidth:!0,createDecoder:()=>ge("utf-16le")}),this.register({name:"utf16be",aliases:["utf-16be"],bomBytes:Buffer.from([254,255]),selfSynchronizing:!1,variableWidth:!0,createDecoder:()=>function(){const t=ge("utf-16le");let e=null;return{write(r){let s=e?function(t,e){const r=new Uint8Array(t.length+e.length);return r.set(t,0),r.set(e,t.length),r}(e,r):r;e=null,s.length%2==1&&(e=s.subarray(s.length-1),s=s.subarray(0,s.length-1));const n=function(t){const e=new Uint8Array(t);for(let t=0;t+1<e.length;t+=2){const r=e[t];e[t]=e[t+1],e[t+1]=r}return e}(s);return t.write(n)},end:()=>t.end()}}()})}register(t){if(!t||"string"!=typeof t.name||!t.name)throw new Rt('Encoding descriptor requires a non-empty "name"',Vt.INVALID_DECODER);if("function"!=typeof t.createDecoder)throw new Rt(`Encoding "${t.name}" is missing createDecoder()`,Vt.INVALID_DECODER);const e=t.createDecoder();if(!e||"function"!=typeof e.write||"function"!=typeof e.end)throw new Rt(`Encoding "${t.name}"'s createDecoder() must return an object with write()/end()`,Vt.INVALID_DECODER);const r={selfSynchronizing:!1,variableWidth:!0,aliases:[],bomBytes:null,...t};this._byName.set(r.name.toLowerCase(),r);for(const t of r.aliases)this._byName.set(t.toLowerCase(),r)}resolve(t){const e=this._byName.get(String(t).toLowerCase());if(!e)throw new Rt(`Unsupported encoding "${t}"`,Vt.UNSUPPORTED_ENCODING);return e}bomCandidates(){const t=new Set,e=[];for(const r of this._byName.values())r.bomBytes&&!t.has(r.name)&&(t.add(r.name),e.push(r));return e.sort((t,e)=>e.bomBytes.length-t.bomBytes.length)}}const _e=new me;function Ee(t){return t<=8||11===t||12===t||t>=14&&t<=31}function xe(t,e,r,s){let n="",i=e;for(;e<r;e++){const r=t.charCodeAt(e);if(13===r)n+=t.substring(i,e)+" ",10===t.charCodeAt(e+1)&&e++,i=e+1;else if(10===r||9===r)n+=t.substring(i,e)+" ",i=e+1;else if(Ee(r))throw new Rt(`Illegal control character 0x${r.toString(16).padStart(2,"0")} in attribute value`,Vt.ILLEGAL_CHARACTER,s?zt(s.source):{})}return n+=t.substring(i,e),n}function be(t,e,r,s){if(!t||0===t.length)return;const n=e.options.limits?.maxAttributesPerTag;if(null!=n&&s>n){const t=e.currentTagDetail?.name??"(unknown)";throw new Rt(`Tag '${t}' has ${s} attributes, exceeding limit of ${n}`,Vt.LIMIT_MAX_ATTRIBUTES,zt(e.source))}const i=t.length;for(let s=0;s<i;s++){const n=t[s],i=void 0!==r?{index:r+n.index}:void 0;e.outputBuilder.addAttribute(n.name,n.value,e.readonlyMatcher,i)}}class Te{constructor(){this.tagName="",this.selfClosing=!1,this.rawAttributes={},this._attrsExp="",this._attrsExpStart=void 0,this._rawAttrMatchCount=0,this._parsedAttrs=[]}}function ye(t){t.source.markTokenStart(1);const e=Yt(t.source),r=!t.options.skip.attributes,s=r?t.source.scanTagExpEnd():t.source.scanTagExpEndFast();if(-1===s)throw new Rt("Unexpected closing of source waiting for '>'",Vt.UNEXPECTED_END);const n=t.source.readStr(s);t.source.updateBufferBoundary(s+1);const i=r&&!1!==t.source._quotePairsUsable;return we(n,t,e,!1,i?t.source._quotePairs:void 0,i?t.source._quotePairsLen:0)}function we(t,e,r,s=!1,n=void 0,i=0){const a=new Te;"/"===t[t.length-1]&&(a.selfClosing=!0,t=t.slice(0,-1));let o,l="",c=0;for(;c<t.length;c++)if(jt(t[c])){a.tagName=t.substring(0,c),l=t.substring(c+1),o=c+1,void 0!==r&&(a._attrsExpStart=r+c+1);break}if(0===a.tagName.length&&c===t.length&&(a.tagName=t),a.tagName=a.tagName.trimEnd(),a._attrsExp=l,!e.isValidQName(a.tagName))throw new Rt("Invalid tag name",Vt.INVALID_TAG_NAME);return(s||l.length>0)&&function(t,e,r,s,n,i){if(!t||0===t.length)return;const a=function(t,e,r,s=0,n){const i=[],a=t.length;let o=0;const l=void 0!==e&&s>0;let c=0;for(;o<a;){for(;o<a&&Xt(t.charCodeAt(o));)o++;if(o>=a)break;const h=o;for(;o<a&&61!==t.charCodeAt(o)&&!Xt(t.charCodeAt(o));)o++;const d=t.substring(h,o);for(;o<a&&Xt(t.charCodeAt(o));)o++;if(o>=a||61!==t.charCodeAt(o)){i.push({name:d,value:void 0,startIndex:h});continue}for(o++;o<a&&Xt(t.charCodeAt(o));)o++;const u=t.charCodeAt(o);if(34!==u&&39!==u)throw new Rt(`Attribute '${d}' has an unquoted value — attribute values must be wrapped in '"' or "'"`,Vt.UNQUOTED_ATTRIBUTE_VALUE,n?zt(n.source):{});let p,f=-1;if(l&&c+1<s&&e[c]===o+r&&(f=e[c+1]-r,c+=2),o++,f>=0)p=f;else for(p=o;p<a&&t.charCodeAt(p)!==u;)p++;const g=xe(t,o,p,n);o=p+1,i.push({name:d,value:g,startIndex:h})}return i}(t,s,n,i,e),o=a.length;r._rawAttrMatchCount=o;const l=[];let c=0;const h=e.options.attributes?.duplicate||"overwrite",d="overwrite"!==h?new Set:null,u=e.options.attributes?.booleanType||"allow";for(let t=0;t<o;t++){const s=a[t];if(d){if(d.has(s.name)){if("throw"===h)throw new Rt(`Duplicate attribute '${s.name}'`,Vt.DUPLICATE_ATTRIBUTE,zt(e.source));continue}d.add(s.name)}const n=s.value;if(void 0===n){if("throw"===u)throw new Rt(`Valueless attribute '${s.name}' is not allowed`,Vt.BOOLEAN_ATTRIBUTE_REJECTED,zt(e.source));if("ignore"===u)continue}const i=e.processAttrName(s.name);if(!1===i)continue;c++;const o=void 0===n||n;r.rawAttributes[s.name]=o,l.push({name:i,value:o,index:s.startIndex})}r.rawAttributesLen=c,r._parsedAttrs=l}(l,e,a,n,o,i),a}class Ie{constructor(t,{nested:e=!1,skipEnclosures:r=[]}={}){this._tagName=t,this._nested=e,this._enclosures=r,this._content="",this._depth=1,this._active=!1}isActive(){return this._active}activate(){this._active=!0,this._content="",this._depth=1}resumeAfterOpenTag(){this._content="",this._depth=1}collect(t){t.markTokenStart(1);const e=this._enclosures.length;return this._nested||0!==e?this._nested&&0===e?this._collectDepthOnly(t):!this._nested&&e>0?this._collectEnclosureOnly(t):this._collectFull(t):this._collectPlain(t)}_collectPlain(t){for(;t.canRead();)if("<"===t.readChAt(0)){if(this._tryConsumeCloseTag(t))return this._finish(t);this._content+=t.readCh()}else this._content+=t.readCh();throw this._unclosedError()}_collectDepthOnly(t){for(;this._depth>0;)if(Qt(t,0,`stop node <${this._tagName}> content`),this._stepDepthTracking(t))return this._finish(t);throw this._unclosedError()}_collectEnclosureOnly(t){for(;t.canRead();)if(!this._trySkipEnclosure(t))if("<"===t.readChAt(0)){if(this._tryConsumeCloseTag(t))return this._finish(t);this._content+=t.readCh()}else this._content+=t.readCh();throw this._unclosedError()}_collectFull(t){for(;this._depth>0;)if(Qt(t,0,`stop node <${this._tagName}> content`),!this._trySkipEnclosure(t)&&this._stepDepthTracking(t))return this._finish(t);throw this._unclosedError()}_finish(t){const e=this._content,r={index:Yt(t)};return this._active=!1,this._content="",this._depth=1,{content:e,end:r}}_trySkipEnclosure(t){const e=this._matchEnclosureOpen(t);if(-1===e)return!1;const r=this._enclosures[e];this._skipChars(t,r.open.length),this._content+=r.open;const s=this._readUpto(t,r.close);return this._content+=s+r.close,!0}_tryConsumeCloseTag(t){const e="</"+this._tagName;if(!this._peekMatch(t,e))return!1;let r=e.length,s=!1;for(;;){const e=t.readChAt(r);if(">"===e){s=!0;break}if(!jt(e))break;r++}if(!s)return!1;for(this._skipChars(t,e.length);t.canRead()&&">"!==t.readCh(););return!0}_stepDepthTracking(t){if("<"!==t.readChAt(0))return this._content+=t.readCh(),!1;if(t.readCh(),Qt(t,0,`stop node <${this._tagName}> tag after '<'`),"/"===t.readChAt(0)){t.readCh();const e=this._readTagName(t),r=this._readToAngleClose(t);return e===this._tagName&&(this._depth--,0===this._depth)||(this._content+="</"+e+r,!1)}const e=this._readTagName(t);this._content+="<"+e;const{selfClosing:r,attrText:s}=this._readTagTail(t);return this._content+=s,r||e!==this._tagName||this._depth++,!1}_unclosedError(){return new Rt(`Unclosed stop node <${this._tagName}> — unexpected end of input`,Vt.UNEXPECTED_END)}_matchEnclosureOpen(t){const e=this._enclosures.length;for(let r=0;r<e;r++)if(this._peekMatch(t,this._enclosures[r].open))return r;return-1}_readUpto(t,e){const r=e[0],s=e.length,n=t.startIndex;let i=0;for(;t.canRead();){if(t.readChAt(0)===r&&this._peekMatch(t,e)){const e=t.readStr(i,n);return this._skipChars(t,s),e}t.readCh(),i++}throw new Rt(`Unclosed stop node <${this._tagName}> — unexpected end looking for '${e}'`,Vt.UNEXPECTED_END)}_peekMatch(t,e){const r=e.length;for(let s=0;s<r;s++)if(t.readChAt(s)!==e[s])return!1;return!0}_skipChars(t,e){for(let r=0;r<e;r++)t.readCh()}_readTagName(t){let e="";for(;t.canRead();){const r=t.readChAt(0);if(">"===r||"/"===r||jt(r))break;e+=t.readCh()}return e}_readTagTail(t){const e=t.startIndex;let r=0,s=!1,n=!1;for(;t.canRead();){const i=t.readCh();if(r++,"'"!==i||n)if('"'!==i||s){if(!s&&!n){if(">"===i)return{selfClosing:!1,attrText:t.readStr(r,e)};if("/"===i&&t.canRead()&&">"===t.readChAt(0))return t.readCh(),r++,{selfClosing:!0,attrText:t.readStr(r,e)}}}else n=!n;else s=!s}throw new Rt(`Unclosed stop node <${this._tagName}> — unexpected end inside tag`,Vt.UNEXPECTED_END)}_readToAngleClose(t){const e=t.startIndex;let r=0;for(;t.canRead();){const s=t.readCh();if(r++,">"===s)return t.readStr(r,e);if(!jt(s))throw new Rt(`Malformed closing tag for </${this._tagName}>`,Vt.UNEXPECTED_END)}throw new Rt(`Unclosed stop node <${this._tagName}> — unexpected end looking for '>'`,Vt.UNEXPECTED_END)}}function Ae(t){const e=t.options.skip;t.source.markTokenStart(1);let r=function(t){t.source.markTokenStart(1);const e=Yt(t.source);let r,s=!1,n=!1,i=!1;for(r=0;t.source.canRead(r);r++){const e=t.source.readChAt(r),a=t.source.readChAt(r+1);if("'"!==e||n?'"'!==e||s||(n=!n):s=!s,!s&&!n&&"?"===e&&">"===a){i=!0;break}}if(!i)throw new Rt("Unexpected closing of source waiting for '?>'",Vt.UNEXPECTED_END);if(s||n)throw new Rt("Invalid attribute expression. Quote is not properly closed in PI tag expression",Vt.UNCLOSED_QUOTE);const a=t.source.readStr(r);return t.source.updateBufferBoundary(r+2),we(a,t,e,!0)}(t);if(!r)throw new Rt("Invalid Pi Tag expression.",Vt.INVALID_TAG,zt(t.source));if("xml"===r.tagName){const e=r.rawAttributes?.version;"1.1"===e&&(t.xmlDec.version=1.1),t.xmlDec.encoding=r.rawAttributes?.encoding,t.xmlDec.standalone=r.rawAttributes?.standalone,t._nameValidators={}}e.attributes||be(r._parsedAttrs,t,r._attrsExpStart,r._rawAttrMatchCount),"xml"===r.tagName?e.declaration||t.outputBuilder.addDeclaration("?xml",t.xmlDec):e.pi||t.outputBuilder.addInstruction("?"+r.tagName)}function Ne(t){const e=t.source;Oe(e),Qt(e,1,"entity name");const r=e.startIndex;let s=0;for(;e.canRead();){const t=e.readCh();if(jt(t)||'"'===t||"'"===t)break;s++}const n=e.readStr(s,r);if(Qt(e,1,`entity name "${n}"`),ke(n,t),Oe(e),Qt(e,0,`after entity name "${n}"`),e.canRead(5)&&!0===e.matchAhead("system",!0))throw new Rt("External entities are not supported",Vt.INVALID_TAG,zt(e));if("%"===e.readStr(1))throw new Rt("Parameter entities are not supported",Vt.INVALID_TAG,zt(e));Qt(e,0,`entity value for "${n}"`);const[i]=De(e,"entity"),a=t.options?.doctypeOptions;if(a?.maxEntitySize&&i.length>a.maxEntitySize)throw new Rt(`Entity "${n}" size (${i.length}) exceeds maximum allowed size (${a.maxEntitySize})`,Vt.ENTITY_MAX_SIZE,zt(e));return e.readUptoChar(">"),[n,i]}function ve(t){const e=t.source;Oe(e),Qt(e,1,"ELEMENT name");const r=e.startIndex;let s=0;for(;e.canRead()&&!jt(e.readCh());)s++;const n=e.readStr(s,r);if(Qt(e,1,"ELEMENT name"),!t.getNameValidator("name")(n))throw new Rt(`Invalid element name: "${n}"`,Vt.INVALID_TAG,zt(e));Oe(e),Qt(e,1,"ELEMENT name");let i=e.readStr(1);if("E"===i)try{Wt(e,"EMPTY","ELEMENT content model keyword EMPTY")}catch(t){return e.readUptoChar(">"),{elementName:n,contentModel:""}}else if("A"===i)try{Wt(e,"ANY","ELEMENT content model keyword ANY")}catch(t){return e.readUptoChar(">"),{elementName:n,contentModel:""}}else"("===i&&(e.updateBufferBoundary(1),e.readUptoChar(")"));return e.readUptoChar(">"),{elementName:n}}function Se(t){t.source.readUptoChar(">")}function Ce(t){const e=t.source;Oe(e),Qt(e,1,"NOTATION name");const r=e.startIndex;let s=0;for(;e.canRead()&&!jt(e.readCh());)s++;const n=e.readStr(s,r);if(Qt(e,1,`after NOTATION name "${n}"`),ke(n,t),Oe(e),Qt(e,6,"NOTATION identifier type"),!0===e.matchAhead("system",!0))e.updateBufferBoundary(6),Oe(e),De(e,"systemIdentifier");else{if(!0!==e.matchAhead("public",!0))throw new Rt(`Expected SYSTEM or PUBLIC in NOTATION, found "${e.readStr(6)}"`,Vt.INVALID_TAG,zt(e));{e.updateBufferBoundary(6),Oe(e),De(e,"publicIdentifier"),Oe(e),Qt(e,1,"after NOTATION PUBLIC identifier");let t=e.readStr(1);'"'!==t&&"'"!==t||De(e,"systemIdentifier")}}e.readUptoChar(">")}function De(t,e){Qt(t,1,e+" opening quote");let r=t.readStr(1);if('"'!==r&&"'"!==r)throw new Rt(`Expected quoted string for ${e}, found "${r}"`,Vt.INVALID_TAG,zt(t));return t.updateBufferBoundary(1),[t.readUptoChar(r)]}function Oe(t){for(;t.canRead()&&jt(t.readChAt(0));)t.updateBufferBoundary(1)}function ke(t,e){if(e.getNameValidator("name")(t))return t;throw new Rt(`Invalid entity name "${t}"`,Vt.ENTITY_INVALID_KEY,{})}const Pe=Object.freeze({UNCLOSED_EOF:"unclosed-eof",MISMATCHED_CLOSE:"mismatched-close",PHANTOM_CLOSE:"phantom-close",PARTIAL_TAG:"partial-tag"});class Le{constructor(t){this.onEof=t.onEof||"throw",this.onMismatch=t.onMismatch||"throw",this.collectErrors=t.collectErrors||!1,this.errors=[]}handleEof(t){if("throw"===this.onEof)throw new Rt("Unexpected data in the end of document",Vt.UNEXPECTED_TRAILING_DATA);const{addTextNode:e,popTag:r}=t;let s=t.currentTagDetail;for(;s&&!s.root;)this._recordError(Pe.UNCLOSED_EOF,{tag:s.name,expected:null,index:s.index}),e(),r(),s=t.currentTagDetail}handleMismatch(t,e){const{tagsStack:r,currentTagDetail:s,source:n,addTextNode:i}=e;if("throw"===this.onMismatch)throw new Rt(`Unexpected closing tag '${t}' expecting '${s.name}'`,Vt.MISMATCHED_CLOSE_TAG,{index:n?Yt(n):void 0});if("discard"===this.onMismatch)return this._recordError(Pe.MISMATCHED_CLOSE,{tag:t,expected:s.name,index:n?Yt(n):null}),{action:"discard"};const a=[...r,s];let o=-1;const l=a.length;for(let e=l-1;e>=0;e--)if(a[e].name===t){o=e;break}if(-1===o)return this._recordError(Pe.PHANTOM_CLOSE,{tag:t,expected:s.name,index:n?Yt(n):null}),{action:"discard"};const c=l-1-o;for(let r=0;r<c;r++){const s=a[l-1-r];this._recordError(Pe.MISMATCHED_CLOSE,{tag:s.name,expected:t,index:s.index}),i(),e.popTag()}return e.currentTagDetail=a[o],{action:"close-matched"}}handlePartialTag(t,e){this._recordError(Pe.PARTIAL_TAG,{tag:Ue(t),expected:null,index:e.source?Yt(e.source):null}),e.tagTextData="",this.handleEof(e)}getErrors(){return this.errors.slice()}reset(){this.errors=[]}_recordError(t,e){this.collectErrors&&this.errors.push({type:t,...e})}}function Ue(t){if(!t)return null;const e=("string"==typeof t.message?t.message:String(t)).match(/[Rr]eading closing tag '<\/([^']*)/);return e&&e[1]||null}const Me={keep:["xml:space"]};function $e(t,e,r){const s=t.get(e);if(void 0!==s||t.has(e))return s;const n=r();return t.size>=2e3&&t.clear(),t.set(e,n),n}class Be{constructor(t,e=0,r=void 0,s=void 0){this.name=t,this.index=e,this.openEnd=r,this.rawName=s}}class Re{constructor(t){this.options=t,this.currentTagDetail=null,this.tagTextData="",this.tagsStack=[],this.doctypeFound=!1,this.matcher=new v,this.readonlyMatcher=this.matcher.readOnly(),this.autoCloseHandler=t.autoClose?new Le(t.autoClose):null,this._unpairedSet=new Set(this.options.tags.unpaired),this.stopNodeExpressionsSet=this.options.tags.stopNodesSet??new B,0===this.stopNodeExpressionsSet.size?this.isStopNode=()=>!1:this.isStopNode=Xe,this.skipTagExpressionsSet=this.options.skip.tagsSet??new B,0===this.skipTagExpressionsSet.size?this.isSkipTag=()=>!1:this.isSkipTag=qe,this._exitIf="function"==typeof t.exitIf?t.exitIf:()=>!1,this._nameCache=t._nameCache||(t._nameCache={tags:new Map,attrs:new Map})}initializeParser(){this.tagTextData="",this.tagsStack=[],this.doctypeFound=!1,this._stopNodeProcessor=null,this._exitIfTriggered=!1,this._nameValidators={},this._validQNames=new Set,this.xmlDec={version:1,lang:null,encoding:null,standalone:"yes"},this.matcher||(this.matcher=new v,this.readonlyMatcher=this.matcher.readOnly()),this.outputBuilder=this._createOutputBuilder(),this.root={root:!0,name:""},this.currentTagDetail=this.root}_createOutputBuilder(){return this.options.OutputBuilder.getInstance(this.options,this.readonlyMatcher)}wasExited(){return!0===this._exitIfTriggered}parse(t){return this.source=new le(t),this.initializeParser(),this._parseAndFinalize(),this.outputBuilder.getOutput()}parseBytesArr(t){const e=this.options.decoding?._registry,r=function(t,e={},r=_e){const s=e.encoding||"auto";let n,i;if("auto"===s){const e=fe(t,r);n=e.encoding,i=e.bomLength}else n=s,i=0;const a=r.resolve(n),o=a.selfSynchronizing?ce("utf8"===a.name?de:he,a.name):{readCh(){return this.buffer[this.startIndex++]},readChAt(t){return this.buffer[this.startIndex+t]},readStr(t,e){return void 0===e&&(e=this.startIndex),this.buffer.substring(e,e+t)},matchAhead(t,e=!1){const r=t.length;for(let s=0;s<r;s++){let r=this.buffer[this.startIndex+s];if(void 0===r)return null;if(e&&(r=r.toLowerCase()),r!==t[s])return!1}return!0},scanTagExpEnd:ae,scanTagExpEndFast:oe,readUpto(t){const e=this.buffer.length,r=t.length;for(let s=this.startIndex;s<e;s++){let e=!0;for(let n=0;n<r;n++)if(this.buffer[s+n]!==t[n]){e=!1;break}if(e){const t=this.buffer.substring(this.startIndex,s);return this.startIndex=s+r,t}}throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END)},readUptoChar(t){const e=this.buffer.indexOf(t,this.startIndex);if(-1===e)throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END);const r=this.buffer.substring(this.startIndex,e);return this.startIndex=e+1,r},readUptoCloseTag(t){const e=this.buffer.length,r=t.length;let s=-1,n=0;for(let i=this.startIndex;i<e;i++){if(1===n){const t=this.buffer[i];if(jt(t))continue;">"===t?n=2:(n=0,s=-1)}else{let e=!0;for(let s=0;s<r;s++)if(this.buffer[i+s]!==t[s]){e=!1;break}e&&(n=1,s=i,i+=r-1)}if(2===n){const t=this.buffer.substring(this.startIndex,s);return this.startIndex=i+1,t}}throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END)},readFromBuffer(t,e){const r=1===t?this.buffer[this.startIndex]:this.buffer.substring(this.startIndex,this.startIndex+t);return e&&this.updateBufferBoundary(t),r},updateBufferBoundary(t=1){this.startIndex+=t,this.autoFlush&&this.startIndex>=this.flushThreshold&&this._tokenStart<0&&this.flush()},canRead(t=0){return this.startIndex+t<this.buffer.length}},l=!a.selfSynchronizing||"utf8"!==a.name;return{descriptor:a,bomLength:i,scanStrategy:o,decodeFirst:!a.selfSynchronizing,quotePairsUsable:l}}(t,this.options.decoding,e);return this.source=new pe(t,{},r),this.initializeParser(),this._parseAndFinalize(),this.outputBuilder.getOutput()}parseXml(){for(;this.source.canRead()&&!this._exitIfTriggered;){this.source.markTokenStart(0);const t=zt(this.source),e=this.source.readCh();if(void 0===e||""===e)break;if("<"===e){const e=t,r=this.source.readChAt(0);if(""===r)throw new Rt("Unexpected end of source after '<'",Vt.UNEXPECTED_END,zt(this.source));"/"===r?(this.source.updateBufferBoundary(),this.readClosingTag(e)):"!"===r?(this.source.updateBufferBoundary(),this.addTextNode(),this.readSpecialTag(r)):"?"===r?(this.source.updateBufferBoundary(),this.addTextNode(),Ae(this)):this.readOpeningTag(e)}else{let t=0;for(;;){const e=this.source.readChAt(t);if("<"===e||void 0===e||""===e)break;t++}t>0?(this.tagTextData+=e+this.source.readStr(t,this.source.startIndex),this.source.updateBufferBoundary(t)):this.tagTextData+=e}}}finalizeXml(){if(this._exitIfTriggered)return;const t=this.tagsStack.length>0||this.currentTagDetail&&!this.currentTagDetail.root,e=!t&&void 0!==this.tagTextData&&this.tagTextData.trimEnd().length>0;if(t||e){if(!this.autoCloseHandler||!t||e)throw new Rt("Unexpected data in the end of document",Vt.UNEXPECTED_TRAILING_DATA,zt(this.source));this.autoCloseHandler.handleEof(this._parserState())}}_parseAndFinalize(){let t=null;this.autoCloseHandler&&this.autoCloseHandler.reset();try{this.parseXml()}catch(e){if(!this.autoCloseHandler||!function(t){return t instanceof Rt?t.code===Vt.UNEXPECTED_END:t.message.startsWith("Unexpected end of source")||t.message.startsWith("Unexpected closing of source")}(e))throw e;t=e}t?this.autoCloseHandler.handlePartialTag(t,this._parserState()):this.finalizeXml()}readClosingTag(t){const e=this.currentTagDetail;if(e&&!e.root&&void 0!==e.rawName){const r=function(t,e){if(!0!==t.matchAhead(e))return-1;let r=e.length,s=t.readChAt(r);if(">"===s)return r+1;for(;jt(s);)if(r++,s=t.readChAt(r),">"===s)return r+1;return">"!==s?-1:r+1}(this.source,e.rawName);if(-1!==r){this.source.updateBufferBoundary(r);const s={name:e.name,index:t.index,closeEnd:Yt(this.source)};return this.addTextNode(),void this.popTag(s)}}const r=this.processTagName(function(t){t.markTokenStart(1);const e=t.startIndex;try{return t.readUptoChar(">").trimEnd()}catch(r){const s=t.readStr(Number.MAX_SAFE_INTEGER,e);throw new Rt(`Unexpected end of source reading closing tag '</${s}'`,Vt.UNEXPECTED_END)}}(this.source)),s={name:r,index:t.index,closeEnd:Yt(this.source)};if(this.isUnpaired(r)||this.isStopNode())throw new Rt(`Unexpected closing tag '${r}'`,Vt.UNEXPECTED_CLOSE_TAG,zt(this.source));if(r!==this.currentTagDetail.name){if(!this.autoCloseHandler)throw new Rt(`Unexpected closing tag '${r}' expecting '${this.currentTagDetail.name}'`,Vt.MISMATCHED_CLOSE_TAG,zt(this.source));if("discard"===this.autoCloseHandler.handleMismatch(r,this._parserState()).action)return}this.currentTagDetail.root||this.addTextNode(),this.popTag(s)}readOpeningTag(t){const e=this.options;if(this.addTextNode(),this._stopNodeProcessor&&this._stopNodeProcessor.isActive()){const{tagDetail:t,isSkip:e}=this._stopNodeProcessorMeta;this._stopNodeProcessor.resumeAfterOpenTag(),ye(this),t.openEnd=Yt(this.source);const{content:r,end:s}=this._stopNodeProcessor.collect(this.source);return e||(this.outputBuilder.addElement(t,this.readonlyMatcher),this.outputBuilder.onStopNode?.(t,r,this.readonlyMatcher,s),this.outputBuilder.addValue(r,this.readonlyMatcher),this.outputBuilder.closeElement(this.readonlyMatcher,{name:t.name,closeEnd:s.index})),this.matcher.pop(),this._stopNodeProcessor=null,void(this._stopNodeProcessorMeta=null)}let r=ye(this);const s=this.processTagName(r.tagName),n=new Be(s,t.index,Yt(this.source),r.tagName),i=r.tagName.indexOf(":"),a=-1!==i?r.tagName.slice(0,i):void 0,o=void 0!==a?r.tagName.slice(i+1):s,l=e.limits?.maxNestedTags;if(null!=l){const t=this.tagsStack.length+1;if(t>l)throw new Rt(`Nesting depth ${t} exceeds limit of ${l} (tag: '${s}')`,Vt.LIMIT_MAX_NESTED_TAGS,{index:n.index})}let c={},h=0;r.rawAttributes&&(c=r.rawAttributes,h=r.rawAttributesLen),h>0?this.matcher.push(o,c,a,Me):this.matcher.push(o,{},a);const d=this.isStopNode(),u=d?null:this.isSkipTag();if(e.skip.attributes||u||be(r._parsedAttrs,this,r._attrsExpStart,r._rawAttrMatchCount),this.isUnpaired(s))this.outputBuilder.addElement(n,this.readonlyMatcher),this.outputBuilder.closeElement(this.readonlyMatcher,this._closeMetaFor(n)),this.matcher.pop();else if(r.selfClosing)u||(this.outputBuilder.addElement(n,this.readonlyMatcher),this.outputBuilder.closeElement(this.readonlyMatcher,this._closeMetaFor(n))),this.matcher.pop();else if(d){this._stopNodeProcessor=new Ie(r.tagName,{nested:d.nested,skipEnclosures:d.skipEnclosures}),this._stopNodeProcessorMeta={tagDetail:n,isSkip:!1},this._stopNodeProcessor.activate();const{content:t,end:e}=this._stopNodeProcessor.collect(this.source);this.outputBuilder.addElement(n,this.readonlyMatcher),this.outputBuilder.onStopNode?.(n,t,this.readonlyMatcher,e),this.outputBuilder.addValue(t,this.readonlyMatcher),this.outputBuilder.closeElement(this.readonlyMatcher,{name:n.name,closeEnd:e.index}),this.matcher.pop(),this._stopNodeProcessor=null,this._stopNodeProcessorMeta=null}else if(u)this._stopNodeProcessor=new Ie(r.tagName,{nested:u.nested,skipEnclosures:u.skipEnclosures}),this._stopNodeProcessorMeta={tagDetail:n,isSkip:!0},this._stopNodeProcessor.activate(),this._stopNodeProcessor.collect(this.source),this.matcher.pop(),this._stopNodeProcessor=null,this._stopNodeProcessorMeta=null;else if(this._exitIf(this.readonlyMatcher)){const t=this.tagsStack.length;for(this.matcher.pop();this.currentTagDetail&&!this.currentTagDetail.root;)this.addTextNode(),this.popTag();"function"==typeof this.outputBuilder.onExit&&this.outputBuilder.onExit({tagDetail:n,matcher:this.readonlyMatcher,depth:t}),this._exitIfTriggered=!0}else this.pushTag(n)}pushTag(t){this.tagsStack.push(this.currentTagDetail),this.outputBuilder.addElement(t,this.readonlyMatcher),this.currentTagDetail=t}popTag(t){this.outputBuilder.closeElement(this.readonlyMatcher,t??{name:this.currentTagDetail?.name}),this.matcher.pop(),this.currentTagDetail=this.tagsStack.pop()}_closeMetaFor(t){return{name:t.name,index:t.index,closeEnd:t.openEnd}}readSpecialTag(t){if("!"!==t)throw new Rt(`Invalid tag '<${t}'`,Vt.INVALID_TAG,zt(this.source));{let t=this.source.readCh();if(null==t)throw new Rt("Unexpected end of source after '<!'",Vt.UNEXPECTED_END,zt(this.source));if("-"===t)!function(t){t.source.markTokenStart(1),Wt(t.source,"-","comment second dash");let e=t.source.readUpto("--\x3e");e=Ht(e,t.source),t.outputBuilder.addComment(e)}(this);else if("["===t)!function(t){t.source.markTokenStart(1),Wt(t.source,"CDATA[","CDATA preamble");let e=t.source.readUpto("]]>");e=Ht(e,t.source),t.outputBuilder.addLiteral(e)}(this);else if("D"===t){const t=function(t){t.source.markTokenStart(1),Wt(t.source,"OCTYPE","DOCTYPE preamble");const e={};let r=0,s=!1,n=!1;for(;t.source.canRead();){const i=t.source.startIndex;let a=t.source.readCh();if("<"===a&&s&&!n)try{Qt(t.source,0,"DOCTYPE sub-tag");let s=t.source.readStr(1);if(t.source.updateBufferBoundary(1),"!"!==s)throw new Rt(`Invalid DOCTYPE body tag starting with "<${s}"`,Vt.INVALID_TAG,zt(t.source));Qt(t.source,0,"DOCTYPE sub-tag type");let n=t.source.readStr(1);if(t.source.updateBufferBoundary(1),"-"===n){Qt(t.source,0,"DOCTYPE comment");let e=t.source.readStr(1);if(t.source.updateBufferBoundary(1),"-"!==e)throw new Rt("Invalid comment in DOCTYPE",Vt.INVALID_TAG,zt(t.source));t.source.readUpto("--\x3e")}else if("E"===n){Qt(t.source,0,"DOCTYPE E-type sub-tag");let s=t.source.readStr(1);if(t.source.updateBufferBoundary(1),"N"===s){Wt(t.source,"TITY","DOCTYPE ENTITY keyword");const[s,n]=Ne(t);if(-1===n.indexOf("&")){const i=t.options?.doctypeOptions;if(i?.maxEntityCount&&r>=i.maxEntityCount)throw new Rt(`Entity count (${r+1}) exceeds maximum allowed (${i.maxEntityCount})`,Vt.ENTITY_MAX_COUNT,zt(t.source));const a=s.replace(/[.\-+*:]/g,"\\$&");e[s]={regx:RegExp(`&${a};`,"g"),val:n},r++}}else{if("L"!==s)throw new Rt(`Invalid DOCTYPE sub-tag "<!E${s}"`,Vt.INVALID_TAG,zt(t.source));Wt(t.source,"EMENT","DOCTYPE ELEMENT keyword"),ve(t)}}else if("A"===n)Wt(t.source,"TTLIST","DOCTYPE ATTLIST keyword"),Se(t);else{if("N"!==n)throw new Rt(`Invalid DOCTYPE sub-tag "<!${n}"`,Vt.INVALID_TAG,zt(t.source));Wt(t.source,"OTATION","DOCTYPE NOTATION keyword"),Ce(t)}}catch(e){throw e.code===Vt.UNEXPECTED_END&&(t.source.startIndex=i),e}else if("["===a)s=!0;else if("]"===a)n=!0;else if(">"===a&&(!s||n))return e}throw new Rt("Unclosed DOCTYPE",Vt.UNEXPECTED_END,zt(t.source))}(this);if(this.doctypeFound)throw new Rt("Multiple DOCTYPE declarations found.",Vt.INVALID_INPUT,zt(this.source));this.doctypeFound=!0,this.options.doctypeOptions.enabled&&t&&Object.keys(t).length>0&&this.outputBuilder.addInputEntities(t)}}}addTextNode(){void 0!==this.tagTextData&&""!==this.tagTextData&&(this.tagTextData=Ht(this.tagTextData,this.source),(!this.options.skip.whitespaceText||this.tagTextData.trim().length>0)&&this.outputBuilder.addValue(this.tagTextData,this.readonlyMatcher),this.tagTextData="")}isValidQName(t){const e=this._validQNames;if(e.has(t))return!0;const r=this.getNameValidator("qName")(t);return r&&(e.size>=2e3&&e.clear(),e.add(t)),r}getNameValidator(t){let e=this._nameValidators[t];if(!e){const r=1.1===this.xmlDec.version||"1.1"===this.xmlDec.version?"1.1":"1.0";e=E(t,{xmlVersion:r}),this._nameValidators[t]=e}return e}processAttrName(t){return $e(this._nameCache.attrs,t,()=>{const e=this.options;let r=Ve(t,e.skip.nsPrefix);if(!this.getNameValidator("qName")(r))throw new Rt(`Invalid attribute name: ${r}`,Vt.INVALID_ATTRIBUTE_NAME,zt(this.source));if(r=je(r,e.onDangerousProperty,e.sanitizeNames,this.source),e.strictReservedNames&&r===e.attributes.groupBy)throw new Rt(`Restricted attribute name: ${r}`,Vt.SECURITY_RESTRICTED_NAME,zt(this.source));return r})}processTagName(t){return $e(this._nameCache.tags,t,()=>{const e=this.options,r=e.nameFor;let s=Ve(t,e.skip.nsPrefix);if(s=je(s,e.onDangerousProperty,e.sanitizeNames,this.source),e.strictReservedNames&&(s===r.comment||s===r.cdata||s===r.text))throw new Rt(`Restricted tag name: ${s}`,Vt.SECURITY_RESTRICTED_NAME,zt(this.source));return s})}isUnpaired(t){return this._unpairedSet.has(t)}_parserState(){const t=this;return{get tagsStack(){return t.tagsStack},get currentTagDetail(){return t.currentTagDetail},set currentTagDetail(e){t.currentTagDetail=e},get outputBuilder(){return t.outputBuilder},get readonlyMatcher(){return t.readonlyMatcher},get matcher(){return t.matcher},get source(){return t.source},get tagTextData(){return t.tagTextData},set tagTextData(e){t.tagTextData=e},addTextNode:t.addTextNode.bind(t),popTag:t.popTag.bind(t)}}}function Ve(t,e){if(e){const e=t.split(":");if(2===e.length)return"xmlns"!==e[0]&&e[1];if(e.length>2)throw new Rt(`Multiple namespaces in name: ${t}`,Vt.MULTIPLE_NAMESPACES,zt(this.source))}return t}function je(t,e,r,s){if(Ft.includes(t))throw new Rt(`[SECURITY] Invalid name: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`,Vt.SECURITY_PROTOTYPE_POLLUTION,zt(s));return!1===r?t:qt.includes(t)?e(t):t}function Xe(){if(0===this.stopNodeExpressionsSet.size)return null;const t=this.stopNodeExpressionsSet.findMatch(this.matcher);return t?t.data:null}function qe(){if(0===this.skipTagExpressionsSet.size)return null;const t=this.skipTagExpressionsSet.findMatch(this.matcher);return t?t.data:null}class Fe{constructor(t={}){this.buffer="",this.startIndex=0,this.isComplete=!1,this._baseOffset=0,this.maxBufferSize=t.maxBufferSize||10485760,this.autoFlush=!1!==t.autoFlush,this.flushThreshold=t.flushThreshold||1024,this._decodingOptions=t.decoding||null;const e=this._decodingOptions?.encoding;if(this._detecting="auto"===e,this._sniffBuffer=this._detecting?Buffer.alloc(0):null,!this._detecting&&e&&this._decodingOptions.registry){const t=this._decodingOptions.registry;this._createDecoder=()=>t.resolve(e).createDecoder()}else this._createDecoder="function"==typeof t.createDecoder?t.createDecoder:null;this._marks=[null,null],this._decoder=null,this._quotePairs=new Int32Array(128),this._quotePairsLen=0}feed(t){if(this._detecting)if("string"==typeof t)this._detecting=!1;else{const e=Buffer.isBuffer(t)?t:Buffer.from(t);this._sniffBuffer=this._sniffBuffer.length?Buffer.concat([this._sniffBuffer,e]):e;const r=this._sniffBuffer.includes(Buffer.from("?>"));if(this._sniffBuffer.length<200&&!r)return 0;t=this._resolveDetection()}let e=this._decodeNow(t);const r=this.buffer.length-this.startIndex;if(r+e.length>this.maxBufferSize)throw new Rt(`Buffer size limit exceeded (${r+e.length} > ${this.maxBufferSize}). Increase feedable.maxBufferSize or reduce chunk size.`,Vt.INVALID_INPUT);return this.buffer+=e,e.length}_decodeNow(t){if("string"==typeof t)return t;if(Buffer.isBuffer(t))return this._decoder||(this._decoder=this._createDecoder?this._createDecoder():ge("utf-8")),this._decoder.write(t);if(t?.toString)return t.toString();throw new Rt("feed() data must be a string or Buffer.",Vt.DATA_MUST_BE_STRING)}_resolveDetection(){const t=this._decodingOptions.registry,{encoding:e,bomLength:r}=fe(this._sniffBuffer,t),s=t.resolve(e);this._createDecoder=()=>s.createDecoder(),this._detecting=!1;const n=r?this._sniffBuffer.subarray(r):this._sniffBuffer;return this._sniffBuffer=null,n}end(){if(this._detecting){const t=this._resolveDetection();this.buffer+=this._decodeNow(t)}if(this._decoder){const t=this._decoder.end();t&&(this.buffer+=t)}this.isComplete=!0}canRead(t=0){return this.startIndex+t<this.buffer.length}markTokenStart(t=0){this._marks[t]=this.startIndex}rewindToMark(){null!==this._marks[0]&&(this.startIndex=this._marks[0]),this._marks[0]=null,this._marks[1]=null}clearMark(){this._marks[0]=null,this._marks[1]=null}readCh(){return this.buffer[this.startIndex++]}readChAt(t){return this.buffer[this.startIndex+t]}readStr(t,e){return void 0===e&&(e=this.startIndex),this.buffer.substring(e,e+t)}matchAhead(t,e=!1){const r=t.length;for(let s=0;s<r;s++){let r=this.buffer[this.startIndex+s];if(void 0===r)return null;if(e&&(r=r.toLowerCase()),r!==t[s])return!1}return!0}scanTagExpEnd=ae;scanTagExpEndFast=oe;readUpto(t){const e=this.buffer.length,r=t.length;for(let s=this.startIndex;s<e;s++){let e=!0;for(let n=0;n<r;n++)if(this.buffer[s+n]!==t[n]){e=!1;break}if(e){const t=this.buffer.substring(this.startIndex,s);return this.startIndex=s+r,t}}throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END)}readUptoChar(t){const e=this.buffer.indexOf(t,this.startIndex);if(-1===e)throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END);const r=this.buffer.substring(this.startIndex,e);return this.startIndex=e+1,r}readUptoCloseTag(t){const e=this.buffer.length,r=t.length;let s=-1,n=0;for(let i=this.startIndex;i<e;i++){if(1===n){const t=this.buffer[i];if(jt(t))continue;">"===t?n=2:(n=0,s=-1)}else{let e=!0;for(let s=0;s<r;s++)if(this.buffer[i+s]!==t[s]){e=!1;break}e&&(n=1,s=i,i+=r-1)}if(2===n){const t=this.buffer.substring(this.startIndex,s);return this.startIndex=i+1,t}}throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END)}updateBufferBoundary(t=1){this.startIndex+=t,this.autoFlush&&this.startIndex>=this.flushThreshold&&this.flush()}flush(){let t=this.startIndex;for(const e of this._marks)null!==e&&e<t&&(t=e);if(t>0){this.buffer=this.buffer.substring(t);const e=this._marks.length;for(let r=0;r<e;r++)null!==this._marks[r]&&(this._marks[r]-=t);this.startIndex-=t,this._baseOffset+=t}}}class Ye extends Fe{attachStream(t,e,r,s){t.on("data",t=>{try{this.feed(t),e(null)}catch(t){e(t)}}),t.on("error",s),t.on("end",()=>{try{this.end(),r()}catch(t){s(t)}})}}class ze{constructor(t){if(this.options=ee(t),this._feedParser=null,this._feedSource=null,this._isFeeding=!1,this._pendingBytes=0,this._batchThreshold=this.options.feedable?.bufferSize,this.options.decoding?.customDecoders){const t=new me;for(const[e,r]of Object.entries(this.options.decoding.customDecoders))t.register({name:e,...r});this.options.decoding._registry=t}else this.options.decoding=this.options.decoding||{},this.options.decoding._registry=_e;this.options._nameCache={tags:new Map,attrs:new Map}}parse(t){if(t instanceof Buffer||ArrayBuffer.isView(t))return this.parseBytesArr(t);if("string"!=typeof t){if(!t||"function"!=typeof t.toString)throw new Rt("XML data must be a string or Buffer.",Vt.INVALID_INPUT);t=t.toString()}const e=this._createParser(),r=e.parse(t);return this.wasExited=e.wasExited(),this._lastParseErrors=e.autoCloseHandler?.getErrors()??[],r}parseBytesArr(t){if(!(t instanceof Uint8Array||ArrayBuffer.isView(t)))throw new Rt("XML data must be a Uint8Array or ArrayBufferView.",Vt.INVALID_INPUT);t=Buffer.from(t);const e=this._createParser(),r=e.parseBytesArr(t);return this.wasExited=e.wasExited(),this._lastParseErrors=e.autoCloseHandler?.getErrors()??[],r}parseStream(t){if(null===(e=t)||"object"!=typeof e||"function"!=typeof e.read||"function"!=typeof e.on||"boolean"!=typeof e.readableEnded)throw new Rt("parseStream() requires a Node.js Readable stream.",Vt.INVALID_STREAM);var e;const r=new Ye({...this.options.feedable,decoding:{encoding:this.options.decoding.encoding,registry:this.options.decoding._registry}}),s=this._createParser();return s.source=r,s.initializeParser(),new Promise((e,n)=>{let i=!1;const a=e=>{i||(i=!0,t.destroy(),n(e))};r.attachStream(t,t=>{if(t)a(t);else try{s.parseXml()}catch(t){t.code===Vt.UNEXPECTED_END?r.rewindToMark():a(t)}},()=>{if(!i)try{s.parseXml(),s.finalizeXml(),this._lastParseErrors=s.autoCloseHandler?.getErrors()??[],i=!0,e(s.outputBuilder.getOutput())}catch(t){a(t)}},a)})}_runParse(){if(!this._feedParser)return;const t=Yt(this._feedSource);try{this._feedParser.parseXml()}catch(t){if(t.code!==Vt.UNEXPECTED_END)throw t;this._feedSource.rewindToMark()}Yt(this._feedSource)>t?(this._pendingBytes=0,this._batchThreshold=this.options.feedable.bufferSize):this._batchThreshold=Math.min(2*this._batchThreshold,this.options.feedable.maxBufferSize)}feed(t){this._isFeeding||this._initFeedSession();const e=this._feedSource.feed(t);return this._pendingBytes+=e,this._pendingBytes>=this._batchThreshold&&this._runParse(),this}end(){if(!this._isFeeding)throw new Rt("No data fed. Call feed() before end().",Vt.NOT_STREAMING);this._runParse();try{this._feedSource.end();let t=null;const e=this._feedParser.autoCloseHandler;e&&e.reset();try{this._feedParser.parseXml()}catch(r){if(r.code!==Vt.UNEXPECTED_END)throw r;if(!e)throw r;t=r}return t?e.handlePartialTag(t,this._feedParser._parserState()):this._feedParser.finalizeXml(),this._lastParseErrors=e?.getErrors()??[],this.wasExited=this._feedParser.wasExited(),this._feedParser.outputBuilder.getOutput()}finally{this._cleanupFeedSession()}}getParseErrors(){return this._lastParseErrors??[]}_createParser(){return new Re(this.options)}_initFeedSession(){this._feedSource=new Fe({...this.options.feedable,decoding:{encoding:this.options.decoding.encoding,registry:this.options.decoding._registry}}),this._feedParser=this._createParser(),this._feedParser.source=this._feedSource,this._feedParser.initializeParser(),this._isFeeding=!0}_cleanupFeedSession(){this._feedParser=null,this._feedSource=null,this._isFeeding=!1}}class Ge extends $t{constructor(t,e,r,s){super(t,e,r,s),this.siblingOrder=new Map}addElement(t){const e=this.matcher.toString(),r=e.lastIndexOf("."),s=-1===r?"":e.substring(0,r);this.siblingOrder.has(s)||this.siblingOrder.set(s,[]);const n=this.siblingOrder.get(s);n[n.length-1]!==t.name&&n.push(t.name),super.addElement(t)}getOutput(){return{data:super.getOutput(),siblingOrder:this.siblingOrder}}}const He=new At({hex:!0,leadingZeros:!0,eNotation:!0,unicode:!0});function We(t){const e=He.parse(t);return"number"==typeof e?e:NaN}const Qe={minLength:(t,e)=>e.length>=t,maxLength:(t,e)=>e.length<=t,length:(t,e)=>e.length===t,pattern:(t,e,r="")=>new RegExp(t,r).test(e),fixed:(t,e)=>t===e,in:(t,e)=>t.split(",").indexOf(e)>-1},Je={min:(t,e)=>We(e)>=t,max:(t,e)=>We(e)<=t},Ze={minOccurs:(t,e)=>e>=t,maxOccurs:(t,e)=>e<=t},Ke=(t,e)=>Date.parse(e)>=Date.parse(t),tr=(t,e)=>Date.parse(e)<=Date.parse(t),er=["positiveInteger","integer","positiveDecimal","decimal","number"];class rr{constructor(t,e,r){this.options=t,this.failures=[],this.validators=e,this._globalUnique=new Map,this._siblingOrder=r||new Map}traverse(t,e,r,s){if(Array.isArray(t)){if(void 0!==r&&void 0!==r["@rules"]&&void 0!==r["@rules"].repeatable)return this.checkOccurences(r["@rules"],t.length,s),void t.forEach((n,i)=>{const a=s+"["+i+"]";Object.keys(r).length>1?this.callForCommonProperties(t[i],r,a):this.traverse(t[i],e,r,a)});this.failures.push({code:"unexpected sequence",path:s.substr(1)})}else"object"==typeof t?this.callForCommonProperties(t,r,s):("object"==typeof r&&r["@rules"]?this.checkDataAndType(t,e,r,s):this.isMapType(r)&&this.validateMandatoryFields(r,s),this.applyCustomValidators(t,r,s))}applyCustomValidators(t,e,r){if(e["@rules"]&&e["@rules"].checkBy&&"function"==typeof this.validators[e["@rules"].checkBy]){let s=this.validators[e["@rules"].checkBy](t,r.substr(1));"object"==typeof s&&this.failures.push(s)}}callForCommonProperties(t,e,r){const s=function(t,e){const r={data:[],rules:[],common:[]};for(let s=0;s<t.length;s++)-1===e.indexOf(t[s])?r.data.push(t[s]):r.common.push(t[s]);for(let s=0;s<e.length;s++)-1===t.indexOf(e[s])&&"@"!==e[s]&&r.rules.push(e[s]);return r}(Object.keys(t),Object.keys(e));this.checkUnknownSiblings(s,r),this.checkMissingSiblings(s,e,r),this.applyCustomValidators(t,e,r);const n=this._buildSiblingValues(t,e,s.common);s.common.forEach(s=>{const n=r+"."+s;this.traverse(t[s],s,e[s],n)}),this._checkOrderingConstraints(t,e,s.common,r),this._checkUniquenessConstraints(t,e,s.common,r,n),this._checkRelationalConstraints(t,e,s.common,r)}_checkOrderingConstraints(t,e,r,s){const n=s.substr(1),i=this._siblingOrder.get(n);i&&r.forEach(r=>{const n=e[r];if(!n||!n["@rules"])return;const a=n["@rules"],o=i.indexOf(r);if(-1!==o){if(a.after){const e=a.after;if(void 0===t[e])return;const n=i.indexOf(e);if(-1===n)return;o<=n&&this.failures.push({code:"after",path:(s+"."+r).substr(1),actual:r,expected:e})}if(a.before){const e=a.before;if(void 0===t[e])return;const n=i.indexOf(e);if(-1===n)return;o>=n&&this.failures.push({code:"before",path:(s+"."+r).substr(1),actual:r,expected:e})}}})}_checkRelationalConstraints(t,e,r,s){const n=["sameAs","notSameAs","lessThan","moreThan"];r.forEach(r=>{const i=e[r];if(!i||!i["@rules"])return;const a=i["@rules"];if(!n.some(t=>void 0!==a[t]))return;const o=t[r];if(null==o)return;if("object"==typeof o)return;const l=a.type||"string";n.forEach(e=>{if(void 0===a[e])return;const n=a[e],i=t[n];if(null==i)return;if("object"==typeof i)return;const c=this._relationalCompare(String(o),String(i),l);if(null===c)return;let h=!1;"sameAs"===e&&0!==c&&(h=!0),"notSameAs"===e&&0===c&&(h=!0),"lessThan"===e&&c>=0&&(h=!0),"moreThan"===e&&c<=0&&(h=!0),h&&this.failures.push({code:e,path:(s+"."+r).substr(1),actual:String(o),expected:n})})})}_relationalCompare(t,e,r){if("date"===r){const r=Date.parse(t),s=Date.parse(e);return isNaN(r)||isNaN(s)?null:r-s}if(-1!==er.indexOf(r)){const r=We(t),s=We(e);return isNaN(r)||isNaN(s)?null:r-s}return t<e?-1:t>e?1:0}_buildSiblingValues(t,e,r){const s=new Map;return r.forEach(e=>{const r=t[e];Array.isArray(r)?s.set(e,r.map(String)):null!=r&&"object"!=typeof r&&s.set(e,[String(r)])}),s}_checkUniquenessConstraints(t,e,r,s,n){r.forEach(r=>{const i=e[r];if(!i||!i["@rules"])return;const a=i["@rules"].unique;if(!a)return;const o=n.get(r)||[];"global"===a&&o.forEach((e,n)=>{const i=Array.isArray(t[r])?(s+"."+r+"["+n+"]").substr(1):(s+"."+r).substr(1);this._assertGlobalUnique(r,e,i)})})}_checkUniqueInCollection(t,e,r){const s=new Map;t.forEach((t,n)=>{const i=t[e];if(null==i||"object"==typeof i)return;const a=String(i);s.has(a)?this.failures.push({code:"unique",path:(r+"["+n+"]."+e).substr(1),value:a}):s.set(a,n)})}_assertGlobalUnique(t,e,r){this._globalUnique.has(t)||this._globalUnique.set(t,new Set);const s=this._globalUnique.get(t);s.has(e)?this.failures.push({code:"unique",path:r,value:e}):s.add(e)}checkDataAndType(t,e,r,s){!0===r["@rules"].repeatable&&this.checkOccurences(r["@rules"],1,s);const n=r["@rules"].type,i=this._expandRange(r);if("map"===n||!n&&this.isMapType(r))"string"==typeof t&&t.length>0&&this.failures.push({code:"unexpected value in a map",path:s.substr(1),value:t}),this.validateMandatoryFields(r,s);else if("date"===n)this.validateDate(t,n,s),this._checkDateBounds(r,t,s);else if("boolean"===n)this.validateBoolean(t,n,s);else if(-1!==er.indexOf(n))this.isValidNum(n,t)?this.assertValue(i["@rules"],"num",We(t),s):this.setInvalidDataType(n,s,t);else{if("string"!==n&&n)throw new Error("Unsupported data type in Rules:"+n);this.assertValue(i["@rules"],"string",t,s)}}_expandRange(t){if(!t["@rules"]||!t["@rules"].range)return t;const e=function(t){if("string"!=typeof t)return null;const e=t.split("..");if(2!==e.length)return null;const r=We(e[0]),s=We(e[1]);return isNaN(r)||isNaN(s)?null:{min:r,max:s}}(t["@rules"].range);return e?{...t,"@rules":{...t["@rules"],min:void 0!==t["@rules"].min?t["@rules"].min:String(e.min),max:void 0!==t["@rules"].max?t["@rules"].max:String(e.max)}}:t}_checkDateBounds(t,e,r){if(isNaN(Date.parse(e)))return;const s=t["@rules"];let n=s.min,i=s.max;if(s.range&&(!n||!i)){const t=function(t){if("string"!=typeof t)return null;const e=t.split("..");if(2!==e.length)return null;const[r,s]=e;return isNaN(Date.parse(r))||isNaN(Date.parse(s))?null:{min:r,max:s}}(s.range);t&&(n||(n=t.min),i||(i=t.max))}void 0===n||Ke(n,e)||this.setInvalidValueError("min",r,e,n),void 0===i||tr(i,e)||this.setInvalidValueError("max",r,e,i)}validateMandatoryFields(t,e){const r=Object.keys(t);for(let s=0;s<r.length;s++){if("@rules"===r[s])continue;const n=t[r[s]]["@rules"];n&&(n.minOccurs&&n.minOccurs>0||void 0!==n.nillable&&"false"===n.nillable)&&this.failures.push({code:"missing",path:(e+"."+r[s]).substr(1)})}}isMapType(t){if("string"==typeof t)return!1;const e=Object.keys(t);return t["@rules"]?1!==e.length&&void 0:0!==e.length}setInvalidValueError(t,e,r,s){this.failures.push({code:t,path:e.substr(1),actual:r,expected:s})}checkOccurences(t,e,r){["minOccurs","maxOccurs"].forEach(s=>{if(void 0!==t[s]){const n=Number(t[s]);Ze[s](n,e)||this.setInvalidValueError(s,r,e,n)}})}checkNumeric(t,e,r){["min","max"].forEach(s=>{if(void 0!==t[s]){const n=Number(t[s]);Je[s](n,e)||this.setInvalidValueError(s,r,e,n)}})}checkString(t,e,r){["minLength","maxLength","length"].forEach(s=>{if(void 0!==t[s]){const n=Number(t[s]);Qe[s](n,e)||this.setInvalidValueError(s,r,e,n)}}),["fixed","in"].forEach(s=>{if(void 0!==t[s]){const n=t[s];Qe[s](n,e)||this.setInvalidValueError(s,r,e,n)}}),["pattern","pattern_i","pattern_im","pattern_mi"].forEach(s=>{if(void 0!==t[s]){let n="";s.length>8&&(n=s.substring(8));const i=t[s];Qe.pattern(i,e,n)||this.setInvalidValueError("pattern",r,e,i)}})}assertValue(t,e,r,s){"string"===e?this.checkString(t,r,s):"num"===e&&this.checkNumeric(t,r,s)}validateBoolean(t,e,r){-1===this.options.boolean.indexOf(t)&&this.setInvalidDataType(e,r,t)}isValidNum(t,e){const r=We(e);return!isNaN(r)&&!("positiveInteger"===t&&r<0||"positiveDecimal"===t&&r<0||"integer"===t&&!function(t){return(0|t)===t}(r))}validateDate(t,e,r){const s=Date.parse(t);isNaN(s)&&this.setInvalidDataType(e,r,t)}setInvalidDataType(t,e,r){this.failures.push({code:"not a "+t,path:e.substr(1),value:r})}checkMissingSiblings(t,e,r){t.rules&&t.rules.forEach(t=>{const s=e[t]["@rules"];s&&("false"===s.nillable||s.minOccurs>0)&&this.failures.push({code:"missing",path:(r+"."+t).substr(1)})})}checkUnknownSiblings(t,e){t.data&&!this.options.unknownAllow&&t.data.forEach(t=>{this.failures.push({code:"unknown",path:(e+"."+t).substr(1)})})}}const sr=rr.prototype.traverse;rr.prototype.traverse=function(t,e,r,s){if(Array.isArray(t)&&void 0!==r&&void 0!==r["@rules"]&&void 0!==r["@rules"].repeatable)return this.checkOccurences(r["@rules"],t.length,s),t.forEach((n,i)=>{const a=s+"["+i+"]";if(Object.keys(r).length>1)this.callForCommonProperties(t[i],r,a);else{const s=r;sr.call(this,t[i],e,s,a)}}),void(t.length>0&&"object"==typeof t[0]&&this._runSiblingUniqueness(t,r,s));sr.call(this,t,e,r,s)},rr.prototype._runSiblingUniqueness=function(t,e,r){Object.keys(e).filter(t=>"@rules"!==t).forEach(s=>{const n=e[s];n&&n["@rules"]&&"true"===n["@rules"].unique&&this._checkUniqueInCollection(t,s,r)})};const nr={unknownAllow:!0,boolean:["true","false"]},ir={tags:{valueParsers:[]},attributes:{valueParsers:[]}},ar=new ze({skip:{attributes:!1},attributes:{prefix:"",groupBy:"@rules",booleanType:!0},OutputBuilder:new Mt(ir)}),or=new ze({skip:{attributes:!1},attributes:{prefix:"",groupBy:":a"},OutputBuilder:new class extends Mt{getInstance(t,e){return new Ge(t,this.builderOptions,e,this.registry)}}(ir)}),lr="__nodableAttrsBucket__",cr=/<(\/?):a(\s|>|\/)/g;function hr(t){if(Array.isArray(t))for(const e of t)hr(e);else if(null!==t&&"object"==typeof t){Object.prototype.hasOwnProperty.call(t,lr)&&(t[":a"]=t[lr],delete t[lr]);for(const e of Object.keys(t))hr(t[e])}return t}function dr(t){if(!t)throw new Error("Empty data");if("string"!=typeof t)throw new Error("Not a valid string")}function ur(t,e){try{return t.parse(e)}catch(t){if(t instanceof Rt){let r=t.message;if("INVALID_ATTRIBUTE_NAME"===t.code){const t=r.slice(r.indexOf(": ")+2);r=`Attribute '${t}' is an invalid name.`}if(void 0===t.index)throw new Error(r);const s=e.substring(0,t.index).split("\n").length;throw new Error(r+":"+s)}throw t}}const pr=class{constructor(t,e){dr(t),this.rules=hr(ur(ar,function(t){return t.replace(cr,`<$1${lr}$2`)}(t))),this.options=Object.assign({},nr,e),this.validators={},this.data=null}register(t,e){this.validators[t]=e}validate(t){dr(t);const{data:e,siblingOrder:r}=ur(or,t);this.data=e;const s=new rr(this.options,this.validators,r);return s.traverse(e,"",this.rules,""),s.failures}};module.exports=e})();
|
|
1
|
+
(()=>{"use strict";var t={d:(e,r)=>{for(var s in r)t.o(r,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:r[s]})},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,{BusinessRulesValidator:()=>pr,SyntaxValidator:()=>$});class r extends Error{constructor(t,e,r,s){super(t),this.name=this.constructor.name,this.code=e,this.line=r,this.col=s,Error.captureStackTrace?.(this,this.constructor)}}function s(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function n(t){return t<=8||11===t||12===t||t>=14&&t<=31}function i(t,e){const r=t.substring(0,e).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function o(t){return t.startIndex+t[1].length}const a=":A-Za-z_À-ÖØ-öø-˿Ͱ-ͽͿ-҆҈--⁰-Ⰰ-、-豈-﷏ﷰ-�",l=":A-Za-z_À-˿Ͱ-ͽͿ-҆҈--⁰-Ⰰ-、-豈-﷏ﷰ-�𐀀-",c=l+"\\-\\.\\d·̀-ͯ҇‿-⁀",h=(t,e,r="")=>{const s=`[${t.replace(":","")}][${e.replace(":","")}]*`;return{name:new RegExp(`^[${t}][${e}]*$`,r),ncName:new RegExp(`^${s}$`,r),qName:new RegExp(`^${s}(?::${s})?$`,r),nmToken:new RegExp(`^[${e}]+$`,r),nmTokens:new RegExp(`^[${e}]+(?:\\s+[${e}]+)*$`,r)}},d=h(a,a+"\\-\\.\\d·̀-ͯ‿-⁀"),u=h(l,c,"u"),p=":A-Za-z_",f=h(p,p+"\\-\\.\\d"),g=(t="1.0",e=!1)=>e?f:"1.1"===t?u:d,m=(t,{xmlVersion:e="1.0",asciiOnly:r=!1}={})=>g(e,r).name.test(t),_=["name","ncName","qName","nmToken","nmTokens"],E=(t,{xmlVersion:e="1.0",asciiOnly:r=!1,maxCacheSize:s=2048}={})=>{if(!_.includes(t))throw new TypeError(`Unknown production "${t}". Must be one of: ${_.join(", ")}`);const n=g(e,r)[t];let i=new Map;const o=t=>{const e=i.get(t);if(void 0!==e)return e;const r=n.test(t);return i.size<s&&i.set(t,r),r};return o.reset=()=>{i=new Map},o};class b{constructor(t="1.0"){this.xmlVersion=t,this.qName=E("qName",{xmlVersion:t}),this.name=E("name",{xmlVersion:t})}isValidQName(t){return this.qName(t)}isValidName(t){return this.name(t)}}function x(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t}class T{constructor(t={},e){this.optional=void 0===t.optional||t.optional,this.argPosition=void 0!==t.argPosition?t.argPosition:void 0===t.argPostion||t.argPostion,this._throwError=e}validate(t){if(!t.startsWith("<?xml"))return this.optional||this._throwError("InvalidXml","XML declaration is required but missing.",{line:1,col:1}),{version:"1.0",end:0};const e=t.indexOf("?>");-1===e&&this._throwError("InvalidXml",'XML declaration is not closed with "?>".',{line:1,col:1});const r=t.substring(5,e),n=e+2,i=["version","encoding","standalone"],{matches:o,leftover:a}=function(t){const e=[];let r="";const n=t.length;let i=0;for(;i<n;){if(!s(t[i])){r+=t[i],i++;continue}const o=i;let a=i;for(;a<n&&s(t[a]);)a++;const l=a;for(;a<n&&x(t[a]);)a++;if(a===l){r+=t.slice(o,a+1<=n?a:n),i=a>o?a:o+1;continue}const c=t.slice(l,a);let h=a;for(;h<n&&s(t[h]);)h++;if("="!==t[h]){r+=t.slice(o,a),i=a;continue}for(h++;h<n&&s(t[h]);)h++;const d=t[h];if('"'!==d&&"'"!==d){r+=t.slice(o,a),i=a;continue}const u=h+1,p=t.indexOf(d,u);-1!==p?(e.push({name:c,value:t.slice(u,p),index:o}),i=p+1):(r+=t.slice(o,a),i=a)}return{matches:e,leftover:r}}(r);let l="1.0",c=-1;for(let t=0;t<o.length;t++){const e=o[t].name,r=o[t].value,s=o[t].index,n=i.indexOf(e);-1===n&&this._throwError("InvalidXml",'XML declaration contains unknown attribute "'+e+'". Allowed: version, encoding, standalone.',{line:1,col:6+s}),this.argPosition&&n<=c&&this._throwError("InvalidXml",'XML declaration attribute "'+e+'" is out of order. Required order: version, encoding, standalone.',{line:1,col:6+s}),c=n,"version"===e?("1.0"!==r&&"1.1"!==r&&this._throwError("InvalidXml",'XML declaration version "'+r+'" is not supported. Must be "1.0" or "1.1".',{line:1,col:6+s}),l=r):"standalone"===e&&"yes"!==r&&"no"!==r&&this._throwError("InvalidXml",'XML declaration standalone "'+r+'" is invalid. Must be "yes" or "no".',{line:1,col:6+s})}const h=a.trim();return h.length>0&&this._throwError("InvalidXml",'XML declaration contains invalid content: "'+h+'".',{line:1,col:1}),{version:l,end:n}}}class y{static findIllegalIndex(t){const e=t.length;for(let r=0;r<e;r++)if(n(t.charCodeAt(r)))return r;return-1}static hasIllegalChar(t){return-1!==this.findIllegalIndex(t)}static describe(t){return`0x${t.toString(16).padStart(2,"0")}`}}class w{constructor(t,e,r){this.options=t,this.nameValidator=e,this.xmlVersion=r}validate(t){const e=function(t){const e=[],r=t.length;let n=0;for(;n<r;){const i=n;for(;n<r&&s(t[n]);)n++;if(n>=r)break;if("="===t[n]){n=i+1;continue}const o=t.slice(i,n),a=n;for(;n<r&&!s(t[n])&&"="!==t[n];)n++;const l=t.slice(a,n);let c,h,d,u=n;for(;u<r&&s(t[u]);)u++;u<r&&"="===t[u]&&(c=t.slice(n,u+1),n=u+1);let p=n;for(;p<r&&s(t[p]);)p++;if(p<r&&('"'===t[p]||"'"===t[p])){const e=p+1,r=t.indexOf(t[p],e);-1!==r&&(h=t[p],d=t.slice(e,r),n=r+1)}const f={startIndex:i};f[1]=o,f[2]=l,f[3]=c,f[4]=void 0!==h||void 0,f[5]=h,f[6]=d,e.push(f)}return e}(t),r={},n=!0===this.options.invalidCharSequence?.attrLt;for(let t=0;t<e.length;t++){const s=e[t];if(0===s[1].length)return this._err("InvalidAttr","Attribute '"+s[2]+"' has no space in starting.",s);const i=void 0!==s[3],o=void 0!==s[4];if(i&&!o)return this._err("UnquotedAttributeValue","Attribute '"+s[2]+"' is without value.",s);if(!i&&!this.options.allowBooleanAttributes)return this._err("InvalidAttr","boolean attribute '"+s[2]+"' is not allowed.",s);const a=s[2];if(!this.nameValidator.isValidQName(a))return this._err("InvalidAttr","Attribute '"+a+"' is an invalid name.",s);const l=s[6]||"";if(o){const t=y.findIllegalIndex(l);if(-1!==t){const e=l.charCodeAt(t);return this._err("IllegalCharacter",`Illegal control character ${y.describe(e)} in attribute '${a}' value.`,s)}if(n&&-1!==l.indexOf("<"))return this._err("InvalidAttr",`Attribute '${a}' value must not contain '<'.`,s)}if(a.startsWith("xmlns:")&&""===s[6]&&"1.0"===this.xmlVersion)return this._err("InvalidAttr",`Undeclaring the prefixed namespace ${a}="" is only permitted in XML 1.1 documents.`,s);if(Object.prototype.hasOwnProperty.call(r,a))return this._err("InvalidAttr","Attribute '"+a+"' is repeated.",s);r[a]=1}return!0}_err(t,e,r){return{err:{code:t,msg:e,line:o(r)}}}}class I{constructor(t={}){this.checkCommentDashes=!0===t.invalidCharSequence?.comment}read(t,e,r){if(t.length>e+2&&"-"===t[e+1]&&"-"===t[e+2])return this._readComment(t,e);if(t.length>e+7&&"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])return r.validateDocType(t,e-1);if(t.length>e+8&&"["===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])return this._readCdata(t,e);throw new Error("Invalid construct starting with '<!'.")}_readComment(t,e){const r=e+3;for(e=r;e<t.length;e++)if("-"===t[e]&&"-"===t[e+1]&&">"===t[e+2]){e+=2;break}if(">"!==t[e])throw new Error('Comment is not closed with "--\x3e".');const s=t.substring(r,e-2),n=y.findIllegalIndex(s);if(-1!==n){const t=s.charCodeAt(n);throw new Error(`Illegal control character ${y.describe(t)} in comment.`)}if(this.checkCommentDashes&&-1!==s.indexOf("--"))throw new Error("Comment must not contain '--'.");return e}_readCdata(t,e){const r=e+8;for(e=r;e<t.length;e++)if("]"===t[e]&&"]"===t[e+1]&&">"===t[e+2]){e+=2;break}if(">"!==t[e])throw new Error('CDATA section is not closed with "]]>".');const s=t.substring(r,e-2),n=y.findIllegalIndex(s);if(-1!==n){const t=s.charCodeAt(n);throw new Error(`Illegal control character ${y.describe(t)} in CDATA section.`)}return e}}class A{constructor(t,e={},r){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this.data=r,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 r=0,s="";for(;r<t.length;)t[r]===this.separator?r+1<t.length&&t[r+1]===this.separator?(s.trim()&&(e.push(this._parseSegment(s.trim())),s=""),e.push({type:"deep-wildcard"}),r+=2):(s.trim()&&e.push(this._parseSegment(s.trim())),s="",r++):(s+=t[r],r++);return s.trim()&&e.push(this._parseSegment(s.trim())),e}_parseSegment(t){const e={type:"tag"};let r=null,s=t;const n=t.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);if(n&&(s=n[1]+n[3],n[2])){const t=n[2].slice(1,-1);t&&(r=t)}let i,o,a=s;if(s.includes("::")){const e=s.indexOf("::");if(i=s.substring(0,e).trim(),a=s.substring(e+2).trim(),!i)throw new Error(`Invalid namespace in pattern: ${t}`)}let l=null;if(a.includes(":")){const t=a.lastIndexOf(":"),e=a.substring(0,t).trim(),r=a.substring(t+1).trim();["first","last","odd","even"].includes(r)||/^nth\(\d+\)$/.test(r)?(o=e,l=r):o=a}else o=a;if(!o)throw new Error(`Invalid segment pattern: ${t}`);if(e.tag=o,i&&(e.namespace=i),r)if(r.includes("=")){const t=r.indexOf("=");e.attrName=r.substring(0,t).trim(),e.attrValue=r.substring(t+1).trim()}else e.attrName=r.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 N{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 r=e[e.length-1];return void 0!==r.values&&t in r.values}getAnyParentAttr(t){return this._matcher.getAnyParentAttr(t)}hasAnyParentAttr(t){return this._matcher.hasAnyParentAttr(t)}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 v{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new N(this),this._keptAttrs=[]}push(t,e=null,r=null,s=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const n=this.path.length;let i=this.siblingStacks[n];i||(i={counts:new Map,total:0},this.siblingStacks[n]=i);const o=r?`${r}:${t}`:t,a=i.counts.get(o)||0,l=i.total;i.counts.set(o,a+1),i.total++;const c={tag:t,position:l,counter:a};null!=r&&(c.namespace=r),null!=e&&(c.values=e),this.path.push(c);const h=this.path.length,d=null!==s?s.keep:null;if(null!=d&&d.length>0&&e)for(let t=0;t<d.length;t++){const r=d[t];void 0!==e[r]&&this._keptAttrs.push({depth:h,name:r,value:e[r]})}}pop(){if(0===this.path.length)return;this._pathStringCache=null;const t=this.path.pop();this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1);const e=this.path.length+1;for(;this._keptAttrs.length>0&&this._keptAttrs[this._keptAttrs.length-1].depth>=e;)this._keptAttrs.pop();return 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}getAnyParentAttr(t){const e=this._keptAttrs;for(let r=e.length-1;r>=0;r--)if(e[r].name===t)return e[r].value}hasAnyParentAttr(t){const e=this._keptAttrs;for(let r=e.length-1;r>=0;r--)if(e[r].name===t)return!0;return!1}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 r=t||this.separator;if(r===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(r);return this._pathStringCache=t,t}return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(r)}toArray(){return this.path.map(t=>t.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[],this._keptAttrs=[]}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,r=t.length-1;for(;r>=0&&e>=0;){const s=t[r];if("deep-wildcard"===s.type){if(r--,r<0)return!0;const s=t[r];let n=!1;for(let t=e;t>=0;t--)if(this._matchSegment(s,this.path[t],t===this.path.length-1)){e=t-1,r--,n=!0;break}if(!n)return!1}else{if(!this._matchSegment(s,this.path[e],e===this.path.length-1))return!1;e--,r--}}return r<0}_matchSegment(t,e,r){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(!r)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(!r)return!1;const s=e.counter??0;if("first"===t.position&&0!==s)return!1;if("odd"===t.position&&s%2!=1)return!1;if("even"===t.position&&s%2!=0)return!1;if("nth"===t.position&&s!==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=>t?{counts:new Map(t.counts),total:t.total}:t),keptAttrs:this._keptAttrs.map(t=>({...t}))}}restore(t){this._pathStringCache=null,this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>t?{counts:new Map(t.counts),total:t.total}:t),this._keptAttrs=(t.keptAttrs||[]).map(t=>({...t}))}readOnly(){return this._view}}class S{constructor(t=[]){this._expressions=t.map(t=>new A(t)),this._matcher=new v,this._enabled=this._expressions.length>0}get enabled(){return this._enabled}push(t,e){if(!this._enabled)return!1;this._matcher.push(t,e||null);for(let t=0;t<this._expressions.length;t++)if(this._matcher.matches(this._expressions[t]))return!0;return!1}pop(){this._enabled&&this._matcher.pop()}}class C{static consume(t,e,r){const s="</"+e;let n=r;for(;;){const r=t.indexOf(s,n);if(-1===r)throw new Error(`Unclosed skipped tag '${e}'.`);let i=r+s.length;for(;i<t.length&&/\s/.test(t[i]);)i++;if(">"===t[i])return i;n=r+s.length}}}const D={maxEntityCount:1/0,maxEntitySize:1/0};class O{constructor(t,e="1.0"){this.options=Object.assign({},D,t),this.suppressValidationErr=!t,this.xmlVersion=e}validateDocType(t,e){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;let r=1,s=!1,n=!1,i=null,o=0;for(;e<t.length;e++)if(null===i)if(s||n||'"'!==t[e]&&"'"!==t[e])if("<"!==t[e]||n)if(">"===t[e]){if(n?"-"===t[e-1]&&"-"===t[e-2]&&(n=!1,r--):r--,0===r)break}else"["===t[e]&&(s=!0);else{if(s&&P(t,"!ENTITY",e))e+=7,[o,e]=this._validateEntityExp(t,e+1,o);else if(s&&P(t,"!ELEMENT",e))e+=8,e=this._validateElementExp(t,e+1);else{if(s&&P(t,"!ATTLIST",e)){e+=8,e=this._validateAttlistExp(t,e+1);continue}if(s&&P(t,"!NOTATION",e))e+=9,e=this._validateNotationExp(t,e+1);else{if(!P(t,"!--",e))throw new Error("Invalid DOCTYPE");n=!0}}r++}else i=t[e];else t[e]===i&&(i=null);if(null!==i||0!==r)throw new Error("Unclosed DOCTYPE");return e}_validateEntityExp(t,e,r){const s=e=k(t,e);for(;e<t.length&&!/\s/.test(t[e])&&'"'!==t[e]&&"'"!==t[e];)e++;const n=t.substring(s,e);if(L(n,this.xmlVersion),e=k(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")}let i;[e,i]=U(t,e,"entity");const{maxEntitySize:o,maxEntityCount:a}=this.options;if(i.length>o)throw new Error(`Entity "${n}" size (${i.length}) exceeds maximum allowed size (${o})`);if(-1===i.indexOf("&")&&++r>a)throw new Error(`Entity count (${r}) exceeds maximum allowed (${a})`);return[r,e-1]}_validateNotationExp(t,e){const r=e=k(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;const s=t.substring(r,e);!this.suppressValidationErr&&L(s,this.xmlVersion),e=k(t,e);const n=t.substring(e,e+6).toUpperCase();if(!this.suppressValidationErr&&"SYSTEM"!==n&&"PUBLIC"!==n)throw new Error(`Expected SYSTEM or PUBLIC, found "${n}"`);return e=k(t,e+=n.length),"PUBLIC"===n?([e]=U(t,e,"publicIdentifier"),'"'!==t[e=k(t,e)]&&"'"!==t[e]||([e]=U(t,e,"systemIdentifier"))):"SYSTEM"===n&&([e]=U(t,e,"systemIdentifier")),--e}_validateElementExp(t,e){const r=e=k(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;const s=t.substring(r,e);if(!this.suppressValidationErr&&!m(s,{xmlVersion:this.xmlVersion}))throw new Error(`Invalid element name: "${s}"`);if("E"===t[e=k(t,e)]&&P(t,"MPTY",e))e+=4;else if("A"===t[e]&&P(t,"NY",e))e+=2;else if("("===t[e]){for(e++;e<t.length&&")"!==t[e];)e++;if(")"!==t[e])throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error(`Invalid Element Expression, found "${t[e]}"`);return e}_validateAttlistExp(t,e){const r=e=k(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;L(t.substring(r,e),this.xmlVersion);const s=e=k(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;if(L(t.substring(s,e),this.xmlVersion),e=k(t,e),"NOTATION"===t.substring(e,e+8).toUpperCase()){if("("!==t[e=k(t,e+=8)])throw new Error(`Expected '(', found "${t[e]}"`);for(e++;e<t.length&&")"!==t[e];){const r=e;for(;e<t.length&&"|"!==t[e]&&")"!==t[e];)e++;L(t.substring(r,e).trim(),this.xmlVersion),"|"===t[e]&&(e=k(t,++e))}if(")"!==t[e])throw new Error("Unterminated list of notations");e++}else{const r=e;for(;e<t.length&&!/\s/.test(t[e]);)e++;const s=t.substring(r,e),n=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!n.includes(s.toUpperCase()))throw new Error(`Invalid attribute type: "${s}"`)}return e=k(t,e),"#REQUIRED"===t.substring(e,e+9).toUpperCase()?e+=9:"#IMPLIED"===t.substring(e,e+8).toUpperCase()?e+=8:[e]=U(t,e,"ATTLIST default value"),e}}function k(t,e){for(;e<t.length&&/\s/.test(t[e]);)e++;return e}function P(t,e,r){for(let s=0;s<e.length;s++)if(e[s]!==t[r+s+1])return!1;return!0}function L(t,e="1.0"){if(!m(t,{xmlVersion:e}))throw new Error(`Invalid entity name "${t}"`)}function U(t,e,r){const s=t[e];if('"'!==s&&"'"!==s)throw new Error(`Expected quoted string for ${r}, found "${s}"`);const n=++e;for(;e<t.length&&t[e]!==s;)e++;if(t[e]!==s)throw new Error(`Unterminated ${r} value`);const i=t.substring(n,e);return[++e,i]}const M={allowBooleanAttributes:!1,unpairedTags:[],docType:{maxEntityCount:1/0,maxEntitySize:1/0},invalidCharSequence:{comment:!1,tagValue:!1,attrLt:!1},xmlDeclaraion:{optional:!0,argPosition:!0},multipleRoots:!0,skipTags:[]};class ${constructor(t){this.options=function(t,e){const r=Object.assign({},t,e);return r.docType=Object.assign({},t.docType,e?.docType),r.invalidCharSequence=Object.assign({},t.invalidCharSequence,e?.invalidCharSequence),r.xmlDeclaraion=Object.assign({},t.xmlDeclaraion,e?.xmlDeclaraion,e?.xmlDeclaration),r.skipTags=e?.skipTags||t.skipTags,r}(M,t)}static validate(t,e){return new $(e).validate(t)}validate(t){const e=this.options,o=[];let a=!1,l=!1,c=!1;"\ufeff"===t[0]&&(t=t.substr(1));const h=(t,e,s)=>{throw new r(e,t,s.line||s,s.col)},d=new T(e.xmlDeclaraion,h).validate(t),u=d.version;t=t.substring(d.end);const p=new O(e.docType,u),f=new I(e),g=new b(u),m=new w(e,g,u),_=new S(e.skipTags),E=!0===e.invalidCharSequence?.tagValue,x=e=>{"<!DOCTYPE"===t.substring(e,e+9).toUpperCase()&&(c&&h("InvalidXml","Multiple DOCTYPE declarations found.",i(t,e)),(a||o.length>0)&&h("InvalidXml","DOCTYPE must appear before the root element.",i(t,e)),c=!0)};for(let r=0;r<t.length;r++)if("<"===t[r]&&"?"===t[r+1])r+=2,r=this._readPI(t,r,g,h);else if("<"===t[r]){let c=r;if(r++,"!"===t[r]){try{x(c),r=f.read(t,r,p)}catch(e){h("InvalidDocType",e.message,i(t,r-1))}continue}{let d=!1;"/"===t[r]&&(d=!0,r++);let u="";for(;r<t.length&&">"!==t[r]&&" "!==t[r]&&"\t"!==t[r]&&"\n"!==t[r]&&"\r"!==t[r];r++)u+=t[r];if(u=u.trim(),"/"===u[u.length-1]&&(u=u.substring(0,u.length-1),r--),!g.isValidQName(u)){let e;e=0===u.trim().length?"Invalid space after '<'.":"Tag '"+u+"' is an invalid name.",h("InvalidTag",e,i(t,c))}const b=this._readAttributeStr(t,r);!1===b&&h("InvalidAttr","Attributes for '"+u+"' have open quote.",i(t,r));let T=b.value;if(r=b.index,"/"===T[T.length-1]){const s=r-T.length;T=T.substring(0,T.length-1);const n=m.validate(T);!0===n?(!0!==l||e.multipleRoots||h("InvalidXml","Multiple possible root nodes found.",i(t,c)),a=!0,0===o.length&&(l=!0),_.push(u),_.pop()):h(n.err.code,n.err.msg,i(t,s+n.err.line))}else if(d)if(b.tagClosed)if(T.trim().length>0)h("InvalidTag","Closing tag '"+u+"' can't have attributes or invalid starting.",i(t,c));else if(0===o.length)h("InvalidTag","Closing tag '"+u+"' has not been opened.",i(t,c));else{const e=o.pop();if(u!==e.tagName){let r=i(t,e.tagStartPos);h("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+r.line+", col "+r.col+") instead of closing tag '"+u+"'.",i(t,c))}_.pop(),0===o.length&&(l=!0)}else h("InvalidTag","Closing tag '"+u+"' doesn't have proper closing.",i(t,r));else{const s=_.push(u);if(!s){const e=m.validate(T);!0!==e&&h(e.err.code,e.err.msg,i(t,r-T.length+e.err.line))}if(!0!==l||e.multipleRoots)if(-1!==e.unpairedTags.indexOf(u))_.pop();else{if(s){r=C.consume(t,u,r+1),_.pop(),0===o.length&&(l=!0),a=!0;continue}o.push({tagName:u,tagStartPos:c})}else h("InvalidXml","Multiple possible root nodes found.",i(t,r));a=!0}let w="";for(r++;r<t.length;r++)if("<"===t[r]){if("!"===t[r+1]){r++;try{x(r-1),r=f.read(t,r,p)}catch(e){h("InvalidDocType",e.message,i(t,r-1))}w="";continue}if("?"!==t[r+1])break;r+=2,r=this._readPI(t,r,g,h),w=""}else if("&"===t[r]){const e=this._validateAmpersand(t,r);-1===e&&h("InvalidChar","char '&' is not expected.",i(t,r)),r=e,w=""}else{const e=t.charCodeAt(r);n(e)&&h("IllegalCharacter",`Illegal control character ${y.describe(e)} in document content.`,i(t,r)),!0!==l||0!==o.length||s(t[r])||h("InvalidXml","Extra text at the end",i(t,r)),E&&(w=(w+t[r]).slice(-2),"]]"===w&&">"===t[r+1]&&h("InvalidXml","Element text content must not contain ']]>'.",i(t,r-1)))}"<"===t[r]&&r--}}else{if(s(t[r]))continue;l&&h("InvalidXml","Extra text at the end: '"+t[r]+"' is not expected.",i(t,r)),h("InvalidChar","char '"+t[r]+"' is not expected.",i(t,r))}return a?1===o.length?h("InvalidTag","Unclosed tag '"+o[0].tagName+"'.",i(t,o[0].tagStartPos)):o.length>0&&h("InvalidXml","Invalid '"+JSON.stringify(o.map(t=>t.tagName)).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):h("InvalidXml","Start tag expected.",{line:1,col:1}),!0}_readPI(t,e,r,s){const n=e,o=e;let a=!1;for(;e<t.length;e++){const l=t[e];if(!a&&(" "===l||"?"===l)){const l=t.substr(o,e-o);a=!0,"xml"===l.toLowerCase()?s("InvalidXml","XML declaration allowed only at the start of the document.",i(t,n-2)):r.isValidName(l)||s("InvalidXml",`Processing instruction target "${l}" is not a valid XML Name.`,i(t,n-2))}if("?"===l&&">"===t[e+1])return++e}s("InvalidXml",'Processing instruction is not closed with "?>".',i(t,n-2))}_readAttributeStr(t,e){let r="",s="",n=!1;for(;e<t.length;e++){if('"'===t[e]||"'"===t[e])""===s?s=t[e]:s!==t[e]||(s="");else if(">"===t[e]&&""===s){n=!0;break}r+=t[e]}return""===s&&{value:r,index:e,tagClosed:n}}_validateNumberAmpersand(t,e){let r=/\d/;for("x"===t[e]&&(e++,r=/[\da-fA-F]/);e<t.length;e++){if(";"===t[e])return e;if(!t[e].match(r))break}return-1}_validateAmpersand(t,e){if(";"===t[++e])return-1;if("#"===t[e])return e++,this._validateNumberAmpersand(t,e);let r=0;for(;e<t.length;e++,r++)if(!(t[e].match(/\w/)&&r<20)){if(";"===t[e])break;return-1}return e}}class B{constructor(){this._byDepthAndTag=new Map,this._wildcardByDepth=new Map,this._deepWildcards=[],this._deepByTerminalTag=new Map,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()){const e=t.segments[t.segments.length-1];if(e&&"deep-wildcard"!==e.type&&"*"!==e.tag){const r=e.tag;this._deepByTerminalTag.has(r)||this._deepByTerminalTag.set(r,[]),this._deepByTerminalTag.get(r).push(t)}else this._deepWildcards.push(t);return this}const e=t.length,r=t.segments[t.segments.length-1],s=r?.tag;if(s&&"*"!==s){const r=`${e}:${s}`;this._byDepthAndTag.has(r)||this._byDepthAndTag.set(r,[]),this._byDepthAndTag.get(r).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(),r=t.getCurrentTag(),s=`${e}:${r}`,n=this._byDepthAndTag.get(s);if(n)for(let e=0;e<n.length;e++)if(t.matches(n[e]))return n[e];const i=this._wildcardByDepth.get(e);if(i)for(let e=0;e<i.length;e++)if(t.matches(i[e]))return i[e];const o=this._deepByTerminalTag.get(r);if(o)for(let e=0;e<o.length;e++)if(t.matches(o[e]))return o[e];for(let e=0;e<this._deepWildcards.length;e++)if(t.matches(this._deepWildcards[e]))return this._deepWildcards[e];return null}}const R={nameFor:{},skip:{},tags:{valueParsers:[]},attributes:{valueParsers:[]},textJoint:"",alwaysArray:[],forceArray:null,forceTextNode:!1},V=["ws","entity","boolean","number"],j=["entity","number","boolean"];function X(t){const e=q(R);t&&void 0!==t.tags?.valueParsers||(e.tags.valueParsers=[...V]),t&&void 0!==t.attributes?.valueParsers||(e.attributes.valueParsers=[...j]);const r=Array.isArray(t?.alwaysArray)?t.alwaysArray:e.alwaysArray,s=new B;for(const t of r)Y(t,"alwaysArray",s);return s.seal(),e._alwaysArraySet=s,t&&F(e,t),e}function q(t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map(q);const e={};for(const r of Object.keys(t))e[r]=q(t[r]);return e}function F(t,e){for(const r of Object.keys(e))"__proto__"!==r&&"constructor"!==r&&"prototype"!==r&&("function"==typeof e[r]||Array.isArray(e[r])?t[r]=e[r]:"object"==typeof e[r]&&null!==e[r]?("object"==typeof t[r]&&null!==t[r]||(t[r]={}),F(t[r],e[r])):t[r]=e[r])}function Y(t,e,r){let s;if("string"==typeof t){if(0===t.length)throw new Error(`${e} expression cannot be empty`);s=t}else{if(!("string"==typeof t?.pattern&&t.pattern.length>0&&Array.isArray(t?.segments)))throw new Error(`Invalid ${e} entry: expected a string, or Expression.`);s=t.toString()}const n=new A(s);return r.add(n),n}const z={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'},G=Object.freeze({ALLOW:"allow",BLOCK:"block",THROW:"throw"}),H=new Set("!?\\\\/[]$%{}^&*()<>|+");function W(t){if("#"===t[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${t}"`);for(const e of t)if(H.has(e))throw new Error(`[EntityReplacer] Invalid character '${e}' in entity name: "${t}"`);return t}function Q(...t){const e=Object.create(null);for(const r of t)if(r)for(const t of Object.keys(r)){const s=r[t];if("string"==typeof s)e[t]=s;else if(s&&"object"==typeof s&&void 0!==s.val){const r=s.val;"string"==typeof r&&(e[t]=r)}}return e}const J="external",Z="base",K="all",tt=Object.freeze({allow:0,leave:1,remove:2,throw:3}),et=new Set([9,10,13]);class rt{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??J)&&e!==J?e===K?new Set([K]):e===Z?new Set([Z]):Array.isArray(e)?new Set(e):new Set([J]):new Set([J]),this._numericAllowed=t.numericAllowed??!0,this._baseMap=Q(z,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 r=function(t){if(!t)return{xmlVersion:1,onLevel:tt.allow,nullLevel:tt.remove};const e=1.1===t.xmlVersion?1.1:1,r=tt[t.onNCR]??tt.allow,s=tt[t.nullNCR]??tt.remove;return{xmlVersion:e,onLevel:r,nullLevel:Math.max(s,tt.remove)}}(t.ncr);this._ncrXmlVersion=r.xmlVersion,this._ncrOnLevel=r.onLevel,this._ncrNullLevel=r.nullLevel,this._onExternalEntity="function"==typeof t.onExternalEntity?t.onExternalEntity:null,this._onInputEntity="function"==typeof t.onInputEntity?t.onInputEntity:null}_applyRegistrationHook(t,e,r,s){if(!t)return!0;const n=t(e,r);if(n===G.BLOCK)return!1;if(n===G.THROW)throw new Error(`[EntityDecoder] Registration of ${s} entity "&${e};" was rejected by hook`);return!0}setExternalEntities(t){if(t)for(const e of Object.keys(t))W(e);if(!this._onExternalEntity)return void(this._externalMap=Q(t));const e=Q(t),r=Object.create(null);for(const[t,s]of Object.entries(e))this._applyRegistrationHook(this._onExternalEntity,t,s,"external")&&(r[t]=s);this._externalMap=r}addExternalEntity(t,e){W(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=Q(t));const e=Q(t),r=Object.create(null);for(const[t,s]of Object.entries(e))this._applyRegistrationHook(this._onInputEntity,t,s,"input")&&(r[t]=s);this._inputMap=r}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,r=[],s=t.length;let n=0,i=0;const o=this._maxTotalExpansions>0,a=this._maxExpandedLength>0,l=o||a;for(;i<s;){if(38!==t.charCodeAt(i)){i++;continue}let e=i+1;for(;e<s&&59!==t.charCodeAt(e)&&e-i<=32;)e++;if(e>=s||59!==t.charCodeAt(e)){i++;continue}const c=t.slice(i+1,e);if(0===c.length){i++;continue}let h,d;if(this._removeSet.has(c))h="",void 0===d&&(d=J);else{if(this._leaveSet.has(c)){i++;continue}if(35===c.charCodeAt(0)){const t=this._resolveNCR(c);if(void 0===t){i++;continue}h=t,d=Z}else{const t=this._resolveName(c);h=t?.value,d=t?.tier}}if(void 0!==h){if(i>n&&r.push(t.slice(n,i)),r.push(h),n=e+1,i=n,l&&this._tierCounts(d)){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=h.length-(c.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 i++}n<s&&r.push(t.slice(n));const c=0===r.length?t:r.join("");return this._postCheck(c,e)}_tierCounts(t){return!!this._limitTiers.has(K)||this._limitTiers.has(t)}_resolveName(t){return t in this._inputMap?{value:this._inputMap[t],tier:J}:t in this._externalMap?{value:this._externalMap[t],tier:J}:t in this._baseMap?{value:this._baseMap[t],tier:Z}:void 0}_classifyNCR(t){return 0===t?this._ncrNullLevel:t>=55296&&t<=57343||1===this._ncrXmlVersion&&t>=1&&t<=31&&!et.has(t)?tt.remove:-1}_applyNCRAction(t,e,r){switch(t){case tt.allow:return String.fromCodePoint(r);case tt.remove:return"";case tt.leave:return;case tt.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference &${e}; (U+${r.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(r)}}_resolveNCR(t){const e=t.charCodeAt(1);let r;if(r=120===e||88===e?parseInt(t.slice(2),16):parseInt(t.slice(1),10),Number.isNaN(r)||r<0||r>1114111)return;const s=this._classifyNCR(r);if(!this._numericAllowed&&s<tt.remove)return;const n=-1===s?this._ncrOnLevel:Math.max(this._ncrOnLevel,s);return this._applyNCRAction(n,t,r)}}const st=[{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}],nt="[\"'\\s]*:",it={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. <script or <script)",pattern:/(?:�*3[Cc];?|�*60;?|<)\s*script/i},{id:"html-entity-obfuscated-javascript",description:'HTML-entity-encoded javascript: (partial — catches common j or j for "j")',pattern:/(?:�*6[Aa];?|�*106;?)\s*(?:�*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:st,"SQL-STRICT":[...st,{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${nt}`,"i")},{id:"nosql-ne-operator",description:'$ne — "not equal" operator used to bypass equality checks',pattern:new RegExp(`\\$ne${nt}`,"i")},{id:"nosql-gt-operator",description:'$gt — "greater than" used to bypass password/value checks',pattern:new RegExp(`\\$gte?${nt}`,"i")},{id:"nosql-lt-operator",description:'$lt / $lte — "less than" bypass variants',pattern:new RegExp(`\\$lte?${nt}`,"i")},{id:"nosql-regex-operator",description:"$regex — can be used to extract data character by character (blind injection)",pattern:new RegExp(`\\$regex${nt}`,"i")},{id:"nosql-or-operator",description:"$or — logical OR; used to create always-true conditions",pattern:new RegExp(`\\$or${nt}\\s*\\[`,"i")},{id:"nosql-and-operator",description:"$and — logical AND operator injection",pattern:new RegExp(`\\$and${nt}\\s*\\[`,"i")},{id:"nosql-nor-operator",description:"$nor — logical NOR operator injection",pattern:new RegExp(`\\$nor${nt}\\s*\\[`,"i")},{id:"nosql-exists-operator",description:"$exists — can enumerate fields to determine schema",pattern:new RegExp(`\\$exists${nt}`,"i")},{id:"nosql-in-operator",description:"$in — matches any value in a list; can enumerate values",pattern:new RegExp(`\\$in${nt}\\s*\\[`,"i")},{id:"nosql-expr-operator",description:"$expr — allows aggregation expressions in queries (MongoDB 3.6+)",pattern:new RegExp(`\\$expr${nt}`,"i")},{id:"nosql-function-operator",description:"$function — executes arbitrary JavaScript in MongoDB 4.4+",pattern:new RegExp(`\\$function${nt}`,"i")},{id:"nosql-accumulator-operator",description:"$accumulator — custom aggregation with arbitrary JS execution",pattern:new RegExp(`\\$accumulator${nt}`,"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\[/}]},ot=it,at=Object.freeze(Object.fromEntries(Object.keys(it).map(t=>[t,t])));function lt(t,e){const r=ot[e];for(const s of r)if(s.pattern.test(t))return{context:e,id:s.id,description:s.description,pattern:s.pattern};return null}function ct(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||!ot[e])throw new TypeError(`is-unsafe: unknown context "${e}" in array. Valid contexts: ${Object.keys(at).join(", ")}`)}else if(!ot[t])throw new TypeError(`is-unsafe: unknown context "${t}". Valid contexts: ${Object.keys(at).join(", ")}`)}(e),e instanceof RegExp)return e.test(t);if("string"==typeof e)return null!==lt(t,e);for(const r of e)if(null!==lt(t,r))return!0;return!1}class ht{constructor(t=!1){this.IS_FINAL=t}init(t){this.ctx=t}reset(){}parse(t,e){throw new Error("You must implement parse() in a value parser.")}}const dt={namedEntities:{...z},numericAllowed:!0,onInputEntity:(t,e)=>ct(e,[at.XML])?G.BLOCK:G.ALLOW},ut=[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],pt=new Map,ft=1632,gt=new Uint8Array(63904).fill(255);for(const t of ut)for(let e=0;e<10;e++){const r=t+e;r<=65535?gt[r-ft]=e:pt.set(r,e)}const mt=new Set([8722,65293,65123]),_t=/^[-+]?0x[a-fA-F0-9]+$/,Et=/^0b[01]+$/,bt=/^0o[0-7]+$/,xt=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Tt={hex:!0,binary:!1,octal:!1,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original",unicode:!1};function yt(t,e={}){if(e=Object.assign({},Tt,e),!t||"string"!=typeof t)return t;let r=t.trim();if(0===r.length)return t;if(void 0!==e.skipLike&&e.skipLike.test(r))return t;if("0"===r)return 0;if(e.unicode&&(r=function(t){if("string"!=typeof t)return t;const e=t.length;if(0===e)return t;let r=-1;for(let s=0;s<e;s++){const n=t.charCodeAt(s);if(!(n>=48&&n<=57||45===n))if(n<ft){if(mt.has(n)){r=s;break}}else if(n>=55296&&n<=56319){if(s+1<e){const e=t.charCodeAt(s+1);if(e>=56320&&e<=57343){const t=65536+(n-55296<<10)+(e-56320);if(pt.has(t)){r=s;break}}}}else if(255!==gt[n-ft]||mt.has(n)){r=s;break}}if(-1===r)return t;const s=[];r>0&&s.push(t.slice(0,r));for(let n=r;n<e;n++){const r=t.charCodeAt(n);if(r>=48&&r<=57||45===r){s.push(t[n]);continue}if(r<ft){s.push(mt.has(r)?"-":t[n]);continue}if(r>=55296&&r<=56319){if(n+1<e){const e=t.charCodeAt(n+1);if(e>=56320&&e<=57343){const t=65536+(r-55296<<10)+(e-56320),i=pt.get(t);if(void 0!==i){s.push(String.fromCharCode(i+48)),n++;continue}}}s.push(t[n]);continue}if(mt.has(r)){s.push("-");continue}const i=gt[r-ft];s.push(255!==i?String.fromCharCode(i+48):t[n])}return s.join("")}(r),"0"===r))return 0;if(e.hex&&_t.test(r))return It(r,16);if(e.binary&&Et.test(r))return It(r,2);if(e.octal&&bt.test(r))return It(r,8);if(isFinite(r)){if(r.includes("e")||r.includes("E"))return function(t,e,r){if(!r.eNotation)return t;const s=e.match(wt);if(s){let n=s[1]||"";const i=-1===s[3].indexOf("e")?"E":"e",o=s[2],a=n?t[o.length+1]===i:t[o.length]===i;return o.length>1&&a?t:(1!==o.length||!s[3].startsWith(`.${i}`)&&s[3][0]!==i)&&o.length>0?r.leadingZeros&&!a?(e=(s[1]||"")+s[3],Number(e)):t:Number(e)}return t}(t,r,e);{const n=xt.exec(r);if(n){const i=n[1]||"",o=n[2];let a=(s=n[3])&&-1!==s.indexOf(".")?("."===(s=s.replace(/0+$/,""))?s="0":"."===s[0]?s="0"+s:"."===s[s.length-1]&&(s=s.substring(0,s.length-1)),s):s;const l=i?"."===t[o.length+1]:"."===t[o.length];if(!e.leadingZeros&&(o.length>1||1===o.length&&!l))return t;{const s=Number(r),n=String(s);if(0===s)return s;if(-1!==n.search(/[eE]/))return e.eNotation?s:t;if(-1!==r.indexOf("."))return"0"===n||n===a||n===`${i}${a}`?s:t;let l=o?a:r;return o?l===n||i+l===n?s:t:l===n||l===i+n?s:t}}return t}}var s;return function(t,e,r){const s=e===1/0;switch(r.infinity.toLowerCase()){case"null":return null;case"infinity":return e;case"string":return s?"Infinity":"-Infinity";default:return t}}(t,Number(r),e)}const wt=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function It(t,e){const r=t.trim();if(2!==e&&8!==e||(t=r.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")}class At extends ht{constructor(t,e=!1){super(e),this.options=t||{}}parse(t){if("string"==typeof t){const e=yt(t,this.options);if(typeof e!==t)return this.IS_FINAL?new Ct(e):e}return t}}const Nt={entity:new class extends ht{#t=!1;#e=null;#r=null;constructor(t,e=!1){super(e),this.#r={...dt,...t||{},namedEntities:{...dt.namedEntities,...t?.namedEntities||{}}}}#s(){if(this.#e||(this.#e=new rt(this.#r)),!this.#t){const t=this.ctx?.get("xmlVersion"),e=this.ctx?.get("inputEntities");t&&this.#e.setXmlVersion(t),e&&this.#e.addInputEntities(e),this.#t=!0}}reset(){this.#t=!1,this.#e&&this.#e.reset()}parse(t){return"string"!=typeof t?t:(this.#s(),this.#e.decode(t))}},trim:new class extends ht{parse(t){return"string"==typeof t?t.trim():t}},ws:new class extends ht{constructor(t,e=!1){super(e);const r=t?.exclude??[],s=new B;for(const t of r)s.add("string"==typeof t?new A(t):t);s.seal(),this._excludeSet=s}parse(t,e){if("string"!=typeof t)return t;if(e){if(e.isAttribute)return t;if(e.matcher){if("preserve"===e.matcher.getAnyParentAttr("xml:space"))return t;if(this._excludeSet.size>0&&this._excludeSet.matchesAny(e.matcher))return t}}return t.replace(/[ \t\r\n]+/g," ").trim()}},boolean:new class extends ht{constructor(t,e,r=!1){super(r),this.trueList=t||["true"],this.falseList=e||["false"]}parse(t){if("string"==typeof t){const e=t.toLowerCase();if(-1!==this.trueList.indexOf(e))return!this.IS_FINAL||new Ct(!0);if(-1!==this.falseList.indexOf(e))return!!this.IS_FINAL&&new Ct(!1)}return t}},number:new At({hex:!0,leadingZeros:!0,eNotation:!0})};class vt{constructor(){this.registered={...Nt}}register(t,e){if(!t||"string"!=typeof t)throw new Error("name must be a string");if(!e)throw new Error("parser is required");if(!e.reset||"function"!=typeof e.reset)throw new Error("parser must implement reset()");if(!e.parse||"function"!=typeof e.parse)throw new Error("parser must implement parse()");this.registered[t]=e}reset(t){this.registered[t]?.reset()}resetAll(){for(const t in this.registered)this.registered[t]?.reset()}get(t){const e=this.registered[t];if(!e)throw new Error("parser not found: "+t);return e}}class St{constructor(t,e,r,s=!1){this.elementName=t,this.matcher=e,this.isLeafNode=r,this.isAttribute=s}}class Ct{constructor(t){this.value=t}}class Dt{#n={};set(t,e){this.#n[t]=e}get(t){return this.#n[t]}clear(){this.#n={}}}class Ot{constructor(t=[],e,r=null){this.valParsers=t,this.registry=e,this.sharedContext=r||new Dt,this._initAll(t)}run(t,e){for(let r=0;r<this.valParsers.length;r++){let s=this.valParsers[r];if("string"==typeof s&&(s=this.registry.get(s)),s){const r=s.parse(t,e);if(r instanceof Ct)return r.value;t=r}}return t}resetAll(){for(let t=0;t<this.valParsers.length;t++){let e=this.valParsers[t];"string"==typeof e&&(e=this.registry.get(e)),e&&e.reset&&"function"==typeof e.reset&&e.reset()}}register(t,e){this.registry.register(t,e),e.init&&e.init(this.sharedContext)}_initAll(t){if(!this.sharedContext)return;const e=new Set;for(const r of t){let t=r;"string"==typeof r&&(t=this.registry.get(r)),t&&"function"==typeof t.init&&!e.has(t)&&(e.add(t),t.init(this.sharedContext))}}}const kt=["ws","entity","boolean","number"],Pt=["entity","boolean","number"];class Lt{constructor(t,e,r,s,n=!0){this.matcher=r,this._rootName="^",this.parserOptions=t,this.builderOptions=e,this.registry=s;const i=e?.tags?.valueParsers??kt,o=e?.attributes?.valueParsers??Pt;this.sharedContext=new Dt,this.tagsPipeline=new Ot(i,this.registry,this.sharedContext),this.attrsPipeline=new Ot(o,this.registry,this.sharedContext),n&&(this.tagsPipeline.resetAll(),this.attrsPipeline.resetAll()),this._pendingStopNode=!1}addAttribute(t,e,r){"version"===t&&this.tagName===this._rootName&&this.sharedContext?.set("xmlVersion",+e);const s=`${this.parserOptions.attributes.prefix}${t}${this.parserOptions.attributes.suffix}`,n=new St(t,r,!0,!0);this.attributes[s]=this.attrsPipeline.run(e,n)}_addChild(t,e){}addComment(t){this.parserOptions.skip.comment||this.parserOptions.nameFor.comment&&this._addChild(this.parserOptions.nameFor.comment,t)}addLiteral(t){this.parserOptions.skip.cdata||(this.parserOptions.nameFor.cdata?this._addChild(this.parserOptions.nameFor.cdata,t):this.addRawValue(t||""))}addRawValue(t){this.addValue(t)}addInputEntities(t){this.sharedContext?.set("inputEntities",t)}addDeclaration(t){this.addInstruction(t)}addInstruction(t){}onStopNode(t,e){this._pendingStopNode=!0,"function"==typeof this.parserOptions.onStopNode&&this.parserOptions.onStopNode(t,e,this.matcher)}onExit(t){}}class Ut{constructor(t={}){this.builderOptions=t,this.registry=new vt}registerValueParser(t,e){this.registry.register(t,e)}getInstance(t,e){throw new Error("getInstance is not implemented")}}class Mt extends Ut{constructor(t={}){super(),this.builderOptions=X(t)}getInstance(t,e){return new $t(t,this.builderOptions,e,this.registry)}}class $t extends Lt{constructor(t,e,r,s){super(t,e,r,s),this.parserOptions=t,this.builderOptions=e,this.tagsStack=[],this.root={},this.parent=this.root,this.tagName=this._rootName,this.value={},this.textValue="",this.attributes={},this.hasAttributes=!1}_buildAttributeValue(){return Bt(this.attributes)?(this.hasAttributes=!1,""):(this.hasAttributes=!0,this.parserOptions.attributes.groupBy?{[this.parserOptions.attributes.groupBy]:this.attributes}:this.attributes)}addElement(t){const e=this._buildAttributeValue();this.tagsStack.push([this.tagName,this.textValue,this.value,this.hasAttributes]),this.tagName=t.name,this.value=e,this.textValue="",this.attributes={}}_resolveForceArray(t){let e,r;if(this.builderOptions._alwaysArraySet.matchesAny(this.matcher)&&(e=!0),"function"==typeof this.builderOptions.forceArray){const e=this.builderOptions.forceArray(this.matcher,t);!0===e?r=!0:!1===e&&(r=!1)}return!1!==e&&!1!==r&&(!0===e||!0===r)}closeElement(){const t=this.tagName;let e=this.value;const r=this.textValue,s=this.hasAttributes,n="object"!=typeof e||Array.isArray(e)||Bt(e)||s,i=new St(t,this.matcher,n,!1);if(n){const t=this._pendingStopNode?r:this.tagsPipeline.run(r,i);s?(""!==t&&null!=t||this.builderOptions.forceTextNode)&&(e[this.parserOptions.nameFor.text]=t):e=this.builderOptions.forceTextNode?{[this.parserOptions.nameFor.text]:t}:t}else if(r.length>0||this.builderOptions.forceTextNode){const t=this._pendingStopNode?r:this.tagsPipeline.run(r,i);e[this.parserOptions.nameFor.text]=t}let o={tagName:t,value:e};const a=this.tagsStack.pop();let l=a[2];const c=this._resolveForceArray(n);l=this._addChildTo(o.tagName,o.value,l,c),this.tagName=a[0],this.textValue=a[1],this.value=l,this.hasAttributes=a[3],this._pendingStopNode=!1}_addChild(t,e){"string"==typeof this.value&&(this.value={[this.parserOptions.nameFor.text]:this.value}),this._addChildTo(t,e,this.value,!1),this.attributes={}}_addChildTo(t,e,r,s){return"string"==typeof r&&(r={}),Object.prototype.hasOwnProperty.call(r,t)?(Array.isArray(r[t])||(r[t]=[r[t]]),r[t].push(e)):r[t]=s?[e]:e,r}addValue(t){this.textValue.length>0?this.textValue+=`${this.builderOptions.textJoint}${t}`:this.textValue=t}addInstruction(t){const e=this._buildAttributeValue();this._addChild(t,e),this.attributes={}}onExit(t){}getOutput(){return this.value}}function Bt(t){return 0===Object.keys(t).length}class Rt extends Error{constructor(t,e,r={}){super(t),this.name="ParseError",this.code=e,this.index=r.index??void 0}toString(){const t=this._posStr();return t?`${this.name} [${this.code}] at ${t}: ${this.message}`:`${this.name} [${this.code}]: ${this.message}`}_posStr(){return void 0!==this.index?`index ${this.index}`:null}}const Vt=Object.freeze({INVALID_INPUT:"INVALID_INPUT",INVALID_STREAM:"INVALID_STREAM",ALREADY_STREAMING:"ALREADY_STREAMING",NOT_STREAMING:"NOT_STREAMING",DATA_MUST_BE_STRING:"DATA_MUST_BE_STRING",UNEXPECTED_END:"UNEXPECTED_END",UNEXPECTED_CLOSE_TAG:"UNEXPECTED_CLOSE_TAG",MISMATCHED_CLOSE_TAG:"MISMATCHED_CLOSE_TAG",UNEXPECTED_TRAILING_DATA:"UNEXPECTED_TRAILING_DATA",INVALID_TAG:"INVALID_TAG",UNCLOSED_QUOTE:"UNCLOSED_QUOTE",INVALID_ATTRIBUTE_NAME:"INVALID_ATTRIBUTE_NAME",MULTIPLE_NAMESPACES:"MULTIPLE_NAMESPACES",ILLEGAL_CHARACTER:"ILLEGAL_CHARACTER",DUPLICATE_ATTRIBUTE:"DUPLICATE_ATTRIBUTE",UNQUOTED_ATTRIBUTE_VALUE:"UNQUOTED_ATTRIBUTE_VALUE",BOOLEAN_ATTRIBUTE_REJECTED:"BOOLEAN_ATTRIBUTE_REJECTED",SECURITY_PROTOTYPE_POLLUTION:"SECURITY_PROTOTYPE_POLLUTION",SECURITY_RESERVED_OPTION:"SECURITY_RESERVED_OPTION",SECURITY_RESTRICTED_NAME:"SECURITY_RESTRICTED_NAME",LIMIT_MAX_NESTED_TAGS:"LIMIT_MAX_NESTED_TAGS",LIMIT_MAX_ATTRIBUTES:"LIMIT_MAX_ATTRIBUTES",ENTITY_MAX_COUNT:"ENTITY_MAX_COUNT",ENTITY_MAX_SIZE:"ENTITY_MAX_SIZE",ENTITY_MAX_EXPANSIONS:"ENTITY_MAX_EXPANSIONS",ENTITY_MAX_EXPANDED_LENGTH:"ENTITY_MAX_EXPANDED_LENGTH",ENTITY_INVALID_KEY:"ENTITY_INVALID_KEY",ENTITY_INVALID_VALUE:"ENTITY_INVALID_VALUE",UNSUPPORTED_ENCODING:"UNSUPPORTED_ENCODING",INVALID_DECODER:"INVALID_DECODER",ENCODING_MISMATCH:"ENCODING_MISMATCH"});function jt(t){return" "===t||"\t"===t||"\n"===t||"\r"===t||"\f"===t}function Xt(t){return 32===t||9===t||10===t||13===t||12===t}const qt=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","toLocaleString","isPrototypeOf","propertyIsEnumerable"],Ft=["__proto__","constructor","prototype"];function Yt(t){return t.startIndex+(t._baseOffset||0)}function zt(t){return{index:Yt(t)}}function Gt(t){return t<=8||11===t||12===t||t>=14&&t<=31}function Ht(t,e){const r=t.length;let s=!1;for(let n=0;n<r;n++){const r=t.charCodeAt(n);if(Gt(r))throw new Rt(`Illegal control character 0x${r.toString(16).padStart(2,"0")} in document content`,Vt.ILLEGAL_CHARACTER,e?zt(e):{});13===r&&(s=!0)}if(!s)return t;let n="",i=0;for(let e=0;e<r;e++)13===t.charCodeAt(e)&&(n+=t.substring(i,e)+"\n",10===t.charCodeAt(e+1)&&e++,i=e+1);return n+=t.substring(i),n}function Wt(t,e,r,s=!1){const n=e.length;if(!t.canRead(n))throw new Rt(`Unexpected end of source reading ${r}`,Vt.UNEXPECTED_END,zt(t));if(!0!==t.matchAhead(e,s))throw new Rt(`Invalid ${r}`,Vt.INVALID_TAG,zt(t));t.updateBufferBoundary(n)}function Qt(t,e,r){if(!t.canRead(e))throw new Rt(`Unexpected end of source reading ${r}`,Vt.UNEXPECTED_END,zt(t))}const Jt=t=>qt.includes(t)?"__"+t:t,Zt={skip:{declaration:!1,pi:!1,attributes:!0,cdata:!1,comment:!1,nsPrefix:!1,tags:[],whitespaceText:!0},nameFor:{text:"#text",cdata:"",comment:""},attributes:{booleanType:"allow",duplicate:"overwrite",groupBy:"",prefix:"@_",suffix:""},tags:{unpaired:[],stopNodes:[]},strictReservedNames:!1,onDangerousProperty:Jt,sanitizeNames:!0,only:[],doctypeOptions:{enabled:!1,maxEntityCount:100,maxEntitySize:1e4},autoClose:null,limits:{maxNestedTags:null,maxAttributesPerTag:null},feedable:{maxBufferSize:10485760,autoFlush:!0,flushThreshold:1024,bufferSize:256},exitIf:()=>!1,OutputBuilder:null,decoding:{encoding:"auto",customDecoders:null}},Kt=new Set([...Ft,...qt]);function te(t,e){if("string"==typeof t&&""!==t&&Kt.has(t))throw new Rt(`SECURITY: '${t}' is a reserved JavaScript keyword and cannot be used as ${e}`,Vt.SECURITY_RESERVED_OPTION)}const ee=function(t){if(t&&(t.nameFor?.text&&te(t.nameFor.text,"nameFor.text"),t.nameFor?.cdata&&te(t.nameFor.cdata,"nameFor.cdata"),t.nameFor?.comment&&te(t.nameFor.comment,"nameFor.comment"),t.attributes?.prefix&&te(t.attributes.prefix,"attributes.prefix"),t.attributes?.groupBy&&te(t.attributes.groupBy,"attributes.groupBy"),void 0!==t.limits&&null!==t.limits)){if("object"!=typeof t.limits)throw new Rt("'limits' must be an object, got "+typeof t.limits,Vt.INVALID_INPUT);const{maxNestedTags:e,maxAttributesPerTag:r}=t.limits;if(null!=e&&("number"!=typeof e||!Number.isInteger(e)||e<1))throw new Rt(`'limits.maxNestedTags' must be a positive integer, got ${e}`,Vt.INVALID_INPUT);if(null!=r&&("number"!=typeof r||!Number.isInteger(r)||r<0))throw new Rt(`'limits.maxAttributesPerTag' must be a non-negative integer, got ${r}`,Vt.INVALID_INPUT)}const e=ne(Zt);if(t&&ie(e,t),e.OutputBuilder||(e.OutputBuilder=new Mt),Array.isArray(e.tags?.stopNodes)){const t=new B;e.tags.stopNodes=e.tags.stopNodes.map(e=>se(e,"stopNodes",t)),t.seal(),e.tags.stopNodesSet=t}if(Array.isArray(e.skip?.tags)){const t=new B;e.skip.tags=e.skip.tags.map(e=>se(e,"skip.tags",t)),t.seal(),e.skip.tagsSet=t}if(null===e.onDangerousProperty&&(e.onDangerousProperty=Jt),null!==e.exitIf&&void 0!==e.exitIf&&"function"!=typeof e.exitIf)throw new Rt("'exitIf' must be a function, got "+typeof e.exitIf,Vt.INVALID_INPUT);return e.autoClose=function(t,e){if(!t)return null;if("html"===t){const t=e.tags.unpaired||[],r=[...new Set([...t,...re])];return e.tags={...e.tags,unpaired:r},{onEof:"closeAll",onMismatch:"discard",collectErrors:!0}}return"string"==typeof t?{onEof:t,onMismatch:"throw",collectErrors:!1}:"object"==typeof t?{onEof:t.onEof||"throw",onMismatch:t.onMismatch||"throw",collectErrors:t.collectErrors||!1}:null}(e.autoClose,e),e},re=["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"];function se(t,e,r){let s,n,i;if("string"==typeof t){if(0===t.length)throw new Rt(`${e} expression cannot be empty`,Vt.INVALID_INPUT);s=t,n=!1,i=[]}else if(t instanceof A)s=t.toString(),n=t.data?.nested??!1,i=t.data?.skipEnclosures??[];else{if(!t||"object"!=typeof t||void 0===t.expression)throw new Rt(`Invalid ${e} entry: expected a string, Expression, or { expression, nested?, skipEnclosures? } object.`,Vt.INVALID_INPUT);{const r=t.expression;if("string"==typeof r){if(0===r.length)throw new Rt(`${e} expression cannot be empty`,Vt.INVALID_INPUT);s=r}else{if(!(r instanceof A))throw new Rt(`${e} expression must be a string or Expression instance`,Vt.INVALID_INPUT);s=r.toString()}n=!0===t.nested,i=Array.isArray(t.skipEnclosures)?t.skipEnclosures:[]}}const o=new A(s,{},{nested:n,skipEnclosures:i});return r.add(o),o}function ne(t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map(ne);if(t instanceof RegExp)return t;if(t instanceof A)return t;const e={};for(const r of Object.keys(t))e[r]="function"==typeof t[r]?t[r]:ne(t[r]);return e}function ie(t,e){for(const r of Object.keys(e))"__proto__"!==r&&"constructor"!==r&&"prototype"!==r&&("OutputBuilder"===r||"function"==typeof e[r]||e[r]instanceof RegExp||Array.isArray(e[r])?t[r]=e[r]:"object"==typeof e[r]&&null!==e[r]?("object"==typeof t[r]&&null!==t[r]||(t[r]={}),ie(t[r],e[r])):t[r]=e[r])}function oe(){const t=this.buffer,e=t.length,r=this.startIndex,s=this._quotePairs,n=s.length;let i=0,o=!1,a=!1;for(let l=r;l<e;l++){const e=t[l];if("'"===e)a||(o=!o,i<n&&(s[i++]=l-r));else if('"'===e)o||(a=!a,i<n&&(s[i++]=l-r));else if(">"===e&&!o&&!a)return this._quotePairsLen=i,l-r}return this._quotePairsLen=i,-1}function ae(){const t=this.buffer,e=t.length,r=this.startIndex;let s=!1,n=!1;for(let i=r;i<e;i++){const e=t[i];if("'"===e)n||(s=!s);else if('"'===e)s||(n=!n);else if(">"===e&&!s&&!n)return i-r}return-1}class le{constructor(t,e={}){this.buffer=t,this.startIndex=0,this._baseOffset=0,this.autoFlush=!1!==e.autoFlush,this.flushThreshold=e.flushThreshold??1024,this._marks=[-1,-1],this._quotePairs=new Int32Array(128),this._quotePairsLen=0}markTokenStart(t=0){this._marks[t]=this.startIndex}rewindToMark(){}clearMark(){this._marks[0]=-1,this._marks[1]=-1}flush(){let t=this.startIndex;for(const e of this._marks)e>=0&&e<t&&(t=e);if(t>0){this.buffer=this.buffer.substring(t);const e=this._marks.length;for(let r=0;r<e;r++)this._marks[r]>=0&&(this._marks[r]-=t);this.startIndex-=t,this._baseOffset+=t}}readCh(){return this.buffer[this.startIndex++]}readChAt(t){return this.buffer[this.startIndex+t]}readStr(t,e){return void 0===e&&(e=this.startIndex),this.buffer.substring(e,e+t)}matchAhead(t,e=!1){const r=t.length;for(let s=0;s<r;s++){let r=this.buffer[this.startIndex+s];if(void 0===r)return null;if(e&&(r=r.toLowerCase()),r!==t[s])return!1}return!0}scanTagExpEnd=oe;scanTagExpEndFast=ae;readUpto(t){const e=this.buffer.length,r=t.length;for(let s=this.startIndex;s<e;s++){let e=!0;for(let n=0;n<r;n++)if(this.buffer[s+n]!==t[n]){e=!1;break}if(e){const t=this.buffer.substring(this.startIndex,s);return this.startIndex=s+r,t}}throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END)}readUptoChar(t){const e=this.buffer.indexOf(t,this.startIndex);if(-1===e)throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END);const r=this.buffer.substring(this.startIndex,e);return this.startIndex=e+1,r}readUptoCloseTag(t){const e=this.buffer.length,r=t.length;let s=-1,n=0;for(let i=this.startIndex;i<e;i++){if(1===n){const t=this.buffer[i];if(jt(t))continue;">"===t?n=2:(n=0,s=-1)}else{let e=!0;for(let s=0;s<r;s++)if(this.buffer[i+s]!==t[s]){e=!1;break}e&&(n=1,s=i,i+=r-1)}if(2===n){const t=this.buffer.substring(this.startIndex,s);return this.startIndex=i+1,t}}throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END)}readFromBuffer(t,e){const r=1===t?this.buffer[this.startIndex]:this.buffer.substring(this.startIndex,this.startIndex+t);return e&&this.updateBufferBoundary(t),r}updateBufferBoundary(t=1){this.startIndex+=t,this.autoFlush&&this.startIndex>=this.flushThreshold&&this.flush()}canRead(t=0){return this.startIndex+t<this.buffer.length}}function ce(t,e="utf8",r=()=>!1){return{readCh(){const{char:e,width:r}=t(this.buffer,this.startIndex);return this.startIndex+=r,e},readChAt(e){return t(this.buffer,this.startIndex+e).char},readStr(t,r){return void 0===r&&(r=this.startIndex),this.buffer.slice(r,r+t).toString(e)},matchAhead(t,e=!1){const r=t.length;for(let s=0;s<r;s++){const r=this.buffer[this.startIndex+s];if(void 0===r)return null;let n=r;if(e&&n>=65&&n<=90&&(n+=32),n!==t.charCodeAt(s))return!1}return!0},scanTagExpEnd(){const t=this.buffer,e=t.length,r=this.startIndex,s=this._quotePairs,n=s.length;let i=0,o=!1,a=!1;for(let l=r;l<e;l++){const e=t[l];if(39===e)a||(o=!o,i<n&&(s[i++]=l-r));else if(34===e)o||(a=!a,i<n&&(s[i++]=l-r));else if(62===e&&!o&&!a)return this._quotePairsLen=i,l-r}return this._quotePairsLen=i,-1},scanTagExpEndFast(){const t=this.buffer,e=t.length,r=this.startIndex;let s=!1,n=!1;for(let i=r;i<e;i++){const e=t[i];if(39===e)n||(s=!s);else if(34===e)s||(n=!n);else if(62===e&&!s&&!n)return i-r}return-1},readUpto(t){const r=this.buffer.length,s=t.length,n=Buffer.from(t);for(let t=this.startIndex;t<r;t++){let r=!0;for(let e=0;e<s;e++)if(this.buffer[t+e]!==n[e]){r=!1;break}if(r){const r=this.buffer.slice(this.startIndex,t).toString(e);return this.startIndex=t+s,r}}throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END)},readUptoChar(t){const r=t.charCodeAt(0),s=this.buffer,n=s.length;for(let t=this.startIndex;t<n;t++)if(s[t]===r){const r=s.slice(this.startIndex,t).toString(e);return this.startIndex=t+1,r}throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END)},readUptoCloseTag(t){const r=this.buffer.length,s=t.length,n=Buffer.from(t);let i=-1,o=0;for(let t=this.startIndex;t<r;t++){const r=this.buffer[t];if(1===o){if(Xt(r))continue;62===r?o=2:(o=0,i=-1)}else{let e=!0;for(let r=0;r<s;r++)if(this.buffer[t+r]!==n[r]){e=!1;break}e&&(o=1,i=t,t+=s-1)}if(2===o){const r=this.buffer.slice(this.startIndex,i).toString(e);return this.startIndex=t+1,r}}throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END)},readFromBuffer(r,s){if(1===r){const{char:e,width:r}=t(this.buffer,this.startIndex);return s&&this.updateBufferBoundary(r),e}const n=this.buffer.slice(this.startIndex,this.startIndex+r).toString(e);return s&&this.updateBufferBoundary(r),n},updateBufferBoundary(t=1){this.startIndex+=t,this.autoFlush&&this.startIndex>=this.flushThreshold&&this._tokenStart<0&&this.flush()},canRead(t=0){return this.startIndex+t<this.buffer.length}}}function he(t,e){return{char:String.fromCharCode(t[e]),width:1}}function de(t,e){const r=t[e];let s=1;return 128&r?192==(224&r)?s=2:224==(240&r)?s=3:240==(248&r)&&(s=4):s=1,e+s>t.length&&(s=t.length-e),{char:t.toString("utf8",e,e+s),width:s}}const ue=ce(de,"utf8");class pe{constructor(t,e={},r=null){if(this.buffer=r?.bomLength?t.subarray(r.bomLength):t,r?.decodeFirst){const t=r.descriptor.createDecoder();this.buffer=t.write(this.buffer)+t.end()}this.startIndex=0,this._baseOffset=0,this.autoFlush=!1!==e.autoFlush,this.flushThreshold=e.flushThreshold??1024,this._tokenStart=-1,this._quotePairs=new Int32Array(128),this._quotePairsLen=0;const s=r?.scanStrategy??ue;Object.assign(this,s),this.encodingName=r?.descriptor?.name??"utf8",this._quotePairsUsable=!!r&&!1!==r.quotePairsUsable}markTokenStart(){this._tokenStart=this.startIndex}rewindToMark(){}flush(){const t=this._tokenStart>=0?this._tokenStart:this.startIndex;t>0&&(this.buffer=Buffer.from(this.buffer.subarray(t)),this._tokenStart>=0?(this.startIndex-=t,this._tokenStart=0):this.startIndex=0,this._baseOffset+=t)}}function fe(t,e){const r=function(t,e){for(const r of e.bomCandidates()){const e=r.bomBytes;if(t.length>=e.length&&e.equals(t.subarray(0,e.length)))return{descriptor:r,bomLength:e.length}}return null}(t,e),s=function(t,e){const r=t.subarray(e,Math.min(t.length,e+200)).toString("latin1").match(/^\s*<\?xml\s+[^?]*\?>/);if(!r)return null;const s=r[0].match(/encoding\s*=\s*["']([^"']+)["']/i);return s?s[1].toLowerCase():null}(t,r?r.bomLength:0);if(r&&s&&!function(t,e,r){try{return r.resolve(t).name===r.resolve(e).name}catch{return!1}}(r.descriptor.name,s,e))throw new Rt(`Byte-order mark indicates "${r.descriptor.name}" but the XML declaration says encoding="${s}"`,Vt.ENCODING_MISMATCH);return r?{encoding:r.descriptor.name,bomLength:r.bomLength,declaredEncoding:s}:s?{encoding:s,bomLength:0,declaredEncoding:s}:{encoding:"utf8",bomLength:0,declaredEncoding:null}}function ge(t){const e=new TextDecoder(t,{fatal:!1,ignoreBOM:!0});return{write:t=>e.decode(t,{stream:!0}),end:()=>e.decode()}}class me{constructor(){this._byName=new Map,this._seedDefaults()}_seedDefaults(){this.register({name:"utf8",aliases:["utf-8"],bomBytes:Buffer.from([239,187,191]),selfSynchronizing:!0,variableWidth:!0,createDecoder:()=>ge("utf-8")}),this.register({name:"ascii",aliases:[],bomBytes:null,selfSynchronizing:!0,variableWidth:!1,createDecoder:()=>ge("windows-1252")}),this.register({name:"latin1",aliases:["iso-8859-1","binary"],bomBytes:null,selfSynchronizing:!0,variableWidth:!1,createDecoder:()=>ge("iso-8859-1")}),this.register({name:"utf16le",aliases:["utf-16le","ucs2","ucs-2"],bomBytes:Buffer.from([255,254]),selfSynchronizing:!1,variableWidth:!0,createDecoder:()=>ge("utf-16le")}),this.register({name:"utf16be",aliases:["utf-16be"],bomBytes:Buffer.from([254,255]),selfSynchronizing:!1,variableWidth:!0,createDecoder:()=>function(){const t=ge("utf-16le");let e=null;return{write(r){let s=e?function(t,e){const r=new Uint8Array(t.length+e.length);return r.set(t,0),r.set(e,t.length),r}(e,r):r;e=null,s.length%2==1&&(e=s.subarray(s.length-1),s=s.subarray(0,s.length-1));const n=function(t){const e=new Uint8Array(t);for(let t=0;t+1<e.length;t+=2){const r=e[t];e[t]=e[t+1],e[t+1]=r}return e}(s);return t.write(n)},end:()=>t.end()}}()})}register(t){if(!t||"string"!=typeof t.name||!t.name)throw new Rt('Encoding descriptor requires a non-empty "name"',Vt.INVALID_DECODER);if("function"!=typeof t.createDecoder)throw new Rt(`Encoding "${t.name}" is missing createDecoder()`,Vt.INVALID_DECODER);const e=t.createDecoder();if(!e||"function"!=typeof e.write||"function"!=typeof e.end)throw new Rt(`Encoding "${t.name}"'s createDecoder() must return an object with write()/end()`,Vt.INVALID_DECODER);const r={selfSynchronizing:!1,variableWidth:!0,aliases:[],bomBytes:null,...t};this._byName.set(r.name.toLowerCase(),r);for(const t of r.aliases)this._byName.set(t.toLowerCase(),r)}resolve(t){const e=this._byName.get(String(t).toLowerCase());if(!e)throw new Rt(`Unsupported encoding "${t}"`,Vt.UNSUPPORTED_ENCODING);return e}bomCandidates(){const t=new Set,e=[];for(const r of this._byName.values())r.bomBytes&&!t.has(r.name)&&(t.add(r.name),e.push(r));return e.sort((t,e)=>e.bomBytes.length-t.bomBytes.length)}}const _e=new me;function Ee(t){return t<=8||11===t||12===t||t>=14&&t<=31}function be(t,e,r,s){let n="",i=e;for(;e<r;e++){const r=t.charCodeAt(e);if(13===r)n+=t.substring(i,e)+" ",10===t.charCodeAt(e+1)&&e++,i=e+1;else if(10===r||9===r)n+=t.substring(i,e)+" ",i=e+1;else if(Ee(r))throw new Rt(`Illegal control character 0x${r.toString(16).padStart(2,"0")} in attribute value`,Vt.ILLEGAL_CHARACTER,s?zt(s.source):{})}return n+=t.substring(i,e),n}function xe(t,e,r,s){if(!t||0===t.length)return;const n=e.options.limits?.maxAttributesPerTag;if(null!=n&&s>n){const t=e.currentTagDetail?.name??"(unknown)";throw new Rt(`Tag '${t}' has ${s} attributes, exceeding limit of ${n}`,Vt.LIMIT_MAX_ATTRIBUTES,zt(e.source))}const i=t.length;for(let s=0;s<i;s++){const n=t[s],i=void 0!==r?{index:r+n.index}:void 0;e.outputBuilder.addAttribute(n.name,n.value,e.readonlyMatcher,i)}}class Te{constructor(){this.tagName="",this.selfClosing=!1,this.rawAttributes={},this._attrsExp="",this._attrsExpStart=void 0,this._rawAttrMatchCount=0,this._parsedAttrs=[]}}function ye(t){t.source.markTokenStart(1);const e=Yt(t.source),r=!t.options.skip.attributes,s=r?t.source.scanTagExpEnd():t.source.scanTagExpEndFast();if(-1===s)throw new Rt("Unexpected closing of source waiting for '>'",Vt.UNEXPECTED_END);const n=t.source.readStr(s);t.source.updateBufferBoundary(s+1);const i=r&&!1!==t.source._quotePairsUsable;return we(n,t,e,!1,i?t.source._quotePairs:void 0,i?t.source._quotePairsLen:0)}function we(t,e,r,s=!1,n=void 0,i=0){const o=new Te;"/"===t[t.length-1]&&(o.selfClosing=!0,t=t.slice(0,-1));let a,l="",c=0;for(;c<t.length;c++)if(jt(t[c])){o.tagName=t.substring(0,c),l=t.substring(c+1),a=c+1,void 0!==r&&(o._attrsExpStart=r+c+1);break}if(0===o.tagName.length&&c===t.length&&(o.tagName=t),o.tagName=o.tagName.trimEnd(),o._attrsExp=l,!e.isValidQName(o.tagName))throw new Rt("Invalid tag name",Vt.INVALID_TAG_NAME);return(s||l.length>0)&&function(t,e,r,s,n,i){if(!t||0===t.length)return;const o=function(t,e,r,s=0,n){const i=[],o=t.length;let a=0;const l=void 0!==e&&s>0;let c=0;for(;a<o;){for(;a<o&&Xt(t.charCodeAt(a));)a++;if(a>=o)break;const h=a;for(;a<o&&61!==t.charCodeAt(a)&&!Xt(t.charCodeAt(a));)a++;const d=t.substring(h,a);for(;a<o&&Xt(t.charCodeAt(a));)a++;if(a>=o||61!==t.charCodeAt(a)){i.push({name:d,value:void 0,startIndex:h});continue}for(a++;a<o&&Xt(t.charCodeAt(a));)a++;const u=t.charCodeAt(a);if(34!==u&&39!==u)throw new Rt(`Attribute '${d}' has an unquoted value — attribute values must be wrapped in '"' or "'"`,Vt.UNQUOTED_ATTRIBUTE_VALUE,n?zt(n.source):{});let p,f=-1;if(l&&c+1<s&&e[c]===a+r&&(f=e[c+1]-r,c+=2),a++,f>=0)p=f;else for(p=a;p<o&&t.charCodeAt(p)!==u;)p++;const g=be(t,a,p,n);a=p+1,i.push({name:d,value:g,startIndex:h})}return i}(t,s,n,i,e),a=o.length;r._rawAttrMatchCount=a;const l=[];let c=0;const h=e.options.attributes?.duplicate||"overwrite",d="overwrite"!==h?new Set:null,u=e.options.attributes?.booleanType||"allow";for(let t=0;t<a;t++){const s=o[t];if(d){if(d.has(s.name)){if("throw"===h)throw new Rt(`Duplicate attribute '${s.name}'`,Vt.DUPLICATE_ATTRIBUTE,zt(e.source));continue}d.add(s.name)}const n=s.value;if(void 0===n){if("throw"===u)throw new Rt(`Valueless attribute '${s.name}' is not allowed`,Vt.BOOLEAN_ATTRIBUTE_REJECTED,zt(e.source));if("ignore"===u)continue}const i=e.processAttrName(s.name);if(!1===i)continue;c++;const a=void 0===n||n;r.rawAttributes[s.name]=a,l.push({name:i,value:a,index:s.startIndex})}r.rawAttributesLen=c,r._parsedAttrs=l}(l,e,o,n,a,i),o}class Ie{constructor(t,{nested:e=!1,skipEnclosures:r=[]}={}){this._tagName=t,this._nested=e,this._enclosures=r,this._content="",this._depth=1,this._active=!1}isActive(){return this._active}activate(){this._active=!0,this._content="",this._depth=1}resumeAfterOpenTag(){this._content="",this._depth=1}collect(t){t.markTokenStart(1);const e=this._enclosures.length;return this._nested||0!==e?this._nested&&0===e?this._collectDepthOnly(t):!this._nested&&e>0?this._collectEnclosureOnly(t):this._collectFull(t):this._collectPlain(t)}_collectPlain(t){for(;t.canRead();)if("<"===t.readChAt(0)){if(this._tryConsumeCloseTag(t))return this._finish(t);this._content+=t.readCh()}else this._content+=t.readCh();throw this._unclosedError()}_collectDepthOnly(t){for(;this._depth>0;)if(Qt(t,0,`stop node <${this._tagName}> content`),this._stepDepthTracking(t))return this._finish(t);throw this._unclosedError()}_collectEnclosureOnly(t){for(;t.canRead();)if(!this._trySkipEnclosure(t))if("<"===t.readChAt(0)){if(this._tryConsumeCloseTag(t))return this._finish(t);this._content+=t.readCh()}else this._content+=t.readCh();throw this._unclosedError()}_collectFull(t){for(;this._depth>0;)if(Qt(t,0,`stop node <${this._tagName}> content`),!this._trySkipEnclosure(t)&&this._stepDepthTracking(t))return this._finish(t);throw this._unclosedError()}_finish(t){const e=this._content,r={index:Yt(t)};return this._active=!1,this._content="",this._depth=1,{content:e,end:r}}_trySkipEnclosure(t){const e=this._matchEnclosureOpen(t);if(-1===e)return!1;const r=this._enclosures[e];this._skipChars(t,r.open.length),this._content+=r.open;const s=this._readUpto(t,r.close);return this._content+=s+r.close,!0}_tryConsumeCloseTag(t){const e="</"+this._tagName;if(!this._peekMatch(t,e))return!1;let r=e.length,s=!1;for(;;){const e=t.readChAt(r);if(">"===e){s=!0;break}if(!jt(e))break;r++}if(!s)return!1;for(this._skipChars(t,e.length);t.canRead()&&">"!==t.readCh(););return!0}_stepDepthTracking(t){if("<"!==t.readChAt(0))return this._content+=t.readCh(),!1;if(t.readCh(),Qt(t,0,`stop node <${this._tagName}> tag after '<'`),"/"===t.readChAt(0)){t.readCh();const e=this._readTagName(t),r=this._readToAngleClose(t);return e===this._tagName&&(this._depth--,0===this._depth)||(this._content+="</"+e+r,!1)}const e=this._readTagName(t);this._content+="<"+e;const{selfClosing:r,attrText:s}=this._readTagTail(t);return this._content+=s,r||e!==this._tagName||this._depth++,!1}_unclosedError(){return new Rt(`Unclosed stop node <${this._tagName}> — unexpected end of input`,Vt.UNEXPECTED_END)}_matchEnclosureOpen(t){const e=this._enclosures.length;for(let r=0;r<e;r++)if(this._peekMatch(t,this._enclosures[r].open))return r;return-1}_readUpto(t,e){const r=e[0],s=e.length,n=t.startIndex;let i=0;for(;t.canRead();){if(t.readChAt(0)===r&&this._peekMatch(t,e)){const e=t.readStr(i,n);return this._skipChars(t,s),e}t.readCh(),i++}throw new Rt(`Unclosed stop node <${this._tagName}> — unexpected end looking for '${e}'`,Vt.UNEXPECTED_END)}_peekMatch(t,e){const r=e.length;for(let s=0;s<r;s++)if(t.readChAt(s)!==e[s])return!1;return!0}_skipChars(t,e){for(let r=0;r<e;r++)t.readCh()}_readTagName(t){let e="";for(;t.canRead();){const r=t.readChAt(0);if(">"===r||"/"===r||jt(r))break;e+=t.readCh()}return e}_readTagTail(t){const e=t.startIndex;let r=0,s=!1,n=!1;for(;t.canRead();){const i=t.readCh();if(r++,"'"!==i||n)if('"'!==i||s){if(!s&&!n){if(">"===i)return{selfClosing:!1,attrText:t.readStr(r,e)};if("/"===i&&t.canRead()&&">"===t.readChAt(0))return t.readCh(),r++,{selfClosing:!0,attrText:t.readStr(r,e)}}}else n=!n;else s=!s}throw new Rt(`Unclosed stop node <${this._tagName}> — unexpected end inside tag`,Vt.UNEXPECTED_END)}_readToAngleClose(t){const e=t.startIndex;let r=0;for(;t.canRead();){const s=t.readCh();if(r++,">"===s)return t.readStr(r,e);if(!jt(s))throw new Rt(`Malformed closing tag for </${this._tagName}>`,Vt.UNEXPECTED_END)}throw new Rt(`Unclosed stop node <${this._tagName}> — unexpected end looking for '>'`,Vt.UNEXPECTED_END)}}function Ae(t){const e=t.options.skip;t.source.markTokenStart(1);let r=function(t){t.source.markTokenStart(1);const e=Yt(t.source);let r,s=!1,n=!1,i=!1;for(r=0;t.source.canRead(r);r++){const e=t.source.readChAt(r),o=t.source.readChAt(r+1);if("'"!==e||n?'"'!==e||s||(n=!n):s=!s,!s&&!n&&"?"===e&&">"===o){i=!0;break}}if(!i)throw new Rt("Unexpected closing of source waiting for '?>'",Vt.UNEXPECTED_END);if(s||n)throw new Rt("Invalid attribute expression. Quote is not properly closed in PI tag expression",Vt.UNCLOSED_QUOTE);const o=t.source.readStr(r);return t.source.updateBufferBoundary(r+2),we(o,t,e,!0)}(t);if(!r)throw new Rt("Invalid Pi Tag expression.",Vt.INVALID_TAG,zt(t.source));if("xml"===r.tagName){const e=r.rawAttributes?.version;"1.1"===e&&(t.xmlDec.version=1.1),t.xmlDec.encoding=r.rawAttributes?.encoding,t.xmlDec.standalone=r.rawAttributes?.standalone,t._nameValidators={}}e.attributes||xe(r._parsedAttrs,t,r._attrsExpStart,r._rawAttrMatchCount),"xml"===r.tagName?e.declaration||t.outputBuilder.addDeclaration("?xml",t.xmlDec):e.pi||t.outputBuilder.addInstruction("?"+r.tagName)}function Ne(t){const e=t.source;Oe(e),Qt(e,1,"entity name");const r=e.startIndex;let s=0;for(;e.canRead();){const t=e.readCh();if(jt(t)||'"'===t||"'"===t)break;s++}const n=e.readStr(s,r);if(Qt(e,1,`entity name "${n}"`),ke(n,t),Oe(e),Qt(e,0,`after entity name "${n}"`),e.canRead(5)&&!0===e.matchAhead("system",!0))throw new Rt("External entities are not supported",Vt.INVALID_TAG,zt(e));if("%"===e.readStr(1))throw new Rt("Parameter entities are not supported",Vt.INVALID_TAG,zt(e));Qt(e,0,`entity value for "${n}"`);const[i]=De(e,"entity"),o=t.options?.doctypeOptions;if(o?.maxEntitySize&&i.length>o.maxEntitySize)throw new Rt(`Entity "${n}" size (${i.length}) exceeds maximum allowed size (${o.maxEntitySize})`,Vt.ENTITY_MAX_SIZE,zt(e));return e.readUptoChar(">"),[n,i]}function ve(t){const e=t.source;Oe(e),Qt(e,1,"ELEMENT name");const r=e.startIndex;let s=0;for(;e.canRead()&&!jt(e.readCh());)s++;const n=e.readStr(s,r);if(Qt(e,1,"ELEMENT name"),!t.getNameValidator("name")(n))throw new Rt(`Invalid element name: "${n}"`,Vt.INVALID_TAG,zt(e));Oe(e),Qt(e,1,"ELEMENT name");let i=e.readStr(1);if("E"===i)try{Wt(e,"EMPTY","ELEMENT content model keyword EMPTY")}catch(t){return e.readUptoChar(">"),{elementName:n,contentModel:""}}else if("A"===i)try{Wt(e,"ANY","ELEMENT content model keyword ANY")}catch(t){return e.readUptoChar(">"),{elementName:n,contentModel:""}}else"("===i&&(e.updateBufferBoundary(1),e.readUptoChar(")"));return e.readUptoChar(">"),{elementName:n}}function Se(t){t.source.readUptoChar(">")}function Ce(t){const e=t.source;Oe(e),Qt(e,1,"NOTATION name");const r=e.startIndex;let s=0;for(;e.canRead()&&!jt(e.readCh());)s++;const n=e.readStr(s,r);if(Qt(e,1,`after NOTATION name "${n}"`),ke(n,t),Oe(e),Qt(e,6,"NOTATION identifier type"),!0===e.matchAhead("system",!0))e.updateBufferBoundary(6),Oe(e),De(e,"systemIdentifier");else{if(!0!==e.matchAhead("public",!0))throw new Rt(`Expected SYSTEM or PUBLIC in NOTATION, found "${e.readStr(6)}"`,Vt.INVALID_TAG,zt(e));{e.updateBufferBoundary(6),Oe(e),De(e,"publicIdentifier"),Oe(e),Qt(e,1,"after NOTATION PUBLIC identifier");let t=e.readStr(1);'"'!==t&&"'"!==t||De(e,"systemIdentifier")}}e.readUptoChar(">")}function De(t,e){Qt(t,1,e+" opening quote");let r=t.readStr(1);if('"'!==r&&"'"!==r)throw new Rt(`Expected quoted string for ${e}, found "${r}"`,Vt.INVALID_TAG,zt(t));return t.updateBufferBoundary(1),[t.readUptoChar(r)]}function Oe(t){for(;t.canRead()&&jt(t.readChAt(0));)t.updateBufferBoundary(1)}function ke(t,e){if(e.getNameValidator("name")(t))return t;throw new Rt(`Invalid entity name "${t}"`,Vt.ENTITY_INVALID_KEY,{})}const Pe=Object.freeze({UNCLOSED_EOF:"unclosed-eof",MISMATCHED_CLOSE:"mismatched-close",PHANTOM_CLOSE:"phantom-close",PARTIAL_TAG:"partial-tag"});class Le{constructor(t){this.onEof=t.onEof||"throw",this.onMismatch=t.onMismatch||"throw",this.collectErrors=t.collectErrors||!1,this.errors=[]}handleEof(t){if("throw"===this.onEof)throw new Rt("Unexpected data in the end of document",Vt.UNEXPECTED_TRAILING_DATA);const{addTextNode:e,popTag:r}=t;let s=t.currentTagDetail;for(;s&&!s.root;)this._recordError(Pe.UNCLOSED_EOF,{tag:s.name,expected:null,index:s.index}),e(),r(),s=t.currentTagDetail}handleMismatch(t,e){const{tagsStack:r,currentTagDetail:s,source:n,addTextNode:i}=e;if("throw"===this.onMismatch)throw new Rt(`Unexpected closing tag '${t}' expecting '${s.name}'`,Vt.MISMATCHED_CLOSE_TAG,{index:n?Yt(n):void 0});if("discard"===this.onMismatch)return this._recordError(Pe.MISMATCHED_CLOSE,{tag:t,expected:s.name,index:n?Yt(n):null}),{action:"discard"};const o=[...r,s];let a=-1;const l=o.length;for(let e=l-1;e>=0;e--)if(o[e].name===t){a=e;break}if(-1===a)return this._recordError(Pe.PHANTOM_CLOSE,{tag:t,expected:s.name,index:n?Yt(n):null}),{action:"discard"};const c=l-1-a;for(let r=0;r<c;r++){const s=o[l-1-r];this._recordError(Pe.MISMATCHED_CLOSE,{tag:s.name,expected:t,index:s.index}),i(),e.popTag()}return e.currentTagDetail=o[a],{action:"close-matched"}}handlePartialTag(t,e){this._recordError(Pe.PARTIAL_TAG,{tag:Ue(t),expected:null,index:e.source?Yt(e.source):null}),e.tagTextData="",this.handleEof(e)}getErrors(){return this.errors.slice()}reset(){this.errors=[]}_recordError(t,e){this.collectErrors&&this.errors.push({type:t,...e})}}function Ue(t){if(!t)return null;const e=("string"==typeof t.message?t.message:String(t)).match(/[Rr]eading closing tag '<\/([^']*)/);return e&&e[1]||null}const Me={keep:["xml:space"]};function $e(t,e,r){const s=t.get(e);if(void 0!==s||t.has(e))return s;const n=r();return t.size>=2e3&&t.clear(),t.set(e,n),n}class Be{constructor(t,e=0,r=void 0,s=void 0){this.name=t,this.index=e,this.openEnd=r,this.rawName=s}}class Re{constructor(t){this.options=t,this.currentTagDetail=null,this.tagTextData="",this.tagsStack=[],this.doctypeFound=!1,this.matcher=new v,this.readonlyMatcher=this.matcher.readOnly(),this.autoCloseHandler=t.autoClose?new Le(t.autoClose):null,this._unpairedSet=new Set(this.options.tags.unpaired),this.stopNodeExpressionsSet=this.options.tags.stopNodesSet??new B,0===this.stopNodeExpressionsSet.size?this.isStopNode=()=>!1:this.isStopNode=Xe,this.skipTagExpressionsSet=this.options.skip.tagsSet??new B,0===this.skipTagExpressionsSet.size?this.isSkipTag=()=>!1:this.isSkipTag=qe,this._exitIf="function"==typeof t.exitIf?t.exitIf:()=>!1,this._nameCache=t._nameCache||(t._nameCache={tags:new Map,attrs:new Map})}initializeParser(){this.tagTextData="",this.tagsStack=[],this.doctypeFound=!1,this._stopNodeProcessor=null,this._exitIfTriggered=!1,this._nameValidators={},this._validQNames=new Set,this.xmlDec={version:1,lang:null,encoding:null,standalone:"yes"},this.matcher||(this.matcher=new v,this.readonlyMatcher=this.matcher.readOnly()),this.outputBuilder=this._createOutputBuilder(),this.root={root:!0,name:""},this.currentTagDetail=this.root}_createOutputBuilder(){return this.options.OutputBuilder.getInstance(this.options,this.readonlyMatcher)}wasExited(){return!0===this._exitIfTriggered}parse(t){return this.source=new le(t),this.initializeParser(),this._parseAndFinalize(),this.outputBuilder.getOutput()}parseBytesArr(t){const e=this.options.decoding?._registry,r=function(t,e={},r=_e){const s=e.encoding||"auto";let n,i;if("auto"===s){const e=fe(t,r);n=e.encoding,i=e.bomLength}else n=s,i=0;const o=r.resolve(n),a=o.selfSynchronizing?ce("utf8"===o.name?de:he,o.name):{readCh(){return this.buffer[this.startIndex++]},readChAt(t){return this.buffer[this.startIndex+t]},readStr(t,e){return void 0===e&&(e=this.startIndex),this.buffer.substring(e,e+t)},matchAhead(t,e=!1){const r=t.length;for(let s=0;s<r;s++){let r=this.buffer[this.startIndex+s];if(void 0===r)return null;if(e&&(r=r.toLowerCase()),r!==t[s])return!1}return!0},scanTagExpEnd:oe,scanTagExpEndFast:ae,readUpto(t){const e=this.buffer.length,r=t.length;for(let s=this.startIndex;s<e;s++){let e=!0;for(let n=0;n<r;n++)if(this.buffer[s+n]!==t[n]){e=!1;break}if(e){const t=this.buffer.substring(this.startIndex,s);return this.startIndex=s+r,t}}throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END)},readUptoChar(t){const e=this.buffer.indexOf(t,this.startIndex);if(-1===e)throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END);const r=this.buffer.substring(this.startIndex,e);return this.startIndex=e+1,r},readUptoCloseTag(t){const e=this.buffer.length,r=t.length;let s=-1,n=0;for(let i=this.startIndex;i<e;i++){if(1===n){const t=this.buffer[i];if(jt(t))continue;">"===t?n=2:(n=0,s=-1)}else{let e=!0;for(let s=0;s<r;s++)if(this.buffer[i+s]!==t[s]){e=!1;break}e&&(n=1,s=i,i+=r-1)}if(2===n){const t=this.buffer.substring(this.startIndex,s);return this.startIndex=i+1,t}}throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END)},readFromBuffer(t,e){const r=1===t?this.buffer[this.startIndex]:this.buffer.substring(this.startIndex,this.startIndex+t);return e&&this.updateBufferBoundary(t),r},updateBufferBoundary(t=1){this.startIndex+=t,this.autoFlush&&this.startIndex>=this.flushThreshold&&this._tokenStart<0&&this.flush()},canRead(t=0){return this.startIndex+t<this.buffer.length}},l=!o.selfSynchronizing||"utf8"!==o.name;return{descriptor:o,bomLength:i,scanStrategy:a,decodeFirst:!o.selfSynchronizing,quotePairsUsable:l}}(t,this.options.decoding,e);return this.source=new pe(t,{},r),this.initializeParser(),this._parseAndFinalize(),this.outputBuilder.getOutput()}parseXml(){for(;this.source.canRead()&&!this._exitIfTriggered;){this.source.markTokenStart(0);const t=zt(this.source),e=this.source.readCh();if(void 0===e||""===e)break;if("<"===e){const e=t,r=this.source.readChAt(0);if(""===r)throw new Rt("Unexpected end of source after '<'",Vt.UNEXPECTED_END,zt(this.source));"/"===r?(this.source.updateBufferBoundary(),this.readClosingTag(e)):"!"===r?(this.source.updateBufferBoundary(),this.addTextNode(),this.readSpecialTag(r)):"?"===r?(this.source.updateBufferBoundary(),this.addTextNode(),Ae(this)):this.readOpeningTag(e)}else{let t=0;for(;;){const e=this.source.readChAt(t);if("<"===e||void 0===e||""===e)break;t++}t>0?(this.tagTextData+=e+this.source.readStr(t,this.source.startIndex),this.source.updateBufferBoundary(t)):this.tagTextData+=e}}}finalizeXml(){if(this._exitIfTriggered)return;const t=this.tagsStack.length>0||this.currentTagDetail&&!this.currentTagDetail.root,e=!t&&void 0!==this.tagTextData&&this.tagTextData.trimEnd().length>0;if(t||e){if(!this.autoCloseHandler||!t||e)throw new Rt("Unexpected data in the end of document",Vt.UNEXPECTED_TRAILING_DATA,zt(this.source));this.autoCloseHandler.handleEof(this._parserState())}}_parseAndFinalize(){let t=null;this.autoCloseHandler&&this.autoCloseHandler.reset();try{this.parseXml()}catch(e){if(!this.autoCloseHandler||!function(t){return t instanceof Rt?t.code===Vt.UNEXPECTED_END:t.message.startsWith("Unexpected end of source")||t.message.startsWith("Unexpected closing of source")}(e))throw e;t=e}t?this.autoCloseHandler.handlePartialTag(t,this._parserState()):this.finalizeXml()}readClosingTag(t){const e=this.currentTagDetail;if(e&&!e.root&&void 0!==e.rawName){const r=function(t,e){if(!0!==t.matchAhead(e))return-1;let r=e.length,s=t.readChAt(r);if(">"===s)return r+1;for(;jt(s);)if(r++,s=t.readChAt(r),">"===s)return r+1;return">"!==s?-1:r+1}(this.source,e.rawName);if(-1!==r){this.source.updateBufferBoundary(r);const s={name:e.name,index:t.index,closeEnd:Yt(this.source)};return this.addTextNode(),void this.popTag(s)}}const r=this.processTagName(function(t){t.markTokenStart(1);const e=t.startIndex;try{return t.readUptoChar(">").trimEnd()}catch(r){const s=t.readStr(Number.MAX_SAFE_INTEGER,e);throw new Rt(`Unexpected end of source reading closing tag '</${s}'`,Vt.UNEXPECTED_END)}}(this.source)),s={name:r,index:t.index,closeEnd:Yt(this.source)};if(this.isUnpaired(r)||this.isStopNode())throw new Rt(`Unexpected closing tag '${r}'`,Vt.UNEXPECTED_CLOSE_TAG,zt(this.source));if(r!==this.currentTagDetail.name){if(!this.autoCloseHandler)throw new Rt(`Unexpected closing tag '${r}' expecting '${this.currentTagDetail.name}'`,Vt.MISMATCHED_CLOSE_TAG,zt(this.source));if("discard"===this.autoCloseHandler.handleMismatch(r,this._parserState()).action)return}this.currentTagDetail.root||this.addTextNode(),this.popTag(s)}readOpeningTag(t){const e=this.options;if(this.addTextNode(),this._stopNodeProcessor&&this._stopNodeProcessor.isActive()){const{tagDetail:t,isSkip:e}=this._stopNodeProcessorMeta;this._stopNodeProcessor.resumeAfterOpenTag(),ye(this),t.openEnd=Yt(this.source);const{content:r,end:s}=this._stopNodeProcessor.collect(this.source);return e||(this.outputBuilder.addElement(t,this.readonlyMatcher),this.outputBuilder.onStopNode?.(t,r,this.readonlyMatcher,s),this.outputBuilder.addValue(r,this.readonlyMatcher),this.outputBuilder.closeElement(this.readonlyMatcher,{name:t.name,closeEnd:s.index})),this.matcher.pop(),this._stopNodeProcessor=null,void(this._stopNodeProcessorMeta=null)}let r=ye(this);const s=this.processTagName(r.tagName),n=new Be(s,t.index,Yt(this.source),r.tagName),i=r.tagName.indexOf(":"),o=-1!==i?r.tagName.slice(0,i):void 0,a=void 0!==o?r.tagName.slice(i+1):s,l=e.limits?.maxNestedTags;if(null!=l){const t=this.tagsStack.length+1;if(t>l)throw new Rt(`Nesting depth ${t} exceeds limit of ${l} (tag: '${s}')`,Vt.LIMIT_MAX_NESTED_TAGS,{index:n.index})}let c={},h=0;r.rawAttributes&&(c=r.rawAttributes,h=r.rawAttributesLen),h>0?this.matcher.push(a,c,o,Me):this.matcher.push(a,{},o);const d=this.isStopNode(),u=d?null:this.isSkipTag();if(e.skip.attributes||u||xe(r._parsedAttrs,this,r._attrsExpStart,r._rawAttrMatchCount),this.isUnpaired(s))this.outputBuilder.addElement(n,this.readonlyMatcher),this.outputBuilder.closeElement(this.readonlyMatcher,this._closeMetaFor(n)),this.matcher.pop();else if(r.selfClosing)u||(this.outputBuilder.addElement(n,this.readonlyMatcher),this.outputBuilder.closeElement(this.readonlyMatcher,this._closeMetaFor(n))),this.matcher.pop();else if(d){this._stopNodeProcessor=new Ie(r.tagName,{nested:d.nested,skipEnclosures:d.skipEnclosures}),this._stopNodeProcessorMeta={tagDetail:n,isSkip:!1},this._stopNodeProcessor.activate();const{content:t,end:e}=this._stopNodeProcessor.collect(this.source);this.outputBuilder.addElement(n,this.readonlyMatcher),this.outputBuilder.onStopNode?.(n,t,this.readonlyMatcher,e),this.outputBuilder.addValue(t,this.readonlyMatcher),this.outputBuilder.closeElement(this.readonlyMatcher,{name:n.name,closeEnd:e.index}),this.matcher.pop(),this._stopNodeProcessor=null,this._stopNodeProcessorMeta=null}else if(u)this._stopNodeProcessor=new Ie(r.tagName,{nested:u.nested,skipEnclosures:u.skipEnclosures}),this._stopNodeProcessorMeta={tagDetail:n,isSkip:!0},this._stopNodeProcessor.activate(),this._stopNodeProcessor.collect(this.source),this.matcher.pop(),this._stopNodeProcessor=null,this._stopNodeProcessorMeta=null;else if(this._exitIf(this.readonlyMatcher)){const t=this.tagsStack.length;for(this.matcher.pop();this.currentTagDetail&&!this.currentTagDetail.root;)this.addTextNode(),this.popTag();"function"==typeof this.outputBuilder.onExit&&this.outputBuilder.onExit({tagDetail:n,matcher:this.readonlyMatcher,depth:t}),this._exitIfTriggered=!0}else this.pushTag(n)}pushTag(t){this.tagsStack.push(this.currentTagDetail),this.outputBuilder.addElement(t,this.readonlyMatcher),this.currentTagDetail=t}popTag(t){this.outputBuilder.closeElement(this.readonlyMatcher,t??{name:this.currentTagDetail?.name}),this.matcher.pop(),this.currentTagDetail=this.tagsStack.pop()}_closeMetaFor(t){return{name:t.name,index:t.index,closeEnd:t.openEnd}}readSpecialTag(t){if("!"!==t)throw new Rt(`Invalid tag '<${t}'`,Vt.INVALID_TAG,zt(this.source));{let t=this.source.readCh();if(null==t)throw new Rt("Unexpected end of source after '<!'",Vt.UNEXPECTED_END,zt(this.source));if("-"===t)!function(t){t.source.markTokenStart(1),Wt(t.source,"-","comment second dash");let e=t.source.readUpto("--\x3e");e=Ht(e,t.source),t.outputBuilder.addComment(e)}(this);else if("["===t)!function(t){t.source.markTokenStart(1),Wt(t.source,"CDATA[","CDATA preamble");let e=t.source.readUpto("]]>");e=Ht(e,t.source),t.outputBuilder.addLiteral(e)}(this);else if("D"===t){const t=function(t){t.source.markTokenStart(1),Wt(t.source,"OCTYPE","DOCTYPE preamble");const e={};let r=0,s=!1,n=!1;for(;t.source.canRead();){const i=t.source.startIndex;let o=t.source.readCh();if("<"===o&&s&&!n)try{Qt(t.source,0,"DOCTYPE sub-tag");let s=t.source.readStr(1);if(t.source.updateBufferBoundary(1),"!"!==s)throw new Rt(`Invalid DOCTYPE body tag starting with "<${s}"`,Vt.INVALID_TAG,zt(t.source));Qt(t.source,0,"DOCTYPE sub-tag type");let n=t.source.readStr(1);if(t.source.updateBufferBoundary(1),"-"===n){Qt(t.source,0,"DOCTYPE comment");let e=t.source.readStr(1);if(t.source.updateBufferBoundary(1),"-"!==e)throw new Rt("Invalid comment in DOCTYPE",Vt.INVALID_TAG,zt(t.source));t.source.readUpto("--\x3e")}else if("E"===n){Qt(t.source,0,"DOCTYPE E-type sub-tag");let s=t.source.readStr(1);if(t.source.updateBufferBoundary(1),"N"===s){Wt(t.source,"TITY","DOCTYPE ENTITY keyword");const[s,n]=Ne(t);if(-1===n.indexOf("&")){const i=t.options?.doctypeOptions;if(i?.maxEntityCount&&r>=i.maxEntityCount)throw new Rt(`Entity count (${r+1}) exceeds maximum allowed (${i.maxEntityCount})`,Vt.ENTITY_MAX_COUNT,zt(t.source));const o=s.replace(/[.\-+*:]/g,"\\$&");e[s]={regx:RegExp(`&${o};`,"g"),val:n},r++}}else{if("L"!==s)throw new Rt(`Invalid DOCTYPE sub-tag "<!E${s}"`,Vt.INVALID_TAG,zt(t.source));Wt(t.source,"EMENT","DOCTYPE ELEMENT keyword"),ve(t)}}else if("A"===n)Wt(t.source,"TTLIST","DOCTYPE ATTLIST keyword"),Se(t);else{if("N"!==n)throw new Rt(`Invalid DOCTYPE sub-tag "<!${n}"`,Vt.INVALID_TAG,zt(t.source));Wt(t.source,"OTATION","DOCTYPE NOTATION keyword"),Ce(t)}}catch(e){throw e.code===Vt.UNEXPECTED_END&&(t.source.startIndex=i),e}else if("["===o)s=!0;else if("]"===o)n=!0;else if(">"===o&&(!s||n))return e}throw new Rt("Unclosed DOCTYPE",Vt.UNEXPECTED_END,zt(t.source))}(this);if(this.doctypeFound)throw new Rt("Multiple DOCTYPE declarations found.",Vt.INVALID_INPUT,zt(this.source));this.doctypeFound=!0,this.options.doctypeOptions.enabled&&t&&Object.keys(t).length>0&&this.outputBuilder.addInputEntities(t)}}}addTextNode(){void 0!==this.tagTextData&&""!==this.tagTextData&&(this.tagTextData=Ht(this.tagTextData,this.source),(!this.options.skip.whitespaceText||this.tagTextData.trim().length>0)&&this.outputBuilder.addValue(this.tagTextData,this.readonlyMatcher),this.tagTextData="")}isValidQName(t){const e=this._validQNames;if(e.has(t))return!0;const r=this.getNameValidator("qName")(t);return r&&(e.size>=2e3&&e.clear(),e.add(t)),r}getNameValidator(t){let e=this._nameValidators[t];if(!e){const r=1.1===this.xmlDec.version||"1.1"===this.xmlDec.version?"1.1":"1.0";e=E(t,{xmlVersion:r}),this._nameValidators[t]=e}return e}processAttrName(t){return $e(this._nameCache.attrs,t,()=>{const e=this.options;let r=Ve(t,e.skip.nsPrefix);if(!this.getNameValidator("qName")(r))throw new Rt(`Invalid attribute name: ${r}`,Vt.INVALID_ATTRIBUTE_NAME,zt(this.source));if(r=je(r,e.onDangerousProperty,e.sanitizeNames,this.source),e.strictReservedNames&&r===e.attributes.groupBy)throw new Rt(`Restricted attribute name: ${r}`,Vt.SECURITY_RESTRICTED_NAME,zt(this.source));return r})}processTagName(t){return $e(this._nameCache.tags,t,()=>{const e=this.options,r=e.nameFor;let s=Ve(t,e.skip.nsPrefix);if(s=je(s,e.onDangerousProperty,e.sanitizeNames,this.source),e.strictReservedNames&&(s===r.comment||s===r.cdata||s===r.text))throw new Rt(`Restricted tag name: ${s}`,Vt.SECURITY_RESTRICTED_NAME,zt(this.source));return s})}isUnpaired(t){return this._unpairedSet.has(t)}_parserState(){const t=this;return{get tagsStack(){return t.tagsStack},get currentTagDetail(){return t.currentTagDetail},set currentTagDetail(e){t.currentTagDetail=e},get outputBuilder(){return t.outputBuilder},get readonlyMatcher(){return t.readonlyMatcher},get matcher(){return t.matcher},get source(){return t.source},get tagTextData(){return t.tagTextData},set tagTextData(e){t.tagTextData=e},addTextNode:t.addTextNode.bind(t),popTag:t.popTag.bind(t)}}}function Ve(t,e){if(e){const e=t.split(":");if(2===e.length)return"xmlns"!==e[0]&&e[1];if(e.length>2)throw new Rt(`Multiple namespaces in name: ${t}`,Vt.MULTIPLE_NAMESPACES,zt(this.source))}return t}function je(t,e,r,s){if(Ft.includes(t))throw new Rt(`[SECURITY] Invalid name: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`,Vt.SECURITY_PROTOTYPE_POLLUTION,zt(s));return!1===r?t:qt.includes(t)?e(t):t}function Xe(){if(0===this.stopNodeExpressionsSet.size)return null;const t=this.stopNodeExpressionsSet.findMatch(this.matcher);return t?t.data:null}function qe(){if(0===this.skipTagExpressionsSet.size)return null;const t=this.skipTagExpressionsSet.findMatch(this.matcher);return t?t.data:null}class Fe{constructor(t={}){this.buffer="",this.startIndex=0,this.isComplete=!1,this._baseOffset=0,this.maxBufferSize=t.maxBufferSize||10485760,this.autoFlush=!1!==t.autoFlush,this.flushThreshold=t.flushThreshold||1024,this._decodingOptions=t.decoding||null;const e=this._decodingOptions?.encoding;if(this._detecting="auto"===e,this._sniffBuffer=this._detecting?Buffer.alloc(0):null,!this._detecting&&e&&this._decodingOptions.registry){const t=this._decodingOptions.registry;this._createDecoder=()=>t.resolve(e).createDecoder()}else this._createDecoder="function"==typeof t.createDecoder?t.createDecoder:null;this._marks=[null,null],this._decoder=null,this._quotePairs=new Int32Array(128),this._quotePairsLen=0}feed(t){if(this._detecting)if("string"==typeof t)this._detecting=!1;else{const e=Buffer.isBuffer(t)?t:Buffer.from(t);this._sniffBuffer=this._sniffBuffer.length?Buffer.concat([this._sniffBuffer,e]):e;const r=this._sniffBuffer.includes(Buffer.from("?>"));if(this._sniffBuffer.length<200&&!r)return 0;t=this._resolveDetection()}let e=this._decodeNow(t);const r=this.buffer.length-this.startIndex;if(r+e.length>this.maxBufferSize)throw new Rt(`Buffer size limit exceeded (${r+e.length} > ${this.maxBufferSize}). Increase feedable.maxBufferSize or reduce chunk size.`,Vt.INVALID_INPUT);return this.buffer+=e,e.length}_decodeNow(t){if("string"==typeof t)return t;if(Buffer.isBuffer(t))return this._decoder||(this._decoder=this._createDecoder?this._createDecoder():ge("utf-8")),this._decoder.write(t);if(t?.toString)return t.toString();throw new Rt("feed() data must be a string or Buffer.",Vt.DATA_MUST_BE_STRING)}_resolveDetection(){const t=this._decodingOptions.registry,{encoding:e,bomLength:r}=fe(this._sniffBuffer,t),s=t.resolve(e);this._createDecoder=()=>s.createDecoder(),this._detecting=!1;const n=r?this._sniffBuffer.subarray(r):this._sniffBuffer;return this._sniffBuffer=null,n}end(){if(this._detecting){const t=this._resolveDetection();this.buffer+=this._decodeNow(t)}if(this._decoder){const t=this._decoder.end();t&&(this.buffer+=t)}this.isComplete=!0}canRead(t=0){return this.startIndex+t<this.buffer.length}markTokenStart(t=0){this._marks[t]=this.startIndex}rewindToMark(){null!==this._marks[0]&&(this.startIndex=this._marks[0]),this._marks[0]=null,this._marks[1]=null}clearMark(){this._marks[0]=null,this._marks[1]=null}readCh(){return this.buffer[this.startIndex++]}readChAt(t){return this.buffer[this.startIndex+t]}readStr(t,e){return void 0===e&&(e=this.startIndex),this.buffer.substring(e,e+t)}matchAhead(t,e=!1){const r=t.length;for(let s=0;s<r;s++){let r=this.buffer[this.startIndex+s];if(void 0===r)return null;if(e&&(r=r.toLowerCase()),r!==t[s])return!1}return!0}scanTagExpEnd=oe;scanTagExpEndFast=ae;readUpto(t){const e=this.buffer.length,r=t.length;for(let s=this.startIndex;s<e;s++){let e=!0;for(let n=0;n<r;n++)if(this.buffer[s+n]!==t[n]){e=!1;break}if(e){const t=this.buffer.substring(this.startIndex,s);return this.startIndex=s+r,t}}throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END)}readUptoChar(t){const e=this.buffer.indexOf(t,this.startIndex);if(-1===e)throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END);const r=this.buffer.substring(this.startIndex,e);return this.startIndex=e+1,r}readUptoCloseTag(t){const e=this.buffer.length,r=t.length;let s=-1,n=0;for(let i=this.startIndex;i<e;i++){if(1===n){const t=this.buffer[i];if(jt(t))continue;">"===t?n=2:(n=0,s=-1)}else{let e=!0;for(let s=0;s<r;s++)if(this.buffer[i+s]!==t[s]){e=!1;break}e&&(n=1,s=i,i+=r-1)}if(2===n){const t=this.buffer.substring(this.startIndex,s);return this.startIndex=i+1,t}}throw new Rt(`Unexpected end of source reading '${t}'`,Vt.UNEXPECTED_END)}updateBufferBoundary(t=1){this.startIndex+=t,this.autoFlush&&this.startIndex>=this.flushThreshold&&this.flush()}flush(){let t=this.startIndex;for(const e of this._marks)null!==e&&e<t&&(t=e);if(t>0){this.buffer=this.buffer.substring(t);const e=this._marks.length;for(let r=0;r<e;r++)null!==this._marks[r]&&(this._marks[r]-=t);this.startIndex-=t,this._baseOffset+=t}}}class Ye extends Fe{attachStream(t,e,r,s){t.on("data",t=>{try{this.feed(t),e(null)}catch(t){e(t)}}),t.on("error",s),t.on("end",()=>{try{this.end(),r()}catch(t){s(t)}})}}class ze{constructor(t){if(this.options=ee(t),this._feedParser=null,this._feedSource=null,this._isFeeding=!1,this._pendingBytes=0,this._batchThreshold=this.options.feedable?.bufferSize,this.options.decoding?.customDecoders){const t=new me;for(const[e,r]of Object.entries(this.options.decoding.customDecoders))t.register({name:e,...r});this.options.decoding._registry=t}else this.options.decoding=this.options.decoding||{},this.options.decoding._registry=_e;this.options._nameCache={tags:new Map,attrs:new Map}}parse(t){if(t instanceof Buffer||ArrayBuffer.isView(t))return this.parseBytesArr(t);if("string"!=typeof t){if(!t||"function"!=typeof t.toString)throw new Rt("XML data must be a string or Buffer.",Vt.INVALID_INPUT);t=t.toString()}const e=this._createParser(),r=e.parse(t);return this.wasExited=e.wasExited(),this._lastParseErrors=e.autoCloseHandler?.getErrors()??[],r}parseBytesArr(t){if(!(t instanceof Uint8Array||ArrayBuffer.isView(t)))throw new Rt("XML data must be a Uint8Array or ArrayBufferView.",Vt.INVALID_INPUT);t=Buffer.from(t);const e=this._createParser(),r=e.parseBytesArr(t);return this.wasExited=e.wasExited(),this._lastParseErrors=e.autoCloseHandler?.getErrors()??[],r}parseStream(t){if(null===(e=t)||"object"!=typeof e||"function"!=typeof e.read||"function"!=typeof e.on||"boolean"!=typeof e.readableEnded)throw new Rt("parseStream() requires a Node.js Readable stream.",Vt.INVALID_STREAM);var e;const r=new Ye({...this.options.feedable,decoding:{encoding:this.options.decoding.encoding,registry:this.options.decoding._registry}}),s=this._createParser();return s.source=r,s.initializeParser(),new Promise((e,n)=>{let i=!1;const o=e=>{i||(i=!0,t.destroy(),n(e))};r.attachStream(t,t=>{if(t)o(t);else try{s.parseXml()}catch(t){t.code===Vt.UNEXPECTED_END?r.rewindToMark():o(t)}},()=>{if(!i)try{s.parseXml(),s.finalizeXml(),this._lastParseErrors=s.autoCloseHandler?.getErrors()??[],i=!0,e(s.outputBuilder.getOutput())}catch(t){o(t)}},o)})}_runParse(){if(!this._feedParser)return;const t=Yt(this._feedSource);try{this._feedParser.parseXml()}catch(t){if(t.code!==Vt.UNEXPECTED_END)throw t;this._feedSource.rewindToMark()}Yt(this._feedSource)>t?(this._pendingBytes=0,this._batchThreshold=this.options.feedable.bufferSize):this._batchThreshold=Math.min(2*this._batchThreshold,this.options.feedable.maxBufferSize)}feed(t){this._isFeeding||this._initFeedSession();const e=this._feedSource.feed(t);return this._pendingBytes+=e,this._pendingBytes>=this._batchThreshold&&this._runParse(),this}end(){if(!this._isFeeding)throw new Rt("No data fed. Call feed() before end().",Vt.NOT_STREAMING);this._runParse();try{this._feedSource.end();let t=null;const e=this._feedParser.autoCloseHandler;e&&e.reset();try{this._feedParser.parseXml()}catch(r){if(r.code!==Vt.UNEXPECTED_END)throw r;if(!e)throw r;t=r}return t?e.handlePartialTag(t,this._feedParser._parserState()):this._feedParser.finalizeXml(),this._lastParseErrors=e?.getErrors()??[],this.wasExited=this._feedParser.wasExited(),this._feedParser.outputBuilder.getOutput()}finally{this._cleanupFeedSession()}}getParseErrors(){return this._lastParseErrors??[]}_createParser(){return new Re(this.options)}_initFeedSession(){this._feedSource=new Fe({...this.options.feedable,decoding:{encoding:this.options.decoding.encoding,registry:this.options.decoding._registry}}),this._feedParser=this._createParser(),this._feedParser.source=this._feedSource,this._feedParser.initializeParser(),this._isFeeding=!0}_cleanupFeedSession(){this._feedParser=null,this._feedSource=null,this._isFeeding=!1}}class Ge extends $t{constructor(t,e,r,s){super(t,e,r,s),this.siblingOrder=new Map}addElement(t){const e=this.matcher.toString(),r=e.lastIndexOf("."),s=-1===r?"":e.substring(0,r);this.siblingOrder.has(s)||this.siblingOrder.set(s,[]);const n=this.siblingOrder.get(s);n[n.length-1]!==t.name&&n.push(t.name),super.addElement(t)}getOutput(){return{data:super.getOutput(),siblingOrder:this.siblingOrder}}}const He=new At({hex:!0,leadingZeros:!0,eNotation:!0,unicode:!0});function We(t){const e=He.parse(t);return"number"==typeof e?e:NaN}const Qe={minLength:(t,e)=>e.length>=t,maxLength:(t,e)=>e.length<=t,length:(t,e)=>e.length===t,pattern:(t,e,r="")=>new RegExp(t,r).test(e),fixed:(t,e)=>t===e,in:(t,e)=>t.split(",").indexOf(e)>-1},Je={min:(t,e)=>We(e)>=t,max:(t,e)=>We(e)<=t},Ze={minOccurs:(t,e)=>e>=t,maxOccurs:(t,e)=>e<=t},Ke=(t,e)=>Date.parse(e)>=Date.parse(t),tr=(t,e)=>Date.parse(e)<=Date.parse(t),er=["positiveInteger","integer","positiveDecimal","decimal","number"];class rr{constructor(t,e,r){this.options=t,this.failures=[],this.validators=e,this._globalUnique=new Map,this._siblingOrder=r||new Map}traverse(t,e,r,s){if(Array.isArray(t)){if(void 0!==r&&void 0!==r["@rules"]&&void 0!==r["@rules"].repeatable)return this.checkOccurences(r["@rules"],t.length,s),void t.forEach((n,i)=>{const o=s+"["+i+"]";Object.keys(r).length>1?this.callForCommonProperties(t[i],r,o):this.traverse(t[i],e,r,o)});this.failures.push({code:"unexpected sequence",path:s.substr(1)})}else"object"==typeof t?this.callForCommonProperties(t,r,s):("object"==typeof r&&r["@rules"]?this.checkDataAndType(t,e,r,s):this.isMapType(r)&&this.validateMandatoryFields(r,s),this.applyCustomValidators(t,r,s))}applyCustomValidators(t,e,r){if(e["@rules"]&&e["@rules"].checkBy&&"function"==typeof this.validators[e["@rules"].checkBy]){let s=this.validators[e["@rules"].checkBy](t,r.substr(1));"object"==typeof s&&this.failures.push(s)}}callForCommonProperties(t,e,r){const s=function(t,e){const r={data:[],rules:[],common:[]};for(let s=0;s<t.length;s++)-1===e.indexOf(t[s])?r.data.push(t[s]):r.common.push(t[s]);for(let s=0;s<e.length;s++)-1===t.indexOf(e[s])&&"@"!==e[s]&&r.rules.push(e[s]);return r}(Object.keys(t),Object.keys(e));this.checkUnknownSiblings(s,r),this.checkMissingSiblings(s,e,r),this.applyCustomValidators(t,e,r);const n=this._buildSiblingValues(t,e,s.common);s.common.forEach(s=>{const n=r+"."+s;this.traverse(t[s],s,e[s],n)}),this._checkOrderingConstraints(t,e,s.common,r),this._checkUniquenessConstraints(t,e,s.common,r,n),this._checkRelationalConstraints(t,e,s.common,r)}_checkOrderingConstraints(t,e,r,s){const n=s.substr(1),i=this._siblingOrder.get(n);i&&r.forEach(r=>{const n=e[r];if(!n||!n["@rules"])return;const o=n["@rules"],a=i.indexOf(r);if(-1!==a){if(o.after){const e=o.after;if(void 0===t[e])return;const n=i.indexOf(e);if(-1===n)return;a<=n&&this.failures.push({code:"after",path:(s+"."+r).substr(1),actual:r,expected:e})}if(o.before){const e=o.before;if(void 0===t[e])return;const n=i.indexOf(e);if(-1===n)return;a>=n&&this.failures.push({code:"before",path:(s+"."+r).substr(1),actual:r,expected:e})}}})}_checkRelationalConstraints(t,e,r,s){const n=["sameAs","notSameAs","lessThan","moreThan"];r.forEach(r=>{const i=e[r];if(!i||!i["@rules"])return;const o=i["@rules"];if(!n.some(t=>void 0!==o[t]))return;const a=t[r];if(null==a)return;if("object"==typeof a)return;const l=o.type||"string";n.forEach(e=>{if(void 0===o[e])return;const n=o[e],i=t[n];if(null==i)return;if("object"==typeof i)return;const c=this._relationalCompare(String(a),String(i),l);if(null===c)return;let h=!1;"sameAs"===e&&0!==c&&(h=!0),"notSameAs"===e&&0===c&&(h=!0),"lessThan"===e&&c>=0&&(h=!0),"moreThan"===e&&c<=0&&(h=!0),h&&this.failures.push({code:e,path:(s+"."+r).substr(1),actual:String(a),expected:n})})})}_relationalCompare(t,e,r){if("date"===r){const r=Date.parse(t),s=Date.parse(e);return isNaN(r)||isNaN(s)?null:r-s}if(-1!==er.indexOf(r)){const r=We(t),s=We(e);return isNaN(r)||isNaN(s)?null:r-s}return t<e?-1:t>e?1:0}_buildSiblingValues(t,e,r){const s=new Map;return r.forEach(e=>{const r=t[e];Array.isArray(r)?s.set(e,r.map(String)):null!=r&&"object"!=typeof r&&s.set(e,[String(r)])}),s}_checkUniquenessConstraints(t,e,r,s,n){r.forEach(r=>{const i=e[r];if(!i||!i["@rules"])return;const o=i["@rules"].unique;if(!o)return;const a=n.get(r)||[];"global"===o&&a.forEach((e,n)=>{const i=Array.isArray(t[r])?(s+"."+r+"["+n+"]").substr(1):(s+"."+r).substr(1);this._assertGlobalUnique(r,e,i)})})}_checkUniqueInCollection(t,e,r){const s=new Map;t.forEach((t,n)=>{const i=t[e];if(null==i||"object"==typeof i)return;const o=String(i);s.has(o)?this.failures.push({code:"unique",path:(r+"["+n+"]."+e).substr(1),value:o}):s.set(o,n)})}_assertGlobalUnique(t,e,r){this._globalUnique.has(t)||this._globalUnique.set(t,new Set);const s=this._globalUnique.get(t);s.has(e)?this.failures.push({code:"unique",path:r,value:e}):s.add(e)}checkDataAndType(t,e,r,s){!0===r["@rules"].repeatable&&this.checkOccurences(r["@rules"],1,s);const n=r["@rules"].type,i=this._expandRange(r);if("map"===n||!n&&this.isMapType(r))"string"==typeof t&&t.length>0&&this.failures.push({code:"unexpected value in a map",path:s.substr(1),value:t}),this.validateMandatoryFields(r,s);else if("date"===n)this.validateDate(t,n,s),this._checkDateBounds(r,t,s);else if("boolean"===n)this.validateBoolean(t,n,s);else if(-1!==er.indexOf(n))this.isValidNum(n,t)?this.assertValue(i["@rules"],"num",We(t),s):this.setInvalidDataType(n,s,t);else{if("string"!==n&&n)throw new Error("Unsupported data type in Rules:"+n);this.assertValue(i["@rules"],"string",t,s)}}_expandRange(t){if(!t["@rules"]||!t["@rules"].range)return t;const e=function(t){if("string"!=typeof t)return null;const e=t.split("..");if(2!==e.length)return null;const r=We(e[0]),s=We(e[1]);return isNaN(r)||isNaN(s)?null:{min:r,max:s}}(t["@rules"].range);return e?{...t,"@rules":{...t["@rules"],min:void 0!==t["@rules"].min?t["@rules"].min:String(e.min),max:void 0!==t["@rules"].max?t["@rules"].max:String(e.max)}}:t}_checkDateBounds(t,e,r){if(isNaN(Date.parse(e)))return;const s=t["@rules"];let n=s.min,i=s.max;if(s.range&&(!n||!i)){const t=function(t){if("string"!=typeof t)return null;const e=t.split("..");if(2!==e.length)return null;const[r,s]=e;return isNaN(Date.parse(r))||isNaN(Date.parse(s))?null:{min:r,max:s}}(s.range);t&&(n||(n=t.min),i||(i=t.max))}void 0===n||Ke(n,e)||this.setInvalidValueError("min",r,e,n),void 0===i||tr(i,e)||this.setInvalidValueError("max",r,e,i)}validateMandatoryFields(t,e){const r=Object.keys(t);for(let s=0;s<r.length;s++){if("@rules"===r[s])continue;const n=t[r[s]]["@rules"];n&&(n.minOccurs&&n.minOccurs>0||void 0!==n.nillable&&"false"===n.nillable)&&this.failures.push({code:"missing",path:(e+"."+r[s]).substr(1)})}}isMapType(t){if("string"==typeof t)return!1;const e=Object.keys(t);return t["@rules"]?1!==e.length&&void 0:0!==e.length}setInvalidValueError(t,e,r,s){this.failures.push({code:t,path:e.substr(1),actual:r,expected:s})}checkOccurences(t,e,r){["minOccurs","maxOccurs"].forEach(s=>{if(void 0!==t[s]){const n=Number(t[s]);Ze[s](n,e)||this.setInvalidValueError(s,r,e,n)}})}checkNumeric(t,e,r){["min","max"].forEach(s=>{if(void 0!==t[s]){const n=Number(t[s]);Je[s](n,e)||this.setInvalidValueError(s,r,e,n)}})}checkString(t,e,r){["minLength","maxLength","length"].forEach(s=>{if(void 0!==t[s]){const n=Number(t[s]);Qe[s](n,e)||this.setInvalidValueError(s,r,e,n)}}),["fixed","in"].forEach(s=>{if(void 0!==t[s]){const n=t[s];Qe[s](n,e)||this.setInvalidValueError(s,r,e,n)}}),["pattern","pattern_i","pattern_im","pattern_mi"].forEach(s=>{if(void 0!==t[s]){let n="";s.length>8&&(n=s.substring(8));const i=t[s];Qe.pattern(i,e,n)||this.setInvalidValueError("pattern",r,e,i)}})}assertValue(t,e,r,s){"string"===e?this.checkString(t,r,s):"num"===e&&this.checkNumeric(t,r,s)}validateBoolean(t,e,r){-1===this.options.boolean.indexOf(t)&&this.setInvalidDataType(e,r,t)}isValidNum(t,e){const r=We(e);return!isNaN(r)&&!("positiveInteger"===t&&r<0||"positiveDecimal"===t&&r<0||"integer"===t&&!function(t){return(0|t)===t}(r))}validateDate(t,e,r){const s=Date.parse(t);isNaN(s)&&this.setInvalidDataType(e,r,t)}setInvalidDataType(t,e,r){this.failures.push({code:"not a "+t,path:e.substr(1),value:r})}checkMissingSiblings(t,e,r){t.rules&&t.rules.forEach(t=>{const s=e[t]["@rules"];s&&("false"===s.nillable||s.minOccurs>0)&&this.failures.push({code:"missing",path:(r+"."+t).substr(1)})})}checkUnknownSiblings(t,e){t.data&&!this.options.unknownAllow&&t.data.forEach(t=>{this.failures.push({code:"unknown",path:(e+"."+t).substr(1)})})}}const sr=rr.prototype.traverse;rr.prototype.traverse=function(t,e,r,s){if(Array.isArray(t)&&void 0!==r&&void 0!==r["@rules"]&&void 0!==r["@rules"].repeatable)return this.checkOccurences(r["@rules"],t.length,s),t.forEach((n,i)=>{const o=s+"["+i+"]";if(Object.keys(r).length>1)this.callForCommonProperties(t[i],r,o);else{const s=r;sr.call(this,t[i],e,s,o)}}),void(t.length>0&&"object"==typeof t[0]&&this._runSiblingUniqueness(t,r,s));sr.call(this,t,e,r,s)},rr.prototype._runSiblingUniqueness=function(t,e,r){Object.keys(e).filter(t=>"@rules"!==t).forEach(s=>{const n=e[s];n&&n["@rules"]&&"true"===n["@rules"].unique&&this._checkUniqueInCollection(t,s,r)})};const nr={unknownAllow:!0,boolean:["true","false"]},ir={tags:{valueParsers:[]},attributes:{valueParsers:[]}},or=new ze({skip:{attributes:!1},attributes:{prefix:"",groupBy:"@rules",booleanType:!0},OutputBuilder:new Mt(ir)}),ar=new ze({skip:{attributes:!1},attributes:{prefix:"",groupBy:":a"},OutputBuilder:new class extends Mt{getInstance(t,e){return new Ge(t,this.builderOptions,e,this.registry)}}(ir)}),lr="__nodableAttrsBucket__",cr=/<(\/?):a(\s|>|\/)/g;function hr(t){if(Array.isArray(t))for(const e of t)hr(e);else if(null!==t&&"object"==typeof t){Object.prototype.hasOwnProperty.call(t,lr)&&(t[":a"]=t[lr],delete t[lr]);for(const e of Object.keys(t))hr(t[e])}return t}function dr(t){if(!t)throw new Error("Empty data");if("string"!=typeof t)throw new Error("Not a valid string")}function ur(t,e){try{return t.parse(e)}catch(t){if(t instanceof Rt){let r=t.message;if("INVALID_ATTRIBUTE_NAME"===t.code){const t=r.slice(r.indexOf(": ")+2);r=`Attribute '${t}' is an invalid name.`}if(void 0===t.index)throw new Error(r);const s=e.substring(0,t.index).split("\n").length;throw new Error(r+":"+s)}throw t}}const pr=class{constructor(t,e){dr(t),this.rules=hr(ur(or,function(t){return t.replace(cr,`<$1${lr}$2`)}(t))),this.options=Object.assign({},nr,e),this.validators={},this.data=null}register(t,e){this.validators[t]=e}validate(t){dr(t);const{data:e,siblingOrder:r}=ur(ar,t);this.data=e;const s=new rr(this.options,this.validators,r);return s.traverse(e,"",this.rules,""),s.failures}};module.exports=e})();
|